Friday, December 18, 2015

Enhanced Syntax Highlighting by HTML

I have been using coloured syntax for codes in my blog for long time. The basic technique is to use VIM's syntax template and TOhtml command. In this way, I can easily get html format for my codes.

The only thing that has been puzzled me is to add line numbers. In VIM is very easy to add line numbers. The view is good. By adding line number, I could explain codes in my blog by line. However, it is a messy if you want to make a copy of my codes in my blog. I would like to have line numbers in my colourful code syntax, but not be copied if selected.

While I was reading Swift Programming Language by Mac Developer Library. I found that code examples there do have the feature I want. By further exploring, I found html ol tag being used. That's the solution for my long time puzzle!

Setup Line Numbers for Codes


Here are steps to get colourful codes in html by VIM:
  1. :set nonumber # to disable line number
  2. :set syntax=swift # change syntax template to swift
  3. :let use_html_css=1 # to use css in html, instead of style attribute
  4. :TOhtml # to convert text to html
  5. remove html tags not needed
  6. :%s:^:<li>:g # add </li> tag to the beginning of each line
  7. :%s:$:</li>:g # append </li> to the end of each line
  8. :%s:\s\@<=\s:\&nbsp;:g # replace continuous spaces, not the first one, by html special code for space.
The html codes generated by above steps are li tags, which can be added to the body of ol tag.
Note
The reason I use css class is that blogger provider allows me to add customized css. If you don't have access to css, then you should use embedded style for syntax colouring.

An example is as follows:





The html codes could be further enhanced, for example, moving ordered line number left out of code box. For the time being, I think it is good enough.

Add Note Section


This is a related topic: adding a note section for code explanation. I like the way in Mac Developer Library to add a note section in simple and clear format. I added this feature to my blog as well.

What I did is to add the following css classes to my html template in blogger:

  1. /* div box with class note for note section */
  2. div .note {
  3.  border-left: 5px solid rgba(233, 233, 233, 1);
  4.  background-color: rgba(249, 249, 249, 1);
  5.  margin: 40px auto 35px;
  6.  padding: 15px 15px 7px;
  7.  width: 85%
  8. }
  9. div .noteTitle {
  10.  color: rgba(128, 128, 128, 1);
  11.  # font-size: 9px;
  12.  letter-spacing: 2px;
  13.  margin-bottom: 8px;
  14.  text-transform: uppercase
  15. }

Here is example of above note section in html:

<div class="note">
<span class="noteTitle">Note</span><br />
The reason I use css class is that blogger provider allows me to add customized css. If you don't have access to css, then you should use embedded style for syntax colouring.
</div>

References



0 comments: