Tuesday, January 26, 2010

Vim, Substitute and Escaping Code

Your browser is designed to read the HTML code on a web page and turn it into something pretty. In my next post I want to show you the code behind the HTML. In order to do that I had to "escape" the code. Of course I used Vim to do this with its Substitute capabilities.

The Substitute command has the form:
<range>substitute/<from>/<to>/<flags>

So to change the "<" on the tags in the code to one that would be displayed as code by your browser, I had to use the code "&lt;"

So my substitution looks like:

%s/</&lt;/g

Which breaks down to mean:
% - over the whole file
s - substitute
/</ - from "<"
&lt;/ - to "&lt;"
g - global flag ie change all occurrences, by default only one occurrence is changed on each line and we usually have two.

Pretty easy eh?

Not really... It changed "<" to "<lt;"

Vim reads the "&" in the "to" to mean the "from" AND the "to". To solve I had to escape the "&".

First I had to correct my mistake and that was easy, I just pressed "u" and it "undid" the last edit command and everything was back to original.

Then I ran:

%s/</\&lt;/g

which worked perfectly. The "\" means that the letter after is not to be parsed by Vim.

The other substitutions were:

%s/>/\&gt;/g
%s/"/\&quot;/g

And finally but with flawed thinking:

%s/&/\&amp;/g

If you have followed me so far you can imagine what the file looked like with every symbolic "&" showing up as "&amp;". But the fix was easy... "u" to undo.

So it is ready to go onto the next post.

One more point, you will notice all the pretty boxes that the code is in, I got the tip from a post by Simrandeep, "Display HTML/CSS Codes On Coloured Background In Blogger Posts"

Ready to continue?

No comments:

Post a Comment