2012-02-29 53 views
1

如何使用tidy在vim中格式化html文件,並使用Jsbeautifull格式化腳本標記的內容?vim自動格式化HTML文件與整潔和<script>標籤與Jsbeautifull

我有這樣的命令::%!tidy -i -xml --char-encoding utf8 --wrap 0 --show-errors 0 2>/dev/null格式化的html文件,

:call g:Jsbeautify()格式化的js文件。我如何才能在腳本標籤的內容上調用g:Jsbeautifull()Jsbeautifull(js_script, options)可以將js源作爲參數。

我想將它映射到<C-S-f>

+0

控制移可能是VIM不能識別格式化而已。 – Benoit 2012-02-29 16:40:30

+0

對於其他文件類型,我有其他格式化工具'',它可以工作。 – microo8 2012-02-29 16:48:01

+0

@ microo8你是否檢查過''與''產生的結果是否相同?它不能工作,因爲1.輸入隊列的內部表示不能保存這個序列; 2.終端仿真器很可能發送這個序列爲''(rxvt-unicode),甚至根本不發送它(konsole); 3.當我執行'nmap smth'後,我的vim在運行''時啓動'smth''',這意味着''x06'('^ F')在解析':map'參數時被轉換爲'\ x06' 。 – ZyX 2012-02-29 20:18:57

回答

0

所以當沒有人回答我的問題時,我不得不學習一些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 :)

0

jsbeautify.vim,線310表明這是不可能的,如果你不修改插件:

let lines = getline(1, "$") 

也許你想自定義部分(修改功能g:Jsbeautify()採取兩個參數,並使用getline(a:start, a:end)代替。

+0

好的,所以當我把'g:Jsbeautify()'改成'g:Jsbeautify(start,end)'並將第310行改成'let lines = getline(start,end)'這會很好嗎? – microo8 2012-02-29 15:54:11

+0

@ microo8:第310行,如果參數被稱爲'start'和'end',則必須使用'a:start'和'a:end'。在一個函數內,前綴'a:'用於參數變量。 – Benoit 2012-02-29 16:03:04

+0

好的,我把'letlines = getline(1,「$」)'改成了'getline(a:start,a:end)'。怎麼辦? – microo8 2012-02-29 16:22:37