給 PHP 和 HTML 專用的 VIM 縮排(Indent)

Vim 在寫 *.html 和 *.php 時, 在 HTML 排版上, 都有些不夠聰明的狀況.

  • *.html => 自動排版會將所有 HTML Tag 都排在同一列, 等同於沒有縮排.
  • *.php => 自動排版會將 HTML Tag 排在在同一列外, 按 Enter 後, 游標會在第一個位置, 不會做聰明的縮排動作.

註: 下述太多不想看, 只想直接解決的, 只要下載 html.vim(於 indent/html.vim) 和 php.vim(於 Better indent support for php with html), 將這兩個檔案放到 ~/.vim/indent, 再於 .vimrc 加入 
filetype indent on 就完成囉~

要解決上述的問題, 由下面兩個步驟來解決:

  1. 設定 VIM 讓 HTML 正確縮排(Indent) - 先讓 HTML 正確縮排
  2. 設定 VIM 讓 *.php 做 HTML 縮排(Indent) - 讓 *.php 遇到 HTML 時, 能用 HTML 縮排來排版

設定 VIM 讓 HTML 正確縮排(Indent)

首先讓 HTML 能正確的縮排, 步驟如下:

  1. indent/html.vim - alternative html indent script
  2. 下載 html.vim
  3. mkdir ~/.vim/indent
  4. mv html.vim ~/.vim/indent
  5. 於 ~/.vimrc 加入 filetype indent on (Enable filetype detection and use of indent plugins)

設定 VIM 讓 *.php 做 HTML 縮排(Indent)

HTML 既然都可以縮排, 本來想法是把 filetype=php 指成 html, 就可以先頂著用, 不過這樣子在寫 php 時又得要換回來, 有點麻煩.

此篇 Better indent support for php with html 有另外一種解法, 解法沒有研究, 不過稍微看看, 大概是下面的流程:

  1. 縮排時先執行 indent/html.vim, 如果有做過縮排, 就結束.
  2. 若沒有縮排, 再執行 indent/php.vim (php.vim 的內容在下面)

php.vim # 將下面的文字存成 php.vim, 並搬到 ~/.vim/indent 下即可. (此 php.vim 轉載自: "Better indent support for php with html")


" Better indent support for PHP by making it possible to indent HTML sections
" as well.
if exists("b:did_indent")
  finish
endif

" This script pulls in the default indent/php.vim with the :runtime command
" which could re-run this script recursively unless we catch that:
if exists('s:doing_indent_inits')
  finish
endif
let s:doing_indent_inits = 1
runtime! indent/html.vim
unlet b:did_indent
runtime! indent/php.vim
unlet s:doing_indent_inits

function! GetPhpHtmlIndent(lnum)
  if exists('*HtmlIndent')
    let html_ind = HtmlIndent()
  else
    let html_ind = HtmlIndentGet(a:lnum)
  endif
  let php_ind = GetPhpIndent()
  " priority one for php indent script
  if php_ind > -1
    return php_ind
  endif
  if html_ind > -1
    if getline(a:num) =~ "^<?" && (0< searchpair('<?', '', '?>', 'nWb')
          \ || 0 < searchpair('<?', '', '?>', 'nW'))
      return -1
    endif
    return html_ind
  endif
  return -1
endfunction

setlocal indentexpr=GetPhpHtmlIndent(v:lnum)
setlocal indentkeys+=<>>

相關網頁

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈給 PHP 和 HTML 專用的 VIM 縮排(Indent)〉中有 13 則留言

  1. 嗯, 文件是有寫這個, 但是我預設就可以動了(可能是我其它設定有含到這個吧?), 所以這段我就沒加了.
    馬上補上~ 感謝提醒~ 🙂

  2. 您好:
    我也非常需要這個功能,照著您的說明安裝後
    我在gvim用自動排版指令ESC -> gg -> = -> G
    (依序按下後)
    gvim還是照著一樣的方式,把所有的tag都排到最前面去了
    有裝跟沒裝的狀況是一樣的,
    不知是不是裝完後,指令有其他的設定?
    謝謝!

  3. 謝謝您的回答
    我原本裝的是c9s包好有enhance vim for win32
    即便加了cindent還是沒有成功
    不過後來又裝了vim7.2
    發現預設的indent似乎修好了?
    目前暫時可以用了
    謝謝!若還有問題再向您請教!

  4. 不過我在php.vim的最後一行加上這個...
    setlocal indentkeys+=*
    也就是說,按「↓」的按鈕就會自動indent,這個蠻方便的,本人用了很多年囉!

  5. 感谢你的分享。但我还是有个问题不能解决。那就是在打“<?php”标签时,输入到?它就将退回到第一列了。这个能解决吗?

johnpupu 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料