Syntax highlighting for the P4 language

Set up P4 syntax highlighting in Nano, Sublime Text, Atom, and VS Code.

Ryan Knightly
The Floating Point
2 min readFeb 2, 2023

--

P4 is a specialized programming language for network switches and routers. It is more obscure than Java or Python, so basic things like syntax highlighting (fancy colors in your text editor) might not work out of the box, and might require some extra setup to get working.

Here’s what I did to get P4 syntax highlighting in Nano, Sublime Text, and VS Code (and why it didn’t work in Atom). Before you know it, your P4 will look as good as mine:

Nano editor with syntax highlighting for the P4 language

Nano

  1. Create a file called /usr/share/nano/p4.nanorc with the following contents (yes, I skimmed the P4 language spec just to have nice colors).
## p4.nanorc for the P4 language, adapted from the default c.nanorc for C/C++
syntax p4 "\.p4$"
comment "//"

# Constants.
color brightred "\<[A-Z_][0-9A-Z_]+\>"

# Labels.
color brightmagenta "^[[:space:]]*[A-Z_a-z]+:[[:space:]]*$"

# P4 keywords.
color cyan "\<(action|apply|control|default|else|extern|exit|false|if|package|parser|return|select|state|switch|table|transition|true|typedef|verify)\>"
color green "\<(bit|bool|const|enum|error|header|header_union|in|inout|int|match_kind|out|struct|tuple|varbit|void)\>"

# Strings.
color brightyellow ""([^"]|\\")*"" "#[[:space:]]*include[[:space:]]+<[^[:blank:]=]*>"

# Preprocessor directives.
color brightcyan start="^[[:space:]]*#[[:space:]]*(if(n?def)?|elif|warning|error|pragma)\>" end="(\`|[^\\])$"
color brightcyan "^[[:space:]]*#[[:space:]]*(define|else|endif|include(_next)?|undef)\>"

# Comments.
color brightblue "//.*"
color brightblue start="/\*" end="\*/"

# Reminders.
color brightwhite,yellow "\<(FIXME|TODO|XXX)\>"

2. If you already have a file named ~/.nanorc add the following line to the end of it (otherwise, skip this step).

include /usr/share/nano/p4.nanorc

Now you should be good to go!

Sublime Text

The P4 Syntax Highlighter extension (created by Gyanesh Patra) worked for me!

Atom*

You can try to install this extension, but it didn’t work when I tried it. Maybe just don’t use Atom — it was killed in December 2022. Blame Microsoft, who bought GitHub (who created Atom) and then swiftly stabbed Atom in the back to prioritize VS Code (see below).

VS Code

VS Code has a P4 extension (created by Ali Fattaholmanan) that should do the trick.

Cheers!

--

--