Personal blog and hacks by Raymundo Cassani

Spellcheck Matlab and Python scripts

Based on icon made by Freepik from

Good code commenting, including good syntax and spelling, is an important feature to assure the high quality of code documentation, which in turn, is vital in development of scientific open-source software. Poor spelling is not only unprofessional, it can create confusion, reduce clarity and meaning, and produce embarrassing typos in the GUI, e.g. "EGG signal" instead of "EEG signal".

Although it's an often demanded functionality, as per July 2021, there is not spellcheck support in Matlab Editor. Some approaches to spellcheck the code consist in: opening the scripts in a different (text) editor, or extracting the comments from the scripts to spellcheck them with a different software, and propagate the changes back to the original files. Link.

In this post, a "simpler" way is described, i.e., configure Aspell and use it to perform spellchecking only in: comments and strings.

The following command installs Aspell and English dictionaries with pacman. Similar commands should work for other package managers.

# pacman -S aspell aspell-en

We need to indicate Aspell to only spellcheck text between delimiters. This is to say text between % and the EOL for comments; and text between ' and ' for strings.

$ aspell --add-filter context --clear-context-delimiters --add-context-delimiters "% \0" --add-context-delimiters "' '" -c matlab_script.m

Although the documentation of Aspell indicates that "If more than one delimiter pair is specified by one call of add|rem-context-delimiters they have to be combined to a comma separated list." the option "% \0,' '" does not work as expected, that's why the previous command has twice the --add-context-delimiters option.

For sake of simplicity it's possible to save such configuration as an Aspell filter mode, defined in a Aspell Mode File (.amf) (Filter Modes), and make it the default mode (behaviour) for .m files. As such, a file matlab.amf file (link) is created in the Aspell path, /usr/lib/aspell in my case, and it contains:

MODE matlab

ASPELL >=0.60.1

MAGIC /<noregex>/m

DESCRIPTION mode for checking Matlab comments

FILTER context
OPTION clear-context-delimiters
OPTION add-context-delimiters % \0
OPTION add-context-delimiters ' '

Thus, to spellcheck a Matlab script, just run:

$ aspell -c matlab_script.m

Bonus content: Spellcheck in Python scripts

Several Python IDEs, such as Spyder already have spellcheck. To use Aspell in spellcheck of comments (which start with #) and strings (that can be between single and double quotes), in theory an similar approach "should" work, however, there is a bug with configuring # in a .amf file. Fortunately, it can be worked out with this messy call to Aspell:

$ aspell --add-filter context --clear-context-delimiters --add-context-delimiters "# \0" --add-context-delimiters "' '" --add-context-delimiters "\" \"" -c


comments powered by Disqus