diff -ur v1/ezmd.py v2/ezmd.py --- v1/ezmd.py 2019-09-22 11:49:17.000000000 +0900 +++ v2/ezmd.py 2019-09-23 04:47:56.000000000 +0900 @@ -1,11 +1,19 @@ #!/usr/bin/env python import yaml +import six import nkf heads = [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'h7', 'h8', 'h9' ] end = '$$$_end_$$$' -modes = heads + [ 'p', end ] +modes = heads + [ 'p', 'pre', end ] + +def is_mode_switch(s, mode): + if mode == 'pre': + return s == '/' + return s in modes and s != mode + +next_mode = lambda s: 'p' if s == '/' else s def do_mode(mode, buf, res): if mode in heads: @@ -26,20 +34,40 @@ lst = [] for lst in lsts: res.append( { 'p': lst } ) + elif mode == 'pre': + while buf and buf[0] == '': + buf.pop(0) + while buf and buf[-1] == '': + buf.pop() + if buf: + s = '\n'.join(buf) + '\n' + res.append( { 'pre': s } ) + def ezmd(lst): lst = ['p'] + lst + [end] (buf, res) = ( [], [] ) mode = '' while mode != end: s = lst.pop(0) - if s in modes and s != mode: + if is_mode_switch(s, mode): do_mode(mode, buf, res) - mode = s + mode = next_mode(s) buf = [] - else: + elif s != mode: buf.append(s) return res +def yaml_dump(o): + def represent_str(dumper, instance): + tag = 'tag:yaml.org,2002:str' + style = '|' if '\n' in instance else None + return dumper.represent_scalar( tag, instance, style=style ) + + for typ in [ str ] + ( [ unicode ] if six.PY2 else [] ): + yaml.add_representer(typ, represent_str) + + return yaml.dump( o, default_flow_style=False, allow_unicode=True, encoding='utf-8' ) + if __name__ == "__main__": b = nkf.get_stdin() (s, nkf_opt) = nkf.to_str(b) @@ -47,7 +75,7 @@ lst = ezmd(lst) - u8 = yaml.dump( lst, default_flow_style=False, allow_unicode=True, encoding='utf-8' ) + u8 = yaml_dump(lst) b = nkf.cvt(u8, nkf_opt) if nkf_opt != '-u' else u8 nkf.put_stdout(b) # EOF