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:
:set nonumber
# to disable line number:set syntax=swift
# change syntax template to swift:let use_html_css=1
# to use css in html, instead of style attribute:TOhtml
# to convert text to html- remove html tags not needed
:%s:^:<li>:g
# add </li> tag to the beginning of each line:%s:$:</li>:g
# append </li> to the end of each line:%s:\s\@<=\s:\ :g
# replace continuous spaces, not the first one, by html special code for space.
li
tags, which can be added to the body of ol
tag.
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:
- /* div box with class note for note section */
- div .note {
- border-left: 5px solid rgba(233, 233, 233, 1);
- background-color: rgba(249, 249, 249, 1);
- margin: 40px auto 35px;
- padding: 15px 15px 7px;
- width: 85%
- }
- div .noteTitle {
- color: rgba(128, 128, 128, 1);
- # font-size: 9px;
- letter-spacing: 2px;
- margin-bottom: 8px;
- text-transform: uppercase
- }
Here is example of above note section in html:
<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
- Apple Developer Library: Swift Programming Language 2.1
0 comments:
Post a Comment