How to configure 'less' to show formatted markdown files?

廉价感情. 提交于 2021-02-17 21:37:46

问题


I would like to have less display *.md markdown files with some formatting -- like I know less can, for manpages, etc. I am running Ubuntu 12.04.

I am as far as putting a user defined filter into .lessfilter:

#!/bin/sh
case "$1" in
  *.md)
    fn=/tmp/$1.$$.html
    markdown "$1" | html2txt > $fn  ### LOSES FORMATTING
    cat $fn                         ### TO STDOUT???
    ;;
  *)
  # We don't handle this format
  exit 1
esac
# No further processing by lesspipe necessary
exit 0

So, the main questions are:

  • How can I pass some basic formatting information to less as well, instead of losing it with html2txt
  • Is it correct to just print the new content to stdout? Or could I just write the *.html to file disk and let less handle that html at its own digression (seeing the html-extension and acting on it?)

回答1:


Take a look at Pandoc. It can convert files from markdown format to groff man pages which you can then view in man.

Your .lessfilter script would be:

case "$1" in
  *.md)
    pandoc -s -f markdown -t man "$1" | man -l -
    ;;

Alternatively, convert it to html using the markdown command and then use the lynx browser to view it, but this didn't work too well for me.

case "$1" in
  *.md)
    markdown "$1" | lynx -stdin
    ;;

And, yes, the lessfilter script must write to stdout.




回答2:


Dogbane's answer is great, but if you use groff -T utf8 -man instead of man -l to do the formatting, then the bold, italic, etc. come through. As seen here: https://stackoverflow.com/a/20197316/2674930.




回答3:


This didn't work on my version of MacOSX (10.10.5 Yosemite). The man page doesn't mention a .lessfilter either. Here is what I did (after reading MAN page - thanks to this question for the prompt and hints).

I created the scripts lessopen.sh and lessclose.sh in my ~/bin. Respectively they are:

#!/bin/bash

case "$1" in
  *.md)
    pandoc -s -f markdown -t man "$1" | groff -T utf8 -man > /tmp/less.$$
    if [ -s /tmp/less.$$ ]; then
        echo /tmp/less.$$
    else
        rm -f /tmp/less.$$
    fi
    ;;
esac

and

#!/bin/sh
rm $2

The return from the lessopen.sh is the name of the file with the contents to lessen. Or if nothing then the original file is used. The -s tests if the file is NOT zero size. The lessclose.sh cleans up.

Then in my ~/.bash_profile is:

export LESSOPEN="lessopen.sh %s"
export LESSCLOSE="less-close.sh %s %s"

I also had to install pandoc - groff already existed

brew install pandoc

Then simply:

less README.md

to read it rendered.



来源:https://stackoverflow.com/questions/15496865/how-to-configure-less-to-show-formatted-markdown-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!