def print(self): rows, columns = os.popen("stty size", "r").read().split() print( f"{fontColor(style = Style.ITALIC)}{self._note.min_path}{fontReset()}" ) raw_markdown = self._read_raw_markdown() mdv.term_columns = 60 if config.get("view-mode") == "interactive": pydoc.pipepager( mdv.main( raw_markdown, theme=self._MDV_theme_id, header_nrs=self._MDV_headers, ), cmd="less -R", ) elif config.get( "view-mode") == "combo" and len(raw_markdown) > int(rows): pydoc.pipepager( mdv.main( raw_markdown, theme=self._MDV_theme_id, header_nrs=self._MDV_headers, ), cmd="less -R", ) else: print(mdv.main(raw_markdown))
def cmd_menu(ctx, menu_name, menu_id, action, scale): db = ctx.obj.open_database() logger = ctx.obj.logger if menu_name is None and menu_id is None: logger.error('Either pass menu name, or use --menu-id option.') return menu = Menu.find(db, name=menu_name, did=menu_id) if not menu: logger.error('No such menu found') return if action == 'show': menu['.pre-formatted'] = { 'tags': [u'**{}**'.format(tag) for tag in menu['tags']] } text = jinja2.Template(MENU_TEMPLATE).render(DB=db, MENU=menu, Recipe=Recipe) formatted = mdv.main(text, theme='785.6556') click.echo(formatted) elif action == 'shopping-list': shopping_list = collections.defaultdict(list) for day in menu['schedule']: for meal in day['meals']: for recipe_name in meal['recipes']: recipe = Recipe.find(db, name=recipe_name, did=recipe_name) if not recipe: logger.warn( "Cannot find recipe '{}'".format(recipe_name)) continue recipe.scale(menu['guests']) for ingredient in recipe['ingredients']: if 'amount' in ingredient: shopping_list[ingredient['name']].append( ingredient['amount']) else: shopping_list[ingredient['name']].append(None) text = jinja2.Template(SHOPPING_LIST_TEMPLATE).render( MENU=menu, SHOPPING_LIST=shopping_list) formatted = mdv.main(text, theme='785.6556') click.echo(formatted)
def render(text, html=True, tab_length=0): """ Renders input text to formatted text ready to send to the terminal. Args: text: input html text Returns: text formatted for print to terminal """ if html: # Convert HTML parser = html2text.HTML2Text() parser.body_width = 0 text = parser.handle(text) text = Query.escape(text) text = mdv.main(text, theme="592.2129", c_theme="953.3567", cols=180, tab_length=tab_length) if html: text = Query.unescape(text) return text.strip()
def __str__(self): ret = self.text ret = ret.replace('_', '') keymap = { r'\le': r"<=", r'\cdot': r".", r'\ge': r">=", r'\lt': r"<", r'$': r"_", r'\dots': r"..." } for key in keymap: value = keymap[key] ret = ret.replace(key, value) # temprorily convert to html mdProcessor = markdown.Markdown() myHtmlFragment = str(mdProcessor.convert(ret)) myHtmlFragment = myHtmlFragment.replace('<code>', r"```") myHtmlFragment = myHtmlFragment.replace('</code>', r"```") ret = Tomd(myHtmlFragment).markdown # calling like this (all CLI options supported, check def main ret = mdv.main(ret) return ret
def render(text, html=True, tab_length=0): """ Renders input text to formatted text ready to send to the terminal. Args: text: input html text Returns: text formatted for print to terminal """ if html: # Convert html to markdown text = Query.markdown(text) text = Query.escape(text) text = mdv.main(text, theme="592.2129", c_theme="953.3567", cols=180, tab_length=tab_length) if html: text = Query.unescape(text) return text.strip()
def test_all(self): df = here + '/files' for f in os.listdir(df): if not f.endswith('.md'): continue print('testfile: ', f) with open(df + '/' + f) as fd: src = fd.read() for col in 20, 40, 80, 200: print('columns: ', col) res = mdv.main( src, cols=col, theme=729.8953, c_theme=729.8953, c_no_guess=True, c_def_lexer='python', ) with open('%s/result.%s/%s.expected' % (df, col, f)) as fd: tgt = fd.read() # print(res) if not unicode(tgt).strip() == unicode(res).strip(): print('error') print('got:\n', res) print('should:\n', unicode(tgt)) raise Exception('Error %s col %s' % (f, col))
def main(): fn, line = get_item() try: import mdv line = mdv.main(line) except ImportError: pass print(u'({0}) Fun fact! {1}'.format(fn, line))
def format_answer(answer): lines = answer.splitlines() for line in lines: m = re.search('(?<=src=")[^"\?]+', line) if m: imgcat(open("bert-as-service/" + m.group(0))) else: formatted = mdv.main(md=line, c_theme=...) print(formatted)
def view(self) -> str: """ View the task in the terminal as colored/stylized output. Returns: str """ content = "File has no content." if not self.content else self.content return mdv.main(content)
def run_card_simulator(raw=False): card_groups = { 'Baselines': [ hp_no_invest, dmg_no_invest, ], 'HP Simulations': [ *collect_cards(hp_cards).values(), ], 'DMG Simulations': [ *collect_cards(dmg_cards).values(), ], 'Random Interesting Cards': [ *collect_cards(meme_cards).values() ], 'Balanced Cards': [ *collect_cards(balanced_cards).values() ], } # validate cards for name, cards in card_groups.items(): card: Card for card in cards: card.is_valid_card() out = StringIO() def p(x=None): return print(x, file=out) if x else print(file=out) p(f"## Simulator Results: {arrow.utcnow()}") p() p(f"### Game Facts") p(f"{combat_strat.__class__.__name__} combat strategy") p(trim_doc(combat_strat.__doc__)) p() p(f"Nature values range from {combat_strat.min_nature_value} to {combat_strat.max_nature_value}") p() p(f"### Cards") p() for name, cards in card_groups.items(): p(f"<details><summary>{name}</summary>" if raw else f"### {name}") p() card: Card for card in cards: p(card_markdown(card)) p(f"</details>" if raw else "") p() if raw: print(out.getvalue()) else: print(mdv.main(out.getvalue(), theme="960.847"))
def test_all(self): df = here + '/files' for f in os.listdir(df): if not f.endswith('.md'): continue print (f) with open(df + '/' + f) as fd: src = fd.read() for col in 20, 40, 80, 200: print (col) rd = 'result.%s' % col res = mdv.main(src, cols=col, theme=729.8953, c_theme=729.8953) with open('%s/result.%s/%s.expected' % (df, col, f)) as fd: tgt = fd.read() print (res) if not unicode(tgt).strip() == unicode(res).strip(): raise Exception("Error %s col %s" % (f, col))
def test_table(self): st = ''' | Item | Value | Qty | | --- | --- | --- | | Computer | $1600 | 5 | | Phone | $12 | 12 | | Pipe | $1 | 234 | ''' s = mdv.main(st) assert clean(s) == clean(''' ──────── ───── ─── Item Value Qty Computer $1600 5 Phone $12 12 Pipe $1 234 ──────── ───── ─── ''')
def open(self, uid): self.uid = uid email = self.model.get(uid) self.data = { 'subject': email.subject, 'from': ', '.join([x['name'] for x in email.sent_from]), 'to': ', '.join([x['name'] for x in email.sent_to]), 'body': mdv.main( html2text('\n'.join(email.body['plain']).replace('\r', ''))), 'date': email.date } self.save() open_view('EmailView')
def cmd_recipe(ctx, recipe_name, recipe_id, action, scale): logger = ctx.obj.logger if recipe_name is None and recipe_id is None: logger.error('Either pass recipe name, or use --recipe-id option.') return db = ctx.obj.open_database() recipe = Recipe.find(db, name=recipe_name, did=recipe_id) if not recipe: logger.error('No such recipe found.') return # adjust scaling if scale is not None: scales = { 'adults': 0.0, 'kids': 0.0 } for bit in [s.strip() for s in scale.split(',')]: name, value = [s.strip() for s in bit.split('=')] scales[name] = float(value) else: scales = { 'adults': recipe['portions'], 'kids': 0.0 } recipe.scale(scales) if action == 'show': recipe['.pre-formatted'] = { 'tags': [u'**{}**'.format(tag) for tag in recipe['tags']] } text = jinja2.Template(RECIPE_TEMPLATE).render(RECIPE=recipe, SCALE=scales) formatted = mdv.main(text, theme='785.6556') click.echo(formatted)
def txt_terminal_render(text, format=None, debug=False): """ This renders input text based on the selected format. :param format: selected format (one of FORMATS) """ format = format or DOCFORMAT __check(format=format) if format is None: return text # collect whitespaces in argument lines and line indentations ARG_REGEX = re.compile( r"((?P<h>\-{1,2})[a-z][a-z0-9_]*(?:\s+[A-Z][A-Z_]*)?" r"(?:\,\s+(?P=h)\-[a-z][a-z0-9_]*(?:\s+[A-Z][A-Z_]*)?)?)(\s+)(.*)$") spaces = {} for line in text.split("\n"): s = ARG_REGEX.search(line) if s: spaces[s.group(1)] = len(s.group(3)) # e.g. "-v, --verbose" and 10 (whitespaces) else: tmp = line.lstrip() indent = len(line) - len(tmp) if indent > 0: spaces[tmp.strip()] = indent # convert here if debug: lines = text.split("\n") n = len(str(len(lines))) + 2 for i, l in enumerate(lines): print(("{: <%d}{}" % n).format(i, l)) md = text if format == "md" else convert_text( text, "md", format=format).replace("\\", "") if format != "md": # bug corrections # 1. misaligned metadata fields # 2. rectify misaligned arguments' helps tmp = md md, l = "", 0 # collect the maximum field length for line in tmp.split("\n"): try: f, v = line.split(":", 1) if f.endswith("default"): raise ValueError if re.search(r"(?P<t>[_\*])(.*?)(?P=t)", f): f = "_" + f.strip(" *_") + "_" l = max(l, len(f)) except ValueError: pass # then, remake markdown string for line in tmp.split("\n"): try: f, v = line.split(":", 1) if f.endswith("default"): raise ValueError() if re.search(r"(?P<t>[_\*])(.*?)(?P=t)", f): f = "_" + f.strip(" *_") + "_" md += ("{: <%d}: {}" % l).format(f, v) + "\n" continue except ValueError: pass # restore spaces between arguments and their help messages s = ARG_REGEX.search(line) if s: l = spaces.get(s.group(1), 0) line = ARG_REGEX.sub(r"\1{}\4".format(" " * l), line) # restore indentations else: try: line = spaces[line] * " " + line except KeyError: pass md += line + "\n" # 3. links incorrectly rendered with mdv after using pandoc for link in re.findall("(<(.*?)>)", md): md = md.replace( link[0], "[{0}]({1}{0})".format(link[1], ["", "mailto:"][is_email(link[1])])) return mdv.main(md, display_links=True, theme=DOCFORMAT_THEME)
async def show_command(session): columns = session.aprompt.get_size().columns with open(session.configuration.description) as f: data = mdv.main(f.read(), cols=columns) await session.aprint(ANSI(data))
def get_mark(html): return mdv.main(ht.html2text(html))