VIM and JSLint

    It turned out that I almost did not write in Habrahabr - there are reasons for this. But I would very much like to share one thing that will surely be useful to all those who work with JavaScript in vim, and besides, I did not find such material on Habrahabr.


    This may seem strange to some, but working in vim is really convenient (especially in the console - I am untied from gui, so I can work through ssh quietly; however, the same thing can be done with gui). In this, I completely agree with Derek Wyatt  , the author of wonderful vim screencasts. True, it is worth noting that it will be convenient after you understand that vim is a slightly different editor (because of which you need to get used to it), as well as adjust it a little for yourself. About customization and will be discussed.

    Those who program a lot and professionally know that the quality of the code affects the number of errors (naturally this is not the only factor). Also, they are often aware of the existence of lint tools (starting with the lint program written in Bell Labs by Stephen Johnson) that help the programmer check his own and other people's code for suspicious, potentially dangerous constructs, as well as just syntax errors. And if it is easy enough to enable lint mode for php, you just need to add in ~/.vim/ftplugin/php.vimtwo lines ( Slides and files of Andrey Zmievsky). and use: make to test, then to test JavaScript you need to make a little more effort, which I'm going to talk about. There is JSLint for JavaScript

    set makeprg=php\ -l\ %
    set errorformat=%m\ in\ %f\ on\ line\ %l




     - online tool for checking js code. Our task is to launch it offline.

    For this, depending on the operating system and available programs, we will need
    1. Some time
    2. Naturally, VIM itself
    3. JSLint sources
    4. One of the JavaScript engines is SpiderMonkey , Rhino , or any other engine . OSX owners are a little luckier - it has a JavaScriptCore (engine for Webkit) ready to use.

    Let's say that you have vim, and some JavaScript engine is already installed (if you have questions about the installation, it is best to ask them in the comments). It is also worth separately clarifying the situation with WSH Command Line and Rhino - for them there are special versions - www.jslint.com/wsh/index.html and www.jslint.com/rhino/index.html , respectively. I'll talk about how to run JSLint for SpiderMonkey / JavaScriptCore.

    To achieve the goal, you will need to edit ~/.vim/ftplugin/javascript.vimby adding such lines where PATH_TO_JS_ENGINE is the path to your js engine (for mac it is /System/Library/Frameworks/JavaScriptCore.framework/Versions/A/Resources/jsc , and for those who installed SpiderMonkey this is the default / usr / local / spidermonkey / bin / js

    if filereadable( 'PATH_TO_JS_ENGINE' )
    set makeprg=PATH_TO_JS_ENGINE\ ~/.vim/jslint_runner.js\ <\ %:p
    set errorformat=Line\ %l\ column\ %c:\ %m
    endif


    )

    After that, add the following code to the end of fulljslint.js

    var body = [],
        line,
        num_empty_lines = 0;
    // Т.к. в большинстве js-движков нет механизма проверки на конец файла,
    // а после конца файла нам валятся пустые строки, используем некоторый
    // разумный предел пустых строк, в данном случае 50
    while ( 50 > num_empty_lines ) {
        line = readline();
        body.push( line );
        if ( 0 === line.length ) {
          // blank line, so increment
          num_empty_lines += 1;
        } else {
          // not blank, so reset
          num_empty_lines = 0;
        }
    }
    body.splice( -num_empty_lines );
    body = body.join( "\n" );
    // Набор настроек из «Good Part», но без проверки whitespace
    options = {
        bitwise    : true,  // if bitwise operators should not be allowed
        eqeqeq     : true,  // if === should be required
        glovar     : true,  // if HTML fragments should be allowed
        regexp     : true,  // if the . should not be allowed in regexp literals
        undef      : false, // if variables should be declared before used
        onevar     : true,  // if only one var statement per function should be allowed.
        newcap     : true,  // if Initial Caps must be used with constructor functions
        immed      : true,  // if immediate function invocations must be wrapped in parens
        plusplus   : true,  // if increment/decrement should not be allowed
        nomen      : true   // if names should be checked
    };
    // Следующий комментарий устанавливает такие же параметры, если помещён
    // в начало js-файла
    /*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true */
    var result = JSLINT( body, options );
    if ( !result ) {
        for ( i = 0; i < JSLINT.errors.length; i+=1 ) {
            var err = JSLINT.errors[i];
            print(
                'Line ' + err.line + ' column ' + err.character + ': ' + err.reason
            );
        }
    } else {
        print( 'No errors found' );
    }


    and save the resulting file as ~/.vim/jslint_runner.js.

    The last code is not my personal one, I found it on the Internet and only edited it a bit.

    After ~/.vim/ftplugin/javascript.vimand ~/.vim/jslint_runner.jsthey will govtovy, perform :so ~/.vim/ftplugin/javascript.vim, or simply restart vim. After that, you can safely perform it :make, and if there are errors, navigate through them using :cnand :cp( :h quickfix).

    I also know that there are plugins for vim ( example ) and other discussions of this task ( example ). If you know anything else useful on this subject - welcome to the comments, I will be grateful.

    ps. There are several other differences for Windows besides WSH - vim’s home folder is in a different location, and .vimrc turns into vimrc.

    pps This article was prepared using vim.

    Also popular now: