Index ¦ Archives  ¦ Atom  ¦ RSS

Nanorc for Python

I use nano all the time because it's the first UNIX editor I've ever used thanks to the Gentoo documentation (long, separate story). Therefore, when I write code I like to have some syntax highlighting, but nano's syntax highlighting is pretty whack since it's all just regex's and nobody likes regex's enough to wade through nano's 27 nanorc's to make them actually work.

However, recently I've been working with Python a great deal and three highlighting bugs have really bothered me:

  1. Empty strings don't get highlighted and instead highlight to the next quote in the line, really annoying for Django URLs.
  2. A # in the middle of a string highlights the rest of the line as a comment, even though it's normal code.
  3. Triple-quotes were either too greedy or didn't accept doc-style comments

I figured there's gotta be a fix for these things so I tried my hand at it and the following python.nanorc file (saved to /usr/share/python.nanorc for Debian systems) fixes the problems above for any test cases I could think of:

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 brightblue "\<(cdef)\>"
color brightgreen "['][^']*[^\\]?[']" "[']{3}.*[^\\][']{3}"
color brightgreen "["][^"]*[^\\]?["]" "["]{3}.*[^\\]["]{3}"
color brightgreen """".*""""

## Triple-quotes
color brightgreen start=""""[^"]?" end=""""" start="'''[^']?" end="'''"
color brightgreen start=""""$" end=""""$" start="'''$" end="'''$"

## normal comments with no quotes
color brightred "#[^'"]*$"
## possibly normal, has some quotes but will check for double later
color brightred "#[^'"]*"
## these are no-doubt valid
color brightred "^\s*#.*"

## for strings with # in it (overriding possibly normal comments from earlier
color brightgreen "['][^']*#[^']*[^\\]?[']" "[']{3}.*[^\\][']{3}"
color brightgreen "["][^"]*#[^"]*[^\\]?["]" "["]{3}.*[^\\]["]{3}"

## for comments with an even number of quotes
color brightred "#([^'"]*['"][^'"]*['"])+[^'"]*$"

## only drawback: comments with an odd number of quotes are not properly
##     highlighted if they don't start at the beginning of the line
## would be possible to check for these correctly if nanorc had negative lookbehinds

These are the best regex's I can come up with given the certain limitations of nano's highlighting engine. I'm sure other editors have better systems in place that highlight more effectively, but I like the simplicity of nano as well as its eventual complexity. I believe in "hidden complexity" for programs I make and use.

color brightgreen start=""""[\^"]?" end=""""" start="'''[\^']?" end="'''" color brightgreen start=""""\$" end=""""\$" start="'''\$" end="'''\$"

© Fahrzin Hemmati. Built using Pelican. Theme by Giulio Fidente on github.