def run(): src = editor.value if storage: storage["markdown_src"]=src mk,scripts = markdown.mark(src) doc['console'].html = mk
def run(): src = editor.value if storage: storage["markdown_src"] = src mk,scripts = markdown.mark(src) doc['console'].html = mk
def save(): req = ajax.ajax() req.open("POST", "/save/", True) req.bind("complete", save_cb) presentation[current] =document["edit"].value req.send(repr(presentation)) html_str, scripts = markdown.mark(presentation[current]) document["present"].html = html_str
def test_browser_markdown(): from browser import document as doc from browser import markdown src = "" # instead of open(url).read() mk, scripts = markdown.mark(src) doc['zone'].html = mk for script in scripts: exec(script, globals())
def render_lesson(req): """Display the given markdown document as a lesson.""" url = req.responseURL if req.status == 200: source = req.text else: source = f"""# Error There was an error loading the lesson {url}. HTTP Error {req.status} """ interactions = [] def match_code(mo): obj_id = f'{url}-{len(interactions)}' mode, content = mo.groups() if mode not in ('repl', 'python', 'exercises', 'exercise'): return mo.group(0) if mode == 'exercise': mode += 's' content = content.rstrip() interactions.append((obj_id, mode, content)) if mode in ('repl', 'python'): return f'<textarea id="{obj_id}"></textarea>' else: return f'<ul class="exercises" id="{obj_id}"></ul>' source = FENCE_RE.sub( match_code, source, ) mk, scripts = markdown.mark(source) container = document['lesson'] container.class_name = '' container.html = window.twemoji.parse(mk) last_ed = None for id, mode, content in interactions: el = document[id] if mode == 'repl': #el.text = REPL_RE.sub('', content.rstrip()) last_ed = Editor(el, content, repl=True) elif mode == 'python': last_ed = Editor(el, content) elif mode == 'exercises': last_ed.add_exercises(content, id)
def md_to_html(md): # https://www.brython.info/static_doc/en/markdown.html html, _ = markdown.mark(md) # this parser had some spurious paragraphs # Only strip starting and trailing ones if html.startswith("<p>"): html = html[3:] if html.endswith("</p>"): html = html[:-4] if html.endswith("<p></p>"): html = html[:-7] return html
def add_exercises(self, source, id): """Attach exercises to this editor component.""" self.exercises = source self.exercise_items = [] triple_quoted = TRIPLE_QUOTES_RE.findall(source) for docstring in triple_quoted: lines = docstring.strip().splitlines() mk, scripts = markdown.mark('\n'.join(ln.strip() for ln in lines)) img = '<img alt="Unsolved" src="static/svg/unsolved.svg">' item = html.LI(**{'class': 'exercise'}) item.html = img + window.twemoji.parse(mk) document[id] <= item self.exercise_items.append(item)
def get_cb(request): global presentation global current presentation = eval(request.text) if current in presentation: document["edit"].value = presentation[current] html_str, scripts = markdown.mark(presentation[current]) document["present"].html = html_str else: print("nope") document['selector'].clear() for i in presentation: a = html.A(str(i), style = {'cursor':'pointer','font-size':"150%"}) a.bind("click", select_cb) document['selector'] <= a document['selector'] <= " "
def get_cb_all(request): # global presentation presentation = eval(request.text) print([a for a in presentation]) print(len(presentation)) for k,v in presentation.items(): print (k, len(v)) presentation_single = "\n\n\n".join([txt for a,txt in presentation.items()]) print(len(presentation_single)) html_str, scripts = markdown.mark(presentation_single) document["contained"].clear() # document["present"].html = html_str document["contained"].style = {'display':"inline"} # document["contained"].html = html_str div = html.DIV(html_str) # div <= html_str div.id = "present" document["contained"] <= div
def show_page(slideshow, zone, page_num): # if table of contents is not empty, add it if slideshow.contents: toc = html.SELECT(name="toc") toc.bind( 'change', lambda ev: show_page( slideshow, zone, int(ev.target.options[ev.target.selectedIndex].value))) for content in slideshow.contents: toc <= html.OPTION( content[0], value=content[1], selected=page_num >= content[1]) slideshow.page_num = int(page_num) zone.clear() body = html.DIV() body.html = markdown.mark(slideshow.pages[page_num])[0] if slideshow.contents: body = html.DIV(toc + body) footer = html.DIV(Id="footer") if slideshow.title: footer <= html.DIV(slideshow.title, style=dict(display='inline')) if slideshow.show_page_num: footer <= html.SPAN(' (%s/%s)' % (page_num + 1, len(slideshow.pages)), style=dict(display='inline')) timeline = html.DIV(Id='timeline') tl_pos = html.DIV(Id='tl_pos') timeline <= tl_pos timeline.bind('click', lambda ev: move_to(ev, slideshow, zone)) tl_pos.bind('click', click_on_tl_pos) zone <= body + footer + timeline tl_pos.style.left = '%spx' % (timeline.width * page_num / len(slideshow.pages)) for elt in zone.get(selector='.python'): src = elt.text.strip() width = max(len(line) for line in src.split('\n')) # replace element content by highlighted code elt.html = highlight.highlight(src).html elt.style.width = '%sem' % int(0.7 * width)
def show_page(slideshow, zone, page_num): # if table of contents is not empty, add it if slideshow.contents: toc = html.SELECT(name="toc") toc.bind('change', lambda ev: show_page(slideshow, zone, int(ev.target.options[ev.target.selectedIndex].value))) for content in slideshow.contents: toc <= html.OPTION(content[0], value=content[1], selected=page_num>=content[1]) slideshow.page_num = int(page_num) zone.clear() body = html.DIV() body.html = markdown.mark(slideshow.pages[page_num])[0] if slideshow.contents: body = html.DIV(toc+body) footer = html.DIV(Id="footer") if slideshow.title: footer <= html.DIV(slideshow.title,style=dict(display='inline')) if slideshow.show_page_num: footer <= html.SPAN(' (%s/%s)' %(page_num+1, len(slideshow.pages)), style=dict(display='inline')) timeline = html.DIV(Id='timeline') tl_pos = html.DIV(Id='tl_pos') timeline <= tl_pos timeline.bind('click', lambda ev:move_to(ev, slideshow, zone)) tl_pos.bind('click', click_on_tl_pos) zone <= body+footer+timeline tl_pos.style.left = '%spx' %(timeline.width*page_num/len(slideshow.pages)) for elt in zone.get(selector='.python'): src = elt.text.strip() width = max(len(line) for line in src.split('\n')) # replace element content by highlighted code elt.html = highlight.highlight(src).html elt.style.width = '%sem' %int(0.7*width)
def load(url, target): # fake query string to bypass browser cache qs = "?foo=%s" % time.time() try: mk, scripts = markdown.mark(open(url + qs).read()) except IOError: doc[target].html = "Page %s not found" % url return False doc[target].html = mk for script in scripts: exec(script) for elt in doc[target].get(selector=".exec"): # Python code executed when user clicks on a button elt.contentEditable = True src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h elt.focus() btn = html.BUTTON("▶") btn.bind("click", run) elt.parent.insertBefore(btn, elt) for elt in doc[target].get(selector=".exec_on_load"): # Python code executed on page load src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h exec(src) for elt in doc[target].get(selector=".python"): src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h return False
def load(url, target): # fake query string to bypass browser cache qs = '?foo=%s' % time.time() try: mk, scripts = markdown.mark(open(url + qs).read()) except IOError: doc[target].html = "Page %s not found" % url return False doc[target].html = mk for script in scripts: exec(script) for elt in doc[target].get(selector='.exec'): # Python code executed when user clicks on a button elt.contentEditable = True src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h elt.focus() btn = html.BUTTON('▶') btn.bind('click', run) elt.parent.insertBefore(btn, elt) for elt in doc[target].get(selector='.exec_on_load'): # Python code executed on page load src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h exec(src) for elt in doc[target].get(selector='.python'): src = elt.text.strip() h = highlight.highlight(src) h.className = "pycode" elt.clear() elt <= h return False
def show(path,zone,page=0): src = open(path).read() title = '' page_num = False while src.startswith('@'): line_end = src.find('\n') key,value = src[:line_end].split(' ',1) if key=='@title': title = value elif key=='@pagenum': page_num = True src = src[line_end+1:] zone.html = '' pages = src.split('../..\n') if page<0: page = 0 elif page >= len(pages): page = len(pages)-1 doc.unbind('keydown') doc.bind('keydown',lambda ev:keydown(ev,path,zone,page)) body = html.DIV() body.html = markdown.mark(pages[page])[0] footer = html.DIV(Id="footer") if title: footer <= html.DIV(title,style=dict(display='inline')) if page_num: footer <= html.SPAN(' (%s/%s)' %(page+1,len(pages)), style=dict(display='inline')) timeline = html.DIV(Id='timeline') tl_pos = html.DIV(Id='tl_pos') timeline <= tl_pos timeline.bind('click',lambda ev:move_to(ev,path,zone,len(pages))) tl_pos.bind('click',click_on_tl_pos) zone <= body+footer+timeline tl_pos.style.left = '%spx' %(timeline.width*page/len(pages))
def flash_text_block(): marked, scripts = markdown.mark('\n'.join(text_block)) page_htmls.append(marked) page_scripts.extend(scripts) text_block[:] = []
def show(path, zone, page_num=0): src = open(path).read() title = '' show_page_num = False # table of contents : matches matter with page number contents = [] # directives for the document while src.startswith('@'): line_end = src.find('\n') key, value = src[:line_end].split(' ', 1) if key == '@title': title = value elif key == '@pagenum': show_page_num = True elif key == "@index": contents.append([value, 0]) src = src[line_end + 1:] zone.html = '' pages = src.split('../..\n') # table of contents for num, _page in enumerate(pages): if num == 0: continue if _page.startswith('@index'): line_end = _page.find('\n') key, value = _page[:line_end].split(' ', 1) contents.append([value, num]) pages[num] = _page[line_end + 1:] if page_num < 0: page_num = 0 elif page_num >= len(pages): page_num = len(pages) - 1 doc.unbind('keydown') doc.bind('keydown', lambda ev: keydown(ev, path, zone, page_num)) # if table of contents is not empty, add it if contents: toc = html.SELECT(name="toc") toc.bind( 'change', lambda ev: show( path, zone, int(ev.target.options[ev.target.selectedIndex].value))) for content in contents: toc <= html.OPTION( content[0], value=content[1], selected=page_num >= content[1]) body = html.DIV() body.html = markdown.mark(pages[page_num])[0] if contents: body = html.DIV(toc + body) footer = html.DIV(Id="footer") if title: footer <= html.DIV(title, style=dict(display='inline')) if show_page_num: footer <= html.SPAN(' (%s/%s)' % (page_num + 1, len(pages)), style=dict(display='inline')) timeline = html.DIV(Id='timeline') tl_pos = html.DIV(Id='tl_pos') timeline <= tl_pos timeline.bind('click', lambda ev: move_to(ev, path, zone, len(pages))) tl_pos.bind('click', click_on_tl_pos) zone <= body + footer + timeline tl_pos.style.left = '%spx' % (timeline.width * page_num / len(pages))
def show(path, zone, page_num=0): src = open(path).read() title = '' show_page_num = False # table of contents : matches matter with page number contents = [] # directives for the document while src.startswith('@'): line_end = src.find('\n') key,value = src[:line_end].split(' ',1) if key=='@title': title = value elif key=='@pagenum': show_page_num = True elif key=="@index": contents.append([value, 0]) src = src[line_end+1:] zone.html = '' pages = src.split('../..\n') # table of contents for num, _page in enumerate(pages): if num==0: continue if _page.startswith('@index'): line_end = _page.find('\n') key,value = _page[:line_end].split(' ',1) contents.append([value, num]) pages[num] = _page[line_end+1:] if page_num<0: page_num = 0 elif page_num >= len(pages): page_num = len(pages)-1 doc.unbind('keydown') doc.bind('keydown',lambda ev:keydown(ev, path, zone, page_num)) # if table of contents is not empty, add it if contents: toc = html.SELECT(name="toc") toc.bind('change', lambda ev: show(path, zone, int(ev.target.options[ev.target.selectedIndex].value))) for content in contents: toc <= html.OPTION(content[0], value=content[1], selected=page_num>=content[1]) body = html.DIV() body.html = markdown.mark(pages[page_num])[0] if contents: body = html.DIV(toc+body) footer = html.DIV(Id="footer") if title: footer <= html.DIV(title,style=dict(display='inline')) if show_page_num: footer <= html.SPAN(' (%s/%s)' %(page_num+1, len(pages)), style=dict(display='inline')) timeline = html.DIV(Id='timeline') tl_pos = html.DIV(Id='tl_pos') timeline <= tl_pos timeline.bind('click', lambda ev:move_to(ev, path, zone, len(pages))) tl_pos.bind('click', click_on_tl_pos) zone <= body+footer+timeline tl_pos.style.left = '%spx' %(timeline.width*page_num/len(pages))