VIM as a full-featured extensible IDE for any language - perl

Hello I would like to master VIM as my primary IDE. I know there are many plugins etc. but I have one question: Is possible for VIM to understand the particular language (in case I wont plugin for my language) in which code is written? I mean some rules that I can define and then use e.g. for auto-completion, refactoring, folding etc. For example consider following two perl codes in which I want refactor variables. In first example there are variables with same names but one is scalar and another are array and hash, in second example same name of variable as was defined before was used in another scope (loop etc.). Thus refactoring using simple text matching is not elegant way I thing:
1st example:
my #same_name;
my $same_name; # How to refactor this variable without affecting all other variables?
my %same_name;
$same_name[0] = 5;
$same_name{"key"} = 5;
$same_name = 5;
2nd example:
my #array;
my $already_existing_variable; # How to refactor this variable
foreach my $already_existing_variable (#array){
print $already_existing_variable; # Without affecting this variable
}
print $already_existing_variable; # Variable that should be also refactorized
Or how can I achieve that when I type $arr {and hit TAB here} it will automatically extend to $array[ ? For this VIM must to know that when I prepend $ before variable which was declared with # I want to access array elements.
Another example would be: how to fold code using e.g. BEGIN and END keywords? Those was jut trivial examples but I think you get the point. I think it is similar task to write own compiler or something. Thank you.

I'm using vim with my perl scripts almost all days:
Rename variables
App::EditorTools gives you the function to rename variables like Padre.
install App::EditorTool $ cpanm App::EditorTools
install vim plugin $ editortools install-vim
move cursor on the variable name in vim.
type \pL
I'm not sure why it parses wrong scope in the 2nd example, but you can temporarily wrap the foreach brock with lambda and rename variables inside the code block first.
sub {
foreach my $already_existing_variable (#array){
print $already_existing_variable; # Without affecting this variable
}
}->();
Reformat script indent
Perl::Tidy has perltidy command line tool to format your script.
install Perl::Tidy $ cpanm Perl::Tidy
create ~/.perltidyrc according to your taste. like folowing:
-pbp
-pt=2
-sbt=2
-bt=2
-bbt=2
-ce
-nbbc
set equalprg to perltidy in your ~/.vimrc
au FileType perl setl ep=perltidy
type gg=G in your script.
Syntax Check
vim's built-in compiler plugin for perl does very well.
set :compilerto perl in your ~/.vimrc
au FileType perl :compiler perl
type :make in normal mode
type :copen to open up quickfix window
if you don't want warnings in your quickfix list, you can unset the flag for it.
let g:perl_compiler_force_warnings = 0
$PERL5LIB is also important while invoking :make, you can give specific directories in it.
let &l:path = './lib,./blib/lib,./blib/arch,' . &l:path
let $PERL5LIB = substitute(&l:path, ',', ':', 'g')
Completions
vim has nice completion tool out of the box. see :help comple-generic
type $ar in insert mode and press CTRL-N
You might be interested in ctags too.

I can already tell something is wrong when the first sentence is "Hello I would like to master VIM as my primary IDE."
Vim is not an IDE. Vim is a text editor. (You can use google to find out more)
If you feel that the features an IDE provides (refactoring, smarter auto-completion...) are more important than the features that vim provides (fast movement, never take your hands off the home row, programmable editor...) then you should use an IDE, or an IDE with a vim plugin. Usually, if you want to mix IDE features with vim features, you do it with a plugin to the IDE, not the other way around (there are some exceptions such as eclim).

Related

Is there a good place in .vim folder to store text filters?

I would like to create a filter folder, best inside .vim and be able to run a text filter just with one file name:! filter.pl
I put up a Perl text filter to change all special Characters in a LaTeX Math Formula, which is running fine so far - only problem it is running on the whole line not the selected formula, but I can live with it ...
#!/usr/bin/perl -np
use strict;
use warnings;
# this filter transforms all special characters in Mathformular for LaTeX
s/\\/\\backslash /g;
s/([\$\#&%_{}])/\\$1/g;
But to call this filter is cumbersome
: '<,'>!"/Users/username/Library/Mobile Documents/com~apple~CloudDocs/my_vim_cheat_sheet/perl_filter.pl"
Apple put in the path to the iCloud a white space, so I have to put "" around! Where I put a collection of text filters?
Thank you for your answers
marek
You can safely create a subfolder with any name different from ones Vim uses itself (see :h 'rtp'). So this is ok:
:*!$HOME/.vim/filters/perl_filter.pl
Also Vim has a predefined interface for a general purpose filter called 'equalprg'. To make use of it simply set a global-local (i.e. both set and setlocal are meaningful) option equalprg to a fully qualified name of your script. Then hit = in visual mode to apply filter (or ={motion} in normal mode). (Read :h 'equalprg' :h =).
If you need several filters at once, and switching equalprg is not convenient, you can still try different options to reduce typing.
For example, mappings, such as
vnoremap <Leader>f :!/path/to/my/filter<CR>
Then hitting \f (or whatever is your "leader" key set) in the visual mode will result in the executing :'<,'>!/path/to/my/filter (note that the visual selection will be applied automatically).
Another attempt is to set a dedicated environment variable (which will be inherited by all child processes including shell(s). For example,
:let $filters = '~/.vim/filters'
:*!$filters/myfilter.pl
Of course, you can put those set equalprg=... vnoremap ... let $filters=... etc.etc. in your vimrc.
I would like to create a filter folder, best inside .vim and be able to run a text filter just with one file name :! filter.pl
Simply add the script to somewhere within your $PATH. Or, if you really only intend to use that from within Vim, then add that directory to your $PATH in your .vimrc, so you have it available there.
For example, if you'd like to use ~/.vim/scripts for your external Perl or shell scripts, you can use this in your ~/.vimrc:
call setenv('PATH', expand('~/.vim/scripts').':'.$PATH)
After that, you can simply use :'<,'> !filter.pl to run it. And Tab completion will work with the name of the script, type :!fil<Tab> and Vim will complete it to filter.pl, assuming it's a unique prefix.
The snippet above for your .vimrc has one minor issue, that if you :source your .vimrc during Vim runtime, it will keep adding the entry to $PATH multiple times. That doesn't typically break anything, only the entry will become longer, you might run into variable length issues.
You can fix it by checking whether that's present in path or not before updating it, perhaps with something like:
let scripts_dir = expand('~/.vim/scripts')
if index(split($PATH, ':'), scripts_dir) < 0
call setenv('PATH', scripts_dir.':'.$PATH)
endif
But also, about this:
I put up a Perl text filter to change all special Characters in a LaTeX Math Formula
s/\\/\\backslash /g;
s/([\$\#&%_{}])/\\$1/g;
Consider writing that in Vim instead.
In fact, almost the same syntax will work as a Vim function:
function! EscapeLatexMathFormula()
s/\\/\\backslash /eg
s/\([$#&%_{}]\)/\\\1/eg
endfunction
You can call it on a range, with:
:'<,'>call EscapeLatexMathFormula()
Calling it without a range will affect the current line only.
You can also make it into a command, with:
command! -range EscapeLatexMathFormula <line1>,<line2> call EscapeLatexMathFormula()
In which case you can simply use:
:'<,'>EscapeLatexMathFormula
You can use tab-completion for the function and command names (though, of course, you can pick shorter names if you'd like, as well.)
Note that user-defined command names need to start with an uppercase letter. Function names can start with an uppercase letter too (there are more options for function names, but making this global with an uppercase is probably the easiest here.)

Always open a txt file using specified app in fish shell

I use fish shell. I always open *.txt files in atom, so I need to type atom filename.txt. I know, that in zsh, there's an option to always open files with some extension in the specific app using alias -s option. Is there a way to achieve the same behavior in fish shell?
Sorry, fish does not support this. Your best bet is to define an ordinary function/alias that calls into atom.
Two solutions come to mind. First, use an abbreviation or function to reduce the number of characters you have to type:
abbr a atom
Now you can just type "a *.txt". The advantage of doing function a; atom $argv; end is that it allows for more complicated steps than just replacing a short command with a longer command. As another example, I have abbr gcm "git checkout master" in my config because that's something I do frequently.
Second, use a key binding. For example, arrange for pressing [meta-a] to insert "atom" at the start of the command and execute it:
function edit_with_atom
set -l line (commandline -b)
commandline -r "atom $line"
commandline -f execute
end
bind \ea edit_with_atom
The key binding allows for more complicated operations than what I've shown above since you can execute arbitrary code.
These solutions don't scale but if there's just a couple of commands you run frequently that you want to invoke with fewer keystrokes they might help.

vim: Interactive search and replace with perl compatible regular expressions

According to this page you can use perl compatible regular expression with
:perldo s/pattern/insert/g.
This works fine.
But, how can I get interactive search and replace with PCRE syntax in vim?
Since this does not work with perldo I search for a different solution.
Till the current release version of vim, there is no way to do :s/[perlRegex]/bar/c
So you are asking for a feature that doesn't exist.
You can do matching with verymagic, however it is not Perl Regex compatible flag. It is still using the vimregex engine, just changed the way of escaping regex patterns.
For example, in perl, you can do lookahead/behind (?<=foo)..., (?=foo), (?!foo).., you can use the handy \K : som.*ing\Kwhatever etc, you cannot use those syntax in vim directly, no matter which 'magic' level you have set. Vim has the same feature, but different syntax:
\#=
\#!
\#<=
and also the \zs \ze are very handy, even more powerful than perl's \K.
Vim is an Editor, with vim regex, you can not only do text matching, but also match base on visual selection, cursor position and so on.
If you really need to do complex pattern matching and really need do them in vim, learn vim regex! It is not difficult for you if you "know pcre very well"
Probably the closest you can get is:
:s/\vfoo/bar/gc
I suggest to try eregex plugin. It maps perl compatible regular expressions to VIM regex syntax.
In your example, s/pattern/insert/g is a perl command, not a Vim command using a perl-compatible regular expression syntax.
If perl doesn't have an equivalent of Vim's /c flag you will need to find an alternate method likeā€¦ writing an actual perl script.

Why is the apostrophe sign a valid path separator in Perl

In Perl, you call modules using :: as path separator. So, if you have a module on site/lib/GD/Image.pm, you call use GD::Image.
However, long time ago I found out that you can also call use GD'Image and things like my $img = new GD'Image;, and there are also modules on CPAN using that syntax on ther names/documentation.
What is the purpose or logic behind that? Is it maybe, as many things in Perl, just a feature intended to humanize sentences and allow you to create and use modules like Acme::Don't?
Does it have any other intention different to ::?
See perlmod for explanation:
The old package delimiter was a single quote, but double colon is now the preferred delimiter
So, the reason is history.
The single quote is an old ADA separator. However, it didn't play well with Emacs, so the double colon became used.
Good God! ADA? Emacs? I am old.

What are the best-practices for implementing a CLI tool in Perl?

I am implementing a CLI tool using Perl.
What are the best-practices we can follow here?
As a preface, I spent 3 years engineering and implementing a pretty complicated command line toolset in Perl for a major financial company. The ideas below are basically part of our team's design guidelines.
User Interface
Command line option: allow as many as possible have default values.
NO positional parameters for any command that has more than 2 options.
Have readable options names. If length of command line is a concern for non-interactive calling (e.g. some un-named legacy shells have short limits on command lines), provide short aliases - GetOpt::Long allows that easily.
At the very least, print all options' default values in '-help' message.
Better yet, print all the options' "current" values (e.g. if a parameter and a value are supplied along with "-help", the help message will print parameter's value from command line). That way, people can assemble command line string for complicated command and verify it by appending "-help", before actually running.
Follow Unix standard convention of exiting with non-zero return code if program terminated with errors.
If your program may produce useful (e.g. worth capturing/grepping/whatnot) output, make sure any error/diagnostic messages go to STDERR so they are easily separable.
Ideally, allow the user to specify input/output files via command line parameter, instead of forcing "<" / ">" redirects - this allows MUCH simpler life to people who need to build complicated pipes using your command. Ditto for error messages - have logfile option.
If a command has side effect, having a "whatif/no_post" option is usually a Very Good Idea.
Implementation
As noted previously, don't re-invent the wheel. Use standard command line parameter handling modules - MooseX::Getopt, or Getopt::Long
For Getopt::Long, assign all the parameters to a single hash as opposed to individual variables. Many useful patterns include passing that CLI args hash to object constructors.
Make sure your error messages are clear and informative... E.g. include "$!" in any IO-related error messages. It's worth expending extra 1 minute and 2 lines in your code to have a separate "file not found" vs. "file not readable" errors, as opposed to spending 30 minutes in production emergency because a non-readable file error was misdiagnosed by Production Operations as "No input file" - this is a real life example.
Not really CLI-specific, but validate all parameters, ideally right after getting them.
CLI doesn't allow for a "front-end" validation like webapps do, so be super extra vigilant.
As discussed above, modularize business logic. Among other reasons already listed, the amount of times I had to re-implement an existing CLI tool as a web app is vast - and not that difficult if the logic is already a properly designed perm module.
Interesting links
CLI Design Patterns - I think this is ESR's
I will try to add more bullets as I recall them.
Use POD to document your tool, follow the guidelines of manpages; include at least the following sections: NAME, SYNOPSIS, DESCRIPTION, AUTHOR. Once you have proper POD you can generate a man page with pod2man, view the documentation at the console with perldoc your-script.pl.
Use a module that handles command line options for you. I really like using Getopt::Long in conjunction with Pod::Usage this way invoking --help will display a nice help message.
Make sure that your scripts returns a proper exit value if it was successful or not.
Here's a small skeleton of a script that does all of these:
#!/usr/bin/perl
=head1 NAME
simplee - simple program
=head1 SYNOPSIS
simple [OPTION]... FILE...
-v, --verbose use verbose mode
--help print this help message
Where I<FILE> is a file name.
Examples:
simple /etc/passwd /dev/null
=head1 DESCRIPTION
This is as simple program.
=head1 AUTHOR
Me.
=cut
use strict;
use warnings;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
exit main();
sub main {
# Argument parsing
my $verbose;
GetOptions(
'verbose' => \$verbose,
) or pod2usage(1);
pod2usage(1) unless #ARGV;
my (#files) = #ARGV;
foreach my $file (#files) {
if (-e $file) {
printf "File $file exists\n" if $verbose;
}
else {
print "File $file doesn't exist\n";
}
}
return 0;
}
Some lessons I've learned:
1) Always use Getopt::Long
2) Provide help on usage via --help, ideally with examples of common scenarios. It helps people don't know or have forgotten how to use the tool. (I.e., you in six months).
3) Unless it's pretty obvious to the user as why, don't go for long period (>5s) without output to the user. Something like 'print "Row $row...\n" unless ($row % 1000)' goes a long way.
4) For long running operations, allow the user to recover if possible. It really sucks to get through 500k of a million, die, and start over again.
5) Separate the logic of what you're doing into modules and leave the actual .pl script as barebones as possible; parsing options, display help, invoking basic methods, etc. You're inevitably going to find something you want to reuse, and this makes it a heck of a lot easier.
The most important thing is to have standard options.
Don't try to be clever, be simply consistent with already existing tools.
How to achieve this is also important, but only comes second.
Actually, this is quite generic to all CLI interfaces.
There are a couple of modules on CPAN that will make writing CLI programs a lot easier:
App::CLI
App::Cmd
If you app is Moose based also have a look at MooseX::Getopt and MooseX::Runnable
The following points aren't specific to Perl but I've found many Perl CL scripts to be deficient in these areas:
Use common command line options. To show the version number implement -v or --version not --ver. For recursive processing -r (or perhaps -R although in my Gnu/Linux experience -r is more common) not --rec. People will use your script if they can remember the parameters. It's easy to learn a new command if you can remember "it works like grep" or some other familiar utility.
Many command line tools process "things" (files or directories) within the "current directory". While this can be convenient make sure you also add command line options for explicitly identifying the files or directories to process. This makes it easier to put your utility in a pipeline without developers having to issue a bunch of cd commands and remember which directory they're in.
You should use Perl modules to make your code reusable and easy to understand.
should have a look at Perl best practices