Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

.vimrc for perl programmers

by nferraz (Monk)
on Mar 30, 2006 at 13:21 UTC ( [id://540167]=perlmeditation: print w/replies, xml ) Need Help??

I started to write this .vimrc file because I wanted my programs to use 4-space (actual spaces!) identation.

That was a simple need, but, after a quick research, I found many features that made Perl programming more enjoyable in Vim.

Without more delay, here's my .vimrc file:

" use visual bell instead of beeping set vb " incremental search set incsearch " syntax highlighting set bg=light syntax on " autoindent autocmd FileType perl set autoindent|set smartindent " 4 space tabs autocmd FileType perl set tabstop=4|set shiftwidth=4|set expandtab|set + softtabstop=4 " show matching brackets autocmd FileType perl set showmatch " show line numbers autocmd FileType perl set number " check perl code with :make autocmd FileType perl set makeprg=perl\ -c\ %\ $* autocmd FileType perl set errorformat=%f:%l:%m autocmd FileType perl set autowrite " dont use Q for Ex mode map Q :q " make tab in v mode ident code vmap <tab> >gv vmap <s-tab> <gv " make tab in normal mode ident code nmap <tab> I<tab><esc> nmap <s-tab> ^i<bs><esc> " paste mode - this will avoid unexpected effects when you " cut or copy some text from one window and paste it in Vim. set pastetoggle=<F11> " comment/uncomment blocks of code (in vmode) vmap _c :s/^/#/gi<Enter> vmap _C :s/^#//gi<Enter> " my perl includes pod let perl_include_pod = 1 " syntax color complex things like @{${"foo"}} let perl_extended_vars = 1 " Tidy selected lines (or entire file) with _t: nnoremap <silent> _t :%!perltidy -q<Enter> vnoremap <silent> _t :!perltidy -q<Enter> " Deparse obfuscated code nnoremap <silent> _d :.!perl -MO=Deparse 2>/dev/null<cr> vnoremap <silent> _d :!perl -MO=Deparse 2>/dev/null<cr>

Most of the features are self-evident when you open your next perl script. Other features deserve some comments:

  • Use ":make" to check your code: it will call "perl -c" to verify your code and, if there are any erros, the cursor will be positioned in the offending line.
  • Get rid of the Ex mode: I often entered in Ex mode when I wanted to type ":q"...
  • Indent code with tabs: Use "v" to select a region, or indent line by line in normal mode. (Use shift-tab to unindent.)
  • Press F11 to toggle the "paste mode", disabling autoindent so that any text you paste won't loose its original layout.
  • UPDATE: added some hints from the comments.

I hope you'll find those tricks useful!

Replies are listed 'Best First'.
Re: .vimrc for perl programmers
by rnahi (Curate) on Mar 30, 2006 at 14:55 UTC
Re: .vimrc for perl programmers
by jasonk (Parson) on Mar 30, 2006 at 14:19 UTC

    A few more useful tips for using vim to write perl...

    " my perl includes pod let perl_include_pod = 1 " syntax color complex things like @{${"foo"}} let perl_extended_vars = 1

    We're not surrounded, we're in a target-rich environment!
Re: .vimrc for perl programmers
by philcrow (Priest) on Mar 30, 2006 at 14:25 UTC
    Nice suggestions. Have you also tried some of these:

    Folding:

    let perl_fold=1 let perl_fold_blocks=1
    Highlight POD correctly:
    let perl_include_pod = 1
    Insert Data::Dumper dumping statement (note that ^[ must be entered as a real escape, use ctrl-V):
    imap <F3> use Data::Dumper; warn Dumper( );^[hhi
    And one I got from this site, it comments out a block (again ^M is a real return):
    map <F8> :'a,.s/^/#/gi^M:nohl^M
    To use this last one, make an 'a' mark (ma) at the top of the block. Move to the bottom of the block and hit F8.

    Phil

      imap <F3>  use Data::Dumper; warn Dumper(  );^[hhi
      after several years of using Dumper() like this i wrote a much more useful macro (see my other post).
      forgetting Dumper() statements in code and finding the right ones to comment out can be really annoying. by using the Dump() method and variable names (Data::Dumper->Dump([\$test], ['test'])) you can debug much more sophisticated.
Re: .vimrc for perl programmers
by tinita (Parson) on Mar 30, 2006 at 14:24 UTC
    • :imap dumper <ESC>^iwarn Data::Dumper->Dump([\<ESC>llyw$a], ['<ESC>pa']);<ESC>
      lets you type '@myarraydumper' and you'll get 'warn Data::Dumper->Dump([\@myarray], ['myarray']);
    • map ß O#!/usr/local/bin/perl<CR><ESC>iuse strict;<CR><ESC>iuse warnings;<CR>
    • (un)comment: (update: this also works in visual mode. just select the block and type §1)
      map §1 :s/^/# /<CR> map §2 :s/^# //<CR>

      Youll get more accurate results on self referential structures by using

      warn Data::Dumper->Dump(sub{\@_}->(\@myarray), ['myarray'])

      it doesnt make that much difference when the example is an array, but when its a scalar it does make a lot of difference.

      Alternatively install Data::Dump::Streamer and get prettier, easier to read and more accurate dumps outright.

      Yes, this is a shameless plug. :-)

      ---
      $world=~s/war/peace/g

        can you provide an example where this (undocumented?) syntax makes a difference?

      For commenting and uncommenting code (in perl and many other languages) have a look at the BlockComment plugin.

Re: .vimrc for perl programmers
by vagnerr (Prior) on Mar 30, 2006 at 15:16 UTC
    I have a couple

    Using folding:

    When you hit F2 inside a code block it folds on that block, working on your {}'s
    set foldmethod=marker nmap <F2> 0v/{<CR>%zf

    Code Skeletons:

    When you start a new perl file have vim automaticaly give you #!/usr/local/perl -w and use strict; :-)
    autocmd BufNewFile *.pm 0r ~/.vim/skeleton.pm autocmd BufNewFile *.pl 0r ~/.vim/skeleton.pl


    _____________________
    Remember that amateurs built Noah's Ark. Professionals built the Titanic.
Re: .vimrc for perl programmers
by jhourcle (Prior) on Mar 30, 2006 at 15:02 UTC
Re: .vimrc for perl programmers
by dragonchild (Archbishop) on Mar 30, 2006 at 16:20 UTC
    Something to note - Mac users, particularly powerbook users, won't be able to use all the F-keys. I personally use comma-commands. So, for example, I use:
    nmap ,c :!perl -wc %^M nmap ,t :!prove -wlv t/*.t^M nmap ,ac :'a,.s/^/#/gi^M:nohl^M nmap ,auc :'a,.s/^#//gi^M:nohl^M
    and so on. The cool thing is that you can have the comma-command use as many characters as possible and reuse commands. So, I have ",s" do one thing and ",sf" do another. If you don't hit the 'f' in a second, vim will execute ",s".

    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?

      Instead of just having those mappings for !perl and !prove, there are actual compiler plugins for both.

      The main benefit of this is that vim will automatically parse any warnings and errors and jump to the correct location in the file. You can then jump to the next or previous error/warning with :cn and :cp or just list all the errors with :cl.

      Thanks for sharing those mappings :-) Maybe this is only applicable to Macs other than PBs, but I am able to map my F-keys. I had to type ^V and then the F-key to get it to map, but it works great. Part of my .vimrc now looks like this:
      map ^[OQ :w!^M:! perl %^M
      which just saves and runs the current file with perl. I'm using a MacMini with a USB keyboard, so I know it's probably not exactly the same. Have you tried pressing ^V before the F-key to map something, or am I just really fortunate?
      For mac users with this problem, have a look at Palua, it allows you to disable the F keys selectively based on the app ... handy for mac terminals
Re: .vimrc for perl programmers
by cees (Curate) on Mar 30, 2006 at 21:50 UTC

    I can't live without perltidy:

    " Tidy selected lines (or entire file) with _t: nnoremap <silent> _t :%!perltidy -q<Enter> vnoremap <silent> _t :!perltidy -q<Enter>

    That lets you highlight some text and hit _t to run it through perltidy and pretty up your code. I often use it in conbination with some of the highlight commands:

    • tidy current block: shift-V%_t
    • tidy next 10 lines: shift-V10j_t
    • whole file: _t
Re: .vimrc for perl programmers
by Codon (Friar) on Mar 31, 2006 at 08:40 UTC
    These are all great. Because of all of your autocmd lines, I'd suggest creating a function to be called:

    Now, I have some things to add that I really like. I like cindent because I can control the indentation style with some rules. I can also add to or remove from the list of indentation keywords:

    Then sometimes I want <Tab> to indent (insert a tab), sometimes I want it to do word autocompletion (like bash). So, I stole^H^H^H^H^Hborrowed this from a former coworker:

    Then a current coworker found/modified/developed (not totally sure which) this nifty status bar which tells you what function (sub) you are in:

    These are, of course, all part of my Perl() function. I have others for toggling list, paste, number, and wrap. And since I use split windows I map Ctrl+[arrow keys] to move between panes. This one is tricky because it really depends on terminal settings; I'm still working on some bugs with it.

    Ivan Heffner
    Sr. Software Engineer, DAS Lead
    WhitePages.com, Inc.
Re: .vimrc for perl programmers
by planetscape (Chancellor) on Mar 31, 2006 at 08:39 UTC
Re: .vimrc for perl programmers
by cees (Curate) on Mar 30, 2006 at 22:30 UTC

    If you want to turn on 'paste' mode while already in 'insert' mode you need a couple of extra mappings. Here is what I have (note that I have mapped F7 and F8 instead of just F11 which you were using):

    :map <F7> :set paste<CR> :map <F8> :set nopaste<CR> :imap <F7> <C-O>:set paste<CR> :imap <F8> <nop> :set pastetoggle=<F8>

    Now you can hit F8 at any time to switch to paste mode.

Re: .vimrc for perl programmers
by idle (Friar) on Mar 31, 2006 at 13:45 UTC
    Nice node nferraz, special thanks for "paste mode", I'v looked for that. Heres my 2c.:
    " run srcipt from Vim pressing F5 map <silent> <F5> :!perl ./%<CR>
    Can't remember where did I get it, I guess its from article at http://mamchenkov.net but its down for now(I hope temporarily). Updated
    It is up now, and I'd like recommend it to everyone, cause its nice and useful article as jhourcle has mention above, with good explanation of every option and even illustrated.
Re: .vimrc for perl programmers
by bowei_99 (Friar) on Apr 02, 2006 at 03:23 UTC
    A .vimrc is also available (along with other sample code) for TheDamian's Perl Best Practices here.

    -- Burvil

Re: .vimrc for perl programmers
by Ovid (Cardinal) on Dec 19, 2007 at 15:09 UTC
Deobfuscate code from vim
by nferraz (Monk) on Aug 28, 2008 at 09:53 UTC
    Here's a small trick to deobfuscate code directly from vim, using B::Deparse. All you have to do is to put this in your vimrc:
    " Deparse obfuscated code nnoremap <silent> _d :.!perl -MO=Deparse 2>/dev/null<cr> vnoremap <silent> _d :!perl -MO=Deparse 2>/dev/null<cr>
    Now, whenever you want to deparse a portion of the code, just press _d. For example, this line:
    --$|&&s|\n|-|;
    Magically becomes:
    s/\n/-/ if --$|;
    I find this particularly useful when I have to work with code that abuses Perl's TIMTOWTDIness:
    $foo and $bar or $baz = 1;
    (Now imagine a three-lines long statement where the attribution comes at the end.) Using B::Deparse, the code becomes more legible:
    $baz = 1 unless $foo and $bar;
    Unfortunatelly, B::Deparse has it own limitations; but I think this technique can be really useful in some situations.
Re: .vimrc for perl programmers
by Codon (Friar) on Dec 19, 2007 at 13:54 UTC
    I know that this is an old node. And that I have already commented on it. However, I wanted to add some updates.

    I had a regex mapped to comment out lines or blocks of code and another to uncomment them. I always hated that this killed my "previous search expression" so that I could not go through a file looking for a pattern, comment out the line, and go to the next occurrence without re-issuing the search command. I always thought "There must be a better way. After OSCON 2007, I found that better way:

    I also got tired of the fancy status line function not working inside closures because sub was indented. So, I did some poking at the code (that a coworker had put together) and made some minor fixes:

    Share and enjoy.

    Ivan Heffner
    Sr. Software Engineer
    WhitePages.com, Inc.

      Possibly overkill for your needs, but I have to say that since I've found the NERDCommenter plugin I've not bothered with anything else for commenting. Does comment / uncomment / toggle comment / add end-of-line comment etc, and does it for lots of different filetypes as well. Worth a look if you have time/inclination.

Re: .vimrc for perl programmers
by shmem (Chancellor) on Nov 02, 2006 at 12:44 UTC
    For the sake of completeness, let's not forget the imho highly useful .exrc from Tom Christiansen, which works fine with legacy vi's and vim.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: .vimrc for perl programmers
by diogoleal (Initiate) on Apr 24, 2011 at 17:11 UTC
    I added some things of his in my vimrc. I liked the part of the indentation using the mode V. Diogo Leal
Re: .vimrc for perl programmers
by vinayendra (Novice) on Oct 05, 2017 at 23:04 UTC
    thanks , this got me started on my .vimrc for perl .

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://540167]
Approved by Arunbear
Front-paged by grinder
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-03-19 09:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found