FactorPad
Build a Better Process

Enable Syntax Highlighting and Colors in nano

The easiest-to-use and widely-available text editor can be enhanced with the steps that follow.
  1. nanorc & .nanorc - Describe the systemwide nanorc and user-specific .nanorc files.
  2. Before & after - Show our goal before and after changes.
  3. Two customizations - Create and edit a local .nanorc file and a programming language-specific file.
  4. nano vs. IDE - Learn why it is important to at least be comfortable with nano.
  5. Next: Python - Move to Project 3 - Python for Beginners.
face pic by Paul Alan Davis, CFA
Updated: February 21, 2021
While nano doesn't offer enough features to be your daily editor, it is a good choice for server configuration files.

Outline Back Tip Next

/ factorpad.com / tech / full-stack / nano-syntax-highlighting.html


An ad-free and cookie-free website.


Learn how to make nano a better-functioning text editor

Beginner

Video Tutorial

Videos can also be accessed from our Full Stack Playlist 2 on YouTube.

Enable syntax highlighting and colors in nano | Linux Tutorial for Beginners (4:58)

Code Examples and Video Script

Welcome. Today's question: How do you enable syntax highlighting in nano?

I'm Paul, and I nudge people from the safe confines of their Windows or Mac PC, to the Linux command line where the plumbing and most of the real work in Data Science is being done.

So here, we'll take a step towards making the easiest-to-learn and widely-distributed text editor nano more user-friendly.

We will walk through the logic of how two configuration files work and monitor changes as we customize nano.

Then, I'll explain why I start with nano and not a full-blown IDE.

(We will work with one new command here)

(And practice with others)

With this 21st Task of our open-ended journey, we close out Linux for Beginners, and head to Project 3, Python for Beginners.

Step 1 - The nanorc & .nanorc Configuration Files

Let's get our Terminal going and I'll print definitions of commands we will use (with whatis).

paul@fullstack:~$ whatis touch whatis nano ls clear mkdir cp touch (1) - change file timestamps whatis (1) - display one-line manual page descriptions nano (1) - Nano's ANOther editor, an enhanced free Pico clone ls (1) - list directory contents clear (1) - clear the terminal screen mkdir (1) - make directories cp (1) - copy files and directories

This Debian 8 Linux server was not installed with a GUI, so our focus is the command line, and yes it isn't as pretty, but pretty requires more maintenance. At least from my experience.

Finding help on nano

Let's start with the --help screen for nano.

paul@fullstack:~$ nano --help Usage: nano [OPTIONS] [[+LINE,COLUMN] FILE]... Option GNU long option Meaning -h, -? --help Show this message +LINE,COLUMN Start at line LINE, column COLUMN -A --smarthome Enable smart home key -B --backup Save backups of existing files -C <dir> --backupdir=<dir> Directory for saving unique backup files -D --boldtext Use bold instead of reverse video text -E --tabstospaces Convert typed tabs to spaces -F --multibuffer Enable multiple file buffers -H --historylog Log & read search/replace string history -I --ignorercfiles Don't look at nanorc files -K --rebindkeypad Fix numeric keypad key confusion problem -L --nonewlines Don't add newlines to the ends of files -N --noconvert Don't convert files from DOS/Mac format -O --morespace Use one more line for editing -Q <str> --quotestr=<str> Quoting string -R --restricted Restricted mode -S --smooth Scroll by line instead of half-screen -T <#cols> --tabsize=<#cols> Set width of a tab to #cols columns -U --quickblank Do quick statusbar blanking -V --version Print version information and exit -W --wordbounds Detect word boundaries more accurately -Y <str> --syntax=<str> Syntax definition to use for coloring -c --const Constantly show cursor position -d --rebinddelete Fix Backspace/Delete confusion problem -i --autoindent Automatically indent new lines -k --cut Cut from cursor to end of line -l --nofollow Don't follow symbolic links, overwrite -m --mouse Enable the use of the mouse -o <dir> --operatingdir=<dir> Set operating directory -p --preserve Preserve XON (^Q) and XOFF (^S) keys -q --quiet Silently ignore startup issues like rc file errors -r <#cols> --fill=<#cols> Set wrapping point at column #cols -s <prog> --speller=<prog> Enable alternate speller -t --tempfile Auto save on exit, don't prompt -u --undo Allow generic undo [EXPERIMENTAL] -v --view View mode (read-only) -w --nowrap Don't wrap long lines -x --nohelp Don't show the two help lines -z --suspend Enable suspension -$ --softwrap Enable soft line wrapping -a, -b, -e, -f, -g, -j (ignored, for Pico compatibility)

One of the 40 options I suggest using is -c, to show the cursor's position.

I mentioned nano is easy to learn, other than Ctrl-x to exit, Ctrl-o to save, the only other navigational keystrokes you need to get started are the arrow keys.

paul@fullstack:~$ nano -c notes/video0021.txt
GNU nano 2.2.6 File: notes/video0021.txt Syntax highlighting in nano (Video 21) Exercise 1. Configuration files SYSCONFDIR/nanorc ( Debian /etc/nanorc ) ~/.nanorc 2. View files in nano before Python .py file 3. Create a configuration directory ~/.nano 4. Copy language-specific .nanorc files /usr/share/nano/python.nanorc 5. Create and customize ~/.nanorc set const to make -c the default point to new python.nanorc 6. Customize the new python.nanorce file 7. View files in nano after Text editors vs. Integrated Development Environments (IDE) [ line 4/24 (16%), col 1/31/ (3%), char 49/528 (9%) ] ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

This file details the steps we will take, and the -c option I mentioned added this feature ([ line 4/24 (16%), col 1/31/ (3%), char 49/528 (9%) ]).

The systemwide nanorc file

Let's talk about two files, first nano searches the systemwide configuration directory (SYSCONFDIR) for a file called nanorc. The directory location differs across Linux distributions. On Debian it's here (/etc/nanorc).

The user-specific .nanorc file

Second, nano will look in each user's home directory for a file called .nanorc to see (user) overrides of the system's default settings. If a .nanorc isn't there, then the systemwide file holds.

Let me show you the logic in another window.

paul@fullstack:~$ nano /etc/nanorc
GNU nano 2.2.6 File: /etc/nanorc ## Sample initialization file for GNU nano. ## ## Please note that you must have configured nano with --enable-nanorc ## for this file to be read! Also note that this file should not be in ## DOS or Mac format, and that characters specially interpreted by the ## shell should not be escaped here. ## ## To make sure a value is disabled, use "unset <option>". ## ## For the options that take parameters, the default value is given. ## Other options are unset by default. ## ## Quotes inside string parameters don't have to be escaped with ## backslashes. The last double quote in the string will be treated as ## its end. For example, for the "brackets" option, ""')>]}" will match ## ", ', ), >, ], and }. ## Use auto-indentation. # set autoindent ## Backup files to filename~. # set backup ## The directory to put unique backup files in. # set backupdir "" ## Do backwards searches by default. # set backwards ## Use bold text instead of reverse video text. # set boldtext ## The characters treated as closing brackets when justifying ## paragraphs. They cannot contain blank characters. Only closing ## punctuation, optionally followed by closing brackets, can end ## sentences. ## # set brackets ""')>]}" ## Do case sensitive searches by default. # set casesensitive ## Constantly display the cursor position in the statusbar. Note that ## this overrides "quickblank". # set const ## Use cut to end of line by default. # set cut ## Set the line length for wrapping text and justifying paragraphs. ## If fill is 0 or less, the line length will be the screen width less ## this number. ## # set fill -8 ## Enable ~/.nano_history for saving and reading search/replace strings. set historylog ## The opening and closing brackets that can be found by bracket ## searches. They cannot contain blank characters. The former set must ## come before the latter set, and both must be in the same order. ## # set matchbrackets "(<[{)>]}" ## Use the blank line below the titlebar as extra editing space. # set morespace ## Enable mouse support, if available for your system. When enabled, ## mouse clicks can be used to place the cursor, set the mark (with a ## double click), and execute shortcuts. The mouse will work in the X ## Window System, and on the console when gpm is running. ## # set mouse ## Allow multiple file buffers (inserting a file will put it into a ## separate buffer). You must have configured with --enable-multibuffer ## for this to work. ## # set multibuffer ## Don't convert files from DOS/Mac format. # set noconvert ## Don't follow symlinks when writing files. # set nofollow ## Don't display the helpful shortcut lists at the bottom of the screen. # set nohelp ## Don't add newlines to the ends of files. # set nonewlines ## Don't wrap text at all. set nowrap ## Set operating directory. nano will not read or write files outside ## this directory and its subdirectories. Also, the current directory ## is changed to here, so any files are inserted from this dir. A blank ## string means the operating directory feature is turned off. ## # set operatingdir "" ## Preserve the XON and XOFF keys (^Q and ^S). # set preserve ## The characters treated as closing punctuation when justifying ## paragraphs. They cannot contain blank characters. Only closing ## punctuation, optionally followed by closing brackets, can end ## sentences. ## # set punct "!.?" ## Do quick statusbar blanking. Statusbar messages will disappear after ## 1 keystroke instead of 26. Note that "const" overrides this. ## # set quickblank ## The email-quote string, used to justify email-quoted paragraphs. ## This is an extended regular expression if your system supports them, ## otherwise a literal string. Default: # set quotestr "^([ ]*[#:>\|}])+" ## if you have extended regular expression support, otherwise: # set quotestr "> " ## Fix Backspace/Delete confusion problem. # set rebinddelete ## Fix numeric keypad key confusion problem. # set rebindkeypad ## Do extended regular expression searches by default. # set regexp ## Make the Home key smarter. When Home is pressed anywhere but at the ## very beginning of non-whitespace characters on a line, the cursor ## will jump to that beginning (either forwards or backwards). If the ## cursor is already at that position, it will jump to the true ## beginning of the line. # set smarthome ## Use smooth scrolling as the default. # set smooth ## Use this spelling checker instead of the internal one. This option ## does not properly have a default value. ## # set speller "aspell -x -c" ## Allow nano to be suspended. set suspend ## Use this tab size instead of the default; it must be greater than 0. # set tabsize 8 ## Convert typed tabs to spaces. # set tabstospaces ## Save automatically on exit, don't prompt. # set tempfile ## Disallow file modification. Why would you want this in an rcfile? ;) # set view ## The two single-column characters used to display the first characters ## of tabs and spaces. 187 in ISO 8859-1 (0000BB in Unicode) and 183 in ## ISO-8859-1 (0000B7 in Unicode) seem to be good values for these. # set whitespace " " ## Detect word boundaries more accurately by treating punctuation ## characters as parts of words. # set wordbounds ## Enable the new (EXPERIMENTAL) generic undo code, not just for line cuts # set undo ## Enable soft line wrapping (AKA full line display) # set softwrap ## Color setup ## ## Format: ## ## syntax "short description" ["filename regex" ...] ## ## The "none" syntax is reserved; specifying it on the command line is ## the same as not having a syntax at all. The "default" syntax is ## special: it takes no filename regexes, and applies to files that ## don't match any other syntax's filename regexes. ## ## color foreground,background "regex" ["regex"...] ## or ## icolor foreground,background "regex" ["regex"...] ## ## "color" will do case sensitive matches, while "icolor" will do case ## insensitive matches. ## ## Valid colors: white, black, red, blue, green, yellow, magenta, cyan. ## For foreground colors, you may use the prefix "bright" to get a ## stronger highlight. ## ## To use multi-line regexes, use the start="regex" end="regex" ## [start="regex" end="regex"...] format. ## ## If your system supports transparency, not specifying a background ## color will use a transparent color. If you don't want this, be sure ## to set the background color to black or white. ## ## If you wish, you may put your syntaxes in separate files. You can ## make use of such files (which can only include "syntax", "color", and ## "icolor" commands) as follows: ## ## include "/path/to/syntax_file.nanorc" ## ## Unless otherwise noted, the name of the syntax file (without the ## ".nanorc" extension) should be the same as the "short description" ## name inside that file. These names are kept fairly short to make ## them easier to remember and faster to type using nano's -Y option. ## ## All regexes should be extended regular expressions. ## Key bindings ## Please see nanorc(5) for more details on this ## ## Here are some samples to get you going ## # bind M-W nowrap main # bind M-A casesens search # bind ^S research main ## Set this if your backspace key sends delete most of the time (2.1.3+) # bind kdel backspace all ## Nanorc files include "/usr/share/nano/nanorc.nanorc" ## C/C++ include "/usr/share/nano/c.nanorc" ## Cascading Style Sheets include "/usr/share/nano/css.nanorc" ## Debian files include "/usr/share/nano/debian.nanorc" ## Gentoo files include "/usr/share/nano/gentoo.nanorc" ## HTML include "/usr/share/nano/html.nanorc" ## PHP include "/usr/share/nano/php.nanorc" ## TCL include "/usr/share/nano/tcl.nanorc" ## TeX include "/usr/share/nano/tex.nanorc" ## Quoted emails (under e.g. mutt) include "/usr/share/nano/mutt.nanorc" ## Patch files include "/usr/share/nano/patch.nanorc" ## Manpages include "/usr/share/nano/man.nanorc" ## Groff include "/usr/share/nano/groff.nanorc" ## Perl include "/usr/share/nano/perl.nanorc" ## Python include "/usr/share/nano/python.nanorc" ## Ruby include "/usr/share/nano/ruby.nanorc" ## Java include "/usr/share/nano/java.nanorc" ## AWK include "/usr/share/nano/awk.nanorc" ## Assembler include "/usr/share/nano/asm.nanorc" ## Bourne shell scripts include "/usr/share/nano/sh.nanorc" ## POV-Ray include "/usr/share/nano/pov.nanorc" ## XML-type files include "/usr/share/nano/xml.nanorc" ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

Here's my 300-line systemwide file with settings for indentation (line # Set auto-indent), spell check (line # set speller "aspell -x -c") and -c (line # set const).

And nano colors are determined by a file for each language.

There's CSS (under ## Cascading Style Sheets), HTML (under ##HTML) and Python (under ## Python).

Use an ls here to see them all.

paul@fullstack:~$ ls /usr/share/nano asm.nanorc debian.nanorc java.nanorc nano-menu.xpm perl.nanorc sh.nanorc awk.nanorc fortran.nanorc makefile.nanorc nanorc.nanorc php.nanorc tcl.nanorc cmake.nanorc gentoo.nanorc man.nanorc objc.nanorc pov.nanorc tex.nanorc c.nanorc groff.nanorc mgp.nanorc ocaml.nanorc python.nanorc xml.nanorc css.nanorc html.nanorc mutt.nanorc patch.nanorc ruby.nanorc paul@fullstack:~$ clear

Step 2 - View a Python File Before and After Changes

Okay, good, so if we open a small Python file already on the system (as an example), located here, we see the systemwide file is working and text blocks are green, keywords are cyan blue. (see video)

paul@fullstack:~$ nano /usr/lib/python2.7/new.py
GNU nano 2.2.6 File: /usr/lib/python2.7/new.py """Create new objects of various types. Deprecated. This module is no longer required except for backward compatibility. Objects of most types can now be created by calling the type object. """ from warnings import warnpy3k warnpy3k("The 'new' module has been removed in Python 3.0; use the 'types' " "module instead.", stacklevel=2) del warnpy3k from types import ClassType as classobj from types import FunctionType as function from types import InstanceType as instance from types import MethodType as instancemethod from types import ModuleType as module from types import CodeType as code ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

Opening that file with -I ignores configuration files.

paul@fullstack:~$ nano -I /usr/lib/python2.7/new.py
GNU nano 2.2.6 File: /usr/lib/python2.7/new.py """Create new objects of various types. Deprecated. This module is no longer required except for backward compatibility. Objects of most types can now be created by calling the type object. """ from warnings import warnpy3k warnpy3k("The 'new' module has been removed in Python 3.0; use the 'types' " "module instead.", stacklevel=2) del warnpy3k from types import ClassType as classobj from types import FunctionType as function from types import InstanceType as instance from types import MethodType as instancemethod from types import ModuleType as module from types import CodeType as code ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

So no colors.

Step 3 - Make Two Customizations and Verify

Create a local version of .nanorc and a language-specific file

Now, follow the logic here. We need to create a directory within our home directory for all of the language-specific *.nanorc files so let's do a mkdir .nano, and ls -al to verify.

paul@fullstack:~$ mkdir .nano paul@fullstack:~$ ls -al total 146636 drwxr-xr-x 14 paul paul 4096 Feb 20 15:49 . drwxr-xr-x 3 root root 4096 Jan 3 2017 .. drwx------ 2 paul paul 4096 Jul 28 2017 .aptitude -rw------- 1 paul paul 24921 Feb 14 03:13 .bash_history -rw-r--r-- 1 paul paul 220 Jan 3 2017 .bash_logout -rw-r--r-- 1 paul paul 3723 Feb 28 2017 .bashrc -rw-r--r-- 1 paul paul 3515 Feb 8 2017 .bashrc.factory -rw------- 1 paul paul 143 Feb 20 08:23 .lesshst drwxr-xr-x 2 paul paul 4096 Apr 10 2017 .nano drwxr-xr-x 2 paul paul 4096 Apr 6 2017 notes -rw-r--r-- 1 paul paul 675 Jan 3 2017 .profile drwx------ 2 paul paul 4096 Jan 24 2017 .w3m paul@fullstack:~$

Good.

Next, let's copy the systemwide python.nanorc from the /usr/share/nano directory over to this new .nano directory.

paul@fullstack:~$ cp /usr/share/nano/python.nanorc .nano

Now we need to point a .nanorc file to that new file. The touch command creates an empty file, and we can run a second command with a semi-colon ; like this.

paul@fullstack:~$ touch .nanorc; nano .nanorc
Edit the .nanorc file

Let's add a line that makes the -c option the default, and a line that points to the python.nanorc file.

GNU nano 2.2.6 File: .nanorc set const include ~/.nano/python.nanorc ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell
Edit the new python.nanorc file

Next, let's edit the python.nanorc file by opening it in nano, editing the section for keywords from, let's say, brightcyan to brightmagenta and save that file.

paul@fullstack:~$ nano .nano/python.nanorc
GNU nano 2.2.6 File: .nano/python.nanorc ## Here is an example for Python. ## syntax "python" "\.py$" header "^#!.*/python[-0-9._]*" icolor brightblue "def [0-9A-Z_]+" color brightcyan "\<(and|as|assert|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|raise|return|try|while|with|yield)\>" color brightgreen "['][^']*[^\\][']" "[']{3}.*[^\\][']{3}" color brightgreen "["][^"]*[^\\]["]" "["]{3}.*[^\\]["]{3}" color brightgreen start=""""[^"]" end=""""" start="'''[^']" end="'''" color brightred "#.*$" ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell
Verify it was done properly

Now, let's see if we succeeded here and open that Python file from eariler.

paul@fullstack:~$ nano /usr/lib/python2.7/new.py
GNU nano 2.2.6 File: /usr/lib/python2.7/new.py """Create new objects of various types. Deprecated. This module is no longer required except for backward compatibility. Objects of most types can now be created by calling the type object. """ from warnings import warnpy3k warnpy3k("The 'new' module has been removed in Python 3.0; use the 'types' " "module instead.", stacklevel=2) del warnpy3k from types import ClassType as classobj from types import FunctionType as function from types import InstanceType as instance from types import MethodType as instancemethod from types import ModuleType as module from types import CodeType as code [ Read 17 lines (Warning: Now write permission) ] ^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos ^X Exit ^J Justify ^W Where Is ^V Next Page ^U UnCut Text ^T To Spell

Keywords are now bright magenta (see the video) and -c (for lines, columns and characters) works.

It's a little tricky, so if you get stuck, pause here and follow the steps.

Step 4 - Text Editor nano vs. Integrated Development Environments (IDE)

On the topic if nano versus IDEs. If you have poked around on the Internet then you know, discussing text editors can be a minefield.

Editors are highly personal, causing some to be very opinionated.

Here I'm starting with nano as it's the easiest for beginners and sits on most Linux boxes. When we get to heavy coding later, I'll use a different editor, but in the meantime, I'll stick with nano.

Step 5 - Next: Linux Environment Variables

Next, I'll show you the software stack we're building.

Oh, and before you return for the next tutorial on Python, on my end I'll fine-tune the colors because the right side of my brain, responsible for all of this, isn't happy with them.

Have a nice day.


What's Next?

If this helped you, please consider subscribing to our YouTube Channel so you won't miss future tutorials.

Outline Back Tip Next

/ factorpad.com / tech / full-stack / nano-syntax-highlighting.html


nano syntax highlighting
nano colors
nano config
nano configuration
nanorc
nano for python
linux editor nano
make nano show colors
nano versus IDE
python nanorc
setting colors in nano
usr share nano
etc nanorc
nano cursor position
linux tutorial

A newly-updated free resource. Connect and refer a friend today.