How can I format JS code in Vim? - vim

I have this bit of JavaScript...
15 $('.ajax_edit_address').each(function() {
16 $(this).ajaxForm({
17 target: $(this).parents('table.address').find('tr.address_header').children(':first'),
18 success: function(response) {
19 $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
20 }
21 });
22 });
That's formatted the way I like it. But let's say I had just finished typing something and I wanted to tidy it up. So I run the Vim code formatter on it...
=7j
The result is...
15 $('.ajax_edit_address').each(function() {
16 $(this).ajaxForm({
17 target: $(this).parents('table.address').find('tr.address_header').children(':first'),
18 success: function(response) {
19 $('input, select, textarea', '.ajax_edit_address').removeClass('updating');
20 }
21 });
22 });
Vim seems to have trouble with functions as method arguments.
Here is what I think is the relevant part of my .vimrc...
:set cindent shiftwidth=2
" indent depends on filetype
:filetype indent on
:filetype plugin on
Is there something else that needs to be installed or configured to format JS code?

VIM plugin Jsbeautify could handle jQuery correctly. It's the vim plugin version of the online Jsbeautify.

There is a far simpler solution that requires no vim plugins.
Install js-beautify to your system python:
pip install jsbeautifier
Then add this to your .vimrc:
autocmd FileType javascript setlocal equalprg=js-beautify\ --stdin
That's it.
Run :help equalprg to see why this works.

If you've got js-beautify installed (it's available for Python: pip install jsbeautifier, or Node: npm -g install js-beautify) then you can just run it directly from vim - to reformat the current file:
:%!js-beautify

I'd recommend the CLI version of einars/jsbeautify, which you can find here: https://github.com/einars/js-beautify.
It's the offline version of www.jsbeautifier.org.
Use this plugin https://github.com/Chiel92/vim-autoformat to run the formatter on your current buffer with one button press.

The biggest issue seems to be the cindent doesn't recognize this type of syntax:
test({
var b = 2;
});
It will turn it into this:
test({
var b = 2;
});
If you handle that case I'd imagine the indent wouldn't be so awful for the jQuery syntax. But this would require you writing a custom javascript indent file. Also, you'd have to edit the html indent file to not use cindent for script tags with javascript content.
I don't think anyone has successfully created a jquery/prototype compatible indent file for javascript. The existing javascript indent scripts are all flawed.

Unfortunately, 'cindent' just isn't going to do the job since it's is very much tied to C syntax. Since all the default indent script for javascript does is turn on 'cindent', that's not much help. It even says so in the script!
" Maintainer: None! Wanna improve this?
I don't do anything other than really basic javascript so I've never bothered trying to find anything better. From a quick look on vim.org, this script looks like it may be worth a shot. It's newer, so it probably takes into account the more complex javascript that's used now days.

Another alternative that do not need to configure anything inside vim is to run the format command manually at save like:
:w !js-beautify --stdin >%
After saving in this way the vim editor will ask you to reload the current file content:
W12: Warning: File "src/static/js/main.js" has changed and the buffer was changed in Vim as well
See ":help W12" for more info.
[O]K, (L)oad File:
This works like the :w sudo tee % command used to save a file that you modified without privilege.
The command uses the standard input(STDIN) and write it to a variable file descriptor % used as source of current file.
PS: of course you need to install the js-beautify.
pip install jsbeautifier

Related

nvim finds the function but vim does not

I am using a vim/nvim plugin asyncrun that enables an API call that works fine in nvim if I implement it in ~/.config/nvim/init.vim using a line:
call asyncrun#run("", "cwd", "firefox")
Now this same line does not work for vim if I try to use it inside ~/.vimrc. I always get a warning:
Unknown finction: asyncrun#run
What needs to be changed in order for this to also work for vim?
Following the #doopNudles comment I also clarify that vim plugin is manually installed in the folder ~/.vim/pack/my-plugins/start/vim-asyncrun/asyncrun.vim/plugin/asyncrun.vim. I install all my vim plugins the same way (using the vim v8 native ability to detect plugins).
The problem was that ~/.vim/pack/my-plugins/start/vim-asyncrun/asyncrun.vim/plugin/asyncrun.vim has one extra folder!
It works if I delete the extra folder asyncrun.vim like this ~/.vim/pack/my-plugins/start/vim-asyncrun/plugin/asyncrun.vim

gVim 7.3 in fullscreen mode

I'm using the script to open gVim in fullscreen downloaded from here: http://www.vim.org/scripts/script.php?script_id=2596.
I've also added this line to the startup settings:
:call libcallnr("gvimfullscreen.dll", "ToggleFullScreen", 0)
When running gVim with this setting, I get the following error:
Error detected while processing _virmc:
E364: Library call failed for "ToggleFullScreen()"
Is there anything else I need to do with the files from that script? If I need to compile it somehow, would like someone to guide me through that process as I'm fairly new to Vim. Thanks!
Edit: I'm running Windows 7
I guess you mean ~/.vimrc or ~/.gvimrc by "startup settings". When that is executed, the GUI isn't initialized yet. Try delaying the execution with an autocmd:
:autocmd GUIEnter * call libcallnr("gvimfullscreen.dll", "ToggleFullScreen", 0)
It doesn't seem to be working if you place that call line in your vimrc. It should be called after Vim has finished loading. I suggest using that mapping from the readme:
map <F11> <Esc>:call libcallnr("gvimfullscreen.dll", "ToggleFullScreen", 0)<CR>
It worked for me.
I had the same problem when I was install this script through Vundle.
It's solved the problem:
Copy the DLL to the folder where GVIM.EXE is located.
An alternative to copying the gvimfullscreen.dll to the executable directory is to specify the file path, like this:
call libcallnr(expand("$VIM") . "/bundle/gvimfullscreen_win32/gvimfullscreen.dll", "ToggleFullScreen", 0)
In this example, I'm using $VIM and the bundle directory, but you can change this to a full path, or use another variable/path that works better for you.
This isn't a direct answer, but after searching for a solution for quite a while, I've decided that the prettiest way to run Vim on Windows is via Cygwin, via the (bundled) mintty terminal. It has a genuine full screen and even transparencies!

Vim script not loaded?

When I work with some Python files, and run :set filetype? in Vim, I get filetype=python, so the file is recognized correctly as Python code.
I've downloaded this plugin: http://www.vim.org/scripts/script.php?script_id=1494
and put it in ftplugin folder, but its f/F keys bindings are not working, and running its :call ReFold() gives E117: Unknown Function indicating that the plugin hasn't been loaded.
Any troubleshooting tips on how to load the plugin?
Try removing this part at the top of the script:
if exists("b:did_ftplugin")
finish
endif
let b:did_ftplugin = 1
And possibly moving the script to after/ftplugin directory (:help after-directory).
I think you have another python specific plugin that comes first at 'runtimepath' and defines b:did_ftplugin, which is OK, but this python script (python_editing.vim) shouldn't check for and define b:did_ftplugin since it doesn't implement the functionality of original plugin, it just extends it.
So the script is loaded, but does nothing. By running :script command without arguments one can check if some script is loaded at all.

Automatic Code formatting conflicts with Javascript Lint in Vim

To enable effective code formatting, I need to set the following in my .vimrc file
filetype plugin indent on
If I do that, code formatting (gg=G) works perfectly. However, I get the following error when I load up javascript files:
Error detected while parsing function <SNR>78_JSLint:
line 25
could not invoke JSLint
and I have to set it back to
filetype on
Now Javascript Lint works (I don't know why it says 'JSLint', I have Syntastic set up to work with Javascript Lint), but code formatting is now less reliable. How do I make it so I can run Javascript Lint (via Syntastic) and proper code formatting, without one interfering with the other.
You probably have another JS linting plugin somewhere (maybe jslint.vim?) that conflicts with syntastic or you don't have said plugin anymore but there's stil an autocmd in your .vimrc.
Search your ~/.vim folder for "JSLint" with
$ grep JSLint ~/.vim
to see where it's invoked.
Either way, your problem has nothing to do with indenting.

How Do I get a syntax check to work in/with vim?

This question has been asked, in one form or another, a dozen times here, and it blows my mind how not a single one actually addresses how to configure syntastic or jslint such that it actually does what it is supposed to do (its README file is completely useless)
see here
Can anyone provide some step by step instructions, or a link to such instructions. I tried to install jslint and spidermonkey, and I got nowhere.
I managed to get the syntax check to work (thanks to romainl). A few things I learned along the way that may help anyone with a similar problem
To build Javascript Lint look for the README file nested in jsl-x.x.x/src/README.html
The build instructions are gmake -f Makefile.ref but gmake is the same thing as make so issue the command sudo ln -s /usr/bin/make /usr/bin/gmake
jsl will now be found in jsl-0.3.0/src/Linux_All_DBG.OBJ/jsl. To make it generally accessible do something like: ln -s /whatever/jsl-0.3.0/src/Linux_All_DBG.OBJ /home/ForestGump/bin/jsl. More information here
To check that jsl actually works find a test file ( here) then issue the command jsl -process test.js. It should list all the errors.
To customize your command line, add this to your vimrc file set statusline=%{SyntasticStatuslineFlag()}
What did you do? What works and what doesn't? Do you get error messages?
Here is what I did:
Downloaded the jsl sources from the JavaScript Lint site.
Built jsl and moved it somewhere in my $PATH.
Checked if it worked by running it against a random .js file
Downloaded and installed Syntastic as a Pathogen bundle.
Typed :helptags /path/to/syntastic/doc because for some reason Pathogen's automatic help tags generation doesn't work for me.
Read Syntastic's documentation: :help syntastic.
Steps 1 to 5 didn't take more than 3 or 4 minutes, maybe less.
Step 6 is obligatory, whatever new tool you try. RTFM.
I didn't have to configure anything beside these 3 lines in my .vimrc (and I believe the third is redundant):
let g:syntastic_auto_loc_list=1
let g:syntastic_disabled_filetypes=['html']
let g:syntastic_enable_signs=1
and customizing my statusline a bit with:
%{SyntasticStatuslineFlag()}
EDIT
Here is my statusline:
set statusline=%<\ %n:%f\ %m%r%y%{SyntasticStatuslineFlag()}%=line:\ %l\ of\ %L,\ col:\ %c%V,\ win:\ %{WindowNumber()}\
Don't copy it verbatim or you'll get some errors due to the function call at the end. There is a paragraph about that in syntastic's help.
END EDIT
After all that, 10 or 12 minutes if you count reading the documentation, I have a very helpful location list and signs poping up each time I save a .js file with syntax errors.
Setup vundle according to its README.
Put this into your .vimrc:
Bundle 'scrooloose/syntastic'
Then enter this command in vim:
:BundleInstall
That's it.
EDIT: Vundle has changed its syntax since I originally wrote this. Nowadays, you use
Plugin 'scrooloose/syntastic'
and then enter
:PluginInstall

Resources