Linux терминал подсветка синтаксиса

Syntax highlighting in the terminal

Lots of programming-oriented editors will colorize source code. Is there a command that will colorize source code for viewing in the terminal? I could open a file with emacs -nw (which opens in the terminal instead of popping up a new window), but I’m looking for something that works like less (or that works with less -R , which passes through color escape sequences in its input).

9 Answers 9

With highlight on a terminal that supports the same colour escape sequences as xterm :

highlight -O xterm256 your-file | less -R 
pygmentize your-file | less -R 
source-highlight -f esc256 -i your-file | less -R 

You can also use vim as a pager with the help of macros/less.sh script shipped with vim (see :h less within vim for details):

sh /usr/share/vim/vim74/macros/less.sh your-file 

Or you could use any of the syntax highlighters that support HTML output and use elinks or w3m as the pager (or elinks -dump -dump-color-mode 3 | less -R ) like with GNU source-highlight :

source-highlight -o STDOUT -i your-file | elinks -dump -dump-color-mode 3 | less -R 

I use GNU source-highlight combined with less -R for this. Add the following lines to your shell’s initialization file ( ~/.bashrc , for example):

That should automatically color source code according to the language used and, if it can’t, it will launch less on its input directly.

If you’re interested in colors in less more generally, you might want to look at lesspipe.sh . See, for example, http://freecode.com/projects/lesspipe.

lesspipe.sh is an input filter for the pager less as described in less’s man page. The script runs under a ksh-compatible shell (e.g. bash, zsh) and allows you to use less to view files with binary content, compressed files, archives, and files contained in archives.

It will also colorize shell scripts, perl scripts, etc. similarly to a text editor, but without the use of any «preprocessing» program to do the colorizing.

acts as cat but pretty-prints the file contents, including file name, line numbers and syntax highlighting. There are options for piping colorized output e.g. to less . By default, when the output is piped, it behaves like cat and just copies the data from stdin to stdout .

Unlike GNU source-highlight which uses the file extension for language recognition, bat recognizes the syntax from the input itself and therefore can read piped input without explicitly specifying the language.

Читайте также:  Linux convert avi to mp4

I enjoy simplicity and I use nano text editor, in this case I usually proceed as follow:

check witch syntax highlight is available: ls -la /usr/share/nano/

include it in my nanorc file with following command, or by doing it manually

echo 'include /usr/share/nano/sh.nanorc' >> ~/.nanorc 

about less I suggest to give a look at this page

You can use the package, e2ansi, that provides syntax highlighting support for pagers like more and less .

The package use the mother of all text editors, Emacs, to perform the actual syntax highlighting. As an added bonus, all other conversions normally performed by Emacs — like uncompressing files — is also performed.

Example

The following is the result of viewing a file using less and e2ansi :

Example

Configuration

The package provides a command-line tool e2ansi-cat that starts Emacs in batch mode, opens files, syntax highlight them, and renders the result using ANSI sequences.

You can integrate this into less by setting the following variables to, for example (the location of your init file may vary):

export "LESSOPEN=||-/usr/local/emacs --batch -Q -l ~/.emacs -l bin/e2ansi-cat %s" export "LESS=-r" alias "more=less -X -E" 

In the configuration above, less restores the original terminal window content whereas more simply output new content after the prompt.

Note: If you use an old version of less , it might not support the || or the — syntax, in which case you may need to use simply LESSOPEN=|/usr/local/emacs . .

Using less in pipes

The «-» character in LESSOPEN indicates that the input filter should also be used when piping text into less . In this case, Emacs can only rely on text itself (and not a file name). Fortunately, Emacs provides a system for this. In addition, the provided file file e2ansi-magic.el sets up additional file types. For example:

Pipe example

Why use Emacs?

  • Emacs has support for virtually all programming languages and structured text formats. In most cases, the syntax highlighting support is excellent.
  • You can easily add support for more languages and formats, or modify existing packages to suit you needs.
  • Emacs support color themes. When using e2ansi , the colors in the theme is preserved when viewing a file in less . You can pick a suitable color theme from a number of sources, or design your own.
  • If you use Emacs as your editor of choice, you will get the same highlighting in the editor as you get when viewing a file using less (minus limitations in ANSI sequence format and the terminal window).
  • less will take advantage of Emacs features that perform automatic conversion, for example uncompressing files. In fact, you can teach Emacs to perform any kind of conversion like automatically convert a binary file to human readable form using an external tool.
  • You can view files located on other machines by using Emacs’ syntax for remote access like /USER@HOST:FILENAME .
Читайте также:  Вывести дерево файлов linux
  • e2ansi is distributed on Melpa and can be installed using the standard Emacs package system
  • e2ansi is hosted on GitHub
  • The e2ansi page on the Emacs Wiki
  • The home of less .

Operating system notes

  • On MS Windows, the console does not natively support ANSI sequences. Fortunately, the less application is capable of rendering them. I am not aware of any contemporary binary distribution of less for MS Windows and the provided build files is hard to use. Fortunately, it’s easy to build less using CMake, see this text for details.
  • OS X distributes an ancient version of less . Fortunately, it’s easy to build a modern version directly from the source.

According to Stéphane Chazelas suggestion, I make a bash function to use highlight show Syntax highlight, put it into .bashrc or so on. It works great, fast and effective.

highlight support 202 language syntax format. see highlight —list-scripts=langs .

Themes, to use with the -s param:

highlight -l --out-format=html -s neon --syntax=php < in.txt 1>out.html 

List themes available on your system:

ls /usr/share/highlight/themes 
acid.theme darkbone.theme edit-matlab.theme maroloccio.theme rdark.theme aiseered.theme darkness.theme edit-msvs2008.theme matrix.theme relaxedgreen.theme andes.theme darkslategray.theme edit-nedit.theme moe.theme rootwater.theme anotherdark.theme darkspectrum.theme edit-purebasic.theme molokai.theme seashell.theme autumn.theme denim.theme edit-vim-dark.theme moria.theme solarized-dark.theme baycomb.theme dusk.theme edit-vim.theme navajo-night.theme solarized-light.theme bclear.theme earendel.theme edit-xcode.theme navy.theme sourceforge.theme biogoo.theme easter.theme ekvoli.theme neon.theme tabula.theme bipolar.theme edit-anjuta.theme fine_blue.theme nightshimmer.theme tcsoft.theme blacknblue.theme edit-bbedit.theme freya.theme night.theme the.theme bluegreen.theme edit-eclipse.theme fruit.theme nuvola.theme vampire.theme breeze.theme edit-emacs.theme github.theme olive.theme whitengrey.theme bright.theme edit-fasm.theme golden.theme orion.theme xoria256.theme camo.theme edit-flashdevelop.theme greenlcd.theme oxygenated.theme zellner.theme candy.theme edit-gedit.theme kellys.theme pablo.theme zenburn.theme clarity.theme edit-godot.theme leo.theme peaksea.theme zmrok.theme dante.theme edit-jedit.theme lucretia.theme print.theme darkblue.theme edit-kwrite.theme manxome.theme rand01.theme 

Themes preview View as html

highlight linux all themes

All theme preview generated with the below php code:

Источник

Подсветка синтаксиса в nano

Но если открыть nano от юзера, то подсветка синтаксиса не работает.

Включение подсветки синтаксиса для юзера.¶

Чтобы её включить необходимо создать файл .nanorc

И добавить в него инклюды на файлы подсветки синтаксиса.

$ find /usr/share/nano/ -iname "*.nanorc" -exec echo include <> \; >> ~/.nanorc

Как можно заметить, в списке отсутсвуют конфиги для синтаксиса conf и yaml файлов.

Добавление подсветки синтаксиса для conf файлов.¶

$ sudo nano /usr/share/nano/conf.nanorc

И добавляем в него следующее содержимое

# config file highlighting syntax "conf" "(\.(conf|config|cfg|cnf|rc|lst|list|defs|ini|desktop|mime|types|preset|cache|seat|service|htaccess)$|(^|/)(\w*crontab|mirrorlist|group|hosts|passwd|rpc|netconfig|shadow|fstab|inittab|inputrc|protocols|sudoers)$|conf.d/|.config/)" # default text color magenta "^.*$" # special values icolor brightblue "(^|\s|=)(default|true|false|on|off|yes|no)(\s|$)" # keys icolor cyan "^\s*(set\s+)?[A-Z0-9_\/\.\%\@+-]+\s*([:]|\>)" # commands color blue "^\s*set\s+\ # punctuation color blue "[.]" # numbers color red "(^|\s|[[/:|<>()<>=,]|\])[-+]?5(\.?1)*%?($|\>)" # keys icolor cyan "^\s*(\$if )?([A-Z0-9_\/\.\%\@+-]|\s)+=" # punctuation color blue "/" color brightwhite "(\]|[()<>[<>,;:=])" color brightwhite "(^|\[|\<|\:)\s*-(\s|$)" # section headings icolor brightyellow "^\s*(\[([A-Z0-9_\.-]|\s)+\])+\s*$" color brightcyan "^\s*((Sub)?Section\s*(=|\>)|End(Sub)?Section\s*$)" color brightcyan "^\s*\$(end)?if(\s|$)" # URLs icolor green "\b(([A-Z]+://|www[.])[A-Z0-9/:#?&$=_\.\-]+)(\b|$| )" # XML-like tags icolor brightcyan "[^"]*"|'[^']*'|!?[A-Z0-9_:/]))*(\s*/)?>" # strings color yellow "\"(\\.|[^"])*\"" "'(\\.|[^'])*'" # comments color white "#.*$" color blue "^\s*##.*$" color white "^;.*$" color white start=" end="-->" 

После сохранения файла его необходимо добавить в .nanorc

$ echo include "/usr/share/nano/conf.nanorc" >> ~/.nanorc

Добавление подсветки синтаксиса для yaml файлов.¶

$ sudo nano /usr/share/nano/yaml.nanorc

И добавляем в него следующее содержимое

# Supports `YAML` files syntax "YAML" "\.ya?ml$" header "^(---|===)" "%YAML" ## Keys color magenta "^\s*[\$A-Za-z0-9_-]+\:" color brightmagenta "^\s*@[\$A-Za-z0-9_-]+\:" ## Values color white ":\s.+$" ## Booleans icolor brightcyan " (y|yes|n|no|true|false|on|off)$" ## Numbers color brightred " [[:digit:]]+(\.[[:digit:]]+)?" ## Arrays color red "\[" "\]" ":\s+[|>]" "^\s*- " ## Reserved color green "(^| )!!(binary|bool|float|int|map|null|omap|seq|set|str) " ## Comments color brightwhite "#.*$" ## Errors color ,red ":\w.+$" color ,red ":'.+$" color ,red ":".+$" color ,red "\s+$" ## Non closed quote color ,red "['\"][^['\"]]*$" ## Closed quotes color yellow "['\"].*['\"]" ## Equal sign color brightgreen ":( |$)" 

После сохранения файла его необходимо добавить в .nanorc

$ echo include "/usr/share/nano/yaml.nanorc" >> ~/.nanorc

Источник

Подсветка синтаксиса в mcedit и bash

Jan 2, 2017 18:07 · 202 words · 1 minute read console

«Как включить подсветку синтаксиса в mcedit и bash?» — ответ на этот несложный вопрос настолько прост, что я сам постоянно забываю как это делается… Давайте разберемся!

Итак, сначала разберемся с mcedit . Чтобы включить подсветку синтаксиса в этом популярном редакторе необходимо открыть любой имеющийся файл в режиме редактирования (начать F4 или в консоли выполнить mcedit somefile.inc ) и нажать комбинацию клавиш Ctrl+S.

Это срабатывает в 99% случаев, но если подсветка синтаксиса в mcedit не включилась, то нужно немного подправить конфигурационный файл /usr/share/mc/syntax/Syntax :

sudo mcedit /usr/share/mc/syntax/Syntax 

Находим строку include unknown.syntax и изменяем ее на include sh.syntax и после проделанных действий появится подсветка синтаксиса.

Чтобы включить подсветку синтаксиса bash для всех пользователей в системе следует в конфигурационном файле /etc/skel/.bashrc найти и раскомментировать строку force_color_prompt=yes , после чего перелогиниться в системе.

Также можно изменить стандартные цвета по своему вкусу, делается это также в конфиге /etc/skel/.bashrc в строке PS1=’$\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ ‘ .

Вот список цветов, которые можно применять для подсветки синтаксиса в bash :

BLACK='\e[0;30m' RED='\e[0;31m' GREEN='\e[0;32m' BROWN='\e[0;33m' BLUE='\e[0;34m' MAGENTA='\e[0;35m' CYAN='\e[0;36m' GRAY='\e[0;37m' DEF='\e[0;39m' DGRAY='\e[1;30m' LRED='\e[1;31m' LGREEN='\e[1;32m' YELLOW='\e[1;33m' LBLUE='\e[1;34m' LMAGENTA='\e[1;35m' LCYAN='\e[1;36m' WHITE='\e[1;37m' NC='\e[0m' # No Color 

Индивидуальные настройки подсветки синтаксиса для каждого пользователя можно настраивать в конфигурационном файле /home/$USER/.bashrc

Еще один пример «раскраски» консоли в Linux, а также изменение приветствия мы рассматривали ранее.

Read more

© Copyright 2023 Yevhen Lebid

Источник

Оцените статью
Adblock
detector