How to syntax highlight via Less

135

63

is there a way to syntax highlight a file I see in Less?

actually I'm using this command to open an xml file (and sometimes a series of them)

less htmleditors/htmleditors_config.xml

or

less [multiple files]

I'd like to stay in Less (to learn that program better and to use my knowledge of :n and :p for next/previous navigation)

But it also want some kind of basic syntax highlighting – at least show the comments differently. Do you know any way to do it?

Jesper Rønn-Jensen

Posted 2009-11-17T10:20:05.990

Reputation: 5 450

Answers

125

You can use GNU's source-highlight, as shown here (path may differ, see below):

 export LESSOPEN="| /usr/bin/src-hilite-lesspipe.sh %s"
 export LESS=' -R '

As of Debian Stretch and Fedora 25, package names and script paths differ

  • 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
    

brandstaetter

Posted 2009-11-17T10:20:05.990

Reputation: 4 119

23On Debian: sudo apt-get install source-highlight, export LESSOPEN="| /usr/share/source-highlight/src-hilite-lesspipe.sh %s", export LESS=' -R ' – Morgan Courbet – 2014-08-22T08:57:40.320

3small caveat: source-highlight does not currently support markdown. – dhulihan – 2016-07-07T06:10:22.233

also alias more='more -R ' or more will stop working. – Brian – 2017-02-08T01:25:58.050

As @dhulihan wrote, source-highlight does not support markdown. But highlight supports markdown and many more. OSX: brew install highlight; export LESSOPEN="| /usr/local/bin/highlight --out-format=xterm265 %s"

– ronen – 2017-05-26T22:26:44.123

Note that the Debian packaging is actually a bit broken: The script itself is in libsource-highlight-common, but calls source-highlight from eponymous package, but does not declare dependency on it (split as they are now, they seem to actually form a circular dependency). – Alois Mahdal – 2017-10-20T00:54:23.080

For Raspbian installs, use export LESSOPEN="| /usr/bin/source-highlight-esc.sh %s". – steviethecat – 2018-01-26T08:53:11.727

After installation and setting the env var, I still get no syntax coloring in less, unless I set the env vars in .bashrc, strange that setting it in /etc/profile.d/less.sh does not work; the vars are read and I can see them loaded(added echo in /etc/profile to see which files are loaded). Someone to help? It's a login shell with putty. – WesternGun – 2018-02-14T09:58:59.913

source-highlight requires a file (a named pipe won't work) for syntax highlighting, so something like pipeline | less won't work. For a solution see this answer. – Tom Hale – 2018-06-17T16:41:58.190

Is it possible to combine this with the default lesspipe(.sh) somehow? – AstroFloyd – 2018-10-07T06:50:16.640

@dhulihan GNU source-highlight - Bugs: bug #46542, Add support for Markdown We are all welcome to send a pull request

– Pablo A – 2019-02-01T17:56:49.910

This works fine but it breaks the ability to use default lesspipe for binary files, so instead I'd suggest something that uses this solution only for binary files (i.e. something like https://gist.github.com/textarcana/4611277#gistcomment-2859093), or just another script that does the same.

– Treviño – 2019-03-11T14:39:34.433

I retrieve the following error message when I run less ~/.zshrc. Error: src-hilite-lesspipe.sh: line 9: source-highlight: command not found. I run this on MacOSX. – JJD – 2012-06-04T16:38:06.087

2@JJD Did you install source-highlight? – Max Nanasy – 2012-08-31T06:00:14.007

13OSX: brew install source-highlight; export LESSOPEN="| /usr/local/bin/src-hilite-lesspipe.sh %s". Note the path change. – Gregg Lind – 2014-04-22T19:26:19.333

98

Best of both previous answers: you can invoke system default editor from within less, by pressing v.

JiM

Posted 2009-11-17T10:20:05.990

Reputation:

@jamesc FYI, you can enable syntax highlighting in Nano, here is how.

– Captain Man – 2016-04-14T19:00:10.617

@CaptainMan Nope nope nope! I change the default back to vim like Daniel H said! :D – jamesc – 2016-04-15T15:23:12.057

3Wow! This is amazingly useful! – StackExchange saddens dancek – 2012-08-09T05:57:04.037

13Curses that opened Nano on my Ubuntu box! – jamesc – 2013-01-18T10:12:16.917

5Then set $EDITOR or $VISUAL to vim (or emacs, or gedit, or joe, or ed, or mined, or…). – Daniel H – 2013-06-05T01:42:46.260

34

pygmentize somefile.ex | less -R

or

function cless () {
    pygmentize -f terminal "$1" | less -R
}

Pygmentize comes as a part of the Pygments Python syntax highliter.

user31752

Posted 2009-11-17T10:20:05.990

Reputation:

3pygmentize also works with the LESSOPEN stuff mentioned in other answers here. – Nathan – 2014-08-05T19:01:40.527

2To get pygmentize, you need Python and then you can install pygmentize with pip install pygments. – wkschwartz – 2015-03-20T01:11:11.637

3To get less to use pygmentize for syntax highlighting use: which pygmentize 2> /dev/null >&2 && export LESSOPEN="| pygmentize -g -f terminal256 %s". -g to make it work with pipes (less <(diff -u file1 files)). It's available in community/pygmentize package for arch linux, and in python-pygments for debian. – x-yuri – 2015-05-16T18:38:11.390

I like the output of pygmentize, but found it to be too slow. I came up with this answer which is faster and still 256-colour pretty.

– Tom Hale – 2018-06-17T16:44:50.977

you can also just pipe to pygmentize first, e.g. cat myfile | pygmentize | less -R – Tasos Papastylianou – 2019-11-12T19:37:01.330

16

I think that you should use a text editor. I like vim myself. That will give you LOTS of power when viewing files and then when you want to edit them you will already know the basics.

Here are some of the advantages of using a text editor (specifically vim):

  • syntax-highlighting
  • powerful movement commands
  • find
  • jump to specific location in a file (called a mark)
  • folding (useful when you just want to see function stubbs)

To open your file in readonly mode use this:

vim -R <file name>

Here is a basic navigation guide:

j - move down one line
k - move up one line
h - left one char
l -right one char

ctrl-f - forward one page
ctrl-b - back one page

/<something> - search for something
n - next of whatever you searched for
N - next (search backwards) of whatever you searched for

:q - quit
:q! - quit without saving
:w - save

Here is a link for more information:

http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html

Just to recap, if you will use unix vim is pretty fundamental. I have heard that learning vim is like learning to type. It is the next most useful tool you can learn for programming.

(Just to avoid editor wars you could also look into emacs or another editor, however I personally prefer vim)

sixtyfootersdude

Posted 2009-11-17T10:20:05.990

Reputation: 6 399

When you have a file of several hundred megabytes, such as for example a huge XML file, you'll really prefer to use less rather than opening the file in Vim, Emacs or any other editor. That's the whole point of opening a file in less. You can also perform text searches in less as you do in Vim, BTW. – José L. Patiño – 2020-01-17T11:22:23.487

1I second this. Vim launches as fast as less, and many of the keyboard shortcuts (e.g., search, next page, previous page) are identical. – Jeremy W. Sherman – 2011-02-10T18:20:42.737

10Just FYI, on a lot of systems, view is an alias for vim -R. – Andrew Ferrier – 2012-09-18T13:12:50.837

16

As others have said, you can use the power of vim. But importantly, you can do so without learning how to use vi/vim.

Vim comes with a less.vim script that works pretty well as a replacement for less, with full color syntax highlighting. It uses less keybindings (just hit 'q' to quit).

It had a few problems, so I improved it. Here's a screenshot from my blog post on it (archived 2013-04-09; original throws 503):

screenshot of https://github.com/huyz/less.vim

huyz

Posted 2009-11-17T10:20:05.990

Reputation: 332

2

Awesome! But as I couldn't find the script right away I'd like to share the command for locating it: find /usr/share/vim -name 'less.sh' which is taken from this gist: https://gist.github.com/chauncey-garrett/9773770

– nuala – 2015-02-21T22:13:30.760

Adding to @yoshi's comment, to quickly add a vimless command (following the nomenclature of vimdiff), do: ln -s $(find /usr/share/vim -name 'less.sh') /usr/local/bin/vimless – waldyrious – 2016-12-27T12:31:18.307

The link is 404! – acgtyrant – 2018-06-22T09:24:59.310

@acgtyrant Should be fixed now; the Internet Archive thankfully has it. – bb010g – 2019-04-19T18:39:17.867

10

I was also searching for this and found another solution using Vim: http://ubuntu-tutorials.com/2008/07/14/use-vim-as-a-syntax-highlighting-pager/

The post is rather old, so now on more recent distros vim 7.2 is shipped and the .bashrc will read: alias vless='vim -u /usr/share/vim/vim72/macros/less.vim'

Lorenzo

Posted 2009-11-17T10:20:05.990

Reputation: 101

1

This feature is documented in Vim itself under :help less

– joeytwiddle – 2018-02-03T16:20:45.110

1MacVim comes with a shell script that you can use directly, located in: /Applications/MacVim.app/Contents/Resources/vim/runtime/macros/less.sh – Nick – 2012-01-14T19:23:21.583

8

I'm glad to announce a new package, e2ansi, that provides syntax highlighting support for pagers like more and less.

The package use the mother of all text editors, Emacs, to perform the actual syntax highlighting. As an added bonus, all other conversions normally performed by Emacs -- like uncompressing files -- is also performed.

Example

The following is the result of viewing a file using less and e2ansi:

Example

Configuration

The package provides a command-line tool e2ansi-cat that starts Emacs in batch mode, opens files, syntax highlight them, and renders the result using ANSI sequences.

You can integrate this into less by setting the following variables to, for example (the location of your init file may vary):

export "LESSOPEN=||-/usr/local/emacs --batch -Q -l ~/.emacs -l bin/e2ansi-cat %s"
export "LESS=-r"
alias "more=less -X -E"

In the configuration above, less restores the original terminal window content whereas more simply output new content after the prompt.

Note: If you use an old version of less, it might not support the || or the - syntax, in which case you may need to use simply LESSOPEN=|/usr/local/emacs ....

Using less in pipes

The "-" character in LESSOPEN indicates that the input filter should also be used when piping text into less. In this case, Emacs can only rely on text itself (and not a file name). Fortunately, Emacs provides a system for this. In addition, the provided file file e2ansi-magic.el sets up additional file types. For example:

Pipe example

Why use Emacs?

  • Emacs has support for virtually all programming languages and structured text formats. In most cases, the syntax highlighting support is excellent.
  • You can easily add support for more languages and formats, or modify existing packages to suit you needs.
  • Emacs support color themes. When using e2ansi, the colors in the theme is preserved when viewing a file in less. You can pick a suitable color theme from a number of sources, or design your own.
  • If you use Emacs as your editor of choice, you will get the same highlighting in the editor as you get when viewing a file using less (minus limitations in ANSI sequence format and the terminal window).
  • less will take advantage of Emacs features that perform automatic conversion, for example uncompressing files. In fact, you can teach Emacs to perform any kind of conversion like automatically convert a binary file to human readable form using an external tool.
  • You can view files located on other machines by using Emacs' syntax for remote access like /USER@HOST:FILENAME.

Useful links

  • e2ansi is distributed on Melpa and can be installed using the standard Emacs package system
  • e2ansi is hosted on GitHub
  • The e2ansi page on the Emacs Wiki
  • The home of less.

Operating system notes

  • On MS Windows, the console does not natively support ANSI sequences. Fortunately, the less application is capable of rendering them. I am not aware of any contemporary binary distribution of less for MS Windows and the provided build files is hard to use. Fortunately, it's easy to build less using CMake, see this text for details.

  • OS X distributes an ancient version of less. Fortunately, it's easy to build a modern version directly from the source.

Lindydancer

Posted 2009-11-17T10:20:05.990

Reputation: 199

For OS X, I'd recommend using the package manager brew [http://brew.sh/] with brew dupes [https://github.com/Homebrew/homebrew-dupes] to install up-to-date versions of things like less. – drevicko – 2016-01-26T10:53:54.887

"powered by emacs" -- running whole VM just to look at a file? ;-) and +1 – Alois Mahdal – 2017-10-19T23:58:22.023

6

If you have GNU Source-highlight installed you can use the following command to highlight the syntax of a single file:

$ src-hilite-lesspipe.sh yourfile.xml | less -R

Oliver

Posted 2009-11-17T10:20:05.990

Reputation: 161

Can src-hilite-lesspipe.sh receive input via a pipe as well? – waldyrious – 2016-12-27T12:42:55.423

2

source-highlight has a .sh script located in /usr/share/source-highlight/*.sh. I've created a symbolic link to it with name hcat in /usr/bin.

It shows highlighted output in terminal (console) – hcat is highlighted cat.

How to:

[me@this]<bash><~> 43 
21:23 Fri Apr 19 > sudo apt-get install source-highlight

[me@this]<bash><~> 28 
21:03 Fri Apr 19 > ll /usr/share/source-highlight/*.sh
-rwxr-xr-x 1 root root 432 May  1  2012 /usr/share/source-highlight/src-hilite-lesspipe.sh*

[me@this]<bash><~> 29 
21:04 Fri Apr 19 > sudo su
root@this:/home/me# cd /usr/bin/
root@this:/usr/bin# ln -s /usr/share/source-highlight/src-hilite-lesspipe.sh hcat

[me@this]<bash><~> 36 
21:07 Fri Apr 19 > hcat test.xml

Vitalie Ghelbert

Posted 2009-11-17T10:20:05.990

Reputation: 131

2

Using OS X 10.9 (Maverick) this would do the trick:

  • brew install source-highlight (Assuming brew is installed - http://brew.sh)
  • sudo nano /etc/launchd.conf

    setenv LESSOPEN="| /usr/local/bin/src-hilite-lesspipe.sh %s"     
    setenv LESS=' -R '
    

    (Add to /etc/launchd.conf)

  • reboot

TeNGiL

Posted 2009-11-17T10:20:05.990

Reputation: 21

0

If you want the same syntax highlighting you use in Vim, but for some reason you prefer to use less as your pager, you can use this script: https://github.com/rkitover/vimpager

The basic usage would be:

vimpager file.txt

or

vimcat file.ext | less -R

You can use -c to pass extra commands which aren't in your .vimrc (e.g. selecting a different colorscheme). The full command I use is:

vimcat -c 'set cmdheight=20' -c 'hi! clear Normal' -o - "$FILENAME" | less -REXS

Beware: If your Vim asks you to press Enter when it starts up, you won't see the prompt, but nothing will happen until you press Enter! The cmdheight trick above can help to mitigate that.

joeytwiddle

Posted 2009-11-17T10:20:05.990

Reputation: 1 346

0

I found highlight which:

  • Supports multiple colour schemes and 256-colours
  • Works on STDIN (unlike source-highlight)
  • Is much faster than pygmentize

Screenshot

Here is a script I call highlight-less-wrapper which includes .bashrc instructions on how to setup less to use it automatically.

#!/bin/bash

# Have highlight read from STDIN if '-' is given as filename

# Setup - Add to .bashrc:
# LESSOPEN='|-highlight-less-wrapper "%s"'
# export LESS=-FMRXis

# Usage:
# $ less file
# OR
# $ pipeline | less

warn () { printf "%s: %s\n" "$(basename "$0")" "$*" 1>&2; }
die () { warn "$@"; exit 1; }

# Argument checking
case $# in
    0)
        # Allow `exec $0` for less setup
        echo "LESSOPEN='|-$(readlink -f "$0") "'"%s"'\'
        exit 255 ;;
    1)
        # Only one argument is expected.
        # less will invoke multiple times given multiple files.
        file=$1
        if [[ $file != - && ! -r $file ]]; then  # less passes '-' for STDIN
            die "Cannot open $file for reading"
        fi ;;
    *)
        die "Expected only one argument" ;;
esac

# Run highlight
# highlight will read from STDIN when given a null filename
run_highlight () {
    highlight --force -O truecolor --style aiseered "$1"
}

if [[ $file == - ]]; then  # Run on stdin
    run_highlight ""
else
    run_highlight "$file"
fi

Tom Hale

Posted 2009-11-17T10:20:05.990

Reputation: 1 348

"Since Github is now part of Mordor Corp, the highlight Git repo moved" Was interested, but cmon it's not the 90's anymore devs need to grow up. – Urda – 2018-10-02T19:15:48.560

0

I had the same question and I landed hear, read all answers and the following is what I finally did to have syntax highlighting everytime I use less or most:

sudo apt install source-highlight

Then I went and created an alias for my less and most (I use ZSH, but you can add aliases for your .bashrc file if you use bash):

vim ~/.zshrc

(For those who might get stuck in vim: press i to go to edit mode, when you are done press Esc then : then x and finally Enter to save the changes)

And paste the following lines for debian-based distros (like Debian, Ubuntu, Mint, etc.):

alias most='AliasFuncLess() { unset -f AliasFuncLess; $(dpkg -L libsource-highlight-common | grep lesspipe) "$1" | less -R };AliasFuncLess'
alias most='AliasFuncMost() { unset -f AliasFuncMost; $(dpkg -L libsource-highlight-common | grep lesspipe) "$1" | most };AliasFuncMost'

or for RPM distros (Redhat, Fedora, Centos):

alias most='AliasFuncLess() { unset -f AliasFuncLess; $(rpm -ql source-highlight | grep lesspipe) "$1" | less -R };AliasFuncLess'
alias most='AliasFuncMost() { unset -f AliasFuncMost; $(rpm -ql source-highlight | grep lesspipe) "$1" | most };AliasFuncMost'

Remember to close the terminal and open it again to make sure alias is created.

Now you can enjoy the colors:

most yourFile.xml

Mehrad Mahmoudian

Posted 2009-11-17T10:20:05.990

Reputation: 187

0

In mac, you can just type view filename, does similar thing like less.

Alan Dong

Posted 2009-11-17T10:20:05.990

Reputation: 173

1With OSX, view filename just launches vim by default - slightly different key bindings to less (see other answers to this question for more details). – drevicko – 2016-01-26T10:56:35.133

0

After installing GNU's source-highlight (package dev-util/source-highlight on sabayon/gentoo), I configured those envs in /etc/bash/bashrc.d/my-less-src-highlight:

#default:    export LESSOPEN="|lesspipe %s"
#don't like: export LESSOPEN="| /usr/bin/src-hilite-lesspipe.sh %s"
#default:    export LESS=" -R -M --shift 5"
export LESSCOLOR=always
export LESSCOLORIZER=/usr/bin/src-hilite-lesspipe.sh

I did not like to replace lesspipe because that has other features. Concatenation did not work.

comonad

Posted 2009-11-17T10:20:05.990

Reputation: 101