Loading

less 命令支持语法高亮

1. How

主要分为两个方面的工作:

① 安装source-highlight

② 对less命令的配置

1.1 安装source-highlight

source-highlight是实现less命令中的语法高亮的核心组件

我们需要其中的src-hilite-lesspipe.sh脚本来完成对less命令的配置

以下是在Debian和Fedora中安装source-highlight、以及查找src-hilite-lesspipe.sh脚本位置命令

  • Debian:

    sudo apt install libsource-highlight-common source-highlight
    dpkg -L libsource-highlight-common | grep lesspipe
    # /usr/share/source-highlight/src-hilite-lesspipe.sh
    
  • Fedora:

    sudo dnf install source-highlight
    rpm -ql source-highlight | grep lesspipe
    # /usr/bin/source-highlight/src-hilite-lesspipe.sh
    

1.2 配置less命令

编辑 .bashrc,对less做配置

$ vim ~/.bashrc # 1. 打开.bashrc文件

# 2. 添加如下语句到.bashrc文件中
export LESSOPEN="| /usr/share/source-highlight/src-hilite-lesspipe.sh %s"
export LESS=" -R "

$ source ~/.bashrc # 3. 使配置生效

其中, /usr/share/source-highlight/src-hilite-lesspipe.sh 就是 src-hilite-lesspipe.sh 脚本的路径,具体的路径已经在前一节给出

1.3 效果图

less-with-syntax-highlight-and-line-number

2. Why

接下来看看到底发生了什么事情,可以做到这么「神奇」的效果。

2.1. LESSOPEN

首先来看source-highlight,这个工具可以根据给定的源文件,读取动态读取语言特性,然后输出一个语法高亮的文件,支持多种输出格式,如 HTML、XHTML、LATEX、 「ANSI color escape sequences 」等;默认是 HTML格式。

最后一种输出格式是 ANSI 颜色转义序列,支持彩色。这种输出格式恰好可以和 less 结合使用,使其输出结果支持语法高亮。

再看 LESSOPEN。查看 less 的 man 帮助手册,可以看到 less 支持一个叫 「input preprocessor」的东西,可以在 less 打开源文件之前对源文件进行一次预处理。这个「input preprocessor」 可以自己定义:

To set up an input preprocessor, set the LESSOPEN environment variable to a command line which will invoke your input preprocessor. This command line should include one occurrence of the string “%s”, which will be replaced by the filename when the input preprocessor command is invoked.

上面这句话说明了如何使用自己定义的预处理器,就是设置一下 LESSOPEN 这个环境变量。那么 LESSOPEN 到底是什么呢? 可以在帮助手册找到定义:

Command line to invoke the (optional) input-preprocessor.

LESSOPEN 指定一个「input preprocessor」,后面用 %s 读取文件路径。

可以看到上面的配置中,有一个前导的竖线 |。熟悉 *nix 命令行的人知道这是管道,这个竖线表示把「input preprocessor」的处理结果写到标准输出(standard output),然后 less 通过 input pipe 读取再显示到屏幕上。

2.2. LESS

另一个变量是 LESS,同样查看帮助手册:

Options which are passed to less automatically.

也就是自动传给 less 的选项,相当于缺省参数。上面设置的缺省选项是 -R,看看 -R 选项的意义:

-R or –RAW-CONTROL-CHARS
Like -r, but only ANSI “color” escape sequences are output in “raw” form. …

这个选项的意义是,对于「ANSI color escape sequences 」是直接输出的,而不错其他处理。

上面用 source-highlight 提供的 src-hilite-lesspipe.sh 脚本用作 「input preprocessor」把源文件进行了高亮处理,并且输出「ANSI color escape sequences 」格式.

这里设置 -R 选项刚好可以把这个高亮过后的字符序列直接输出,因此就可以看到 less 下的语法高亮。

References

posted @ 2022-08-04 10:09  Minerw  阅读(1171)  评论(0编辑  收藏  举报