Monday, May 19, 2014

Syntax check for PHP and JavaScript inside Vim

Many development tools such as Visual Studio or Eclipse have a feature to automatically detect syntax errors when writing code.

This feature is also available inside Vim using a very good plugin called syntastic (it is provided by the same author of another great plugin called The NERD Tree).
This plugin makes it possible to detect syntax and style errors of a wide range of programming languages and it highlights the affected rows of code.

In this article I will explain how to install syntastic and how to enable the syntax check for PHP and JavaScript in a Windows environment.
If you are working on a Linux or a Mac you should still be able to follow and adapt the various steps.


About Vim


This article assumes that you already know Vim's fundamentals and you are able to install a plugin.
If you would like to know more about Vim, a very good and powerful open-source editor, you can find a lot of online tutorials, for example:


If you prefer a book to learn or know more about Vim I highly recommend a manual called Practical Vim (on Amazon.com it has more than forty 5-stars reviews). It is currently the best book around for this subject:


Installation

The best way to install syntastic is to use pathogen.vim, a plugin which can be used to manage and install other plugins while keeping them on their respective folder. If you already have installed pathogen on your system, please jump to the next section.

Installing pathogen.vim


In order to install pathogen you can take the following steps:

  1. Download the file pathogen.vim from http://www.vim.org/scripts/script.php?script_id=2332
  2. Open Vim's plugin directory, usually located at %USERPROFILE%\vimfiles (eg. C:\Users\Luca\vimfiles\). In a Linux environment the directory is named .vim and it's a hidden directory
  3. Copy the file you downloaded in step 1 into the autoload folder
  4. Create a new folder named bundle into the previous vimfiles folder
  5. Open the _vimrc file (.vimrc in a Linux environment) usually located in %USERPROFILE% (eg. C:\Users\Luca\_vimrc) and add the following line:
    execute pathogen#infect()

Now all the new plugins can be easily installed by copying them into the bundle folder and pathogen will start them automatically.

In order to load the help and documentation for each installed plugin you could type:

:Helptags (Note the capital H)

Installing syntastic


In order to install syntastic you can download the main zip file from https://github.com/scrooloose/syntastic and extract it into the syntastic folder inside the bundle folder you have previously created. Alternatively you can just clone the git repository on GitHub (always into the bundle folder).


Once installed, you can type :Helptags to load the documentation. In this way you can type :h syntastic to see the help.

Basic usage


Once installed, syntastic is automatically activated, assuming that it manages to find a suitable checker for the current programming language.
As already mentioned, in this article I will show how to install a checker for PHP and JavaScript, but you should be able to install a checker for another language with little effort.

PHP checker


Open a new terminal window with cmd and write php -v on the command line.
If you can see a result similar to the one in the picture below, then the php intepreter is already on your system path and you can skip to the following paragraph.


If you receive an error which says that php is not a valid command, then you must add the php interpreter path to the system environment variables. I use Xampp so php is located in C:\xampp\php. You should add the following string to the PATH variable:


Once added to the PATH variable, restart the terminal and try again digit php -v. You should now see the installed version of PHP.

Now open a PHP file and digit :SyntasticInfo to see which checkers can be enabled:


The default PHP checker is phpcs (PHP CodeSniffer di Pear) but it turns out to be a bit too picky for my taste (e.g. it will highlight as an error the fact that the line terminator is \r\n instead of \n).
In order to set another default checker for PHP files open the _vimrc file and add the following line:

let g:syntastic_php_checkers = ['php']

Reload the _vimrc file with :source $MYVIMRC (or close and reopen Vim).

By default syntastic will automatically activate every time a file is written to the disk (for example when you write :w myfile.php) or manually when typing the :SyntasticCheck command. Please note that syntastic will analyze saved files only, it will not consider unsaved changes!

If there are any errors, syntastic will highlight the corresponding lines and will show a tooltip with a descriptive message. In the next picture I have omitted a parenthesis and syntastic is highlighting the row. If you put your mouse over the line you will see a tooltip.


Using the command :Errors you can open a list with all the errors along with their descriptive message and line number. To close the list, simply type the command :lclose.


Now you just have to fix all the errors found by syntastic!

We'll see in the next section how to install a checker for JavaScript files.

Checker per JavaScript e jQuery


As for JavaScript (and jQuery of course!) the process will be similar but we're going to install JSHint as the default checker.


First you will need to install Node.js. You can download the Windows installer at http://nodejs.org/download/

Once installed, open the Node.js command prompt and use the npm package manager to install JSHint by typing the following statement:

npm install jshint -g


Open a JavaScript file and type :SyntasticInfo to see which checker are enabled:


As mentioned before By default syntastic will automatically activate every time a file is written to the disk (for example when you write :w jquery-myplugin.js) or manually when typing the :SyntasticCheck command. Please note that syntastic will analyze saved files only, it will not consider unsaved changes!

Lines with syntax errors, warnings or coding hints will be underlined and a tooltip will appear when placing the cursor above them.


The :Errors command will open a list with all the error messages and the corresponding line numbers.
Pressing enter or when you double click on a line will move you directly to the corrisponding position of the error.
To close the list, simply type the command :lclose.


Now you just have to eliminate all the errors, rinse and repeat until your code will not be ready!

Set the syntax check manually


Sometimes it can be too much the fact that the syntax check is activated every time you save a file, but it's possible to configure Vim to execute it only on demand (for example by binding it to a specific hotkey).

First you need to set syntastic in passive mode; in this way the check will be run only when you execute the command :SyntasticCheck.
You also need to set a variable to avoid running the command every time you save a file.
You will need to add the following two lines to the file _vimrc:

let g:syntastic_check_on_wq = 0
let g:syntastic_mode_map = { 'mode': 'passive' }

Now if you want to bind the check to a specific hotkey (F6 in my case), you can do a remap by adding the following line:

nnoremap <silent> <F6> :SyntasticCheck<CR>

Now the syntax check will be only executed when you press the F6 key.

Automatically open the list of errors


As we saw before, you need to type :Errors to open a list with all the errors found in the file.
In order to automatically open the list every time the syntax check is run, you just need to add the following line to the file _vimrc:

let g:syntastic_auto_loc_list = 1

Ignore style errors


Many of the checkers (e.g. JSHint) are able to distinguish between three different type of errors:

  • Errors
    The real errors (for example a missing bracket)
  • Warnings
    Warning messages which do not usually stop the execution of the code but it is recommended to fix
  • Style
    These are style "errors" (such as indenting rules or best practices)

Sometimes you just want to detect real errors or warnings, maybe because you are using different conventions and you don't want to be "bothered" by unnecessary messages (in the case of PHP, the checker phpcs will detect a style error if your line terminating characters will be \r\n by default in Windows instead of just \r).

Although they can be useful, you can silence these warnings by adding the following line to our _vimrc file::

let g:syntastic_quiet_messages = { "type":  "style" }

All the instructions added so far by this post are the following:


To view the additional options available for this plugin and for more information about the available checkers you can always read the very good documentation by typing h: syntastic

I hope this article will help you developing quality code in a better way and expecially help you finding your code error faster!

1 comment:

  1. Your blog has given me that thing which I never expect to get from all over the websites. Nice post guys!

    Web Development Melbourne

    ReplyDelete