Viewing Colored Source Code with Pygments
Learn how to use Pygments to implement syntax highlighting.
We'll cover the following
Setting up Pygments
Commands like cat
and less
are great for viewing the contents of a file, but when we’re looking at code, syntax coloring makes things easier to see.
The Pygments
library for Python can scan code and produce colored output. When we install it globally, we get a pygmentize
command to print a file to our screen with color.
Let’s install Pygments
using the pip3
command:
pip3 install Pygments
Once installed, we use it to read a file. Let’s create the following Ruby file named person.rb
in our current directory:
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
"#{self.first_name} #{self.last_name}"
end
end
Using Pygments
Then, we use pygmentize
to view the file in color.
pygmentize -g person.rb
Run the complete code on the terminal below for practice.
cat << "EOF" > person.rb
class Person
attr_accessor :first_name, :last_name
def initialize(first_name, last_name)
@first_name = first_name
@last_name = last_name
end
def full_name
"#{self.first_name} #{self.last_name}"
end
end
EOF
pygmentize -g person.rb
Get hands-on with 1400+ tech skills courses.