cql

导航

用Notepad++为博客插入高亮代码

我最初是使用的博客园在线编辑器的插入代码功能,后来看了YJingLee的CnBlogs博文排版技巧一文,觉得他的代码样式很好看,便想学习过来。但他推荐使用的Paste from Visual Studio插件需要从Visual Studio中复制代码,这样适用的编程语言就比较少。而我在上一篇博文中要插入AutoHotkey的代码,连博客园的插入代码中也不支持。所以就想到了一直在用的Notepad++,默认就支持很多种语言的高亮,还支持自定义的扩展,如果能把它显示的高亮代码复制为html格式就好了。

已经有人做了这样的插件,单击Notepad++菜单中的 插件->NppExport->Export to HTML,就可以生成对应的HTML文件,但它生成的代码不太方便直接插入在博客文章中,而且也不够精简,连回车符都用了<span>。我想把它变成Paste from Visual Studio生成代码那样的格式,就写了一段AutoHotkey代码,主要就是进行正则替换。

ahk代码如下:

FileSelectFile, CodeFile, 3 ;1:文件必须存在+2:路径必须存在
FileRead, CodeStr, %CodeFile%
StartPos := 1
while 1
{
    StartPos := RegExMatch(CodeStr, "\.(sc\d+).*\{\r\n([\s\S]*?)}", Match, StartPos)
    if(StartPos>0)
        StartPos := StartPos+1
    else
        break
    if(Match2 == "")
        CodeStr := RegExReplace(CodeStr, "<span class=""" . Match1 . """>([\s\S]*?)</span>", "$1")
    else
    {
        Match2 := RegExReplace(Match2, "\r\n", " ")
        Match2 := RegExReplace(Match2, "\t", "")
        CodeStr := RegExReplace(CodeStr, "(?<=<span )class=""" . Match1 . "(?="">[\s\S]*?</span>)", "style=""" . Match2)
    }
}
CodeStr := RegExReplace(CodeStr, "[\s\S]*?(<span[\s\S]*?)</div>[\s\S]*", "<pre class=""code"">`n$1`n</pre>")
FileDelete, %CodeFile%
clipboard = %CodeStr%
;Author http://cql.cnblogs.com

C++高亮效果如下,同在Notepad++下一样。

#include <GPL.h>
#include <free_software.h>

void notepad4ever()
{
    while (true)
    {
        Notepad++;
    }
}

使用时将上面提供的ahk代码复制在记事本中,保存为文件名后缀为ahk(如convert.ahk)。先将要插入的代码用Notepad++打开,用Export to HTML导出为html文件(注意:notepad++ 中 export to html乱码的解决办法),再双击运行convert.ahk(也可以设置成快捷键运行),选择刚导出的html文件,则转换后的结果会保存在剪切板中,另外会自动删除导出的html文件。最后在编辑器(我使用的是Windows Live Writer)的源代码模式下粘贴就行了。

再贴上从YJingLee那里抄来的代码边框样式:

.code
{
    font-family: Consolas,'Courier New',sans-serif;
    background-color: #f8f8ee;
    border: solid 1px #e8e7d0;
    padding: 5px 10px 0px 10px;
    min-height: 10px;
    margin-top: 10px;
    margin-bottom: 30px;
    color: #666666;
    border-left: solid 5px #6ce26c;
}

粘贴在博客后台管理——设置——通过CSS定制页面风格 里就行了。

最后感谢YJingLee,还有deerchao关于正则表达式的教程及测试器。

附:AutoHotkey下载http://www.autohotkey.com请选择Unicode版本安装

posted on 2012-12-11 20:36  cql blog  阅读(650)  评论(0编辑  收藏  举报