Ruby Markdown 解析过程中语法高亮问题

xautjzd · May 25, 2014 · Last by xautjzd replied at May 25, 2014 · 3907 hits

最近突然了解到 markdown 的解析器及语法高亮开源项目,便尝试自己来解析 markdown 文件,以下是我的源码:

#!/usr/bin/env ruby

require 'redcarpet'
require 'rouge'
require 'rouge/plugins/redcarpet'

class HTML < Redcarpet::Render::HTML
    include Rouge::Plugins::Redcarpet
end

render_options = {
    filter_html:     true,
    # will insert <br /> tags in paragraphs where are newlines 
    # (ignored by default)
    hard_wrap:       true, 
    # hash for extra link options, for example 'nofollow'
    link_attributes: { rel: 'nofollow' }
}

# renderer = Redcarpet::Render::HTML.new(render_options)
renderer = HTML.new(render_options)

markdown = Redcarpet::Markdown.new(renderer, fenced_code_blocks: true, autolink: true)

# Get markdown file name to parse to html
origin_name = ARGV[0]
# Create xxx.html(origin file: xxx.markdown)
des_file = File.open(File.basename(origin_name, ".*")+".html", "w")

des_file.write("<html>")
des_file.write("<head>")
des_file.write("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>")
des_file.write("</head>")
des_file.write("<body>")

# Parse markdown to html
File.open(origin_name).each do |line|
    des_file.write(markdown.render(line))
end

des_file.write("</body>")
des_file.write("</html>")

执行这个脚本时,ruby myscript.rb xxx.markdown,需要给脚本传一个待解析的 markdown 文本参数。markdown 里有以下的代码块:

#include <stdio.h>
#include <unistd.h>

int main(char **argv, int argc)
{
    int fd;
    FILE *fp;
    char proclnk[255];
    char filepath[255];

    # test.txt为已存在的文件
    fp = fopen("test.txt", "r");
    if (fp != NULL) {
        fd = fileno(fp);
        sprintf(proclnk, "/proc/self/fd/%d", fd);
        readlink(proclnk, filepath, 255);

        printf("fp->fd->filepath: %p->%d->%s\n", fp, fd, filepath);
    }

    return 0;
}

但最后解析时,其他的 markdown 都能正确解析出来,惟独这个代码块解析有问题,一是没有语法高亮,二是

#include <stdio.h>
#include <unistd.h>

最后被解析成

<h1>include </h1>
<h1>include </h1>

请问有人碰到过这个问题么

我觉得是不是 markdown 变量需要把文件所有内容读进来,再 render。而不是读一行,render 一行。毕竟 markdown 的语法需要上下文。

建议在客户端解析。。。。让 rails 变快的方法就是尽量不让请求到达 rails。。。。

你需要先将 markdown 里的代码预处理一下,不然#这种会被当做 markdown 语法处理的,参考 github 的处理方法:https://gist.github.com/mojombo/118964

@bastengao 一次读取内容,然后再解析,确实能正确解析,不过代码还是没高亮显示,我再看看。

@pynix 我没有采用 rails.

@tsl0922 好的,谢谢。我看看

You need to Sign in before reply, if you don't have an account, please Sign up first.