Source-highlight for matlab/octave

1 minute read

I recently worked with Matlab a lot. When in console, sometimes I want to use less to quickly examine the file content, and I have already set it up such that it uses source-highlight to output colorful escape sequence to the console. However, source-highlight does not come with a syntax support for Matlab by default. Luckily, this post and this (in Chinese) provides a solution.

First of all, install source-highlight using homebrew.

brew install source-highlight

Note that source-highlight depends on boost, and as of the date of this post, brew provides a precompiled library (bottle) for boost. However, the python support is compiled against the system python, so if you installed a custom one (say installed via homebrew) and use it by default, brew will compile the boost from source instead, which takes an extremely long time. To prevent this, we need to unlink it first, and link it back afterwards. That is,

brew unlink python
brew link python    # after installation

Go to the following folder and create two files,

cd `brew --prefix source-highlight`/share/source-highlight
keyword blue;
string #a020f0;
comment darkgreen;
keyword = "break|case|catch|classdef|continue|else|elseif|end|for|function|global|if|otherwise|parfor|persistent|return|spmd|switch|try|while"

keyword = '^\s*(break|case|catch|classdef|continue|else|elseif|end|for|function|global|if|otherwise|parfor|persistent|return|spmd|switch|try|while)(?=\s)'

include "function.lang"

state command start '^\s*[a-zA-Z][\w]*(?=\s)(?!\s+\.?[*/+-:]\s+\w)(?!\s+=)' begin
        comment start "%"
        string delim '[[:blank:]]' '[^%;]*'

comment delim "%{" "%}" multiline nested
comment start "%"

string delim '(?<![\w.])\'' "'" escape "''"

Finally, edit to create a mapping for matlab file.

echo 'm = matlab.lang' >>