Esempio n. 1
0
 def _pre_save(cls, data):
     from par.bootstrap_ext import blocks
     from par.md import parseHtml
     
     data['html'] = parseHtml(data['content'], block_callback=blocks,
         tag_class={'table':'table table-bordered', 'pre':'prettyprint'},
     )
Esempio n. 2
0
File: md2html.py Progetto: lowks/par
def test_html(text):
    from par.bootstrap_ext import blocks

    def parseHtml(text, template=None, tag_class=None, block_callback=None, init_callback=None):
        template = template or ''
        tag_class = tag_class or {}
        g = MarkdownGrammar()
        resultSoFar = []
        result, rest = g.parse(text, resultSoFar=resultSoFar, skipWS=False
#            ,root=g['dl_dd_2']
            )
        v = MarkdownHtmlVisitor(template, tag_class, g, block_callback=block_callback, init_callback=init_callback)
        print(result[0].render())
        return v.template(result)

    x = parseHtml(text, '%(body)s', block_callback=blocks, tag_class={'table':'table'})
    print(str(x, 'utf8').encode('gbk'))
Esempio n. 3
0
def createMDHtmlViewWindow(win, side, document):
    from par.md import parseHtml
    
    dispname = document.getShortFilename()
    obj = None
    for pagename, panelname, notebook, page in win.panel.getPages():
        if is_mdhtmlview(page, document):
            obj = page
            break

    if not obj:
        if win.document.documenttype == 'texteditor':
            text = parseHtml(document.GetText().encode('utf-8'), template=md_html_template)
            if text:
                page = MDHtmlView(win.panel.createNotebook(side), text, document)
                win.panel.addPage(side, page, dispname)
                win.panel.setImageIndex(page, 'html')
                return page
    return obj
Esempio n. 4
0
def createMDHtmlViewWindow(win, side, document):
    from par.md import parseHtml

    dispname = document.getShortFilename()
    obj = None
    for pagename, panelname, notebook, page in win.panel.getPages():
        if is_mdhtmlview(page, document):
            obj = page
            break

    if not obj:
        if win.document.documenttype == "texteditor":
            text = parseHtml(document.GetText().encode("utf-8"), template=md_html_template)
            if text:
                page = MDHtmlView(win.panel.createNotebook(side), text, document)
                win.panel.addPage(side, page, dispname)
                win.panel.setImageIndex(page, "html")
                return page
    return obj
Esempio n. 5
0
 def f():
     try:
         text = parseHtml(win.GetText().encode('utf-8'), template=md_html_template)
         page.refresh(text)
     finally:
         page.rendering = False
Esempio n. 6
0
    def handle(self, options, global_options, *args):
        from utils import extract_dirs, copy_dir
        from par.bootstrap_ext import blocks
        from md_ext import new_code_comment, toc
        from functools import partial

        if not conf:
            log.error('Current directory is not a parm project')
            sys.exit(1)
            
        #make output directory
        if not os.path.exists(options.directory):
            print 'Make directories [%s]' % options.directory
            os.makedirs(options.directory)
            
        #copy static files
        print 'Copy default templates/static to %s' % options.directory
        extract_dirs('parm', 'templates/static', 
            os.path.join(options.directory, 'static'))
            
        #create source directory
        source_path = os.path.join(options.directory, 'source')
        if not os.path.exists(source_path):
            print 'Make directories [%s]' % source_path
            os.makedirs(source_path)
        
        #compile markdown files
        files = list(os.listdir('.'))
        headers = {}
        relations = {}
        
        #prepare block process handlers
        blocks['code-comment'] = new_code_comment
        blocks['toc'] = partial(toc, headers=headers, relations=relations)

        output_files = {}
        
        while 1:
            if not files:
                break
            
            path = files.pop(0)
            fname, ext = os.path.splitext(path)
            if os.path.isfile(path) and (ext in conf.source_suffix):
                if fname == conf.master_doc and len(files)>1:
                    files.append(path)
                    continue
                
                with open(path) as f:
                    
                    data = {}
                    data['conf'] = conf
                    
                    #process markdown convert
                    data['body'] = parseHtml(f.read(), 
                        '', 
                        conf.tag_class,
                        block_callback=blocks)
                    page_nav = relations.get(fname, {})
                    data['prev'] = page_nav.get('prev', {})
                    data['next'] = page_nav.get('next', {})
                    data['source'] = '<a href="source/%s">%s</a>' % (path, conf.download_source)
                    
                    #parse header from text
                    h = headers.setdefault(path, [])
                    title = self.parse_headers(path, data['body'], h)
                    if title:
                        data['title'] = unicode(title, 'utf8') + ' - ' + conf.project 
                    else:
                        print 'Error: Heading 1 not found in file %s' % path
                        continue

                    #convert conf attributes to data
                    for k in dir(conf):
                        if not k.startswith('_'):
                            data[k] = getattr(conf, k)
                       
                    #process template
                    template_file = conf.templates.get(fname, conf.templates.get('*', 'default.html'))
                    hfilename = os.path.join(options.directory, fname + '.html').replace('\\', '/')
                    with open(hfilename, 'wb') as fh:
                        print 'Convert %s to %s' % (path, hfilename)
                        fh.write(template.template_file(template_file, data, dirs=['_build']))
                
                    output_files[fname] = hfilename
                    #copy source file
                    sfilename = os.path.join(source_path, path)
                    shutil.copy(path, sfilename)
                    
            elif os.path.isdir(path) and not path.startswith('_'):
                print 'Copy %s to %s' % (path, options.directory)
                copy_dir(path, os.path.join(options.directory, path))
                
        prev_next_template_top = """{{if prev:}}<div class="chapter-prev chapter-top">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-top">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        prev_next_template_down = """{{if prev:}}<div class="chapter-prev chapter-down">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-down">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        
        for name, f in output_files.items():
            text = open(f, 'rb').read()
            
            x = relations.get(name, {})
            data = {}
            data['prev'] = x.get('prev', {})
            data['next'] = x.get('next', {})
            
            prev_next_text_top = template.template(prev_next_template_top, data)
            prev_next_text_down = template.template(prev_next_template_down, data)
            text = text.replace('<!-- prev_next_top -->', prev_next_text_top)
            text = text.replace('<!-- prev_next_down -->', prev_next_text_down)
            with open(f, 'wb') as fh:
                fh.write(text)
Esempio n. 7
0
File: md2html.py Progetto: lowks/par
def main(text):
    from par.md import parseHtml, parseText
    print(parseHtml(text, template, tag_class).encode('utf8'))
Esempio n. 8
0
    def handle(self, options, global_options, *args):
        from .utils import extract_dirs, copy_dir, walk_dirs, import_attr, json_dumps
        from .md_ext import new_code_comment, toc, include
        from .mermaid_ext import mermaid
        from functools import partial
        from shutil import copy2

        if not conf:
            log.error('Current directory is not a parm project')
            sys.exit(1)
            
        #make output directory
        if not os.path.exists(options.directory):
            print('Make directories [%s]' % options.directory)
            os.makedirs(options.directory)
            
        #get theme config
        theme = getattr(conf, 'theme', 'semantic')
        print('Using theme [%s]' % theme)
        
        #copy static files
        print('Copy %s to %s' % ('theme/%s/static' % theme, os.path.join(options.directory, 'static')))
        extract_dirs('parm', 'templates/theme/%s/static' % theme, 
            os.path.join(options.directory, 'static'))
            
        dst_dir = os.path.normpath(os.path.abspath(options.directory)).replace('\\', '/') + '/'
        
        #process exclude
        if os.path.exists('exclude.txt'):
            _exclude = open('exclude.txt').read().splitlines()
        else:
            _exclude = []
        _exclude.extend([options.directory, conf.template_dirs])
        files = list(walk_dirs('.', exclude=_exclude))
        headers = {}
        relations = {}
        
        #prepare block process handlers
        blocks = {}
        blocks['code-comment'] = new_code_comment
        blocks['toc'] = partial(toc, headers=headers, relations=relations)
        blocks['include'] = include
        blocks['mermaid'] = mermaid

        #according theme import different blocks
        mod_path = 'par.%s_ext.blocks' % theme
        b = import_attr(mod_path)
        blocks.update(b)
        
        output_files = {}
        template_dirs = conf.template_dirs
        
        while 1:
            if not files:
                break
            
            path = files.pop(0)
            fname, ext = os.path.splitext(path)
            if os.path.isfile(path) and (ext in conf.source_suffix):
                if fname == conf.master_doc and len(files)>0:
                    files.append(path)
                    continue
                
                with open(path, encoding=conf.encoding) as f:
                    
                    data = {}
                    data['conf'] = conf
                    data['json_dumps'] = json_dumps
                    
                    #process markdown convert
                    data['body'] = parseHtml(f.read(), 
                        '', 
                        conf.tag_class,
                        block_callback=blocks,
                        filename=path,
                        visitor=MDVisitor)
                    page_nav = relations.get(fname, {})
                    data['prev'] = page_nav.get('prev', {})
                    data['next'] = page_nav.get('next', {})
                    data['relpath'] = '.' * (path.count('/')+1)
                    data['source'] = '<a href="%s/%s">%s</a>' % (data['relpath'], path, conf.download_source)
                    
                    #parse header from text
                    h = headers.setdefault(path, [])
                    title = self.parse_headers(path, data['body'], h)
                    if title:
                        data['title'] = title + ' - ' + conf.project
                    else:
                        if fname != conf.master_doc:
                            print('Error: Heading 1 not found in file %s' % path)
                            continue
                        else:
                            data['title'] = conf.project

                    #convert conf attributes to data
                    for k in dir(conf):
                        if not k.startswith('_'):
                            data[k] = getattr(conf, k)
                       
                    #process template
                    template_file = conf.templates.get(fname, conf.templates.get('*', 'default.html'))
                    hfilename = os.path.join(options.directory, fname + '.html').replace('\\', '/')
                    fix_dir(hfilename)
                    with open(hfilename, 'w', encoding=conf.encoding) as fh:
                        print('Convert %s to %s' % (path, hfilename))
                        fh.write(template.template_file(template_file, data, dirs=[template_dirs]))
                        copy2(path, os.path.join(options.directory, path))
                    output_files[fname] = hfilename
                    
            else:
                if os.path.isdir(path):
                    dpath = os.path.join(dst_dir, path)
                    if not os.path.exists(dpath):
                        print('Makedir %s' % os.path.join(dst_dir, path))
                        os.makedirs(dpath)
                else:
                    print('Copy %s to %s' % (path, os.path.join(dst_dir, path)))
                    shutil.copy(path, os.path.join(dst_dir, path))
                
        prev_next_template_top = """{{if prev:}}<div class="chapter-prev chapter-top">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-top">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        prev_next_template_down = """{{if prev:}}<div class="chapter-prev chapter-down">
    <a prev-chapter href="{{<< prev['link']}}"><i class="icon-arrow-left"></i> {{=prev['title']}}</a>
</div>{{pass}}
{{if next:}}<div class="chapter-next chapter-down">
    <a next-chapter href="{{<< next['link']}}">{{=next['title']}} <i class="icon-arrow-right"></i></a>
</div>{{pass}}"""
        
        for name, f in output_files.items():
            text = open(f, encoding=conf.encoding).read()
            
            x = relations.get(name, {})
            data = {}
            data['prev'] = x.get('prev', {})
            if data['prev']:
                relpath = '.' * (data['prev']['link'].count('/')+1)
                data['prev']['link'] = relpath + '/' + data['prev']['link']
            data['next'] = x.get('next', {})
            if data['next']:
                relpath = '.' * (data['next']['link'].count('/')+1)
                data['next']['link'] = relpath + '/' + data['next']['link']
            
            prev_next_text_top = template.template(prev_next_template_top, data)
            prev_next_text_down = template.template(prev_next_template_down, data)
            text = text.replace('<!-- prev_next_top -->', prev_next_text_top)
            text = text.replace('<!-- prev_next_down -->', prev_next_text_down)
            with open(f, 'w', encoding=conf.encoding) as fh:
                fh.write(text)
Esempio n. 9
0
 def f():
     try:
         text = parseHtml(win.GetText().encode("utf-8"), template=md_html_template)
         page.refresh(text)
     finally:
         page.rendering = False