Saturday, July 10, 2010

Painless inserting of nicely highlighted code block to my blog

If u happen to like the way i display code blocks in this blog & have read my previous post abt how i have given this blog a face-lifting, here are some extra steps i've taken to conveniently allow me to:

# 1. edit whatever code i want to display in vim

# 2. use a user-defined command (while still in vim) :Xc to process the entire (or selected lines) of the current buffer to yield nicely-highlighted code block & load it to the X11 clipboard (using xclip)

# 3. use middle mouse click (hehe, i'm using thinkpad, anyway, this can be done by doing left & right click together on mouse) to paste it to whereever i like (eg. the textarea i'm typing in right now)

Enough said, let's get into action:

# S1. Installing the required packages:

pacman -S xclip

# S2. Inserting the user-defined command :Xc to ~/.vimrc
1
2
3
4
5
func! Xclip() range
execute ":!~/bin/code2html.rb " . bufname('%') . " " . a:firstline . ":" . a:lastline . " | xclip"
endfu

com! -range=% -nargs=0 Xc <line1>,<line2>call Xclip()

# S3. Revising the existing ~/bin/code2html.rb to accept extra args
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env ruby

require 'rubygems'
require 'coderay'
require 'tempfile'

file = ARGV[0]
range = ARGV[1].split(':').map(&:to_i).map(&:pred) rescue nil

if range
basename = Time.now.to_i.to_s
extension = file[/\/.*?.(\.[^\.]*?)$/,1]
Tempfile.open(extension ? [basename, extension] : basename) do |fh|
fh.write(File.readlines(file)[range[0] .. range[-1]].join)
file = fh.path
end
end

puts %|#{coderay.scan_file(file).html(:line_numbers => :table)}|.
gsub('coderay','coderay').split('<pre').map{|s|
!s.include?('</pre>') ? s.gsub("\n",'').squeeze(' ') : (
parts = s.split('</pre>')
[parts[0], parts[1].gsub("\n",'').squeeze(' ')].join('</pre>')
)
}.join('<pre')

To try out, restart ur vim to edit any file, to convert the entire file, run the following command in vim:

:Xc

Alternatively, if u want to convert the selected lines (in visual mode, using Shift-v to select the specific lines):

:'<,'>Xc

And to do the pasting, just do middle (mouse) click on any textarea u are working on.

No comments:

Post a Comment

Labels