最近突然了解到 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>
请问有人碰到过这个问题么