diff -ur v2/ezmd.py v3/ezmd.py --- v2/ezmd.py 2019-09-23 04:47:56.000000000 +0900 +++ v3/ezmd.py 2019-09-24 00:19:15.000000000 +0900 @@ -5,8 +5,7 @@ import nkf heads = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9' ] -end = '$$$_end_$$$' -modes = heads + [ 'p', 'pre', end ] +modes = heads + [ 'p', 'pre', 'ul' ] def is_mode_switch(s, mode): if mode == 'pre': @@ -15,6 +14,68 @@ next_mode = lambda s: 'p' if s == '/' else s +def strip_head(s): + while s and s[0] in (' ', '\t'): + s = s[1:] + return s + +def strip_tail(s): + while s and s[-1] in (' ', '\t'): + s = s[:-1] + return s + +def idt_cnt(s): + i = 0 + while s and s[0] in (' ', '\t'): + i += 1 + s = s[1:] + return (i, s) + +def esc_join(lst): + res = [] + for s in lst: + if res and res[-1][-1] == '\\': + t = res[-1][:-1] + res[-1] = strip_tail(t) + strip_head(s) + else: + res.append(s) + return res + +def do_mode_ul(buf, res): + buf = esc_join(buf) + buf = list( filter( lambda s: s.strip(), buf ) ) + buf = list( map(idt_cnt, buf) ) # (i, s) + + (stk, lsts) = ( [], [] ) + + def push(i, s): + lst = [s] + ( stk[-1][1] if stk else lsts ).append(lst) + stk.append( (i, lst) ) + + def buf_to_stk_lsts(i_s): + (i, s) = i_s + if stk: + (ci, clst) = stk[-1] + if i > ci: + push(i, s) + elif i < ci: + stk.pop() + buf_to_stk_lsts(i_s) + else: # i == ci + clst.append(s) + else: + push(i, s) + + list( map(buf_to_stk_lsts, buf) ) # make lists + + def lst_to(lst): + f = lambda o: lst_to(o) if type(o) == list else {'li /': o} + lst = list( map(f, lst) ) + return { 'ul': lst } + + res.extend( list( map(lst_to, lsts) ) ) + def do_mode(mode, buf, res): if mode in heads: buf = list( map( lambda s: s.strip(), buf ) ) @@ -42,12 +103,14 @@ if buf: s = '\n'.join(buf) + '\n' res.append( { 'pre': s } ) + elif mode == 'ul': + do_mode_ul(buf, res) def ezmd(lst): - lst = ['p'] + lst + [end] + lst = ['p'] + lst (buf, res) = ( [], [] ) mode = '' - while mode != end: + while lst: s = lst.pop(0) if is_mode_switch(s, mode): do_mode(mode, buf, res) @@ -55,6 +118,7 @@ buf = [] elif s != mode: buf.append(s) + do_mode(mode, buf, res) return res def yaml_dump(o):