How can I integrate jscs autofix feature into vim?
Asked Answered
S

2

9

I'm trying to get a command I can run within vim to get jscs auto correct formatting issues in my code. So far I've come up with :

:nmap <F5> :!jscs -x .<CR>

which is ok, but it runs it on the entire directory and I need to confirm to vim that I want to reload the buffer. Is there a way to get vim to fix the current file only and didsplay the changes without reloading?

Spiritless answered 23/4, 2015 at 9:24 Comment(0)
P
8

This will pipe the current file through jscs's fix mode whenever you save the file (your mileage may vary using this in practice!):

function! JscsFix()
    "Save current cursor position"
    let l:winview = winsaveview()
    "Pipe the current buffer (%) through the jscs -x command"
    % ! jscs -x
    "Restore cursor position - this is needed as piping the file"
    "through jscs jumps the cursor to the top"
    call winrestview(l:winview)
endfunction
command! JscsFix :call JscsFix()

"Run the JscsFix command just before the buffer is written for *.js files"
autocmd BufWritePre *.js JscsFix

It also creates a command JscsFix which you can run whenever you want with :JscsFix. To bind it to a key (in this case <leader>g) use noremap <leader>g :JscsFix<cr>.

Petrology answered 23/4, 2015 at 9:26 Comment(2)
When I add those lines to my vimrc, it's ok the first time, and I can use jscs by pressing F3 to restyle my file. But the next time I want to source my vimrc again (using :so %) I get these errors: Error detected while processing /home/omid/.vimrc: line 197: E174: Command already exists: add ! to replace it Press ENTER or type command to continue Here's my full snippet: jsfiddle.net/2pLoczwsGastineau
Changing the line command JscsFix :call JscsFix() to add the exclamation mark after command, e.g. command! JscsFix :call JscsFix() might do what you want?Petrology
D
5

vim-autoformat supports JSCS out of the box. Invoke its :Autoformat command to fix only the current file. Note it edits the file in the current buffer, so the changes will just appear; you will not be prompted to reload.

Dysentery answered 8/12, 2015 at 22:44 Comment(1)
Great tip! Additionally run auto-format on save with autocmd BufWritePre *.js Autoformat.Tootsie

© 2022 - 2024 — McMap. All rights reserved.