Skip to content

Move styles inline in vim’s 2HTML for easy blogging of code

2012-04-30

You may have heard of vim’s 2HTML (:help :TOhtml) tool for exporting your syntax highlighted code to html. It produces a complete html page, which doesn’t quite work with blogs, since you can’t use its html, head and body tags as is. So I use the following awk script to get rid of those tags and move all the styling inline:

BEGIN {
    i = 0;
    isStyle = 0;
    isPre = 0;
    preStyle = "";
}
/^<style [^>]*type="text\/css" ?[^>]*>/ { isStyle = 1; }
/^<\/style>/ { isStyle = 0; }
/^pre { .+ }$/ {
    if (isStyle == 1) {
        match($0, / { [^}]* }/);
        preStyle = substr($0, RSTART+3, RLENGTH-5);
    }
}
/^\.\w+[^{]* { .+ }$/ {
    if (isStyle == 1) {
        match($0, / { [^}]* }/);
        class[i] = "class=\"" substr($0, 2, RSTART-2) "\"";
        style[i] = substr($0, RSTART+3, RLENGTH-5); i++;
    }
}
/span class="[^"]*"/ {
    for (j=0; j < i; j++) {
        gsub(class[j], "& style=\"" style[j] "\"");
    }
}
// { if (isPre == 1) { print; } }
/^<pre ?[^>]*>/ {
    isPre = 1;
    printf "<pre style=\"%s\">\n", preStyle;
}
/^<\/pre>/ { isPre = 0; }

Now you’ll have just one pre tag, ready to be included in any blog post.

:TOhtml
:%! awk -f ~/.bin/inline_style.awk
Advertisements

From → vim

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: