vim で HTML文字実体参照の変換を行うスクリプト
選択範囲を数値文字参照に変換するスクリプト str2numchar.vim – 川o・-・)<2nd life を参考にして HTML文字実体参照(& < > " => & < > ")の変換・逆変換をするvimスクリプトを作った。
スクリプトファイル str2htmlentity.vim を $HOME/.vim/plugin/ に配置して .vimrc に次の記述を加える。
vmap <silent> sx :Str2HtmlEntity<cr>
vmap <silent> sr :Entity2HtmlString<cr>
ビジュアルモードで範囲選択を行いキー sx を押すと "文字から文字実体参照へ" の変換が、
キー sr を押すと "文字実体参照から文字へ" の変換ができる。
コード
追記:範囲選択を行っても行単位で変換されていたのを、選択範囲内のみ変換を行うように修正しました。
function! s:char2entity(str) let result = a:str if a:str ==? '<' let result = '<' elseif a:str ==? '>' let result = '>' elseif a:str ==? '"' let result = '"' elseif a:str ==? '&' let result = '&' endif return result endfunction function! s:entity2char(str) let result = a:str if a:str ==? '<' let result = '<' elseif a:str ==? '>' let result = '>' elseif a:str ==? '"' let result = '"' elseif a:str ==? '&' let result = '&' endif return result endfunction function! s:range2HtmlEntity() range silent execute "normal! gv:s/\\%V[\&<>\"]/\\= s:char2entity(submatch(0)) /g\<CR>" endfunction function! s:range2HtmlString() range silent execute "normal! gv:s/\\%V\&[^;#]\\+;/\\= s:entity2char(submatch(0)) /g\<CR>" endfunction " for range command command! -range Str2HtmlEntity :<line1>,<line2>call s:range2HtmlEntity() command! -range Entity2HtmlString :<line1>,<line2>call s:range2HtmlString()
function! s:char2entity(str) let result = a:str let result = substitute(result, '&', '\\&', 'g') let result = substitute(result, '<', '\<', 'g') let result = substitute(result, '>', '\>', 'g') let result = substitute(result, '"', '\"', 'g') return result endfunction function! s:entity2char(str) let result = a:str let result = substitute(result, "\<", "<", 'g') let result = substitute(result, "\>", '>', 'g') let result = substitute(result, "\"", '"', 'g') let result = substitute(result, "\&", '\&', 'g') return result endfunction function! s:range2HtmlEntity() range silent execute "normal! gv:s/\\%V\&\\|<\\|>\\|\"/\\= s:char2entity(submatch(0)) /g\<CR>" endfunction function! s:range2HtmlString() range silent execute "normal! gv:s/\\%V\&\\|\<\\|\>\\|"/\\= s:entity2char(submatch(0)) /g\<CR>" endfunction " for range command command! -range Str2HtmlEntity :<line1>,<line2>call s:range2HtmlEntity() command! -range Entity2HtmlString :<line1>,<line2>call s:range2HtmlString()
ViIMproved‐Vim完全バイブル
posted with amazlet at 08.11.07
Steve Oualline 高橋 則利
技術評論社
売り上げランキング: 219168
技術評論社
売り上げランキング: 219168




Thanks!,
Web屋のためのVim設定・Tipsまとめ 2/2…
「Web屋のためのVim設定・Tipsまとめ 1/2」からの引き続き。
Vimを使ったHTMLとCSSの編集について、さらに関係しそうな事項を紹介します。
HTML編集でもよく使うVim基本機能
=キーで自動イ…
[...] vimでHTML文字実体参照の変換を行うスクリプト [...]