Wednesday, June 20th, 2007

How to Debug PHP with Vim and XDebug on Linux

By

Here is the scenario: You have multiple developers logged into a Linux server which is running Apache and PHP using Vim to write PHP code. They’re using error_log and echo statements to debug their code. It takes forever, it’s tedious and can result in bugs from forgotten debug statements. You stare enviously at .NET programmers with fancy debuggers (while you snicker knowing that you edit 10x faster with Vim anyways). But still, you know there has to be a better way. There is. Here’s how it works. You’re coding away in vim. You hit F5; Vim waits for a connection from the PHP server. You refresh the PHP page you’re working on. It attempts to contact Vim — connection successful. You are launched into a debugging session right inside Vim. You can step into, over, and out of statements, eval statements, get all variables in context, get and set properties, remove and set breakpoints, all on the fly. Finally, some real programming tools.

The environment: Vim

First, we need to make sure vim is compiled correctly. Type :version in your Vim and check the features section. If you have +python and +signs, you’re good to go. Skip ahead to the next section. Otherwise, you need to compile from source. On Linux, download and untar the source code, and open up src/feature.h. You need to comment out the conditional statements around the +signs feature. In Vim 7.1, it looks like this:

/* * +signs Allow signs to be displayed to the left of text lines. * Adds the ":sign" command. */ #if defined(FEAT_BIG) || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG) # define FEAT_SIGNS # if ((defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) && defined(HAVE_X11_XPM_H)) || defined(FEAT_GUI_GTK) || (defined(WIN32) && defined(FEAT_GUI)) # define FEAT_SIGN_ICONS # endif #endif 

You need to comment out both if statements and their respective endif’s, so it looks like this:

/* * +signs Allow signs to be displayed to the left of text lines. * Adds the ":sign" command. */ /*#if defined(FEAT_BIG) || defined(FEAT_SUN_WORKSHOP) || defined(FEAT_NETBEANS_INTG)*/ # define FEAT_SIGNS /*# if ((defined(FEAT_GUI_MOTIF) || defined(FEAT_GUI_ATHENA)) && defined(HAVE_X11_XPM_H)) || defined(FEAT_GUI_GTK) || (defined(WIN32) && defined(FEAT_GUI))*/ # define FEAT_SIGN_ICONS /*# endif #endif*/ 

then cd back to the top source directory and run:

./configure --enable-pythoninterp 

If on a 64-bit system or a system with a strange python installation, you may have to add --with-python-config-dir=/usr/lib64/python2.3/config to the configure string. If the configure script can’t find the config directory it will say so in the script output, but the configure won’t explicitly fail — so you have to be sure that all the python stuff is OK. After configuration, do

make && make install 

to install your newly python’d vim.

The client: Debugger.vim (and Debugger.py)

Now that vim is ready, download the DBGp client script. Extract the two files (debugger.vim and debugger.py) to your vim plugin directory or your .vim home directory. In Vim 7.1 compiled on Linux, the default load-for-everyone plugin location is /usr/local/share/vim/vim71/plugin/, so you would put both files in that directory. Try to run vim — if you get no errors, everything should be good. If you get an error, double check :version to make sure +python and +signs are there. If they are, post a comment here with the vi error you get. If they aren’t, the vim compilation/installation didn’t work — go back and try it again. Now your debugging client is ready. Now let’s setup the server.

The server (engine): XDebug

Download XDebug. Download the source, compile the .so and add the following lines to your php.ini:

[Zend] zend_extension = /full/path/to/xdebug.so xdebug.remote_enable = 1 xdebug.remote_port = 9000 xdebug.remote_host = localhost 

Open a file in your browser which outputs <?php phpinfo(); ?> to make sure xdebug is loaded.

Now, with your site being example.com, go to http://example.com/index.php?XDEBUG_SESSION_START=1. This will set a cookie in your browser which expires in 1 hour which tells the PHP XDebug module to try to make a connection every time a page loads to a debugging client which is listening on port 9000. The cool thing is that if it can’t make a connection, it just keeps loading the page, so there’s no issue just leaving the cookie on. Now go back to vim and press F5. You should see a message like “waiting for a new connection on port 9000 for 5 seconds…” at the bottom of the screen. You have five seconds to now refresh the PHP page. This will create a connection between the debugger and client. Now you’re debugging. Follow the instructions in the Help window to step into, over and out of code. Press F5 to run the code until a breakpoint (which you can set using :Bp).

But what if I have multiple developers on the same machine?

No problem. Simply set g:debuggerPort in each developer’s .vimrc to get the client listening on a different port. So if you wanted one developer to connect on 9001 instead of the standard 9000, you would add this line to their .vimrc:

let g:debuggerPort = 9001 

Getting the server to connect on a different port is a little trickier. You need to set a custom php.ini value (xdebug.remote_port) for each user. It works best if you’re using VirtualHost’s in Apache. Just add the following line to the VirtualHost section of your httpd.conf:

php_value xdebug.remote_port 9001 

Now restart Apache and if you use that VirtualHost and that vi user, then they should connect successfully.

That’s about it

Please post any questions or suggestions you may have. I hope this helps a few of you out there who want debugging tools but don’t want to give up Vim editing. Also be sure to post any alternate methods, or any patches or improvements to the remote PHP debugger vim script, and I’ll be sure to incorporate them. [Note: This is the first in a series of posts we'll be doing along the lines of tutorials, tools we've developed, tech commentary, and so on. Please feel free to subscribe, as well as leave any comments, thoughts or suggestions below so we can be sure to improve with each article! Thanks!]

By

See all of Sam's articles.

  • Trenton Weir

    Thanks, this looks very interesting, but the link to ‘DBGp client script’ doesn’t work.

  • http://www.box.net/ Sam Ghods

    Thanks! This has been fixed.

  • Pingback: How to Debug PHP with Vim and XDebug on Linux at BetaSoft Developers Log

  • Pingback: » ???vim?xdebug???php » WEB??????

  • Erik Schwartz

    This is a great tutorial — thank you very much for the effort. I run Feisty Fawn with backported php 4.3.10-10ubuntu3 and everything worked great.

    The one question I have is about debugging forms. Does anyone know of a way to begin debugging a page once a form has been submitted with xdebug+vim? I currently use the Zend Client and this feature has proven extremely useful. I’m really hoping to move to an open source environment and I’ve not been able to configure Eclipse PDT, Protoeditor, or PHPEclipse to work on my machine. This seems like a great solution but I hope to discover a native form debugging capability.

    Cheers and thanks again,
    Erik

  • Erik Schwartz

    Scratch that last comment — my apologies. It’s easy enough to debug a form by submitting it the 5 second window after pressing f5 in vim.

  • http://www.spoon.com.au Ben Giles

    thank you for keeping the xdebug vim script alive!

  • Brownie

    Hey Just letting anyone know Xdebug can work as both as an extension and a zend_extension (eg. the ubuntu pecl install initially suggests you add extension=xdebug.so which works fine for profiling)..

    The debugger will only work if its loaded as a zend_extension (as it is of course explained in the blog) . but I still managed to get caught!. The debugger will initially look like it was working but fail when it tries to set the breakpoint.

    hope this helps someone else. Many thanks for the article

  • http://www.exfer.net david_kw

    Thanks for the tutorial and the script/configuration files. I was able to get it up and running in Windows. In the process, I made some changes and feature upgrades to the script. Things like the ability to do a get_property on a selected area and changing the EVAL_RESULT to the actual name of the property when available (there was code that was trying to do it but didn’t work for me).

    I also changed the function keys to be more like FireBug and a few other user specific changes, but I could work those out if you are interested in integrating my other changes. If so, just send me an email.

  • bitlogic

    Hi,

    Nice article.
    I has just installed XDebug and the plugins without problem.
    But when try to debug I’m getting this error:
    (, , )
    File “/home/llsousa/.vim/plugin/debugger.py”, line 1078, in debugger_run
    try:
    File “/home/llsousa/.vim/plugin/debugger.py”, line 928, in run
    self.clear()
    File “/home/llsousa/.vim/plugin/debugger.py”, line 560, in accept
    serv.close()

    What can be wrong?

  • http://www.itopen.it alessandro

    Hi,

    thanks for this script!

    I have an error after hitting F5:

    waiting for a new connection on port 9000 for 5 seconds…
    Connection closed, stop debugging (, AttributeE
    rror(“DbgProtocol instance has no attribute ‘stop’”,), )

    What can I do?

    Xdebug is 2.0.0RC4 on ubuntu linux

  • Wally Brock

    Works with Mac OS X as Well!

    Even though the tutorial says “Linux” this also works on Mac OS X as well.

    Thank you for an excellent tool!

  • http://www.koch.ro Thomas Koch

    Definitely live changing!

    But I’ve some issues with Breakpoints. They doesn’t seem to work if the Breakpoint is placed in some deeper file in the stack. Wouldn’t you like to place this project somewhere in a development environment with public svn, bugtracker and mailinglist?

  • http://2bits.com Khalid — 2bits
  • Pingback: PHPDeveloper.org

  • Pingback: developercast.com » Box.net: How to Debug PHP with Vim and XDebug on Linux

  • http://www.littlehart.net/atthekeyboard Chris Hartjes

    Great post as I like to use vim from time to time when Komodo pisses me off. I’m running this on OS-X and had no problems getting it run, but I couldn’t see in the debugging window what the values of the variables at that point would be like I would see in Komodo. Any tips on that?

  • Pingback: What’s In Chris’ Brain: November 2007 Edition — @TheKeyboard

  • http://www.box.net/ Sam Ghods

    Chris,

    Do you mean just having a watch window which displays pretty much any variable currently in the scope? That would be pretty cool… the client script doesn’t implement it currently but it shouldn’t be too hard. I think you would just have to run the get_defined_variables() PHP function after each time the debugger pauses and put the results stuff in one of the windows. I don’t have the time or Python experience to rig that up at the moment but if anyone wants to write that in and send me a diff, I’d be more than happy to incorporate it in the script and publish it on the vi plugin page.

  • http://www.travisswicegood.com Travis Swicegood

    Running MacVim (vim 7) I had to use Andrei’s modified debugger.py file to get it working. It’s available at: http://www.gravitonic.com/blog/archives/000357.html along with some excellent slides for anyone who’s new to vim.

  • Pingback: Donncha’s Friday Links at Holy Shmoly!

  • http://www.littlehart.net/atthekeyboard Chris Hartjes

    Sam,

    Yes, that’s exactly what I’m talking about. In Komodo when you use their built-in support for XDebug they provide you with a small window that shows you all the variables currently in scope and their values. I find that very useful as I’m trying to wean myself off of the old print_r and echo style of debugging.

  • http://pedantic.co.za Gavin

    Hey. Just wanted to point out that you can install xdebug with pecl install xdebug
    On Ubuntu you might/will need to install build-essential and possibly other packages.

    Gav

  • http://pedantic.co.za Gavin

    The webserver and the machine I’m typing on are two difference machines. Is that a problem?

  • http://www.box.net/ Sam Ghods

    Gavin,

    Not a problem, as long as the webserver has access to your debug machine. Simply change xdebug.remote_host = , and change xdebug.remote_port = . The only problem might be that you might need to set up your router or firewall to allow and route incoming requests to port 9000 (or whichever port you choose) to your local machine. Good luck!

  • http://pedantic.co.za Gavin

    Aaaah yes. Thanks, that was it. Next question :)

    I set a breakpoint in a script inside my framework; when I debug it stops at line 1 of the first script. Pressing lands me back at line 1 of script 1. Pressing again shows me “Connection closed, stop debugging etc”. Am I doing something wrong ?

    Also, I was thinking about the keys. I already have F1-F12 mapped. I tweaked debugger.vim to (only) use “d*” with * being something appropriate (although you already had some d mappings.) It might make the script less invasive.

    gav

  • http://pedantic.co.za Gavin

    Can I file bug reports here ?

    get_property_at_cursor doesn’t handle static properties of classes e.g.
    I want to see the value of

    App::$route

    but the watch window says

    property_get: $route

    .

  • http://pedantic.co.za Gavin

    re the keys: earlier. I “meant” to talk about the script using
    Leader d*, but my “html tags” were stripped:

    d*

    gav

  • pa

    Hello, maybe it is a vim 7.0 only error, but when I press F5 in vim I get :
    waiting for a new connection on port 9000 for 5 seconds…
    Connection closed, stop debugging (, , )

    When I press enter to see the result, I get :
    (, , )
    File “/usr/share/vim/vim70/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/usr/share/vim/vim70/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/usr/share/vim/vim70/plugin/debugger.py”, line 560, in accept
    self.stop()

    Where am I wrong ? I have +signs and +python in :version, I have the extension, I have the XDEBUG_SESSION cookie too…

  • dbu

    [this was a "bug" report, until i realized my setup was wrong. now its just a bunch of tips:]

    if you want the +signs and +python on ubuntu, just do ‘apt-get install vim-python’ if you don’t want to compile it yourself.

    instead of telling something of a timeout, my vim tells me “DbgProtocol instance has no attribute ‘stop’” if nothing connected to it for 5 seconds.

    if your phpinfo tells you “XDEBUG NOT LOADED AS ZEND EXTENSION” you did not include the .so as zend_extension (which is required, as mentioned above).
    xdebug.remote_enable must be set to 1 or on, it defaults to off.
    (i was confused because xdebug.remote_host defaults to localhost, xdebug.remote_port to 9000 if not set)

  • Pingback: ????? » Blog Archive » ?vim???php??????php????

  • N.

    Don’t forget to set

    xdebug.remote_handler = dbgp

    otherwise you will get a error.

  • http://www.letsgym.com Nasko

    Nice article, Sam! Thank you!
    I can confirm this setup works perfectly under Window XP w/ Python 2.4, Vim 7.0 (gVim), Xdebug 2.0.2. However, both debugger.vim and debugger.py files need to be modified slightly:
    - debugger.py:
    1) In DebugUI::init around line 440 modify the path to self.sessfile – by default it is set to ‘/tmp’ and obviously this will not work in WinXP
    2) Apply the modifications refferenced by Kevin Dahlhausen in the comments to Khalid’s post here: Modification #1 and Modification #2

    debugger.vim:
    Around line 124 modify (if necessary) the path to debugger.py. In my case I had to change ‘$HOME/.vim/plugin’ to ‘$HOME/vimfiles/plugin’, or Vim complained about not being able to locate debugger.py

    I have one question though: when I try to eval a variable or get the whole scope I’m not getting the values of multi-dimensional arrays. If I have $messages[0][key1], $messages[0][key2], etc. I only get this:

    /{{{1/ => eval: $messages
    $command = ‘eval’;
    EVAL_RESULT = (array) ; /{{{2/
    EVAL_RESULT = (array)
    /}}}2/
    /}}}1/

    I have to explicitly type the path to the index I’m interested in as in:
    eval: $messages[0]['Recipient']['Photo']

    The problem is more often than not I don’t know the exact structure of variables that I want to debug.

    Is there anything I may be missing? I’d be thankful for every hint that could help me out!

  • http://www.letsgym.com Nasko

    Regarding my previous comment: I noticed the instructions in the comments in debugger.vim. I increased the debuggerMaxDepth to 10 and was able to retrieve all values from the array. The only issue left is I’m not able to see the array keys. I get a result like this:

    EVAL_RESULT = (array) ; /{{{3/
    EVAL_RESULT = (array) ; /{{{4/
    EVAL_RESULT = (string) ’6′;
    EVAL_RESULT = (string) ’3′;
    EVAL_RESULT = (string) ’5′;
    EVAL_RESULT = (string) ’1′;
    EVAL_RESULT = (string) ’0′;
    /}}}4/
    EVAL_RESULT = (array) ; /{{{4/
    EVAL_RESULT = (string) ‘Inbox’;

    Is there any setting I could change in order to get array keys as well?

    Thank you!

  • http://www.sappyberry.com ruslanix

    Hi!
    I try this script for MS Windows.
    I have some problem to run this plugin.

    If interested here i describe some problem and solution:

    errors occurred because this script was written to linux.
    And on windows you should do some changes

    At vim startrup error: ‘Can’ find debugger.py’

    put debugger.py to $VIMRUNTIME/plugin directory

    After starting debuggin, error : ‘can’t open session file’

    go to line 442 at debugger.py and change self.sessfile to file suit for you.

    When press ‘Setp into, F2′, error: ‘wrong buffre name /….’

    you must change in all lines code from getAttribute(‘filename’)[7:] to getAttribute(‘filename’)[8:]

    By;)

  • Pingback: PHP, VIM, Ubuntu, XDEBUG From the blog archives of rjmolesa

  • Pingback: PHP::impact ([str blog [, str comments]]) » Blog Archive » Debug PHP applications with Vim and xDebug

  • Pingback: DaveDevelopment » Archive » 10 tools for Modern PHP Development

  • Pingback: ???@??? » ????php????

  • alexander

    thanks

  • Pingback: ?vim ?debug php (use xdebug) at JohnPuPu

  • http://www.ilkebenson.com Mjaque

    Great article and great plugin. Thanks

    I am getting an error when opening files with non-ascii characters in their paths. When opening (after F5 and refreshing browser) I get a E499 vim error (Empty file name).

    The problem is that vim tries to open a file with urlencoded name (‘my%20file’), which obviously does not exist.

    I’ve been able to replace %20 for ‘ ‘ (escaped white character).

    (Add file = file.replace(‘%20′,’ ‘) at handle_init method (line 794) in debugger.py)

    But (due to my lack of Python knowledge) I haven’t been able to replace other non-ascii characters (Spanish accented words áéíóú…). Same strategy (file = file.replace(‘%C3%A1′, ‘á’) produces a UnicodeDecodeError in Python.

    Does anybody have the same problem? Any idea how to proceed?

    Thanks

  • Joker

    You’d probably be better off just doing:
    CFLAGS=”-D FEAT_SIGNS” ./configure –enable-pythoninterp
    instead of messing with the source code to enable the FEAT_SIGNS macro.

  • Jack

    Thanks very much! it’s very useful

  • http://ws.wesconet.com David Damstra

    I am so close to getting this working. Hope you can help…

    Developing on WinXP with GVIM connected via sftpdrive to the remote Ubuntu box with the website on it.

    Set up php.ini for remote debugging on my local WinXP IP.

    I edit the file in vim, hit F5, refresh the page in firefox. It connects, but I get the following error in gVim:

    E185: Invalid buffer name: var/www/{siteName}}/htdocs/filename.php

    Seems to me that its trying to map the same directory structure on my locally mapped drive (via sftp) to the one on the webserver and they don’t match.

    Any ideas? Thanks for your help!

  • http://www.lifeofadishwasher.com Derek Schrock

    My setup
    Windows 2003 Server
    Apache 2.2
    PHP 5.2.5 Binary install from php.net
    XDebug 2.0.3 for PHP 5.2 binary from xdebug.org
    Cygwin’s Python 2.5.1
    Custom rolled VIM 7.1; compiled with Cygwin GCC

    This article is perfect for setting up XDebug my setup with the exception of having to hack a little bit of the debugger.py. Since my binary of XDebug is native to Windows any file string XDebug out puts is a Windows native path ( /C:/…. ) and not a UNIX/Cygwin path ( /cygdrive/c/… ). A simple file.replace( ‘/C:/’, ‘/cygdrive/c/’) in about three locations of the Python debugger file.

    I wonder who I could poke to try and get this to be an official feature? Maybe set in php.ini xdebug.env “cygwin” ? Thoughts?

    Finally, using F5 to run till a break point is hit does not want to work. I get the following message in the trace window:

    response xmlns:xdebug=http://xdebug.org/dbgp/xdebug xmlns=urn:debugger_protocol_v1 command=stack_get transaction_id=7
    error code=5 : Command not available (Is used for async commands. For instance if the engine is in state “run” than only “break” and “status” are available).
    message
    command is not available

    Has the protocol of GDBp stack_get been changed since the release of of this article? Any idea how I can get this fixed? Is there a point where I have to set the filename back to the Windows native path?

    PS: I can single set through the executing file just fine ( as well as context, and cursor context ).

  • http://www.programming-web.com/index.php?option=com_content&view=article&id=3:installation-of-apache-php-and-mysql&catid=4:php-basics&Itemid=10 PHP

    knowledge of Debugging information is very useful and necessary to save time and increase performance. And this article has helped me alot.Thanks.

  • http://megas.name MegaS

    Thanks for article!
    Right now using this techinque for debugging code

  • Ma’moon

    Thank you very much for this great article, it was really very useful and i do appreciate your time and effort to show it up.

    answering the previous comment, what you have to do exactly is:
    (1) mkdir -p ~/.vim/plugin “check if you have a .vim DIR in your home directory, if yes then you may omit the -p option from your mkdir command ==> mkdir ~/.vim/plugin” and make sure that you set the correct permissions over the created directory.
    (2) mv /path/to/debugger.py ~/.vim/plugin/
    (3) mv /path/to/debugger.vim ~/.vim/plugin/

    and there you go, the plugin should be activated by now.

  • http://www.lifeofadishwasher.com Derek Schrock

    Good news. I found out what my problem was with setting break points.
    From my previous posts I’m using a Windows build of XDebug in a Cygwin rolled VIM. My problem was that set_srcview from debugger.py used a native Windows fileuri not a Cygwin/UNIX type of path. This wasn’t that big of a deal; all I had to edit the file string in set_strview ( file = file.replace( ‘/C:/’, ‘/cygdrive/c/’ ) ).

    After that setting break points wouldn’t want to set because of the filename that pass was no to spec. At first the cygwin path was sent /cygdrv/c/….. A quick change in Breakpoint.add() to switch file back to a native Windows path I thought would fix the problem ( file = file.replace( ‘/cygdrive/c/’, ‘/C:/’ ) )
    Finally, after reading the DBGp spec the file name passed to breakpoint_set needs to have file:// or dbgp:

    Back to Breakpoint.add() ( file = file.replace( ‘/cygdrive/c/’, ‘file:///C:/’ )

    That fixed it!

  • http://www.pui.ch/phred/ Philipp Keller

    A solution of this eval thing is to type:

    ,e (for entering eval mode)
    print_r($this, true)

    which returns a string which then is printed in vi

  • http://www.mastermoz.com Paul

    Thanks so much. This made me feel great as it helped me get to the next level with vim. It’s so exciting to know I can use vim vs. big heavy IDEs for my PHP development. Your writing is very clean and clear and precise. Thanks again.

  • Pingback: Add debug support to Vim with xdebug.dll « PHP Hints

  • Pingback: pasunclou | Vim et Xdebug pour débugger votre code PHP

  • Pingback: An Ingres Blog › links for 2008-12-18

  • Pingback: blogs.planetingres.org » links for 2008-12-18

  • http://www.manuel-blechschmidt.de Manuel Blechschmidt

    I just want to thank you for this article.
    I love the debugging feature on the server. This saves a lot of time.

    /Manuel

  • Pingback: Depuracion PHP con Emacs, geben y Xdebug LIBERTAD DIGITAL

  • http://www.metal3d.org Metal3d

    Very useful and strangely easy to use. The interface is clearer than the Eclipse (PDT) and I am honestly impressed by the speed at which I understood how this plugin works.

    Great !

  • http://www.komentokehote.net Juha

    Thank you! Seems to work just fine, saves lot of time. Have to admit, that I thought that “this will never work, but let’s see what happens” :)

  • Pingback: gdb + vim, vim + macro

  • Pingback: Vim: 35 ressources pour apprendre à l’utiliser

  • Jared

    Just thought I’d mention, for centos 5/rhel 5 users out there:

    If you’ve enabled the epel repository, you can install xdebug with ‘yum install php-pecl-xdebug’, insert the debugger.py and debugger.vim scripts (at vim.org, linked in the above article) into your .vim/plugins directory, and put the xdebug settings (xdebug.remote_port and so on) into /etc/php.d/xdebug.ini, and this will work out of the box. :-)

  • http://www.13latvia.ru/ Владимир Осокин

    Благодарен. Появилась новая мысль, но она нуждается в глубокой реорганизации старой идеи, займусь завтра. И сразу поделюсь информацией с читателями блога!

  • Jim

    Installed a new server, fedora 10, recently and xdebug/debugger. Have xdebug and debugger vim running on 3 other machines and using it for sometime, it is a great tool. When I try to test on the newest server, the debugger session is started and is receiving output from the web server. But the php-code portion of the debugger window is empty. Any suggestions where to start looking ?

    Thanks for your time…..

  • nomuna

    Man this is awesome… Thanks a lot. I got it working with a single PHP file…
    But soon will try it with a really big Zend project…
    Will keep you posted…

  • http://northirelandfootball.ru/ Алексей Андреев

    Такое впечатление, будто это не Вы писали. А какой то дежурный блогер по поручению.

  • intuited

    Anybody wondering how to pipe/redirect/copy the output from :version into a buffer is advised to type “:help redir” from the vim command line.

  • http://www.spiralti.com Matias

    Im getting this error when i make F5 in vim.

    waiting for a new connection on port 9000 for 5 seconds…
    Connection closed, stop debugging (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), <traceback object at 0xb78e97fc

    )

    Full message:
    (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), )
    File “/home/matias/.vim/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/home/matias/.vim/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/home/matias/.vim/plugin/debugger.py”, line 555, in accept
    serv.bind((”, self.port))
    File “”, line 1, in bind

  • http://leon.vankammen.eu sqz

    Amazing!
    Although it conflicts a bit with my shortcut keys…still this is vim a true powerup! :)

  • http://www.irelandgoal.ru/ Дмитрий Шеметов

    Классная статья – спасибо!

  • http://www.hungarygoal.ru/ Павел Хохолин

    Спасибо за статью! Надеюсь, автор не против, если я использую это для своего блога

  • http://musicxsat.ru/ Мечеслав Андреев

    Занятно пишете, жизненно. Все-таки, для того, чтобы делать по-настоящему интересный блог, нужно не только сообщать о чем-то, но и делать это в интересной форме:)

  • Simon Coggins

    I was having the same problem as Derek, when I tried to run by pressing F5 I got this error:

    response xmlns:xdebug=http://xdebug.org/dbgp/xdebug xmlns=urn:debugger_protocol_v1 command=stack_get transaction_id=7
    error code=5 : Command not available (Is used for async commands. For instance if the engine is in state “run” than only “break” and “status” are available).
    message
    command is not available

    The problem (for me) was that I was setting breakpoints on blank lines – make sure you put the breakpoint on a line with valid code!

    See also this thread:
    http://xdebug.org/archives/xdebug-general/1202.html

  • Pingback: 網站製作學習誌 » [Web] 連結分享

  • http://dutcherdesign.com bob d

    I’d love to have this working, but I get compilation errors during the make step. The first error is:
    ex_cmds.c: In function ‘ex_sign’:
    ex_cmds.c:6541: error: ‘gui’ undeclared (first use in this function)
    ex_cmds.c:6541: error: (Each undeclared identifier is reported only once
    ex_cmds.c:6541: error: for each function it appears in.)
    ex_cmds.c:6546: warning: assignment makes pointer from integer without a cast
    ex_cmds.c: In function ‘sign_gui_started’:
    ex_cmds.c:6832: warning: assignment makes pointer from integer without a cast
    make[1]: *** [objects/ex_cmds.o] Error 1

    It is complaining that the object ‘gui’ isn’t defined. gui is defined in gui.h but including that file in ex_cmds.c results in a link error.

    The source code looks like this:

    ifdef FEAT_SIGN_ICONS

    if (gui.in_use) <---- causes compilation error

    So, I commented on the #define of FEAT_SIGN_ICONS in src/feature.h and everyhing build fine. But, alas, vim’s :version command shows -python and -signs.

    I tried this on vim71 and vim72.

  • Pingback: 在vim中调试PHP | an vimmer,one linuxer and a rider

  • CL

    Please provide some more info on how you can have one user debugging at the same time cause i am having a hard time doing that.

  • Khai Doan

    Feature request: permanent break point

    For the site the I am working on, all the pages are funneled through a single index.php file. This index.php file will load the php file that I want to debug after about 100 lines of code.

    So I hit F5, and click on the link / button in the browser, and vim open on the first line of index.php, and I either have to hit F4 100 times, or scroll 100 lines down and set the breakpoint (using Bp)

    Is it possible to set a permanent / persistent breakpoint that survive across debugging sessions?

    Thanks

  • Khai Doan

    Another feature request: Ability to ignore ajax requests

    My web application use AJAX IM, which ping the server once every 30 seconds. These ajax requests got in my way when I needed to debug some other script.

    Thanks!

  • Michael Hendry

    Here’s how I got this to work with Windows XP and XDEBUG, with a lot of help from this thread.

    Starting point:

    Windows XP Professional
    Vim v7.0 compiled with python support
    Apache 2.2.4
    PHP 5.2.3

    I downloaded the most recent beta version of xdebug, and amended php.ini by appending the following:

    zend_extension_ts=c:/program files/php/modules/php_xdebug-2.1.0beta1-5.2-vc6.dll
    xdebug.remote_enable = 1
    xdebug.remote_port = 9000
    xdebug.remote_host = localhost
    xdebug.remote_handler = dbg

    I downloaded the original scripts (debugger.py and debugger.com) from http://www.vim.org/scripts/script.php?script_id=1152 and placed them in my plugin folder.

    I got error messages about the missing import files when I started vim, but couldn’t find them on my system so I downloaded and installed python version 2.6, and copied them one by one into the plugin folder, eventually coming to a halt when one of the import files was apparently incompatible with vim’s version of python (2.4).

    I therefore downloaded and installed the binaries for vim 7.2, but found that this version is also compiled with python version 2.4, so I downloaded and installed python 2.4, which got the import statements working.

    At some stage in the process I realised I needed more recent versions of the debugger scripts, and got hold of these from:

    http://www.vim.org/scripts/script.php?script_id=1929

    I was now beginning to get a little closer to having a working debugger, but got stuck with error messages relating to files whose names start with “/C:/Program%20Files/Apache%20Software%20Foundation…”.

    Appending the following function from the thread…

    import urllib
    import os
    def fixFileName(fileName):
    fileName = urllib.unquote(fileName)
    if os.name==’nt’ and fileName[0]==”/”:
    fileName = fileName[1:] # strip off initial slash char
    return fileName

    … to the end of debugger.py, and adjusting these lines:


    file = res.firstChild.getAttribute(‘fileuri’)[7:]
    file = fixFileName(file)
    self.ui.set_srcview(file, 1)

    for s in stacks:
    self.stacks.append( {‘file’: fixFileName(s.getAttribute(‘filename’)[7:]),
    ‘line’: int(s.getAttribute(‘lineno’)),

    gets rid of the “/” in front of the filename, and adjusting fixFileName() as below sorts out the “%20″ characters. (This way of stripping out the leading “/” character is preferable to the replacement of [7:] by [8:] in that it checks the OS before stripping it out).

    import urllib
    import os
    def fixFileName(fileName):
    fileName = urllib.unquote(fileName)
    if os.name==’nt’ and fileName[0]==”/”:
    fileName = fileName[1:] # strip off initial slash char
    fileName = fileName.replace(‘%20′,’ ‘)
    return fileName

    BRILLIANT! I now have a debugger for PHP scripts!

    I suspect my methods could be improved, I present them now in the hope of saving others in my position from hours of frustration!

    As I’ve never had anything to do with python before this exercise, I leave it to those more enlightened than I to make further improvements to the code.

    SUGGESTION: It would be very handy to have a “run to breakpoint” key, intead of stepping repeatedly with F2.

  • Lao Meng

    Last Sept 17 Matias submitted the following question and I am having the same problem. Any answers? I see this was asked a year or two ago but I don’t see any responses then either. I am very excited to get going with this tool. Anything that works together with vi must be great! Thanks for all the work on it.

    waiting for a new connection on port 9000 for 5 seconds…
    Connection closed, stop debugging (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), <traceback object at 0xb78e97fc

    )

    Full message:
    (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), )
    File “/home/matias/.vim/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/home/matias/.vim/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/home/matias/.vim/plugin/debugger.py”, line 555, in accept
    serv.bind((”, self.port))
    File “”, line 1, in bind

  • Michael Hendry

    In the third paragraph from the top it says “You can step into, over, and out of statements, eval statements, get all variables in context, get and set properties, remove and set breakpoints, all on the fly.”

    I can’t work out how to “set properties” – help, please!

    Michael

  • lvzhxznu

    waiting for a new connection on port 9000 for 5 seconds…
    Connection closed, stop debugging (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), <traceback object at 0xb78e97fc

    )

    Full message:
    (, error(98, ‘Direccixc3xb3n ya estxc3xa1 en uso’), )
    File “/home/matias/.vim/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/home/matias/.vim/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/home/matias/.vim/plugin/debugger.py”, line 555, in accept
    serv.bind((”, self.port))
    File “”, line 1, in bind

    if your php is fastcgi mod then the port 9000 is default,so you can change the debug port from 9000 to 9001

    on server edit php.ini:
    xdebug.remote_port = 9000

    on vim edit .vimrc:
    let g:debuggerPort = 9001

  • lvzhxznu

    on server edit php.ini:
    xdebug.remote_port = 9001

    on vim edit .vimrc:
    let g:debuggerPort = 9001

  • frode

    Great write up, thanks!

    One question though: xdebug seems to close the connection if I’ve stopped at a breakpoint for too long. The STACK_WINDOW in vim says:

    27 : send =====> step_over -i 27
    (, EOFError(‘Socket Closed’,),
    (…)

    Any clues on how to solve this?

  • Lao Meng

    Thanks for the info Ivzhxznu. I’ve been on hoilday so took a while before I saw your reply. Unfortunately I’m not running in fastcgi mode. I did try changing port numbers (previously I didn’t know how to do this for vim, so thanks) to 9001 and 9002. Neither worked. My current error messages are:
    (, AttributeError(“DbgProtocol instance has no attribute ‘stop’”,), )
    File “/usr/share/vim/vim72/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/usr/share/vim/vim72/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/usr/share/vim/vim72/plugin/debugger.py”, line 560, in accept
    self.stop()

    I’m actually not sure that these things mean anything since no connection was established. Any other ideas on what the problem is? By the way, my server is Ubuntu 9.10 Karmic Koala Server and the Client is also Ubuntu 9.10.

  • Lao Meng

    Doh! I was brain dead. I had left my xdebug.remote_host set to localhost when I was trying to run on a client machine. After I changed to my IP address it works. Sorry about that.

    Does anyone know if xdebug.remote_host can take wild cards or ranges so that I can enable debugging on multiple machines?

  • Lao Meng

    Sorry, brain dead again…I must need another holiday. The instructions for my last question are already given above.

  • Pingback: VIM, LE « Halak » des éditeurs de code « Sylvain Lévesque ≈ Blogue

  • e.

    If you get this error:

    ex_cmds.c: In function ‘ex_sign’:
    ex_cmds.c:6541: error: ‘gui’ undeclared (first use in this function)
    ex_cmds.c:6541: error: (Each undeclared identifier is reported only once
    ex_cmds.c:6541: error: for each function it appears in.)
    ex_cmds.c:6546: warning: assignment makes pointer from integer without a cast
    ex_cmds.c: In function ‘sign_gui_started’:
    ex_cmds.c:6832: warning: assignment makes pointer from integer without a cast
    make[1]: *** [objects/ex_cmds.o] Error 1

    The fix for me was to NOT comment out the if statement for:

    define FEAT_SIGN_ICONS

    So, that define was not set when compiling.

  • http://camilbancioiu.myopenid.com/ Camil Bancioiu

    Don’t forget that your home plugin directory is ~/.vim/plugin, not just ~/.vim. In other words, copy debugger.py and debugger.vim to the ~/.vim/plugin directory (you must create it, it’s probably not there).

  • http://twitter.com/timhheuer Tim-Hinnerk Heuer

    Awesome, VIM is the best!

  • Brandon Woodmansee

    Good tutorial –

    Vim threw some errors similar to the following:

    ‘DbgProtocol instance has no attribute’

    solved by adding:
    xdebug.remote_handler = dbgp

    to the PHP config

  • Florian Margaine

    I just wanted to say: thank you. Your plugin has completely changed my life.

  • Lee

    I must agree, this is a nice integration of a tried & true editor with runtime debugging.

  • http://twitter.com/ButlerPCnet Michael Butler

    When I hit F5 in VIM, I get a “socket.error”. any ideas?

    (, , )
    File “/home/michael/.vim/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/home/michael/.vim/plugin/debugger.py”, line 928, in run
    self.protocol.accept()
    File “/home/michael/.vim/plugin/debugger.py”, line 555, in accept
    serv.bind((”, self.port))
    File “”, line 1, in bind

  • turpana

    here’s a nice custom brew formula for installing vim with ruby & python support on your mac
    http://iamnearlythere.com/installing-vim-python-ruby-support-homebrew/

  • http://twitter.com/gbhatnag Gaurav Bhatnagar

    This is a great tool & tutorial, really appreciate it. Getting a debugger going for PHP is going to be excellent. I’ve gotten to the point where xdebug is set up properly with PHP (I see it in phpinfo), I’ve set up my page with the XDEBUG_SESSION_START=1 flag, I’ve hit F5 in Vim and am seeing the ‘waiting for a new connection on port 9000 for 5 seconds…’ message.

    Unfortunately, refreshing the page at that point does not make the connection. I am wondering if ‘xdebug.remote_host = localhost’ is not the correct hostname to use in this case. I am developing on a development server (i.e. dev.highlighter.com) and accessing the page from my local machine (i.e. some IP elsewhere out on the Internet).

    Should I be setting a different value for xdebug.remote_host?

  • Matt

    I am unable to debug a file, and observe the following symptoms:

    1) A connection is established with Xdebug, but I get a blank debugging screen with the following error message in the Trace Window:

    (, timeout(‘timed out’,), )
    File “/home/mmikitka/.vim/plugin/debugger.py”, line 1078, in debugger_run
    debugger.run()
    File “/home/mmikitka/.vim/plugin/debugger.py”, line 932, in run
    self.recv(1)
    File “/home/mmikitka/.vim/plugin/debugger.py”, line 715, in recv
    txt = self.protocol.recv_msg()
    File “/home/mmikitka/.vim/plugin/debugger.py”, line 604, in recv_msg
    length = self.recv_length()
    File “/home/mmikitka/.vim/plugin/debugger.py”, line 576, in recv_length
    c = self.sock.recv(1)

    2) I observe the following error message in /var/log/apache2/error.log:

    [error] [client 127.0.0.1] PHP Warning: The remote debug handler ‘DBGp’ is not suapported. in Unknown on line 0
    h
    I ran the following diagnostic checks, all of which passed:

    1) Installed the debugclient tool from Xdebug (see http://www.xdebug.org/docs/install). I was able to establish a connection.

    2) The Xdebug tailored installation instructions (see http://xdebug.org/wizard.php) indicate that there is no problem with my configuration

    I am using the latest Ubuntu, PHP 5.3 and Xdebug versions:

    OS: Ubuntu 12.04
    PHP version: 5.3.10 (1ubuntu3.2)
    Xdebug version: 2.2.1

    Thank you for your help.

    regards,
    matt

  • kyu

    finally figured out how to use F12. Thank you for the great plugin and functionality!

  • Alpay Önal

    Hi,

    If you get “debugger is not running”, “socket is closed” or something like this, try to load xdebug.so extension with zend prefix.

  • http://www.cloudstaff.com/ Hoyt Velasquez

    Thank you for sharing this great article on PHP debugging. It is very helpful. Cheers!