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!

Check della sintassi per PHP e JavaScript in Vim

Una funzione molto utile presente in numerosi strumenti di sviluppo (i cosiddetti IDE come Visual Studio, Eclipse, NetBeans ecc…) è la possibilità di individuare eventuali errori di sintassi durante la scrittura del codice.

Questa funzionalità è disponibile anche per Vim utilizzando un ottimo plugin chiamato syntastic (l’autore è lo stesso di un altro plugin molto famoso e utilizzato: The NERD Tree).
Questo permette infatti di individuare eventuali errori di sintassi o di stile evidenziando le righe interessate e supporta una grande varietà di linguaggi.

In questo articolo vedremo come installare syntastic e come abilitare il controllo della sintassi per PHP e JavaScript in ambiente Windows.
Se lavorate in ambiente Linux o Mac dovreste comunque essere in grado di seguire e adattare i vari passaggi.


Premessa su Vim


Questo articolo parte dal presupposto che conosciate già le basi Vim e che siate in grado di installare un plugin.
Se vi interessa sapere di più su Vim, un editor molto potente free e open source, potete trovare numerosissimi tutorial in rete, ad esempio:


Se invece volete un libro per conoscere o approfondire Vim vi consiglio caldamente questo manuale chiamato Practical Vim (su Amazon.com ha 44 recensioni tutte da 5 stelle). Credo che attualmente non esista un libro migliore disponibile sull’argomento:


Installazione


Il modo migliore per installare syntastic è sicuramente quello di utilizzare pathogen.vim, un plugin che permette di gestire e installare facilmente altri plugin mantenendoli ordinati nelle loro rispettive cartelle. Se avete già installato pathogen.vim saltate pure alla sezione seguente.

Installazione di pathogen.vim


Per installare pathogen basterà seguire i seguenti step:

  1. Scaricate il file pathogen.vim all’indirizzo http://www.vim.org/scripts/script.php?script_id=2332
  2. Aprite la cartella contenente i plugin di Vim, solitamente situata in %USERPROFILE%\vimfiles (es. C:\Users\Luca\vimfiles\). In ambiente Linux la cartella è nascosta e si trova nella home con il nome di .vim
  3. Copiate il file scaricato al punto 1 all’interno della cartella autoload
  4. Tornate nella cartella vimfiles e create una nuova cartella di nome bundle
  5. Aprite il file _vimrc (.vimrc in ambiente Linux) che si trova sempre in %USERPROFILE% (es. C:\Users\Luca\_vimrc) o nella home e aggiungete la seguente linea

    execute pathogen#infect()

In questo modo tutti i plugin potranno essere installati semplicemente inserendoli all’interno della cartella bundle e pathogen.vim li caricherà automaticamente.

Per caricare anche gli help e la documentazione di ciascun plugin installato tramite pathogen basterà digitare:

:Helptags (notare la H maiuscola)

Installazione di syntastic


Per installare syntastic basterà scaricare lo zip all’indirizzo https://github.com/scrooloose/syntastic ed estrarlo nella cartella syntastic all’interno della cartella bundle creata al punto precedente. In alternativa potete anche effettuare un clone con git del repository presente su Github (sempre all’interno della cartella bundle).


Una volta installato aprite Vim e digitate :Helptags per caricare la documentazione di syntastic. In questo modo sarà possibile digitare :h syntastic in qualunque momento per consultare l’help.

Utilizzo


Una volta installato syntastic si attiva automaticamente, supponendo che riesca a trovare un checker per il linguaggio che si vuole utilizzare.
Come già detto, in questo articolo installeremo un checker per PHP e JavaScript, ma una volta capito il concetto è molto semplice installare un checker per altri linguaggi.

Checker per PHP


Aprite una nuova finestra del terminale con cmd e scrivete php -v sulla linea di comando.
Se compare un risultato simile a quello nell’immagine seguente significa che php è già all’interno del vostro PATH e non dovete fare altro.


Se il comando invece non viene invece riconosciuto, sarà necessario aggiungere alla variabile di ambiente PATH il percorso in cui si trova l’interprete php. Nel mio caso, utilizzando Xampp, si trova in C:\xampp\php, pertanto ho dovuto aprire le proprietà di sistema e aggiungere la seguente stringa alla variabile PATH:


Una volta aggiunta la variabile al PATH, riavviate il terminale e riprovate a digitare php -v. Dovrebbe comparire la versione installata di PHP.

Apriamo ora un file PHP qualsiasi e digitiamo :SyntasticInfo per vedere quali checker sono attualmente utilizzati:


Il checker di default per PHP è phpcs (PHP CodeSniffer di Pear) che però risulta essere un po’ troppo intrusivo per i miei gusti (ad esempio segnalerà come errore il fatto che il terminatore di riga non sia \n ma \r\n). Per impostare php invece di phpcs come checker predefinito per i file PHP apriamo il file _vimrc e aggiungiamo la seguente linea:

let g:syntastic_php_checkers = ['php']

Ricarichiamo il file _vimrc con :source $MYVIMRC (oppure chiudendo e riaprendo Vim).

Di default syntastic si attiva automaticamente ogni volta che un file viene scritto su disco (ad esempio quando scriviamo :w myfile.php) oppure su richiesta con il comando :SyntasticCheck (da notare che il programma analizzerà comunque solo i file già salvati, non terrà conto di eventuali modifiche non ancora salvate!).

Se sono presenti degli errori e il file viene salvato, syntastic evidenzierà le linee interessate e mostrerà dei tooltip con dei messaggi descrittivi. Nell’immagine successiva ho di proposito omesso una parentesi e al momento del salvataggio il programma ha sottolineato la riga interessata. Mettendo il mouse sopra la riga viene mostrato un tooltip.


Utilizzando il comando :Errors, verrà aperta una lista contenente tutti gli errori con indicato il numero di riga e il messaggio di errore. Per chiudere la lista è sufficiente digitare il comando :lclose.


A questo punto non resta che correggere tutti gli errori rilevati e riprovare fino a quando non saranno stati tutti debellati :)

Vediamo adesso come installare un checker i file JavaScript.

Checker per JavaScript e jQuery


Per quanto riguarda JavaScript (e jQuery naturalmente!) il procedimento sarà abbastanza simile anche se andremo a installare JSHint come checker.


Per prima cosa sarà necessario installare Node.js, scaricando l’installer per Windows all'indirizzo http://nodejs.org/download/

Una volta installato apriamo la console di Node.js (troverete Node.js command prompt nella lista dei programmi se avete scaricato l’installer) e usiamo il package manager per installare JSHint digitando la seguente istruzione:

npm install jshint -g


Come per PHP apriamo un file JavaScript qualunque e digitiamo :SyntasticInfo per vedere quali checker sono attualmente utilizzati:


Come detto precedentemente, syntastic si attiva di default al momento del salvataggio del file (ad esempio quando scriviamo :w jquery-myplugin.js) oppure su richiesta con il comando :SyntasticCheck (da notare che il programma analizzerà comunque solo i file già salvati, non terrà conto di eventuali modifiche non ancora salvate!).

Le righe che presentano eventuali errori di sintassi, warning o semplicemente consigli sullo stile verranno sottolineate e comparirà un tooltip posizionando il cursore o il mouse sulla riga corrispondente.


Con il comando :Errors verrà aperta una lista contenente tutti gli errori con indicato il numero di riga e il messaggio di errore.
Premendo invio o anche solo facendo doppio clic su una riga si arriverà direttamente alla posizione corrispondente dell’errore.
Per chiudere la lista è sufficiente digitare il comando :lclose.


Non resta quindi che debellare tutti gli errori, controllare e ripetere fino a quando il nostro codice non sarà pronto!

Impostare il controllo della sintassi manualmente


A volte può risultare troppo “invasivo” il fatto che il controllo della sintassi venga eseguito ad ogni salvataggio del file, ma è possibile configurare Vim per eseguirlo solamente su richiesta (ad esempio associandolo a uno specifico hotkey).

Per prima cosa è necessario impostare syntastic in modalità passiva; in questo modo il controllo dei file sarà eseguito soltanto tramite il comando :SyntasticCheck.
Bisogna inoltre impostare una variabile per evitare di eseguire il controllo al salvataggio del file. Nel dettaglio le due istruzioni da aggiungere al file _vimrc sono le seguenti:

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

Se adesso vogliamo associare il controllo a un determinato hotkey (nel mio caso F6), basta effettuare un remap aggiungendo la seguente istruzione:

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

In questo modo il controllo verrà eseguito solamente premendo il tasto F6.

Aprire automaticamente la lista degli errori


Come abbiamo visto, è necessario digitare :Errors per far comparire la lista con tutti gli errori rilevati all’interno del file.
Per fare sì che la lista venga aperta automaticamente dopo ogni controllo di sintassi basta aggiungere la seguente istruzione al file _vimrc:

let g:syntastic_auto_loc_list = 1

Ignorare gli errori di “stile”


Molti dei checker (come ad esempio JSHint) sono in grado di distinguere 3 tipi diversi di errori:

  • Errori
    Gli errori veri e propri (esempio una parentesi obbligatoria mancante)
  • Warning
    Avvertimenti che normalmente non bloccherebbero l’esecuzione del programma ma che è comunque consigliato correggere
  • Style
    Questi sono “errori” di stile (come ad esempio le best practice sull’indentatura)

Alle volte si è interessati solamente agli errori e ai warning veri e propri, magari perché si usano convenzioni diverse da quelle consigliate e quindi non si vuole essere “disturbati” da eventuali messaggi non strettamente necessari (nel caso di PHP, ad esempio phpcs segnalerà come errore di stile il fatto che le linee terminano con \r\n di default in Windows, invece che in \n).

Anche se spesso utili, è possibile mettere a tacere questi warning aggiungendo la seguente istruzione al file _vimrc:

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

In definitiva, tutte le istruzioni viste finora da aggiunge al file _vimrc per quanto riguarda syntastic sono le seguenti:


Per consultare le altre opzioni relative al plugin e per avere ulteriori informazioni sui vari checker è sufficiente leggere l’ottima documentazione fornita digitando h: syntastic

Spero che questo articolo vi possa aiutare a sviluppare codice di qualità in maniera migliore e soprattutto a trovare eventuali errori più velocemente!