所以當沒有人回答我的問題時,我不得不學習一些vim腳本,我做到了!
我已將~/.vim/plugin/jsbeautify.vim
複製到~/.vim/plugin/jsbeautify_replace.vim
並對其進行修改。這裏是一個diff jsbeautify.vim jsbeautify_replace.vim
:
1c1
< if &cp || exists("loaded_jsbeautify")
---
> if &cp || exists("loaded_jsbeautify_replace")
4c4
< let loaded_jsbeautify = 3
---
> let loaded_jsbeautify_replace = 3
286,291c286
< "function! g:Jsbeautify(js_source_text)
< function! g:Jsbeautify()
< if !s:is_js()
< echo "Not a JS file."
< return
< endif
---
> function! Jsbeautify_replace(js_source_text, indent)
310c305
< let lines = getline(1, "$")
---
> "let lines = getline(1, "$")
312,313c307,308
< let s:input = join(lines, "\n")
< "let s:input = a:js_source_text
---
> "let s:input = join(lines, "\n")
> let s:input = a:js_source_text
617c612
<
---
>
619,622c614,615
< :g/.*/d
< let @0 = ret
< :put!0
< endfunction
---
> let lines = split(ret, '\n')
> let result = ""
624c617,624
< nnoremap <silent> <leader>ff :call g:Jsbeautify()<cr>
---
> for line in lines
> let result .= a:indent." ".line."\n"
> endfor
> ":g/.*/d
> "let @0 = ret
> ":put!0
> return a:indent."<script type=\"text/javascript\">\n".result.a:indent."</script>"
> endfunction
而且在~/.vim/plugin/tidy_jsbeautify.vim
已經寫了一些劇本:
function! g:tidy_js()
%!tidy -i -xml --char-encoding utf8 --wrap 0 --show-errors 0 2>/dev/null
%s#\(\s*\)<script\_\s*type="text/[jJ]ava[sS]cript"\_\s*>\(\_.\{-1,}\)</script>#\= Jsbeautify_replace(submatch(2),submatch(1))#g
endfunction
這就要求我的緩衝整齊,然後在所有腳本標籤內容jsbeautify +腳本標籤的縮進會被添加。然後在~/.vim/ftplugin/html.vim
:
:map <buffer> <C-f> :call g:tidy_js()
現在是我的整個HTML文件很好地與快捷CTRL+F ENTER
:)
控制移可能是VIM不能識別格式化而已。 – Benoit 2012-02-29 16:40:30
對於其他文件類型,我有其他格式化工具'',它可以工作。 –
microo8
2012-02-29 16:48:01
@ microo8你是否檢查過''與''產生的結果是否相同?它不能工作,因爲1.輸入隊列的內部表示不能保存這個序列; 2.終端仿真器很可能發送這個序列爲''(rxvt-unicode),甚至根本不發送它(konsole); 3.當我執行'nmap smth'後,我的vim在運行''時啓動'smth''',這意味着''x06'('^ F')在解析':map'參數時被轉換爲'\ x06' 。 –
ZyX
2012-02-29 20:18:57