%%%------------------------------------------------------------------- %%% @author Gordon Guthrie %%% @copyright (C) 2009, Gordon Guthrie %%% @doc, %%% %%% @end %%% Created : 10 Sep 2009 by gordonguthrie@backawinner.gg %%%------------------------------------------------------------------- -module(erlmd). -include_lib("erlmd/include/types.hrl"). -export([conv/1, conv/2, conv_utf8/1, conv_file/2, conv_ast/1, conv_html/1, default_opts/0]). -import(lists, [flatten/1, reverse/1]). -define(SPACE, 32). -define(TAB, 9). -define(LF, 10). -define(CR, 13). -define(NBSP, 160). -define(AMP, $&, $a, $m, $p, $;). -define(COPY, $&, $c, $o, $p, $y, $;). %%% the lexer first lexes the input %%% make_lines does 2 passes: %%% * it chops the lexed strings into lines which it represents as a %%% list of lists %%% * it then types the lines into the following: %%% * normal lines %%% * reference style links %%% * reference style images %%% * special line types %%% - blank %%% - SETEXT header lines %%% - ATX header lines %%% - blockquote %%% - unordered lists %%% - ordered lists %%% - code blocks %%% - horizontal rules %%% the parser then does its magic interpolating the references as appropriate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% Public API %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% @doc Default options for conversion -spec default_opts() -> map(). default_opts() -> #{format => html}. %% @doc Convert Markdown using default options (HTML output) -spec conv(string()) -> string(). conv(Input) -> conv(Input, default_opts()). %% @doc Convert Markdown with options %% Options: %% #{format => html} - Convert to HTML (default) %% #{format => ast} - Return AST structure -spec conv(string() | document(), map()) -> string() | document(). conv(Input, #{format := ast}) -> conv_ast(Input); conv(Input, #{format := html}) -> conv_html(Input). %% @doc Convert Markdown string to AST -spec conv_ast(string()) -> document(). conv_ast(String) when is_list(String) -> Lex = lex(String), UntypedLines = make_lines(Lex), {TypedLines, Refs} = type_lines(UntypedLines), erlmd_ast:build(TypedLines, Refs). %% @doc Convert to HTML (accepts AST or Markdown string) -spec conv_html(document() | string()) -> string(). conv_html(AST) when is_record(AST, document) -> erlmd_html:render(AST); conv_html(String) when is_list(String) -> conv_html(conv_ast(String)). %% @doc Convert UTF-8 encoded Markdown to HTML -spec conv_utf8(list()) -> list(). conv_utf8(Utf8) -> Str = xmerl_ucs:from_utf8(Utf8), Res = conv(Str), % Uses default HTML output xmerl_ucs:to_utf8(Res). %% @doc Convert Markdown file to HTML file conv_file(FileIn, FileOut) -> case file:open(FileIn, [read]) of {ok, Device} -> Input = get_all_lines(Device,[]), Output = conv(Input), % Uses default HTML output write(FileOut, Output); _ -> error end. get_all_lines(Device, Accum) -> case io:get_line(Device,"") of eof -> file:close(Device), Accum; Line -> get_all_lines(Device,Accum ++ Line) end. write(File, Text) -> _Return=filelib:ensure_dir(File), case file:open(File, [write]) of {ok, Id} -> io:fwrite(Id, "~s~n", [Text]), file:close(Id); _ -> error end. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% Make the lines from the raw tokens %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% make_lines(Tokens) -> ml1(Tokens, [], []). ml1([], [], A2) -> reverse(A2); ml1([], A1, A2) -> ml1([], [], [reverse(A1) | A2]); ml1([{{lf, _}, _} = H | T], A1, A2) -> ml1(T, [], [ml2(H, A1) | A2]); ml1([H | T], A1, A2) -> ml1(T, [H | A1], A2). ml2(H, List) -> reverse([H | List]). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%% Process the lines and give each line a type. The valid types are: %%% * normal line %%% * reference style links %%% * reference style images %%% * special line types %%% - blank %%% - SETEXT header lines %%% - ATX header lines %%% - unordered lists (including code blocks) %%% - ordered lists (including code blocks) %%% - blockquotes %%% - code blocks %%% - horizontal rules %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% type_lines(Lines) -> {Refs, TypedLines} = t_l1(Lines, [], []), % io:format("TypedLines before stripping ~p~n", [TypedLines]), {strip_lines(TypedLines), Refs}. t_l1([], A1, A2) -> {A1, reverse(A2)}; %% this clause extracts URL and Image refs %% (it is the only one that uses A1 and A2... %% inlines can have up to 3 spaces before it t_l1([[{{ws, sp}, _}, {{inline, open}, _} | T1] = H | T2], A1, A2) -> t_inline(H, T1, T2, A1, A2); t_l1([[{{ws, tab}, _}, {{inline, open}, _} | _] = H | T2], A1, A2) -> t_l1(T2, A1, [type_ws(H) | A2]); t_l1([[{{ws, comp}, W}, {{inline, open}, _} | T1] = H | T2], A1, A2) -> case gt(W, 4) of {true, _R} -> t_l1(T2, A1, [type_ws(H) | A2]); false -> t_inline(H, T1, T2, A1, A2) end; t_l1([[{{inline, open}, _} | T1] = H | T2], A1, A2) -> t_inline(H, T1, T2, A1, A2); %% types setext lines t_l1([[{{md, eq}, _} | _T] = H | T], A1, A2) -> t_l1(T, A1, [type_setext_h1(H) | A2]); %% NOTE 1: generates a ul as the default not a normal line %% NOTE 2: depending on the context this might generate an
"} ,R ,
{tags, "\n\n"} | []])
end.
is_double_indent(List) -> is_double_indent1(List, 0).
%% double indent is any combination of tabs and spaces that add
%% up to 8
is_double_indent1([], _N) -> false;
is_double_indent1(Rest, N) when N > 7 -> {true, Rest};
is_double_indent1([{{ws, sp}, _} | T], N) -> is_double_indent1(T, N + 1);
is_double_indent1([{{ws, tab}, _} | T], N) -> is_double_indent1(T, N + 4);
is_double_indent1(_List, _N) -> false.
%% All ref processing can ignore the original values 'cos those
%% have already been captured at a higher level
snip_ref(List) ->
case get_id(List) of
{[{_, Id}], Rest} -> {_Rest2, Ref, Title} = parse_inline(Rest),
Ref2 = trim(Ref),
Rs = htmlencode(make_plain_str(Ref2)),
Ts = make_plain_str(Title),
{inlineref, {Id, {Rs, Ts}}};
normal -> normal
end.
get_id(List) -> g_id1(List, []).
g_id1([], _Acc) -> normal;
g_id1([{{inline, close}, _},
{{punc, colon}, _}, {{ws, _}, _}
| T], Acc) -> {reverse(Acc), T};
g_id1([H | T], Acc) -> g_id1(T, [H | Acc]).
parse_inline(List) -> p_in1(List, []).
%% snip off the terminal linefeed (if there is one...)
p_in1([{{lf, _}, _} | []], A) -> {[], reverse(A), []};
p_in1([], A) -> {[], reverse(A), []};
%% brackets can be escaped
p_in1([{{punc, bslash}, _},
{bra, _} = B | T], A) -> p_in1(T, [B | A]);
p_in1([{{punc, bslash}, _},
{ket, _} = B | T], A) -> p_in1(T, [B | A]);
p_in1([{{punc, bslash}, _},
{{punc, doubleq}, _} = Q | T], A) -> p_in1(T, [Q | A]);
p_in1([{{punc, bslash}, _},
{{punc, singleq}, _} = Q | T], A) -> p_in1(T, [Q | A]);
%% these clauses capture the start of the title...
p_in1([{{punc, doubleq}, _} | T], A) -> p_in2(T, reverse(A), doubleq, []);
p_in1([{{punc, singleq}, _} | T], A) -> p_in2(T, reverse(A), singleq, []);
p_in1([{bra, _} | T], A) -> p_in2(T, reverse(A), brackets, []);
p_in1([{ket, _} | T], A) -> {T, reverse(A), []};
p_in1([H | T], A) -> p_in1(T, [H | A]).
%% this gets titles in single and double quotes
%% the delimiter type is passed in as 'D'
p_in2([], Url, _D, A) -> {[], Url, flatten(reverse(A))};
%% brackets can be escaped
p_in2([{{punc, bslash}, _},
{bra, _} = B | T], Url, D, A) -> p_in2(T, Url, D, [B | A]);
p_in2([{{punc, bslash}, _},
{ket, _} = B | T], Url, D, A) -> p_in2(T, Url, D, [B | A]);
%% quotes can be escaped
p_in2([{{punc, bslash}, _},
{{punc, doubleq}, _}= Q | T], Url, D, A) -> p_in2(T, Url, D, [Q | A]);
p_in2([{{punc, bslash}, _},
{{punc, singleq}, _} = Q | T], Url, D, A) -> p_in2(T, Url, D, [Q | A]);
%% these clauses capture the end of the title and drop the delimiter...
p_in2([{{punc, doubleq}, _} | T], Url, doubleq, A) -> p_in2(T, Url, none, A);
p_in2([{{punc, singleq}, _} | T], Url, singleq, A) -> p_in2(T, Url, none, A);
p_in2([{ket, _} | T], Url, brackets, A) -> p_in2(T, Url, none, A);
%% terminator clause
p_in2([{ket, _} | T], Url, none, A) -> {T, Url, flatten(reverse(A))};
%% this clause silently discards stuff after the delimiter...
p_in2([_H | T], Url, none, A) -> p_in2(T, Url, none, [A]);
p_in2([H | T], Url, D, A) -> p_in2(T, Url, D, [H | A]).
trim(String) -> trim_left(trim_right(String)).
trim_right(String) -> reverse(trim_left(reverse(String))).
trim_left([{{ws, _}, _} | T]) -> trim_left(T);
trim_left([[] | T]) -> trim_left(T);
trim_left(List) -> List.
%% end of ref processing
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% Build the Lexed Token List
%%% This is a two part lexer, first it chunks the input and then on the second
%%% pass it gathers it into lines and types the lines
%%%
%%% NOTE that there are two different styles of processing lines:
%%% * markdown transformed
%%% * block
%%% inside block processing the whole text is dumped and just url encoded
%%% and the original text is always maintained during the lexing/parsing
%%% so that it can be recreated if the context requires it...
%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lex(String) -> merge_ws(l1(String, [], [])).
merge_ws(List) -> m_ws1(List, []).
m_ws1([], Acc) -> reverse(Acc);
m_ws1([{{ws, _}, W1}, {{ws, _}, W2} | T], Acc) ->
m_ws1([{{ws, comp}, W1 ++ W2} | T], Acc);
m_ws1([H | T], Acc) -> m_ws1(T, [H | Acc]).
%% this is the terminal head which ends the parsing...
l1([], [], A2) -> flatten(reverse(A2));
l1([], A1, A2) -> l1([], [], [l2(A1) | A2]);
%% these two heads capture opening and closing tags
l1([$<, $/|T], A1, A2) -> {Tag, NewT} = closingdiv(T, []),
l1(NewT, [], [Tag, l2(A1) | A2]);
l1([$< | T], A1, A2) -> {Tag, NewT} = openingdiv(T),
l1(NewT, [], [Tag , l2(A1) | A2]);
%% these clauses are the normal lexer clauses
l1([$= | T], A1, A2) -> l1(T, [], [{{md, eq}, "="}, l2(A1) | A2]);
l1([$- | T], A1, A2) -> l1(T, [], [{{md, dash}, "-"}, l2(A1) | A2]);
l1([$# | T], A1, A2) -> l1(T, [], [{{md, atx}, "#"}, l2(A1) | A2]);
l1([$> | T], A1, A2) -> l1(T, [], [{{md, gt}, ">"}, l2(A1) | A2]);
l1([$+ | T], A1, A2) -> l1(T, [], [{{md, plus}, "+"}, l2(A1) | A2]);
l1([$* | T], A1, A2) -> l1(T, [], [{{md, star}, "*"}, l2(A1) | A2]);
l1([$_ | T], A1, A2) -> l1(T, [], [{{md, underscore}, "_"}, l2(A1) | A2]);
l1([$1 | T], A1, A2) -> l1(T, [], [{num, "1"}, l2(A1) | A2]);
l1([$2 | T], A1, A2) -> l1(T, [], [{num, "2"}, l2(A1) | A2]);
l1([$3 | T], A1, A2) -> l1(T, [], [{num, "3"}, l2(A1) | A2]);
l1([$4 | T], A1, A2) -> l1(T, [], [{num, "4"}, l2(A1) | A2]);
l1([$5 | T], A1, A2) -> l1(T, [], [{num, "5"}, l2(A1) | A2]);
l1([$6 | T], A1, A2) -> l1(T, [], [{num, "6"}, l2(A1) | A2]);
l1([$7 | T], A1, A2) -> l1(T, [], [{num, "7"}, l2(A1) | A2]);
l1([$8 | T], A1, A2) -> l1(T, [], [{num, "8"}, l2(A1) | A2]);
l1([$9 | T], A1, A2) -> l1(T, [], [{num, "9"}, l2(A1) | A2]);
l1([$0 | T], A1, A2) -> l1(T, [], [{num, "0"}, l2(A1) | A2]);
l1([$. | T], A1, A2) -> l1(T, [], [{{punc, fullstop}, "."}, l2(A1) | A2]);
l1([$: | T], A1, A2) -> l1(T, [], [{{punc, colon}, ":"}, l2(A1) | A2]);
l1([$' | T], A1, A2) -> l1(T, [], [{{punc, singleq}, "'"}, l2(A1) | A2]); %'
l1([$" | T], A1, A2) -> l1(T, [], [{{punc, doubleq}, "\""}, l2(A1) | A2]); %"
l1([$` | T], A1, A2) -> l1(T, [], [{{punc, backtick}, "`"}, l2(A1) | A2]); %"
l1([$! | T], A1, A2) -> l1(T, [], [{{punc, bang}, "!"}, l2(A1) | A2]); %"
l1([$\\ | T], A1, A2) -> l1(T, [], [{{punc, bslash}, "\\"}, l2(A1) | A2]); %"
l1([$/ | T], A1, A2) -> l1(T, [], [{{punc, fslash}, "/"}, l2(A1) | A2]); %"
l1([$( | T], A1, A2) -> l1(T, [], [{bra, "("}, l2(A1) | A2]);
l1([$) | T], A1, A2) -> l1(T, [], [{ket, ")"}, l2(A1) | A2]);
l1([$[ | T], A1, A2) -> l1(T, [], [{{inline, open}, "["}, l2(A1) | A2]);
l1([$] | T], A1, A2) -> l1(T, [], [{{inline, close}, "]"}, l2(A1) | A2]);
%% note there is a special 'whitespace' {{ws, none}, ""} which is used to generate non-space
%% filling whitespace for cases like '*bob* is great' which needs a non-space filling
%% whitespace prepended to trigger emphasis so it renders as "bob is great...
%% that 'character' doesn't exist so isn't in the lexer but appears in the parser
l1([?SPACE | T], A1, A2) -> l1(T, [], [{{ws, sp}, " "}, l2(A1) | A2]);
l1([?TAB | T], A1, A2) -> l1(T, [], [{{ws, tab}, "\t"}, l2(A1) | A2]);
l1([?NBSP | T], A1, A2) -> l1(T, [], [{{ws, sp}, " "}, l2(A1) | A2]);
l1([?CR, ?LF | T], A1, A2) -> l1(T, [], [{{lf, crlf}, [?CR , ?LF]}, l2(A1) | A2]);
l1([?LF | T], A1, A2) -> l1(T, [], [{{lf, lf}, [?LF]}, l2(A1) | A2]);
%% l1([?CR | T], A1, A2) -> l1(T, [], [{{lf, cr}, [?CR]}, l2(A1) | A2]);
%% this final clause accumulates line fragments
l1([H|T], A1, A2) -> l1(T, [H |A1] , A2).
l2([]) -> [];
l2(List) -> {string, flatten(reverse(List))}.
%% need to put in regexes for urls and e-mail addies
openingdiv(String) ->
case get_url(String) of
{{url, URL}, R1} -> {{url, URL}, R1};
not_url ->
case get_email_addie(String) of
{{email, EM}, R2} -> {{email, EM}, R2};
not_email -> openingdiv1(String, [])
end
end.
% dumps out a list if it is not an opening div
openingdiv1([], Acc) -> {flatten([{{punc, bra}, "<"}
| lex(reverse(Acc))]), []};
openingdiv1([$/,$>| T], Acc) -> Acc2 = flatten(reverse(Acc)),
Acc3 = string:to_lower(Acc2),
[Tag | _T] = string:tokens(Acc3, " "),
{{{{tag, self_closing}, Tag}, "<"
++ Acc2 ++ "/>"}, T};
%% special for non-tags
openingdiv1([$>| T], []) -> {[{{punc, bra}, "<"},
{{punc, ket}, ">"}], T};
openingdiv1([$>| T], Acc) -> Acc2 = flatten(reverse(Acc)),
Acc3 = string:to_lower(Acc2),
[Tag | _T] = string:tokens(Acc3, " "),
{{{{tag, open}, Tag}, "<"
++ Acc2 ++ ">"}, T};
openingdiv1([H|T], Acc) -> openingdiv1(T, [H | Acc]).
% dumps out a list if it is not an closing div
closingdiv([], Acc) -> {flatten([{{punc, bra}, "<"},
{{punc, fslash}, "/"}
| lex(reverse(Acc))]), []};
closingdiv([$>| T], Acc) -> Acc2 = flatten(reverse(Acc)),
Acc3 = string:to_lower(Acc2),
[Tag | _T] = string:tokens(Acc3, " "),
{{{{tag, close}, Tag}, ""
++ Acc2 ++ ">"}, T};
closingdiv([H|T], Acc) -> closingdiv(T, [H | Acc]).
get_url(String) -> HTTP_regex = "^(H|h)(T|t)(T|t)(P|p)(S|s)*://",
case re:run(String, HTTP_regex, [unicode]) of
nomatch -> not_url;
{match, _} -> get_url1(String, [])
end.
get_url1([], Acc) -> URL = flatten(reverse(Acc)),
{{url, URL}, []};
% allow escaped kets
get_url1([$\\, $> | T], Acc) -> get_url1(T, [$>, $\\ | Acc]);
get_url1([$> | T], Acc) -> URL = flatten(reverse(Acc)),
{{url, URL}, T};
get_url1([H | T], Acc) -> get_url1(T, [H | Acc]).
get_email_addie(String) ->
Snip_regex = ">",
case re:run(String, Snip_regex, [unicode]) of
nomatch -> not_email;
{match, [{N, _} | _T]} ->
{Possible, [$> | T]} = lists:split(N, String),
EMail_regex = "[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+"
++ "(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*"
++ "@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+"
++ "(?:[a-zA-Z]{2}|com|org|net|gov|mil"
++ "|biz|info|mobi|name|aero|jobs|museum)",
case re:run(Possible, EMail_regex, [unicode]) of
nomatch -> not_email;
{match, _} -> {{email, Possible}, T}
end
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%
%%% Internal functions
%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
make_plain_str(List) -> m_plain(List, []).
m_plain([], Acc) -> flatten(reverse(Acc));
m_plain([{{ws, none}, none} | T], Acc) -> m_plain(T, [" " | Acc]);
m_plain([{_, Str} | T], Acc) -> m_plain(T, [Str | Acc]).
%% convert ascii into html characters
htmlencode(List) ->
htmlencode(List, []).
htmlencode([], Acc) ->
lists:flatten(lists:reverse(Acc));
htmlencode([$& | Rest], Acc) -> htmlencode(Rest, ["&" | Acc]);
htmlencode([$< | Rest], Acc) -> htmlencode(Rest, ["<" | Acc]);
htmlencode([$> | Rest], Acc) -> htmlencode(Rest, [">" | Acc]);
htmlencode([160 | Rest], Acc) -> htmlencode(Rest, [" " | Acc]);
htmlencode([Else | Rest], Acc) -> htmlencode(Rest, [Else | Acc]).