首页 > 代码库 > 0012 vim下php文件中自动缩排html代码

0012 vim下php文件中自动缩排html代码

问题:vim下怎样在php文件中通过 = 命令自动缩排html代码?

解决:

1、先说下html自动缩排
我的vim是7.4版本,已经包含了html.vim之类的缩排插件,但是缩排的时候<body> <head> 没有进行缩排
在.vimrc中加入如下代码即可对 <body> <head> 也进行缩排

" html indent
filetype indent on 
let g:html_indent_inctags = "body,head,tbody" 	" 缩进body head
" let g:html_indent_script1 = "inc"		" 缩进<script>标签
" let g:html_indent_style1 = "inc"		" 缩进<style>标签

2、解决php文件中html代码缩进

创建 ~/.vim/indent/php.vim 文件,如果没有indent目录,就先创建indent目录
然后在 php.vim 文件中粘贴如下代码并保存

" 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+=<>>

3、在 .vimrc 中还需要添加 filetype indent on 打开根据文件类型自动缩进
在vim命令模式下中输入 gg=G 即可完成自动缩排

参考:
http://www.vim.org/scripts/script.php?script_id=2075
http://blog.longwin.com.tw/2009/01/vim-indent-for-php-html-2009/
http://cache.baiducontent.com/c?m=9d78d513d9871af04fede53c5754c066680ec63c62c0d0642488c51fcf224f060738ece161645213d2b6617a45f4164bea8773296e5873a09bbfd91782a6d77376d33a44275ac01652c41edb901a73967cd64deedb58a0f8b26fd3e8c5d4ab000e8a44020ec2aac94d07608f34b64e26e4d2c30e4a01&p=c06ccc04969d12a05abd9b7e0b1791&newp=9370c64ad48703fa08e294780c4dcf231610db2151d6d7143b96c6&user=baidu&fm=sc&query=vim+php+html+indent&qid=a72951080000046d&p1=2

0012 vim下php文件中自动缩排html代码