vim tips for php programmers

This post assumes you’re a php developer and you’re at least vaguely familiar with the VIM text-editor. For those who aren’t here’s a quick run-down:

VIM is a powerful command-line text editor usually a default package in the majority of *nix distros (that includes Mac’s OS X). I believe there are ports available for other OSes, even winblows.

Firstly, vim is a man’s editor. Whiners and GUI lovers can stop reading now. Although, VIM offer GUI ports such as MacVim. Men with thick beards, please stay tuned.

The lightweight text-editor VS bloated IDE debate

It’s a matter of preference really. Some like to use IDEs such as Zend Studio for Eclipse, Eclipse PDT, phpeclipse, Komodo ActiveState, Dreamweaver (*oh dear*) etc. And some prefer lightweight editors such as Coda, Textmate, Notepad++, Textpad, GNU Nano, Emacs, Vi, VIM etc.

I use both Eclipse PDT (just installed version 2.0) and VIM 7.x. Lightweight editors and IDEs are powerful in their own right. I’m not going to argue that you should use one over the other. Use whatever works for you. This is not an evangelism post.

Some say the following about VIM

“vim is for people who like pain – I’ll know what to order at your bachelor’s party” – @donaldza

“#vim is great for scripts, configs etc but let’s be honest, this is the 21st century ;) I still use it for merging/diff” – @donaldza

Okay, maybe just @donaldza has an issue :-) the rest of us continuing reading

What VIM offers programmers (sysadmins too) in general

  • powerful linguistic interface (ie. command-driven so your fingers never need to leave the keyboard)
  • syntax highlighting
  • so lightweight you can edit files over SSH connections on a distant remote server
  • available on just about any *nix
  • blah blah yada yada

Straight into the good stuff: Tips for PHP programmers

Assuming you’re already familiar with the basic editing features of such as copying, pasting, yanking, deleting and so forth. If not, try “vimtutor” from your *nix command-line.

This is a copy-paste of my .vimrc file. You can find yours in $HOME/.vimrc. If VIM is already open you can use the “:edit $MYVIMRC” command. I wouldn’t mess with the system-wide default (usually /etc/vimrc/vimrc). Other vim users on your server might not appreciate your preferences

Syntax highlighting. You gotta switch it on like this:


syntax on

Usually triggered by the file extensions you’re using. This list of extensions is configurable so you can highlight your .inc’s too. That’s an old habit you should toss btw. You might wanna change your terminal colour theme. White background works best with syntax highlighting. Then again you could also change VIMs colour theme.

Search highlighting.

set hlsearch

Includes simple and regex searches within VIM

Tabs as spaces.

Often you want X spaces instead of a real tab

set tabstop=4

Starting to get cool…

set autoindent

Autoindent remembers the indentation of the previous line and so your next line starts directly beneath. Python okes should appreciate this one

In the middle of a series of keystrokes?

set showcmd

Often vim has double-barreled commands that require a sequence of more than one keystroke. Showcmd displays on the footer of your screen informing you which command you have initiated

Search and show matches as you type

set incsearch

In the middle of issuing your full search phrase incsearch will highlight matched words. Useful when constructing a long-ish regex

PHP-specific highlighting

The general syntax highlighting offers some php syntax but not everything

" highlights interpolated variables in sql strings and does sql-syntax highlighting. yay
autocmd FileType php let php_sql_query=1
" does exactly that. highlights html inside of php strings
autocmd FileType php let php_htmlInStrings=1
" discourages use oh short tags. c'mon its deprecated remember
autocmd FileType php let php_noShortTags=1
" automagically folds functions & methods. this is getting IDE-like isn't it?
autocmd FileType php let php_folding=1

Note: This is just the beginning of code-folding. A number keystroke combinations exist to expand, contract foldings within the opened file

Syntax checking within VIM (sort of)

" set "make" command when editing php files
set makeprg=php\ -l\ %
set errorformat=%m\ in\ %f\ on\ line\ %l

To use, simply issue “:make %” command inside of VIM to check the syntax of your php against the interpreter. Syntax highlighting can only do so much

Highlighting matching brackets/parentheses

" set auto-highlighting of matching brackets for php only
autocmd FileType php DoMatchParen
autocmd FileType php hi MatchParen ctermbg=blue guibg=lightblue

This automatically highlights brackets and parentheses as the cursor passes over them. Colours configurable

Auto-completion of functions and constants

" autocomplete funcs and identifiers for languages
autocmd FileType python set omnifunc=pythoncomplete#Complete
autocmd FileType javascript set omnifunc=javascriptcomplete#CompleteJS
autocmd FileType html set omnifunc=htmlcomplete#CompleteTags
autocmd FileType css set omnifunc=csscomplete#CompleteCSS
autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags
autocmd FileType php set omnifunc=phpcomplete#CompletePHP
autocmd FileType c set omnifunc=ccomplete#Complete

The above is really auto-completion for more than just PHP as you can tell. Auto-complete is triggered in the middle of typing the identifier

” Basically, while in insert mode, you can type <C-x> <C-o> to have vim attempt to autocomplete the current keyword. If more than one possibility exists, it shows a dropdown, and you can use your arrow keys to highlight the keyword that you wish to use.

But it gets better! Not only does it do this kind of autocompletion, but it also opens a small ‘scratch preview’ pane showing the function/method signature — i.e., the expected arguments and return value! ” – Matthew Weier O’ Phinney

Auto change to to editing file’s cwd


" auto switch to folder where editing file


autocmd BufEnter * cd %:p:h

Often one would open a file for editing in VIM from a different working directory eg. vim ~/somewhere_else/myfile.php. This command automagically changes vim’s current working directory to that of the file you’ve opened making it easy to open other files which are close by on the filesystem

Split-panes

Often you want to edit more than one file inside of VIM without having to open and close between them. Using “:split otherfile.php” and “:vsplit otherfile2.php” you can create horizontal and vertical split-panes respectively. You can of course split the same file across two-panes simultaneously using “:split %”

You can split splitted panes to infinity but…

Tabbed-panes are better

With the “:tabnew filename.php” or just “:tabnew” commands you have tabbed panes. voila! “:tabclose”, “:tabprev”, “:tabnext” does exactly what one would expect

You can also use keystrokes such as “gt” to jump between tabs quickly. Of course there are dozens more in-editor commands and keystrokes associated with the above tips/preferences. This post was merely meant to open your eyes to a whole new world of powerful lightweight text-editing. You can find a whole lot more in the resource links that follow and vim help! (“:help”)

More cool vim stuff


Published in: on February 5, 2009 at 6:40 am  Comments (22)  
Tags: ,

The URI to TrackBack this entry is: http://phpslacker.com/2009/02/05/vim-tips-for-php-programmers/trackback/

RSS feed for comments on this post.

22 Comments Leave a comment

  1. Nice write up. Good to see I’m not the only one still using (g)vim

    To add to this:
    set smartindent – indents on function bodies, loops etc. rather than to same level as previous line

    • Hey Sven, you’re welcome. Thanks for the smartindent tip

      And hey anyone else please drop me your VIM tips. I know there’s thousands more that I haven’t listed on this post

  2. Great post. Thanks. Just in the past few days I’ve been wishing for code completion/function signatures in VIM. Simply awesome. I really should put my .vimrc online. I’ve been using GVIM on Windows for a long time. Since it’s availible for both platforms makes it easy to switch between Windows & Linux. I have the Windows cut/copy/paste/undo shortcuts mapped into my Linux .vimrc. Now if I could only get them to work in the terminal window.

  3. vim rules!

    Everyone at work thinks I’m an old geezer that’s not aware that a gui exists for all things now. But I love the shell, vim, and screen. Anyway, take a look at this http://notvincenz.blogspot.com/2007/03/vim-sessions.html, bad to the bone. Also check this out http://www.cipherdyne.org/blog/2008/02/interfacing-vim-with-gnupg-encrypted-files.html.

    These are good to have:
    set backup ” make a backup file
    set backupdir=$HOME/.vim/backup ” where to put backup file
    set directory=$HOME/.vim/temp ” directory is the directory for temp files

    Also if you want run time debugging with code breaks and all check out my list here http://blog.rjmolesa.com/archives/2008/02/06/php-vim-ubuntu-xdebug/ especially this one http://tech.blog.box.net/2007/06/20/how-to-debug-php-with-vim-and-xdebug-on-linux/

  4. Can’t let a post on VIM and PHP go by without mentioning Andrei’s VIM for (PHP) Developers talks

    http://gravitonic.com/talks

    • Brilliant. Thanks for the link. Looks like good stuff there. One of the links in my post does in fact point to one of Andrei’s VIM for PHP Programmer’s presentations :-)

  5. I should add that when you’ve got auto indent or smartindent on, pasting code can be messy as it just keep indenting each line. You can prevent this with
    set paste
    and then go back to normal with
    set nopaste

    I have these mapped to keys for convenience

  6. [...] Read more: vim tips for php programmers « phpslacker [...]

  7. what a poor piece of crippled software that you need to read tutorials and pecial blog tips to get even the most simple things done. At least what I do with an editor most of the time is writing, not using it “features”. If I need some help from the software, it should be there immediately, visible, understandable and without having to “learn how to do this tricks” disracting me from what I am doing.
    vim is a usability catastrophe – no man can do even the most simple things without having to study it. That is a real antisocial software design as it burns life time of many, many people around the world and that time is needed to solve the problems we have. Of course you might use whatever you like but it is important to say loud anmd clear that we NEED easy and INUITIVE software to build a better world. Software needs to get better, not manhood-primitivism-I-Know-you-dont-know-tricky-cool-admire-me-like.

    • You obviously don’t have any clue how powerful and intuitive vim is once you know the commands. I have used all the existing text editors existence in the world and I have settled with vim 2 years ago, now I can use any other editor anymore.

      • Sorry type for the last sentence, it should read “now I CAN NOT use any other editor anymore”.

  8. Hi, I’m really interested in the syntax checking.
    When I do the makeprg things and type “make %” it only says whether there is an error or not. Not which error or on which line.
    Is it possible to do this? Because afaik you cannot do this with “php -l” anyway.

    Thanks,
    Dieter

    • Hi Dieter

      Sorry for the late reply. I’ve been away from the intertubes (including my mobile) for a few days now but i’m back!

      I made a dummy php file with a syntax error and got this message:


      :!php -l test.php 2>&1| tee /var/folders/Qf/QfkahnyQEbGjd0Xeco3zf++++TI/-Tmp-/v971323/2
      PHP Parse error: syntax error, unexpected $end in test.php on line 4

      Parse error: syntax error, unexpected $end in test.php on line 4
      Errors parsing test.php
      (1 of 4): PHP Parse error: syntax error, unexpected $end

      So it certainly works. You may have to check your php.ini. Perhaps your error_reporting and display_errors directives are switched off.

      For example:


      qbook:~ quinton$ php -l -d error_reporting=E_NONE -d display_errors=0 /tmp/test.php
      Errors parsing /tmp/test.php

      See. No explanation of the error message when error_reporting and display_errors switched off

  9. On syntax highlighting you say:
    quote
    White background works best with syntax highlighting.
    /quote
    This may be true for the default color scheme, which looks not too impressive at all IMHO, regardless of light or dark background. Generally I find darker backgrounds in Vim much nicer to read, in the GUI version (which I use most of the time) as well as on the terminal. (Well designed color schemes provided). Thankfully recent Vim’s come with a good set of alternative color schemes included. My favorites for standard black or dark terminals are “desert” and “murphy”. On the GUI I use mostly “desert” and “navajo-night” (not included with the standard distributions).

    To change the color scheme:
    :colo {name}

    To find which color schemes are available:
    Look in $HOME/vimfiles or $VIMRUNTIME/vimfiles or $VIM/vimfiles (or similar places) for “colors”. There is very probably a command for this too, I don’t know it for now.
    On the GUI you can use Edit/Color Scheme to get a convenient menu.

    For help on the topic (as usual) simply type
    :help colorscheme

    For lots of additional colorschemes you may see
    http://www.vim.org
    http://www.vim.org/scripts/index.php
    http://www.vim.org/search.php

    BTW:
    I’m using vim for over ten years now, not as my one-and-only editing solution, but as a substantial part of my editing tools kit. For what I can say, your compilation of tips is one of the most lean while useful / essential I have seen. And I found at least one thing (Autochange to editing file’s cwd) that was really out of my attention so far. Thank you!

    • Hi Stefan

      Thanks for that. You’re quite right. “Desert” is a fantastic color scheme for the “darker” terminal backgrounds. Most prefer dark terminals anyhoo

      Personally, I prefer a black terminal and I wish I knew about Desert sooner

      Cheers,
      phpslacker

  10. Awesome! It’s amazing how sometimes one can forget options who are right in front of him. I have seen both behaviors on various OS’s/installations so I knew it was possible. I had been recompiling with different configure flags, searching on the net (with no results, oddly enough) , but didn’t realize it was this simple.

    Thanks a lot! Enabling display_errors is all that was needed.

  11. [...] original here: vim tips for php programmers " phpslacker Share and [...]

  12. That C-X C-O thingie is very nice… Didn’t have it in my head just yet , hope it will stick. :P

    As to the cwd thing , I got this one from somewhere recently:
    ” Set current directory for file being edited :
    au! BufEnter * exe “silent! lcd %:p:h”

    Which uses lcd instead of cd , which only changes the cwd for the current file that is being edited.

    I also use windows quite a lot:
    C-w s – create a horizontal split window
    C-w v – create a vertical split window
    C-w c – close window
    C-6 – Switch between last used tabs (same as C-^)
    C-w h,j,k,l – You should know this. ;) (moving around within windows)

    And I recently discovered
    :args
    which is nice ’cause it lets me open multiple files in multiple subdirectories all at once. :)

    And some auto-complete features :
    set wildmenu ” turn on command line completion wild style
    ” have command-line completion (for filenames, help topics, option names)
    ” first list the available options and complete the longest common part, then
    ” have further s cycle through the possibilities:
    set wildmode=list:longest,full ” list:longest > turn on wild mode huge list

    ghehe. Maybe I will as well do a blog-post about my vim-stuff some day… :)

    Anyway, thanks!

  13. hey i have a question.
    if you can help me out or lead me to where can i get what i’m looking for.
    i want to know if any one of you had do this.
    (autocompletion help , cuz I’m not a senior php programer and i dislike dreamweaver a lot for taking my hand out of the keyboard).
    http://fisadev.blogspot.com/feeds/posts/default

    it’s the completion help fisa get with VI of python, if you are so kind just to look the pic. (I know it’s no english) and obviously for php???.
    i right now use emacs to do that job due to the don’t-know how to get it in Vim.

    if anyone can help me out send an mail.
    thx anyways =D.
    Marcos
    programerrr novice.


Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>