Skip to main content

终端降价查看器

项目描述

终端降价查看器

这是axiros mdv 的一个分支 不再维护原始 repo。这是一个积极维护的分支,它放弃了对 python2 的支持,并包括对 python3.9+ 的支持

当您远程编辑多个 md 文件时,例如在较大的 mkdocs项目中,编辑终端和查看浏览器之间的上下文切换可能会对效率产生一些影响。有时也没有浏览器,比如通过安全网关在跳进机器上只提供一组固定的应用程序。此外,通过使用颜色通常可以显着提高阅读效率和便利性。最后,在 cli 应用程序中使用这样的东西可能会改善用户输出,例如帮助文本。

这就是 mdv,一个基于 Python 的终端 Markdown 查看器可能是一个不错的选择。

如果降价通常“简单”到足以在 256 色终端(图像除外)上有些可读性。

### 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

您还可以将 mdv 用作源代码查看器,最好在代码中包含带有 markdown 的文档字符串时:

~/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__,

(文档字符串后的 '_' 告诉 mdv 降价紧随其后)


mdv 是一个概念验证 hack:虽然对于简单的结构,它可以很好地完成它的工作,但对于复杂的 markdown,您需要使用其他工具。特别是对于内联的 html,它根本就失败了。


特征

  • 大量的主题组合:mdv 附带 > 200 个 luminocity 排序主题,从 html 主题表转换为 ansi。这些可以组合用于代码与常规降价输出......
  • 告诫
  • 桌子,包括。宽表处理避免“交错”
  • 有点可破解,都在一个模块中
  • 也可用作 lib
  • 文件更改监视器
  • 文字换行
  • 源代码高亮
  • 小目录更改监视器(在处理多个文件时派上用场,以始终显示当前文件)
    • 可以对文件更改运行任意命令
    • 它将文件路径,原始和漂亮的内容传递给另一个命令注意:可怜的人的实现,轮询。如果您想要更好的东西,请检查基于 inotify 的工具。

备择方案

我知道的那些(这让我写了 mdv ;-)):

  1. js 社区有很多(例如msee、ansidown、ansimd 和 nd 都很棒),但它们需要 nodejs 和 npm,而我的服务器上没有。此外,我个人还希望在整个过程中提供表格处理和警告支持。太老了,无法破解其他人的 js(我自己的 js 已经够挣扎了)。但是看看他们,他们在这个早期版本中比 mdv 做得更好(我尝试向他们学习)。这值得一看;-)
  2. pandoc -> html -> elinks、lynx 或 pandoc -> groff -> man。(在其他程序中很重且难以使用。样式不理想)
  3. vimcat(在其他程序中也很重且难以内联)

总结:对于生产就绪的强大降价查看(例如,为您的客户),由于 mdv 的早期状态,我仍然建议使用 nd。对于玩耍,尤其是在使用主题或使用 Python 时,这可能是一个有效的替代方案。

安装

pip install mdv

如果你得到no attribute HTML_PLACEHOLDER:更新你的降价包。

是一个macport(感谢Aljaž)。

手动安装:要求

  • 蟒蛇 == 2.7 或 > 3.5
  • py markdown (pip install markdown)
  • py pygments(点安装 pygments)
  • py yaml(点安装 pyyaml)
  • py docopt(点安装 docopt)
  • py 制表(点安装制表)

此外,还有一个 256 色终端(目前最好使用深色背景)和一些特殊分隔符的字体支持(您可以通过配置更改)。

对于浅色术语,您只需要从主题中恢复 5 种颜色,因为它们是按亮度排序的。

我没有在 Windows 上测试任何东西。

手动安装:设置

通过 setuptools 分发。如果未安装 setuptools,请运行:

pip install setuptools

使用里面提供的setup.py,即运行:

sudo ./setup.py install
(or ./setup.py install --user to install only for the current user)

用法

命令行界面

# 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.

关于奇怪的主题 ID:这些数字是 5 种主题颜色的计算总亮度。

排队

mdv 被设计为可以从其他(Py2)程序中很好地使用,当他们手头有 md 时,应该向用户显示:

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=...)  

请注意,我在__main__. 我将此作为我的默认 python2 设置,并且没有测试内联用法。检查是否存在风险。

示例内联用例:单击模块文档

Armin Ronacherclick是编写大型 CLI 应用程序的绝佳框架 - 但它的帮助文本有点乏味,旨在定制。

方法如下:

编写一个带有函数但没有 oa 文档字符串的普通点击模块,如下所示:

@pass_context                                                                   
def cli(ctx, action, name, host, port, user, msg):           
	""" docu from module __doc__ """

在模块级别,您为其提供降价,例如:

~/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
(...)

您在单击模块导入时设置的:

mod.cli.help = mod.__doc__

最后在您的应用程序模块中执行此操作:

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

输出有颜色:

并且在较小的条件下很好地重新包装:

此外,在模块中使用 markdown__doc__可以很容易地添加到全局项目文档框架中,例如 mkdocs。

定制

$HOME/.mdv您可以以 yaml 格式提供所有 CLI 参数。

更多 flex 你有 via $HOME/.mdv.py,如果存在,则在运行时执行main

或者,在mdv.py中,您可以直接更改一些配置。

# ---------------------------------------------------------------------- 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

任何导入模块也可以覆盖这些模块全局变量。

如果您还需要其他主题,ansi_tables.json请通过在此处添加您的 ansi 代码将它们添加到文件中。

截图

随机结果,使用主题滚轮功能:

第二

请注意表格不适合时的表格块拆分(最后一张图片)。

去做

  • 使用配置类重构实现
  • 行分隔符不是最佳的(nd更好)
  • 测试灯光配色方案
  • 调光
  • 几个灰度和8个颜色主题
  • 按亮度对 json 进行排序
  • 一些主题将黑色作为最暗的颜色,更改为深灰色
  • 通用标记而不是降价

性能测试

将此自述文件渲染100 次

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 比不带扩展的 commonmark 做得更好,但 99% 的用户肯定需要表格和防护代码。

  • paka 是 C 参考库的包装器 -> 需要编译。

  • 槲寄生是纯蟒蛇,疯狂到它们比 CommonMark 快得多。他们在 pypy 中说他们的速度更快。

槲寄生的缺点:py2 只能通过叉子。

学分

pygments(使用他们的词法分析器)

制表

当然还有python markdown 项目

更新:下一个版本将基于 CommonMark...

更新

2016 年 7 月:

很长一段时间没有更新的借口:我确实开始研究基于 CommonMark 的更可靠的版本,但有点超出范围,进入一般的 html 终端查看器,这可能永远不会完成:-/

所以至少这里有一个包含你们作为 PR 发送的东西的更新,谢谢大家!!

  • 通过 setup.py 安装和依赖(感谢 Martin
  • 支持echo -e "# foo\n## bar" | mdv -和“轻”主题(感谢 Stanislav
  • 以及关于 python2.7、文件位置和 pyyaml 的其他一些改进,谢谢大家。

还:

  • 使用嵌套的有序列表和无序列表修复了最明显的错误
  • 固定粗体标记
  • 列表标记的不同颜色突出显示
  • 添加了一个源代码高亮模式,它也高亮了 markdown ( -C <mode>)中的文档字符串
  • 测试文件夹中的一些测试
  • 使用textwrapnow 进行包装,以避免这些单词中断一些抱怨
  • 您现在可以提供默认的词法分析器,例如-X javascript [-x]
  • 已修复但未呈现强文本
  • 点安装 mdv

2016 年 11 月:

  • 特拉维斯

  • 内联链接表

2018 年 9 月:

  • 合并了一些 PR,谢谢。
  • 体面的代码格式化程序。并不是说这个周末的黑客变得更具可读性。好吧,也许有点。
  • 修改后的 Py3 支持(终于找到了和平,因为它们在任何地方都强制执行 UTF-8,新功能开始超过试图在不需要的情况下解码所有内容的噩梦)。
  • PY3 中的缩进代码已损坏,已修复。为什么,PY3,你是在创造废话,"b'foo'"而不是提高或自动解码(因为你无论如何都只使用你的 UTF8 无处不在的假设)!?
  • 添加了标题编号功能(-n 2-4-n 1-
- 删除了 docopt 和 pyyaml 安装要求,更好的配置文件处理。- 最后,为自述文件提供 pypi markdown 渲染。

项目详情


下载文件

下载适用于您平台的文件。如果您不确定要选择哪个,请了解有关安装包的更多信息。

内置分布

mdv3-2.0.2-py3-none-any.whl (45.9 kB 查看哈希

已上传 py3