Vim – What A Nice Editor

Vim Logo

About half a year ago, I tried to write with Vim/GVim instead of traditional BBS editor. It’s so convenient to use regular expression to replace some words to other forms, such as trimming the spaces, connecting separate sentences, adding or appending some HTML tags in order to put them onto my blog, etc. Before this afternoon, I wrote English pieces directly in the blog’s web-based editor, but I thought I may want to keep a copy in plain text in my hard drive. Thus, I tried Vim.

I was very used to the UI of Vim and that’s not the problem. But when I’d like to put the article onto my blog, I didn’t want to correct manually all the html special characters, such as “'” and ‘"’ into special forms. I tried to use replace function with regular expression.

The first encountered problem was to find a proper pattern to recognize where to be corrected. It took me a lot of time and finally I found as below:

:map <F7> %s/\\(\\s\\\\|\\_^\\)\\"\\(.\\+\\)\\"\\(\\s\\\\|\\_$\\)/\\1\\&lsquo;\\2\\&rsquo;\\3/g<CR>

But it will match as many words as posible that I couldn’t replace a clause. Then, I replaced the “\+” with “\{-1,},” which means to match as few as posible, just like “+?” in Perl.

:map <F7> %s/\\(\\s\\\\|\\_^\\)\\"\\(.\\{-1,}\\)\\"\\(\\s\\\\|\\_$\\)/\\1\\&lsquo;\\2\\&rsquo;\\3/g<CR>

Second, I couldn’t replace ‘"’ and “'” in only one pattern due to Vim doesn’t support conditional expression. But if I map the replacement and some errors are encountered while executing, the following won’t be continued. Thus, I found the “e” option which means to ignore errors.

Third, after replacing all the single and double quotes, the remaining single quotes and the AND symbol are replaced. And the final mapping was:

:map <F7> :%s/&/\\&amp;/ge<CR>:%s/</\\&lt;/ge<CR>:%s/>/\\&gt;/ge<CR>:%s/\\(\\s\\\\|\\_^\\)\\'\\(.\\{-1,}\\)\\'\\(\\s\\\\|\\_$\\)/\\&lsquo;\\1\\&rsquo;\\2/ge<CR>:%s/\\(\\s\\\\|\\_^\\)\\"\\(.\\{-1,}\\)\\"\\(\\s\\\\|\\_$\\)/\\1\\&ldquo;\\2\\&rdquo;\\3/ge<CR>:%s/\\'\\(\\w\\)/\\&rsquo;\\1/ge<CR>:%s/\\'/\\&\\#39;/ge<CR>:%s/\\"/\\&quot;/ge<CR>

Yeah, from now on, I just have to press a key and Vim will prepare a HTML compatible form for me. HaHaHa…


Leave a Reply