Something went wrong. Try again.
Highlighting for Python
Something went wrong. Try again.
13 kB · 290 lines
at dev
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291" Vim syntax file" Language: Python" Maintainer: Dominic Ricottone <me@dominic-ricottone.com>" Last Change: 2022 Sep 15" Credits: Zvezdan Petkovic <zpetkovic@acm.org>" Neil Schemenauer <nas@python.ca>" Dmitry Vasiliev"" This version is a minor rewrite by Dominic Ricottone"" let python_no_builtin_highlight = 1" let python_no_exception_highlight = 1" let python_no_number_highlight = 1" let python_space_error_highlight = 1"" All the options above can be switched on together."" let python_highlight_all = 1"
" quit when a syntax file was already loaded.if exists("b:current_syntax") finishendif
" We need nocompatible mode in order to continue lines with backslashes." Original setting will be restored.let s:cpo_save = &cposet cpo&vim
if exists("python_highlight_all") if exists("python_no_builtin_highlight") unlet python_no_builtin_highlight endif if exists("python_no_exception_highlight") unlet python_no_exception_highlight endif if exists("python_no_number_highlight") unlet python_no_number_highlight endif let python_space_error_highlight = 1endif
" Keep Python keywords in alphabetical order inside groups for easy" comparison with the table in the 'Python Language Reference'" https://docs.python.org/reference/lexical_analysis.html#keywords." Groups are in the order presented in NAMING CONVENTIONS in syntax.txt." Exceptions come last at the end of each group (class and def below)."" The list can be checked using:"" python3 -c 'import keyword, pprint; pprint.pprint(keyword.kwlist + keyword.softkwlist, compact=True)'"" Keywords 'with' and 'as' are new in Python 2.6" (use 'from __future__ import with_statement' in Python 2.5)."" Some compromises had to be made to support both Python 3 and 2." We include Python 3 features, but when a definition is duplicated," the last definition takes precedence."" - 'False', 'None', and 'True' are keywords in Python 3 but they are" built-ins in 2 and will be highlighted as built-ins below." - 'nonlocal' is a keyword in Python 3 and will be highlighted." - async and await were added in Python 3.5 and are soft keywords."syn keyword pythonStatement False None Truesyn keyword pythonStatement as assert break continue del globalsyn keyword pythonStatement lambda nonlocal pass return with yieldsyn keyword pythonStatement class def nextgroup=pythonFunction skipwhitesyn keyword pythonConditional elif else ifsyn keyword pythonRepeat for whilesyn keyword pythonOperator and in is not orsyn keyword pythonException except finally raise trysyn keyword pythonInclude from importsyn keyword pythonAsync async await
" Soft keywords" These keywords do not mean anything unless used in the right context" See https://docs.python.org/3/reference/lexical_analysis.html#soft-keywords " for more on this.syn match pythonConditional "^\s*\zscase\%(\s\+.*:.*$\)\@="syn match pythonConditional "^\s*\zsmatch\%(\s\+.*:\s*\%(#.*\)\=$\)\@="
" Decorators (new in Python 2.4)" A dot must be allowed because of @MyClass.myfunc decorators.syn match pythonDecorator "@" display containedsyn match pythonDecoratorName "@\s*\h\%(\w\|\.\)*" display contains=pythonDecorator
" Python 3.5 introduced the use of the same symbol for matrix multiplication:" https://www.python.org/dev/peps/pep-0465/. We now have to exclude the" symbol from highlighting when used in that context." Single line multiplication.syn match pythonMatrixMultiply \ "\%(\w\|[])]\)\s*@" \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction \ transparent" Multiplication continued on the next line after backslash.syn match pythonMatrixMultiply \ "[^\\]\\\s*\n\%(\s*\.\.\.\s\)\=\s\+@" \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction \ transparent" Multiplication in a parenthesized expression over multiple lines with @ at" the start of each continued line; very similar to decorators and complex.syn match pythonMatrixMultiply \ "^\s*\%(\%(>>>\|\.\.\.\)\s\+\)\=\zs\%(\h\|\%(\h\|[[(]\).\{-}\%(\w\|[])]\)\)\s*\n\%(\s*\.\.\.\s\)\=\s\+@\%(.\{-}\n\%(\s*\.\.\.\s\)\=\s\+@\)*" \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction \ transparent
syn match pythonFunction "\h\w*" display contained
syn match pythonComment "#.*$" contains=pythonTodo,@Spellsyn keyword pythonTodo FIXME NOTE NOTES TODO XXX contained
" Triple-quoted strings are doc strings.syn region pythonString matchgroup=pythonQuotes \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" \ contains=pythonEscape,@Spellsyn region pythonDocString matchgroup=pythonTripleQuotes \ start=+[uU]\=\z('''\|"""\)+ skip=+\\["']+ end="\z1" keepend \ contains=pythonEscape,pythonSpaceError,@Spellsyn region pythonRawString matchgroup=pythonQuotes \ start=+[uU]\=[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" \ contains=@Spellsyn region pythonRawDocString matchgroup=pythonTripleQuotes \ start=+[uU]\=[rR]\z('''\|"""\)+ end="\z1" keepend \ contains=pythonSpaceError,@Spell
syn match pythonEscape +\\[abfnrtv'"\\]+ containedsyn match pythonEscape "\\\o\{1,3}" containedsyn match pythonEscape "\\x\x\{2}" containedsyn match pythonEscape "\%(\\u\x\{4}\|\\U\x\{8}\)" contained" Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/syn match pythonEscape "\\N{\a\+\%(\s\a\+\)*}" containedsyn match pythonEscape "\\$"
" It is very important to understand all details before changing the" regular expressions below or their order." The word boundaries are *not* the floating-point number boundaries" because of a possible leading or trailing decimal point." The expressions below ensure that all valid number literals are" highlighted, and invalid number literals are not. For example,"" - a decimal point in '4.' at the end of a line is highlighted," - a second dot in 1.0.0 is not highlighted," - 08 is not highlighted," - 08e0 or 08j are highlighted,"" and so on, as specified in the 'Python Language Reference'." https://docs.python.org/reference/lexical_analysis.html#numeric-literalsif !exists("python_no_number_highlight") " numbers (including longs and complex) syn match pythonNumber "\<0[oO]\=\o\+[Ll]\=\>" syn match pythonNumber "\<0[xX]\x\+[Ll]\=\>" syn match pythonNumber "\<0[bB][01]\+[Ll]\=\>" syn match pythonNumber "\<\%([1-9]\d*\|0\)[Ll]\=\>" syn match pythonNumber "\<\d\+[jJ]\>" syn match pythonNumber "\<\d\+[eE][+-]\=\d\+[jJ]\=\>" syn match pythonNumber \ "\<\d\+\.\%([eE][+-]\=\d\+\)\=[jJ]\=\%(\W\|$\)\@=" syn match pythonNumber \ "\%(^\|\W\)\zs\d*\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>"endif
" Group the built-ins in the order in the 'Python Library Reference' for" easier comparison." https://docs.python.org/library/constants.html" http://docs.python.org/library/functions.html" Python built-in functions are in alphabetical order."" The list can be checked using:"" python3 -c 'import builtins, pprint; pprint.pprint(dir(builtins), compact=True)'"" The constants added by the `site` module are not listed below because they" should not be used in programs, only in interactive interpreter." Similarly for some other attributes and functions `__`-enclosed from the" output of the above command."if !exists("python_no_builtin_highlight") " built-in constants " 'False', 'True', and 'None' are also reserved words in Python 3 syn keyword pythonBuiltin False True None syn keyword pythonBuiltin NotImplemented Ellipsis __debug__ " constants added by the `site` module syn keyword pythonBuiltin quit exit copyright credits license " built-in functions syn keyword pythonBuiltin abs all any ascii bin bool breakpoint bytearray syn keyword pythonBuiltin bytes callable chr classmethod compile complex syn keyword pythonBuiltin delattr dict dir divmod enumerate eval exec syn keyword pythonBuiltin filter float format frozenset getattr globals syn keyword pythonBuiltin hasattr hash help hex id input int isinstance syn keyword pythonBuiltin issubclass iter len list locals map max syn keyword pythonBuiltin memoryview min next object oct open ord pow syn keyword pythonBuiltin print property range repr reversed round set syn keyword pythonBuiltin setattr slice sorted staticmethod str sum super syn keyword pythonBuiltin tuple type vars zip __import__ " avoid highlighting attributes as builtins syn match pythonAttribute /\.\h\w*/hs=s+1 \ contains=ALLBUT,pythonBuiltin,pythonFunction,pythonAsync \ transparentendif
" From the 'Python Library Reference' class hierarchy at the bottom." http://docs.python.org/library/exceptions.htmlif !exists("python_no_exception_highlight") " builtin base exceptions (used mostly as base classes for other exceptions) syn keyword pythonExceptions BaseException Exception syn keyword pythonExceptions ArithmeticError BufferError LookupError " builtin exceptions (actually raised) syn keyword pythonExceptions AssertionError AttributeError EOFError syn keyword pythonExceptions FloatingPointError GeneratorExit ImportError syn keyword pythonExceptions IndentationError IndexError KeyError syn keyword pythonExceptions KeyboardInterrupt MemoryError syn keyword pythonExceptions ModuleNotFoundError NameError syn keyword pythonExceptions NotImplementedError OSError OverflowError syn keyword pythonExceptions RecursionError ReferenceError RuntimeError syn keyword pythonExceptions StopAsyncIteration StopIteration SyntaxError syn keyword pythonExceptions SystemError SystemExit TabError TypeError syn keyword pythonExceptions UnboundLocalError UnicodeDecodeError syn keyword pythonExceptions UnicodeEncodeError UnicodeError syn keyword pythonExceptions UnicodeTranslateError ValueError syn keyword pythonExceptions ZeroDivisionError " builtin exception aliases for OSError syn keyword pythonExceptions EnvironmentError IOError WindowsError " builtin OS exceptions in Python 3 syn keyword pythonExceptions BlockingIOError BrokenPipeError syn keyword pythonExceptions ChildProcessError ConnectionAbortedError syn keyword pythonExceptions ConnectionError ConnectionRefusedError syn keyword pythonExceptions ConnectionResetError FileExistsError syn keyword pythonExceptions FileNotFoundError InterruptedError syn keyword pythonExceptions IsADirectoryError NotADirectoryError syn keyword pythonExceptions PermissionError ProcessLookupError TimeoutError " builtin warnings syn keyword pythonExceptions BytesWarning DeprecationWarning FutureWarning syn keyword pythonExceptions ImportWarning PendingDeprecationWarning syn keyword pythonExceptions ResourceWarning RuntimeWarning syn keyword pythonExceptions SyntaxWarning UnicodeWarning syn keyword pythonExceptions UserWarning Warningendif
if exists("python_space_error_highlight") " trailing whitespace syn match pythonSpaceError display excludenl "\s\+$" " mixed tabs and spaces syn match pythonSpaceError display " \+\t" syn match pythonSpaceError display "\t\+ "endif
" Sync at the beginning of class, function, or method definition.syn sync match pythonSync grouphere NONE "^\%(def\|class\)\s\+\h\w*\s*[(:]"
" The default highlight links. Can be overridden later.hi def link pythonStatement Statementhi def link pythonConditional Conditionalhi def link pythonRepeat Repeathi def link pythonOperator Operatorhi def link pythonException Exceptionhi def link pythonInclude Includehi def link pythonAsync Statementhi def link pythonDecorator Definehi def link pythonDecoratorName Functionhi def link pythonFunction Functionhi def link pythonComment Commenthi def link pythonTodo Todohi def link pythonString Stringhi def link pythonRawString Stringhi def link pythonDocString Commenthi def link pythonRawDocString Commenthi def link pythonQuotes Stringhi def link pythonTripleQuotes Commenthi def link pythonEscape Specialif !exists("python_no_number_highlight") hi def link pythonNumber Numberendifif !exists("python_no_builtin_highlight") hi def link pythonBuiltin Functionendifif !exists("python_no_exception_highlight") hi def link pythonExceptions Structureendifif exists("python_space_error_highlight") hi def link pythonSpaceError Errorendif
let b:current_syntax = "python"
let &cpo = s:cpo_saveunlet s:cpo_save
" vim:set sw=2 sts=2 ts=8 noet: