# Terminal Markdown Viewer
> This is a fork of the [axiros mdv](https://github.com/axiros/terminal_markdown_viewer)
> The original repo is no longer being maintained. This is an actively maintained fork that drops python2 support and includes support of python3.9+
When you edit multiple md files remotely, like in a larger
[mkdocs](http://www.mkdocs.org/) project, context switches between editing
terminal(s) and viewing browser may have some efficiency impact.
Also sometimes there is just no browser, like via security gateways offering
just a fixed set of applications on the hop in machine.
Further, reading efficiency and convenience is often significantly improved
by using colors.
And lastly, using such a thing for cli applications might improve user output,
e.g. for help texts.
This is where mdv, a Python based Markdown viewer for the terminal might be
a good option.
<!-- toc -->
- [Terminal Markdown Viewer](#terminal-markdown-viewer)
- [Features](#features)
- [Alternatives](#alternatives)
- [Installation](#installation)
- [Usage](#usage)
- [CLI](#cli)
- [Inline](#inline)
- [Sample Inline Use Case: click module docu](#sample-inline-use-case-click-module-docu)
- [Customization](#customization)
- [Screenshots](#screenshots)
- [TODO](#todo)
- [Credits](#credits)
- [Updates](#updates)
<!-- tocstop -->
If markdown is often "simple" enough to be somewhat readable on 256 color terminals (except images that is).
<img src="https://raw.githubusercontent.com/WillNye/terminal_markdown_viewer/master/samples/1.png" width=500>
from
### Source
# Header 1
## Header 2
### Header 3
#### Header 4
##### Header 5
###### Header 6
```python
""" Test """
# Make Py2 >>> Py3:
import os, sys; reload(sys); sys.setdefaultencoding('utf-8')
# no? see http://stackoverflow.com/a/29832646/4583360 ...
# code analysis for hilite:
try:
from pygments import lex, token
from pygments.lexers import get_lexer_by_name, guess_lexer
```
| Tables | Fmt |
| -- | -- |
| !!! hint: wrapped | 0.1 **strong** |
!!! note: title
this is a Note
You can also use mdv as a **source code** viewer, best when you have docstrings with markdown in your code:
![](./samples/5.png)
from
```python
~/terminal_markdown_viewer $ cat setup.py
#!/usr/bin/env python2.7
# coding: utf-8
"""_
# Mdv installation
## Usage
[sudo] ./setup.py install
----
"""
from setuptools import setup, find_packages
import mdv
setup(
name='mdv',
version=mdv.__version__,
```
(the '_' after the docstring telling mdv that markdown follows)
----
> mdv is a proof of concept hack: While for simple structures it does its job quite well, for complex markdown you want to use other tools.
> Especially for inlined html it simply fails.
----
## Features
- Tons of theme combinations: mdv ships with > 200 luminocity sorted themes, converted from html themes tables to ansi. Those can be combined for code vs regular markdown output...
- Admonitions
- Tables, incl. wide table handling avoiding "interleaving"
- Somewhat hackable, all in [one](mdv/markdownviewer.py) module
- Useable as lib as well
- File change monitor
- Text wrapping
- Source code highlighter
- Little directory change monitor (cames handy when working on multiple files, to get the current one always displayed)
- which can run arbitrary commands on file changes
- which passes filepath, raw and prettyfied content to the other command
Note: Poor man's implementation, polling. Check inotify based tools if you want sth better.
## Alternatives
The ones I know of (and which made me write mdv ;-) ):
1. There are quite a few from the js community (e.g. [msee](https://www.npmjs.com/package/msee), ansidown, ansimd and also nd which is great) but they require nodejs & npm, which I don't have on my servers. Also I personally wanted table handling and admonition support throughout and prob. too old to hack other peoples' js (struggling enough with my own). But have a look at them, they do some things better than mdv in this early version (I try to learn from them). Also [this](https://github.com/substack/picture-tube) would be worth a look ;-)
2. pandoc -> html -> elinks, lynx or pandoc -> groff -> man. (Heavy and hard to use from within other programs. Styling suboptimal)
3. vimcat (Also heavy and hard to use inline in other programs)
Summary: For production ready robust markdown viewing (e.g. for your customers) I recommend nd still, due to the early state of mdv. For playing around, especially with theming or when with Python, this one might be a valid alternative to look at.
## Installation
pip install mdv
If you get `no attribute HTML_PLACEHOLDER`: update your markdown package.
[Here](https://trac.macports.org/ticket/53591) is a macport (thanks Aljaž).
### Manual Install: Requirements
- python == 2.7 or > 3.5
- py markdown (pip install markdown)
- py pygments (pip install pygments)
- py yaml (pip install pyyaml)
- py docopt (pip install docopt)
- py tabulate (pip install tabulate)
Further a 256 color terminal (for now best with dark background) and font support for a few special separator characters (which you could change via config).
> For light terms you'd just need to revert the 5 colors from the themes, since they are sorted by luminocity.
I did not test anything on windows.
### Manual Install: Setup
Distribution via setuptools. If setuptools is not installed, run:
pip install setuptools
Use the setup.py provided inside, I.e. run:
sudo ./setup.py install
(or ./setup.py install --user to install only for the current user)
## Usage
### CLI
```markdown
# Usage:
mdv [OPTIONS] MDFILE
# Options:
MDFILE : Path to markdown file
-A : Strip all ansi (no colors then)
-C MODE : Sourcecode highlighting mode
-H : Print html version
-L : Backwards compatible shortcut for '-u i'
-M DIR : Monitor directory for markdown file changes
-T C_THEME: Theme for code highlight. If not set: Using THEME.
-X Lexer : Default lexer name (default: python). Set -x to use it always.
-b TABL : Set tab_length to sth. different than 4 [default: 4]
-c COLS : Fix columns to this (default: your terminal width)
-f FROM : Display FROM given substring of the file.
-h : Show help
-i : Show theme infos with output
-l : Light background (not yet supported)
-m : Monitor file for changes and redisplay FROM given substring
-n NRS : Header numbering (default: off. Say e.g. -3 or 1- or 1-5
-t THEME : Key within the color ansi_table.json. 'random' accepted.
-u STYL : Link Style (it=inline table=default, h=hide, i=inline)
-x : Do not try guess code lexer (guessing is a bit slow)
# Notes:
We use stty tool to derive terminal size. If you pipe into mdv we use 80 cols.
## To use mdv.py as lib:
Call the main function with markdown string at hand to get a
formatted one back. Sorry then for no Py3 support, accepting PRs if they don't screw Py2.
## FROM:
FROM may contain max lines to display, seperated by colon.
Example:
-f 'Some Head:10' -> displays 10 lines after 'Some Head'
If the substring is not found we set it to the *first* character of the file -
resulting in output from the top (if your terminal height can be derived correctly through the stty cmd).
## Code Highlighting
Set -C <all|code|doc|mod> for source code highlighting of source code files.
Mark inline markdown with a '_' following the docstring beginnings.
- all: Show markdown docstrings AND code (default if you say, e.g. `-C.`)
- code: Only Code
- doc: Only docstrings with markdown
- mod: Only the module level docstring
## File Monitor:
If FROM is not found we display the whole file.
## Directory Monitor:
We check only text file changes, monitoring their size.
By default .md, .mdown, .markdown files are checked but you can change like `-M 'mydir:py,c,md,'` where the last empty substrings makes mdv also monitor any file w/o extension (like 'README').
### Running actions on changes:
If you append to `-M` a `'::<cmd>'` we run the command on any change detected (sync, in foreground).
The command can contain placeholders:
_fp_ # Will be replaced with filepath
_raw_ # Will be replaced with the base64 encoded raw content
of the file
_pretty_ # Will be replaced with the base64 encoded prettyfied output
Like: mdv -M './mydocs:py,md::open "_fp_"' which calls the open
command with argument the path to the changed file.
## Themes
### Theme Rollers
mdv -T all [file]: All available code styles on the given file.
mdv -t all [file]: All available md styles on the given file.
If file is not given we use a short sample file.
So to see all code hilite variations with a given theme:
Say C_THEME = all and fix THEME
Setting both to all will probably spin your beach ball...
### Environ Vars
`$MDV_THEME` and `$MDV_CODE_THEME` are understood, e.g. `export
MDV_THEME=729.8953` in your .bashrc will give you a consistent color scheme.
```
> Regarding the strange theme ids: Those numbers are the calculated total luminocity of the 5 theme colors.
### Inline
mdv is designed to be used well from other (Py2) programs when they have md at hand which should be displayed to the user:
```python
import mdv
# config like this:
mdv.term_columns = 60
# calling like this (all CLI options supported, check def main
formatted = mdv.main(my_raw_markdown, c_theme=...)
```
> Note that I set the defaultencoding to utf-8 in ``__main__``. I have this as my default python2 setup and did not test inline usage w/o. Check [this](http://stackoverflow.com/a/29832646/4583360) for risks.
### Sample Inline Use Case: click module docu
[Armin Ronacher](http://lucumr.pocoo.org/2014/5/12/everything-about-unicode/)'s
[click](http://click.pocoo.org) is a great framework for writing larger CLI apps - but its help texts are a bit boring, intended to be customized.
Here is how:
Write a normal click module with a function but w/o a doc string as shown:
```python
@pass_context
def cli(ctx, action, name, host, port, user, msg):
""" docu from module __doc__ """
```
On module level you provide markdown for it, like:
```shell
~/axc/plugins/zodb_sub $ cat zodb.py | head
"""
# Fetch and push ZODB trees
## ACTION: < info | pull | push | merge | dump | serve>
- info: Requests server availability information
(...)
```
which you set at click module import time:
mod.cli.help = mod.__doc__
Lastly do this in your app module:
```python
from click.formatting import HelpFormatter
def write_text(self, text):
""" since for markdown pretty out on cli I found no good tool
so I built my own """
# poor man's md detection:
if not text.strip().startswith('#'):
return orig_write_text(self, text)
from axc.markdown.mdv import main as mdv
self.buffer.append(mdv(md=text, theme=os.environ['AXC_THEME']))
HelpFormatter.orig_write_text = HelpFormatter.write_text
HelpFormatter.write_text = write_text
```
The output has then colors:
![](samples/3.png)
and at smaller terms rewraps nicely:
![](samples/4.png)
Further, having markdown in the module ``__doc__`` makes it simple to add into a global project docu framework, like mkdocs.
## Customization
You can supply all CLI args in `$HOME/.mdv`, in yaml format.
More flex you have via `$HOME/.mdv.py`, which is execed if present, when
running `main`.
Alternatively, in [mdv.py](mdv.py) you can change some config straight forward.
```python
# ---------------------------------------------------------------------- Config
txt_block_cut, code_pref, list_pref, br_ends = '✂', '| ', '- ', '◈'
# ansi cols (default):
# R: Red (warnings), L: low visi, BG: background, BGL: background light, C=code
# H1 - H5 = the theme, the numbers are the ansi color codes:
H1, H2, H3, H4, H5, R, L, BG, BGL, T, TL, C = \
231, 153, 117, 109, 65, 124, 59, 16, 188, 188, 59, 102
# Code (C is fallback if we have no lexer). Default: Same theme:
CH1, CH2, CH3, CH4, CH5 = H1, H2, H3, H4, H5
code_hl = { "Keyword" : 'CH3', "Name" : 'CH1',
"Comment" : 'L', "String": 'CH4',
"Error" : 'R', "Number": 'CH4',
"Operator": 'CH5',
"Generic" : 'CH2'
}
admons = {'note' : 'H3', 'warning': 'R',
'attention': 'H1', 'hint' : 'H4',
'summary' : 'H1', 'hint' : 'H4',
'question' : 'H5', 'danger' : 'R',
'caution' : 'H2'
}
def_lexer = 'python'
guess_lexer = True
# also global. but not in use, BG handling can get pretty involved...
background = BG
# normal text color:
color = T
show_links = None
# could be given, otherwise read from ansi_tables.json:
themes = {}
# sample for the theme roller feature:
md_sample = ''
# ------------------------------------------------------------------ End Config
```
Any importing module can overwrite those module global variables as well.
Should you need yet additional themes, add them to ``ansi_tables.json`` file by adding your ansi codes there.
## Screenshots
Random results, using the theme roller feature:
![second](https://github.com/axiros/terminal_markdown_viewer/blob/master/samples/2.png)
Note the table block splitting when the table does not fit (last picture).
## TODO
- Refactor the implementation, using a config class
- Lines separators not optimal ([nd](https://www.npmjs.com/package/nd) does better)
- Test light colorscheme
- Dimming
- A few grey scale and 8 color themes
- Sorting of the json by luminance
- Some themes have black as darkest color, change to dark grey
- Common Mark instead of markdown
## PerfTests
Rendering this readme [100 times](./mdv/misc/perftest.py):
```
black root@ip-10-34-2-19:~/terminal_markdown_viewer/mdv/misc# python perfest.py
0.03 paka
0.04 paka_breaks
0.04 paka_xml
1.47 mistletoe
8.70 markdown
5.22 commonmark
```
- markdown did better than commonmark w/o extensions but table and fenced code
are definitelly required for 99% users.
- paka is a wrapper around the C reference lib -> requires compilation.
- mistletoe is pure python, crazy that they are so much faster than CommonMark.
They say in pypy they are speed up even much more.
mistletoe downside: py2 only via a fork.
## Credits
[pygments](http://pygments.org/) (using their lexer)
[tabulate](https://pypi.python.org/pypi/tabulate)
and, naturally, the [python markdown project](https://pythonhosted.org/Markdown/authors.html)
Update: Next version will be CommonMark based though...
## Updates
### July 2016:
Sort of an excuse for the long long time w/o an update:
I did actually start working on a more solid version based on CommonMark but
that went a bit out of scope, into a general html terminal viewer, which will
probably never be finished :-/
So at least here an update containing the stuff you guys sent as PRs, thanks all!!
- installation and dependencies via a setup.py (thanks
[Martin](https://github.com/althonos))
- supporting `echo -e "# foo\n## bar" | mdv -` and a 'light' theme (thanks
[Stanislav](https://github.com/seletskiy))
- and a few other improvements regarding python2.7, file location and pyyaml, thanks all.
Also:
- fixed the most obvious bugs with nested ordered and unordered lists
- fixed bold marker
- different color highlighting for the list markers
- added a source code highlighting mode, which highlights also docstrings in markdown (`-C <mode>`)
- some tests in the tests folder
- using `textwrap` now for the wrapping, to avoid these word breaks a few complained about
- you can supply the default lexer now, e.g. `-X javascript [-x]`
- fixed but with not rendered strong texts
- pip install mdv
### Nov 2016:
- travis
- Inline link tables
![](./samples/links.png)
[travis]: https://travis-ci.org/axiros/terminal_markdown_viewer
[travis_img]: https://travis-ci.org/axiros/terminal_markdown_viewer.svg?branch=master
### Sept 2018:
- Merged some PRs, thanks.
- Decent [code formatter](https://github.com/ambv/black). Not that this weekend hack got more readable though. Well, maybe a bit.
- Revised Py3 support (finally found peace with it, since they enforce UTF-8 everywhere the new features begin to outweigh the nightmares of trying to decode everything without need).
- Indented code in PY3 was broken, fixed that. Why, PY3, are you creating crap like `"b'foo'"` instead raising or auto-decoding (since you work anyway only with your UTF8-everywhere-assumption)!?
- Header numbering feature added (`-n 2-4` or `-n 1-`)
<img src="https://raw.githubusercontent.com/WillNye/terminal_markdown_viewer/master/samples/header_num.png" width="400"/>
- docopt and pyyaml install requirement removed, better config file handling.
- pypi markdown rendering for the readme, finally.
Raw data
{
"_id": null,
"home_page": "http://github.com/WillNye/terminal_markdown_viewer",
"name": "mdv3",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": "",
"keywords": "markdown,markup,terminal,hilighting,syntax,source code",
"author": "Will Beasley",
"author_email": "willbeas88@gmail.com",
"download_url": "http://github.com/WillNye/terminal_markdown_viewer/tarball/",
"platform": "",
"description": "# Terminal Markdown Viewer\n> This is a fork of the [axiros mdv](https://github.com/axiros/terminal_markdown_viewer) \n> The original repo is no longer being maintained. This is an actively maintained fork that drops python2 support and includes support of python3.9+\n\nWhen you edit multiple md files remotely, like in a larger\n[mkdocs](http://www.mkdocs.org/) project, context switches between editing\nterminal(s) and viewing browser may have some efficiency impact.\nAlso sometimes there is just no browser, like via security gateways offering\njust a fixed set of applications on the hop in machine.\nFurther, reading efficiency and convenience is often significantly improved\nby using colors.\nAnd lastly, using such a thing for cli applications might improve user output,\ne.g. for help texts.\n\nThis is where mdv, a Python based Markdown viewer for the terminal might be\na good option.\n\n<!-- toc -->\n\n- [Terminal Markdown Viewer](#terminal-markdown-viewer)\n\t- [Features](#features)\n\t- [Alternatives](#alternatives)\n\t- [Installation](#installation)\n\t- [Usage](#usage)\n\t\t- [CLI](#cli)\n\t\t- [Inline](#inline)\n\t\t- [Sample Inline Use Case: click module docu](#sample-inline-use-case-click-module-docu)\n\t- [Customization](#customization)\n\t- [Screenshots](#screenshots)\n\t- [TODO](#todo)\n\t- [Credits](#credits)\n\t- [Updates](#updates)\n\n\n<!-- tocstop -->\n\n\n\nIf markdown is often \"simple\" enough to be somewhat readable on 256 color terminals (except images that is).\n\n<img src=\"https://raw.githubusercontent.com/WillNye/terminal_markdown_viewer/master/samples/1.png\" width=500>\n\nfrom\n\n\t### Source\n\t# Header 1\n\t## Header 2\n\t### Header 3\n\t#### Header 4\n\t##### Header 5\n\t###### Header 6\n\t```python\n\t\"\"\" Test \"\"\"\n\t# Make Py2 >>> Py3:\n\timport os, sys; reload(sys); sys.setdefaultencoding('utf-8')\n\t# no? see http://stackoverflow.com/a/29832646/4583360 ...\n\n\t# code analysis for hilite:\n\ttry:\n\t from pygments import lex, token\n\t from pygments.lexers import get_lexer_by_name, guess_lexer\n\t```\n\n\t| Tables | Fmt |\n\t| -- | -- |\n\t| !!! hint: wrapped | 0.1 **strong** |\n\n\t!!! note: title\n\t this is a Note\n\n\nYou can also use mdv as a **source code** viewer, best when you have docstrings with markdown in your code:\n\n![](./samples/5.png)\n\nfrom\n\n```python\n~/terminal_markdown_viewer $ cat setup.py\n#!/usr/bin/env python2.7\n# coding: utf-8\n\n\"\"\"_\n# Mdv installation\n\n## Usage\n\n [sudo] ./setup.py install\n\n----\n\"\"\"\n\nfrom setuptools import setup, find_packages\n\nimport mdv\n\nsetup(\n name='mdv',\n version=mdv.__version__,\n\n```\n(the '_' after the docstring telling mdv that markdown follows)\n\n----\n\n> mdv is a proof of concept hack: While for simple structures it does its job quite well, for complex markdown you want to use other tools.\n> Especially for inlined html it simply fails.\n\n----\n\n\n## Features\n\n- Tons of theme combinations: mdv ships with > 200 luminocity sorted themes, converted from html themes tables to ansi. Those can be combined for code vs regular markdown output...\n- Admonitions\n- Tables, incl. wide table handling avoiding \"interleaving\"\n- Somewhat hackable, all in [one](mdv/markdownviewer.py) module\n- Useable as lib as well\n- File change monitor\n- Text wrapping\n- Source code highlighter\n- Little directory change monitor (cames handy when working on multiple files, to get the current one always displayed)\n\t- which can run arbitrary commands on file changes\n\t- which passes filepath, raw and prettyfied content to the other command\n Note: Poor man's implementation, polling. Check inotify based tools if you want sth better.\n\n## Alternatives\n\nThe ones I know of (and which made me write mdv ;-) ):\n\n1. There are quite a few from the js community (e.g. [msee](https://www.npmjs.com/package/msee), ansidown, ansimd and also nd which is great) but they require nodejs & npm, which I don't have on my servers. Also I personally wanted table handling and admonition support throughout and prob. too old to hack other peoples' js (struggling enough with my own). But have a look at them, they do some things better than mdv in this early version (I try to learn from them). Also [this](https://github.com/substack/picture-tube) would be worth a look ;-)\n2. pandoc -> html -> elinks, lynx or pandoc -> groff -> man. (Heavy and hard to use from within other programs. Styling suboptimal)\n3. vimcat (Also heavy and hard to use inline in other programs)\n\nSummary: For production ready robust markdown viewing (e.g. for your customers) I recommend nd still, due to the early state of mdv. For playing around, especially with theming or when with Python, this one might be a valid alternative to look at.\n\n## Installation\n\n pip install mdv\n\nIf you get `no attribute HTML_PLACEHOLDER`: update your markdown package.\n\n[Here](https://trac.macports.org/ticket/53591) is a macport (thanks Alja\u017e).\n\n\n### Manual Install: Requirements\n\n- python == 2.7 or > 3.5\n- py markdown (pip install markdown)\n- py pygments (pip install pygments)\n- py yaml (pip install pyyaml)\n- py docopt (pip install docopt)\n- py tabulate (pip install tabulate)\n\nFurther a 256 color terminal (for now best with dark background) and font support for a few special separator characters (which you could change via config).\n\n> For light terms you'd just need to revert the 5 colors from the themes, since they are sorted by luminocity.\n\nI did not test anything on windows.\n\n### Manual Install: Setup\n\nDistribution via setuptools. If setuptools is not installed, run:\n\n pip install setuptools\n\n\nUse the setup.py provided inside, I.e. run:\n\n\tsudo ./setup.py install\n (or ./setup.py install --user to install only for the current user)\n\n\n\n## Usage\n\n### CLI\n\n```markdown\n\n# Usage:\n\n mdv [OPTIONS] MDFILE\n\n# Options:\n\n MDFILE : Path to markdown file\n -A : Strip all ansi (no colors then)\n -C MODE : Sourcecode highlighting mode\n -H : Print html version\n -L : Backwards compatible shortcut for '-u i'\n -M DIR : Monitor directory for markdown file changes\n -T C_THEME: Theme for code highlight. If not set: Using THEME.\n -X Lexer : Default lexer name (default: python). Set -x to use it always.\n -b TABL : Set tab_length to sth. different than 4 [default: 4]\n -c COLS : Fix columns to this (default: your terminal width)\n -f FROM : Display FROM given substring of the file.\n -h : Show help\n -i : Show theme infos with output\n -l : Light background (not yet supported)\n -m : Monitor file for changes and redisplay FROM given substring\n -n NRS : Header numbering (default: off. Say e.g. -3 or 1- or 1-5\n -t THEME : Key within the color ansi_table.json. 'random' accepted.\n -u STYL : Link Style (it=inline table=default, h=hide, i=inline)\n -x : Do not try guess code lexer (guessing is a bit slow)\n\n\n# Notes:\n\nWe use stty tool to derive terminal size. If you pipe into mdv we use 80 cols.\n\n## To use mdv.py as lib:\n\nCall the main function with markdown string at hand to get a\nformatted one back. Sorry then for no Py3 support, accepting PRs if they don't screw Py2.\n\n## FROM:\n\nFROM may contain max lines to display, seperated by colon.\nExample:\n\n -f 'Some Head:10' -> displays 10 lines after 'Some Head'\n\nIf the substring is not found we set it to the *first* character of the file -\nresulting in output from the top (if your terminal height can be derived correctly through the stty cmd).\n\n## Code Highlighting\n\nSet -C <all|code|doc|mod> for source code highlighting of source code files.\nMark inline markdown with a '_' following the docstring beginnings.\n\n- all: Show markdown docstrings AND code (default if you say, e.g. `-C.`)\n- code: Only Code\n- doc: Only docstrings with markdown\n- mod: Only the module level docstring\n\n\n## File Monitor:\n\nIf FROM is not found we display the whole file.\n\n## Directory Monitor:\n\nWe check only text file changes, monitoring their size.\n\nBy default .md, .mdown, .markdown files are checked but you can change like `-M 'mydir:py,c,md,'` where the last empty substrings makes mdv also monitor any file w/o extension (like 'README').\n\n### Running actions on changes:\n\nIf you append to `-M` a `'::<cmd>'` we run the command on any change detected (sync, in foreground).\n\nThe command can contain placeholders:\n\n _fp_ # Will be replaced with filepath\n _raw_ # Will be replaced with the base64 encoded raw content\n of the file\n _pretty_ # Will be replaced with the base64 encoded prettyfied output\n\nLike: mdv -M './mydocs:py,md::open \"_fp_\"' which calls the open\ncommand with argument the path to the changed file.\n\n\n## Themes\n\n### Theme Rollers\n\n\n mdv -T all [file]: All available code styles on the given file.\n mdv -t all [file]: All available md styles on the given file.\n If file is not given we use a short sample file.\n\nSo to see all code hilite variations with a given theme:\n\nSay C_THEME = all and fix THEME\n\nSetting both to all will probably spin your beach ball...\n\n### Environ Vars\n\n`$MDV_THEME` and `$MDV_CODE_THEME` are understood, e.g. `export\nMDV_THEME=729.8953` in your .bashrc will give you a consistent color scheme.\n\n\n```\n\n> Regarding the strange theme ids: Those numbers are the calculated total luminocity of the 5 theme colors.\n\n### Inline\n\nmdv is designed to be used well from other (Py2) programs when they have md at hand which should be displayed to the user:\n\n```python\nimport mdv\n\n# config like this:\nmdv.term_columns = 60\n\n# calling like this (all CLI options supported, check def main\nformatted = mdv.main(my_raw_markdown, c_theme=...) \n```\n\n> Note that I set the defaultencoding to utf-8 in ``__main__``. I have this as my default python2 setup and did not test inline usage w/o. Check [this](http://stackoverflow.com/a/29832646/4583360) for risks.\n\n### Sample Inline Use Case: click module docu\n\n[Armin Ronacher](http://lucumr.pocoo.org/2014/5/12/everything-about-unicode/)'s\n[click](http://click.pocoo.org) is a great framework for writing larger CLI apps - but its help texts are a bit boring, intended to be customized.\n\nHere is how:\n\nWrite a normal click module with a function but w/o a doc string as shown:\n```python\n@pass_context \ndef cli(ctx, action, name, host, port, user, msg): \n\t\"\"\" docu from module __doc__ \"\"\"\n```\n\nOn module level you provide markdown for it, like:\n\n```shell\n~/axc/plugins/zodb_sub $ cat zodb.py | head\n\"\"\"\n# Fetch and push ZODB trees\n\n## ACTION: < info | pull | push | merge | dump | serve>\n\n- info: Requests server availability information\n(...)\n```\nwhich you set at click module import time:\n\n\tmod.cli.help = mod.__doc__\n\n\nLastly do this in your app module:\n\n```python\nfrom click.formatting import HelpFormatter\ndef write_text(self, text):\n \"\"\" since for markdown pretty out on cli I found no good tool\n\tso I built my own \"\"\"\n # poor man's md detection:\n if not text.strip().startswith('#'):\n return orig_write_text(self, text)\n from axc.markdown.mdv import main as mdv\n self.buffer.append(mdv(md=text, theme=os.environ['AXC_THEME']))\n\nHelpFormatter.orig_write_text = HelpFormatter.write_text\nHelpFormatter.write_text = write_text\n```\n\nThe output has then colors:\n\n![](samples/3.png)\n\nand at smaller terms rewraps nicely:\n\n![](samples/4.png)\n\nFurther, having markdown in the module ``__doc__`` makes it simple to add into a global project docu framework, like mkdocs.\n\n\n\n## Customization\n\nYou can supply all CLI args in `$HOME/.mdv`, in yaml format.\n\nMore flex you have via `$HOME/.mdv.py`, which is execed if present, when\nrunning `main`.\n\nAlternatively, in [mdv.py](mdv.py) you can change some config straight forward.\n\n```python\n# ---------------------------------------------------------------------- Config\ntxt_block_cut, code_pref, list_pref, br_ends = '\u2702', '| ', '- ', '\u25c8'\n# ansi cols (default):\n# R: Red (warnings), L: low visi, BG: background, BGL: background light, C=code\n# H1 - H5 = the theme, the numbers are the ansi color codes:\nH1, H2, H3, H4, H5, R, L, BG, BGL, T, TL, C = \\\n231, 153, 117, 109, 65, 124, 59, 16, 188, 188, 59, 102\n# Code (C is fallback if we have no lexer). Default: Same theme:\nCH1, CH2, CH3, CH4, CH5 = H1, H2, H3, H4, H5\n\ncode_hl = { \"Keyword\" : 'CH3', \"Name\" : 'CH1',\n \"Comment\" : 'L', \"String\": 'CH4',\n \"Error\" : 'R', \"Number\": 'CH4',\n \"Operator\": 'CH5',\n \"Generic\" : 'CH2'\n }\n\nadmons = {'note' : 'H3', 'warning': 'R',\n 'attention': 'H1', 'hint' : 'H4',\n 'summary' : 'H1', 'hint' : 'H4',\n 'question' : 'H5', 'danger' : 'R',\n 'caution' : 'H2'\n }\n\ndef_lexer = 'python'\nguess_lexer = True\n# also global. but not in use, BG handling can get pretty involved...\nbackground = BG\n\n# normal text color:\ncolor = T\n\nshow_links = None\n\n# could be given, otherwise read from ansi_tables.json:\nthemes = {}\n\n\n# sample for the theme roller feature:\nmd_sample = ''\n\n# ------------------------------------------------------------------ End Config\n```\n\nAny importing module can overwrite those module global variables as well.\n\nShould you need yet additional themes, add them to ``ansi_tables.json`` file by adding your ansi codes there.\n\n\n\n## Screenshots\n\nRandom results, using the theme roller feature:\n\n![second](https://github.com/axiros/terminal_markdown_viewer/blob/master/samples/2.png)\n\nNote the table block splitting when the table does not fit (last picture).\n\n## TODO\n\n- Refactor the implementation, using a config class\n- Lines separators not optimal ([nd](https://www.npmjs.com/package/nd) does better)\n- Test light colorscheme\n- Dimming\n- A few grey scale and 8 color themes\n- Sorting of the json by luminance\n- Some themes have black as darkest color, change to dark grey\n- Common Mark instead of markdown\n\n## PerfTests\n\nRendering this readme [100 times](./mdv/misc/perftest.py):\n```\nblack root@ip-10-34-2-19:~/terminal_markdown_viewer/mdv/misc# python perfest.py\n0.03 paka\n0.04 paka_breaks\n0.04 paka_xml\n1.47 mistletoe\n8.70 markdown\n5.22 commonmark\n```\n- markdown did better than commonmark w/o extensions but table and fenced code\nare definitelly required for 99% users.\n\n- paka is a wrapper around the C reference lib -> requires compilation.\n\n- mistletoe is pure python, crazy that they are so much faster than CommonMark.\nThey say in pypy they are speed up even much more.\n\nmistletoe downside: py2 only via a fork.\n\n\n## Credits\n\n[pygments](http://pygments.org/) (using their lexer)\n\n[tabulate](https://pypi.python.org/pypi/tabulate)\n\nand, naturally, the [python markdown project](https://pythonhosted.org/Markdown/authors.html)\n\nUpdate: Next version will be CommonMark based though...\n\n\n## Updates\n\n### July 2016:\n\nSort of an excuse for the long long time w/o an update:\nI did actually start working on a more solid version based on CommonMark but\nthat went a bit out of scope, into a general html terminal viewer, which will\nprobably never be finished :-/\n\nSo at least here an update containing the stuff you guys sent as PRs, thanks all!!\n\n- installation and dependencies via a setup.py (thanks\n [Martin](https://github.com/althonos))\n- supporting `echo -e \"# foo\\n## bar\" | mdv -` and a 'light' theme (thanks\n [Stanislav](https://github.com/seletskiy))\n- and a few other improvements regarding python2.7, file location and pyyaml, thanks all.\n\nAlso:\n\n- fixed the most obvious bugs with nested ordered and unordered lists\n- fixed bold marker\n- different color highlighting for the list markers\n- added a source code highlighting mode, which highlights also docstrings in markdown (`-C <mode>`)\n- some tests in the tests folder\n- using `textwrap` now for the wrapping, to avoid these word breaks a few complained about\n- you can supply the default lexer now, e.g. `-X javascript [-x]`\n- fixed but with not rendered strong texts\n- pip install mdv\n\n\n### Nov 2016:\n\n- travis\n\n- Inline link tables\n\n![](./samples/links.png)\n\n\n\n[travis]: https://travis-ci.org/axiros/terminal_markdown_viewer\n[travis_img]: https://travis-ci.org/axiros/terminal_markdown_viewer.svg?branch=master\n\n\n\n### Sept 2018:\n\n- Merged some PRs, thanks.\n- Decent [code formatter](https://github.com/ambv/black). Not that this weekend hack got more readable though. Well, maybe a bit.\n- Revised Py3 support (finally found peace with it, since they enforce UTF-8 everywhere the new features begin to outweigh the nightmares of trying to decode everything without need).\n- Indented code in PY3 was broken, fixed that. Why, PY3, are you creating crap like `\"b'foo'\"` instead raising or auto-decoding (since you work anyway only with your UTF8-everywhere-assumption)!?\n- Header numbering feature added (`-n 2-4` or `-n 1-`)\n<img src=\"https://raw.githubusercontent.com/WillNye/terminal_markdown_viewer/master/samples/header_num.png\" width=\"400\"/>\n- docopt and pyyaml install requirement removed, better config file handling.\n- pypi markdown rendering for the readme, finally.\n\n\n",
"bugtrack_url": null,
"license": "",
"summary": "Terminal Markdown Viewer",
"version": "2.0.2",
"project_urls": {
"Download": "http://github.com/WillNye/terminal_markdown_viewer/tarball/",
"Homepage": "http://github.com/WillNye/terminal_markdown_viewer"
},
"split_keywords": [
"markdown",
"markup",
"terminal",
"hilighting",
"syntax",
"source code"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "fd72b9cff2e72f89a7c9ab64bbd032e4e478cc613c39c777152c4e9e74ee26ca",
"md5": "bca6d3fcde16065af2150dce6d3cd464",
"sha256": "693460722a396cd85c4962efeded1b06570e2f9b3c1bbce5f1df710fe31e328e"
},
"downloads": -1,
"filename": "mdv3-2.0.2-py3-none-any.whl",
"has_sig": false,
"md5_digest": "bca6d3fcde16065af2150dce6d3cd464",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7",
"size": 45900,
"upload_time": "2021-06-29T18:30:19",
"upload_time_iso_8601": "2021-06-29T18:30:19.223143Z",
"url": "https://files.pythonhosted.org/packages/fd/72/b9cff2e72f89a7c9ab64bbd032e4e478cc613c39c777152c4e9e74ee26ca/mdv3-2.0.2-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2021-06-29 18:30:19",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "WillNye",
"github_project": "terminal_markdown_viewer",
"travis_ci": true,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "markdown",
"specs": []
},
{
"name": "pygments",
"specs": []
},
{
"name": "six",
"specs": []
},
{
"name": "tabulate",
"specs": []
}
],
"lcname": "mdv3"
}