neovim

Neovim text editor
git clone https://git.dasho.dev/neovim.git
Log | Files | Refs | README

python2.vim (15836B)


      1 " Vim syntax file
      2 " Language:	Python 2
      3 " Maintainer:	Zvezdan Petkovic <zpetkovic@acm.org>
      4 " Last Change:	2016 Oct 29
      5 " 2025 Jul 14 by Vim project: highlight unicode strings
      6 " 2025 Jul 15 by Vim project: highlight b-strings
      7 " Credits:	Neil Schemenauer <nas@python.ca>
      8 "		Dmitry Vasiliev
      9 "		Rob B
     10 "
     11 "		This version is a major rewrite by Zvezdan Petkovic.
     12 "
     13 "		- introduced highlighting of doctests
     14 "		- updated keywords, built-ins, and exceptions
     15 "		- corrected regular expressions for
     16 "
     17 "		  * functions
     18 "		  * decorators
     19 "		  * strings
     20 "		  * escapes
     21 "		  * numbers
     22 "		  * space error
     23 "
     24 "		- corrected synchronization
     25 "		- more highlighting is ON by default, except
     26 "		- space error highlighting is OFF by default
     27 "
     28 " Optional highlighting can be controlled using these variables.
     29 "
     30 "   let python_no_builtin_highlight = 1
     31 "   let python_no_doctest_code_highlight = 1
     32 "   let python_no_doctest_highlight = 1
     33 "   let python_no_exception_highlight = 1
     34 "   let python_no_number_highlight = 1
     35 "   let python_space_error_highlight = 1
     36 "
     37 " All the options above can be switched on together.
     38 "
     39 "   let python_highlight_all = 1
     40 "
     41 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
     42 " NOTE: This file is a copy of the last commit of runtime/syntax/python.vim
     43 " that still supported Python 2. There is support for Python 3, up to 3.5,
     44 " and it was kept in the file as is, because it supports the straddling code
     45 " (Python 2 and 3 compatible) better.
     46 """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
     47 
     48 " quit when a syntax file was already loaded.
     49 if exists("b:current_syntax")
     50  finish
     51 endif
     52 
     53 " We need nocompatible mode in order to continue lines with backslashes.
     54 " Original setting will be restored.
     55 let s:cpo_save = &cpo
     56 set cpo&vim
     57 
     58 if exists("python_no_doctest_highlight")
     59  let python_no_doctest_code_highlight = 1
     60 endif
     61 
     62 if exists("python_highlight_all")
     63  if exists("python_no_builtin_highlight")
     64    unlet python_no_builtin_highlight
     65  endif
     66  if exists("python_no_doctest_code_highlight")
     67    unlet python_no_doctest_code_highlight
     68  endif
     69  if exists("python_no_doctest_highlight")
     70    unlet python_no_doctest_highlight
     71  endif
     72  if exists("python_no_exception_highlight")
     73    unlet python_no_exception_highlight
     74  endif
     75  if exists("python_no_number_highlight")
     76    unlet python_no_number_highlight
     77  endif
     78  let python_space_error_highlight = 1
     79 endif
     80 
     81 " Keep Python keywords in alphabetical order inside groups for easy
     82 " comparison with the table in the 'Python Language Reference'
     83 " https://docs.python.org/2/reference/lexical_analysis.html#keywords,
     84 " https://docs.python.org/3/reference/lexical_analysis.html#keywords.
     85 " Groups are in the order presented in NAMING CONVENTIONS in syntax.txt.
     86 " Exceptions come last at the end of each group (class and def below).
     87 "
     88 " Keywords 'with' and 'as' are new in Python 2.6
     89 " (use 'from __future__ import with_statement' in Python 2.5).
     90 "
     91 " Some compromises had to be made to support both Python 3 and 2.
     92 " We include Python 3 features, but when a definition is duplicated,
     93 " the last definition takes precedence.
     94 "
     95 " - 'False', 'None', and 'True' are keywords in Python 3 but they are
     96 "   built-ins in 2 and will be highlighted as built-ins below.
     97 " - 'exec' is a built-in in Python 3 and will be highlighted as
     98 "   built-in below.
     99 " - 'nonlocal' is a keyword in Python 3 and will be highlighted.
    100 " - 'print' is a built-in in Python 3 and will be highlighted as
    101 "   built-in below (use 'from __future__ import print_function' in 2)
    102 " - async and await were added in Python 3.5 and are soft keywords.
    103 "
    104 syn keyword pythonStatement	False None True
    105 syn keyword pythonStatement	as assert break continue del exec global
    106 syn keyword pythonStatement	lambda nonlocal pass print return with yield
    107 syn keyword pythonStatement	class def nextgroup=pythonFunction skipwhite
    108 syn keyword pythonConditional	elif else if
    109 syn keyword pythonRepeat	for while
    110 syn keyword pythonOperator	and in is not or
    111 syn keyword pythonException	except finally raise try
    112 syn keyword pythonInclude	from import
    113 syn keyword pythonAsync		async await
    114 
    115 " Decorators (new in Python 2.4)
    116 " A dot must be allowed because of @MyClass.myfunc decorators.
    117 syn match   pythonDecorator	"@" display contained
    118 syn match   pythonDecoratorName	"@\s*\h\%(\w\|\.\)*" display contains=pythonDecorator
    119 
    120 " Python 3.5 introduced the use of the same symbol for matrix multiplication:
    121 " https://www.python.org/dev/peps/pep-0465/.  We now have to exclude the
    122 " symbol from highlighting when used in that context.
    123 " Single line multiplication.
    124 syn match   pythonMatrixMultiply
    125      \ "\%(\w\|[])]\)\s*@"
    126      \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
    127      \ transparent
    128 " Multiplication continued on the next line after backslash.
    129 syn match   pythonMatrixMultiply
    130      \ "[^\\]\\\s*\n\%(\s*\.\.\.\s\)\=\s\+@"
    131      \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
    132      \ transparent
    133 " Multiplication in a parenthesized expression over multiple lines with @ at
    134 " the start of each continued line; very similar to decorators and complex.
    135 syn match   pythonMatrixMultiply
    136      \ "^\s*\%(\%(>>>\|\.\.\.\)\s\+\)\=\zs\%(\h\|\%(\h\|[[(]\).\{-}\%(\w\|[])]\)\)\s*\n\%(\s*\.\.\.\s\)\=\s\+@\%(.\{-}\n\%(\s*\.\.\.\s\)\=\s\+@\)*"
    137      \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
    138      \ transparent
    139 
    140 syn match   pythonFunction	"\h\w*" display contained
    141 
    142 syn match   pythonComment	"#.*$" contains=pythonTodo,@Spell
    143 syn keyword pythonTodo		FIXME NOTE NOTES TODO XXX contained
    144 
    145 " Triple-quoted strings can contain doctests.
    146 syn region  pythonString matchgroup=pythonQuotes
    147      \ start=+[bB]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
    148      \ contains=pythonEscape,@Spell
    149 syn region  pythonString matchgroup=pythonTripleQuotes
    150      \ start=+[bB]\=\z('''\|"""\)+ end="\z1" keepend
    151      \ contains=pythonEscape,pythonSpaceError,pythonDoctest,@Spell
    152 syn region  pythonRawString matchgroup=pythonQuotes
    153      \ start=+[bB]\=[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
    154      \ contains=@Spell
    155 syn region  pythonRawString matchgroup=pythonTripleQuotes
    156      \ start=+[bB]\=[rR]\z('''\|"""\)+ end="\z1" keepend
    157      \ contains=pythonSpaceError,pythonDoctest,@Spell
    158 
    159 " Unicode strings
    160 syn region  pythonString
    161      \ matchgroup=pythonQuotes
    162      \ start=+[uU]\z(['"]\)+
    163      \ end="\z1"
    164      \ skip="\\\\\|\\\z1"
    165      \ contains=pythonEscape,pythonUnicodeEscape,@Spell
    166 syn region  pythonString
    167      \ matchgroup=pythonTripleQuotes
    168      \ start=+[uU]\z('''\|"""\)+
    169      \ end="\z1"
    170      \ keepend
    171      \ contains=pythonEscape,pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell
    172 
    173 " Raw Unicode strings recognize Unicode escape sequences
    174 " https://docs.python.org/2.7/reference/lexical_analysis.html#string-literals
    175 syn region  pythonRawString
    176      \ matchgroup=pythonQuotes
    177      \ start=+[uU][rR]\z(['"]\)+
    178      \ end="\z1"
    179      \ skip="\\\\\|\\\z1"
    180      \ contains=pythonUnicodeEscape,@Spell
    181 syn region  pythonRawString
    182      \ matchgroup=pythonTripleQuotes
    183      \ start=+[uU][rR]\z('''\|"""\)+
    184      \ end="\z1"
    185      \ keepend
    186      \ contains=pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell
    187 
    188 syn match   pythonEscape	+\\[abfnrtv'"\\]+ contained
    189 syn match   pythonEscape	"\\\o\{1,3}" contained
    190 syn match   pythonEscape	"\\x\x\{2}" contained
    191 syn match   pythonUnicodeEscape	"\%(\\u\x\{4}\|\\U\x\{8}\)" contained
    192 " Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/
    193 syn match   pythonUnicodeEscape	"\\N{\a\+\%(\s\a\+\)*}" contained
    194 syn match   pythonEscape	"\\$"
    195 
    196 " It is very important to understand all details before changing the
    197 " regular expressions below or their order.
    198 " The word boundaries are *not* the floating-point number boundaries
    199 " because of a possible leading or trailing decimal point.
    200 " The expressions below ensure that all valid number literals are
    201 " highlighted, and invalid number literals are not.  For example,
    202 "
    203 " - a decimal point in '4.' at the end of a line is highlighted,
    204 " - a second dot in 1.0.0 is not highlighted,
    205 " - 08 is not highlighted,
    206 " - 08e0 or 08j are highlighted,
    207 "
    208 " and so on, as specified in the 'Python Language Reference'.
    209 " https://docs.python.org/2/reference/lexical_analysis.html#numeric-literals
    210 " https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
    211 if !exists("python_no_number_highlight")
    212  " numbers (including longs and complex)
    213  syn match   pythonNumber	"\<0[oO]\=\o\+[Ll]\=\>"
    214  syn match   pythonNumber	"\<0[xX]\x\+[Ll]\=\>"
    215  syn match   pythonNumber	"\<0[bB][01]\+[Ll]\=\>"
    216  syn match   pythonNumber	"\<\%([1-9]\d*\|0\)[Ll]\=\>"
    217  syn match   pythonNumber	"\<\d\+[jJ]\>"
    218  syn match   pythonNumber	"\<\d\+[eE][+-]\=\d\+[jJ]\=\>"
    219  syn match   pythonNumber
    220 \ "\<\d\+\.\%([eE][+-]\=\d\+\)\=[jJ]\=\%(\W\|$\)\@="
    221  syn match   pythonNumber
    222 \ "\%(^\|\W\)\zs\d*\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>"
    223 endif
    224 
    225 " Group the built-ins in the order in the 'Python Library Reference' for
    226 " easier comparison.
    227 " https://docs.python.org/2/library/constants.html
    228 " https://docs.python.org/3/library/constants.html
    229 " http://docs.python.org/2/library/functions.html
    230 " http://docs.python.org/3/library/functions.html
    231 " http://docs.python.org/2/library/functions.html#non-essential-built-in-functions
    232 " http://docs.python.org/3/library/functions.html#non-essential-built-in-functions
    233 " Python built-in functions are in alphabetical order.
    234 if !exists("python_no_builtin_highlight")
    235  " built-in constants
    236  " 'False', 'True', and 'None' are also reserved words in Python 3
    237  syn keyword pythonBuiltin	False True None
    238  syn keyword pythonBuiltin	NotImplemented Ellipsis __debug__
    239  " built-in functions
    240  syn keyword pythonBuiltin	abs all any bin bool bytearray callable chr
    241  syn keyword pythonBuiltin	classmethod compile complex delattr dict dir
    242  syn keyword pythonBuiltin	divmod enumerate eval filter float format
    243  syn keyword pythonBuiltin	frozenset getattr globals hasattr hash
    244  syn keyword pythonBuiltin	help hex id input int isinstance
    245  syn keyword pythonBuiltin	issubclass iter len list locals map max
    246  syn keyword pythonBuiltin	memoryview min next object oct open ord pow
    247  syn keyword pythonBuiltin	print property range repr reversed round set
    248  syn keyword pythonBuiltin	setattr slice sorted staticmethod str
    249  syn keyword pythonBuiltin	sum super tuple type vars zip __import__
    250  " Python 2 only
    251  syn keyword pythonBuiltin	basestring cmp execfile file
    252  syn keyword pythonBuiltin	long raw_input reduce reload unichr
    253  syn keyword pythonBuiltin	unicode xrange
    254  " Python 3 only
    255  syn keyword pythonBuiltin	ascii bytes exec
    256  " non-essential built-in functions; Python 2 only
    257  syn keyword pythonBuiltin	apply buffer coerce intern
    258  " avoid highlighting attributes as builtins
    259  syn match   pythonAttribute	/\.\h\w*/hs=s+1
    260 \ contains=ALLBUT,pythonBuiltin,pythonFunction,pythonAsync
    261 \ transparent
    262 endif
    263 
    264 " From the 'Python Library Reference' class hierarchy at the bottom.
    265 " http://docs.python.org/2/library/exceptions.html
    266 " http://docs.python.org/3/library/exceptions.html
    267 if !exists("python_no_exception_highlight")
    268  " builtin base exceptions (used mostly as base classes for other exceptions)
    269  syn keyword pythonExceptions	BaseException Exception
    270  syn keyword pythonExceptions	ArithmeticError BufferError
    271  syn keyword pythonExceptions	LookupError
    272  " builtin base exceptions removed in Python 3
    273  syn keyword pythonExceptions	EnvironmentError StandardError
    274  " builtin exceptions (actually raised)
    275  syn keyword pythonExceptions	AssertionError AttributeError
    276  syn keyword pythonExceptions	EOFError FloatingPointError GeneratorExit
    277  syn keyword pythonExceptions	ImportError IndentationError
    278  syn keyword pythonExceptions	IndexError KeyError KeyboardInterrupt
    279  syn keyword pythonExceptions	MemoryError NameError NotImplementedError
    280  syn keyword pythonExceptions	OSError OverflowError ReferenceError
    281  syn keyword pythonExceptions	RuntimeError StopIteration SyntaxError
    282  syn keyword pythonExceptions	SystemError SystemExit TabError TypeError
    283  syn keyword pythonExceptions	UnboundLocalError UnicodeError
    284  syn keyword pythonExceptions	UnicodeDecodeError UnicodeEncodeError
    285  syn keyword pythonExceptions	UnicodeTranslateError ValueError
    286  syn keyword pythonExceptions	ZeroDivisionError
    287  " builtin OS exceptions in Python 3
    288  syn keyword pythonExceptions	BlockingIOError BrokenPipeError
    289  syn keyword pythonExceptions	ChildProcessError ConnectionAbortedError
    290  syn keyword pythonExceptions	ConnectionError ConnectionRefusedError
    291  syn keyword pythonExceptions	ConnectionResetError FileExistsError
    292  syn keyword pythonExceptions	FileNotFoundError InterruptedError
    293  syn keyword pythonExceptions	IsADirectoryError NotADirectoryError
    294  syn keyword pythonExceptions	PermissionError ProcessLookupError
    295  syn keyword pythonExceptions	RecursionError StopAsyncIteration
    296  syn keyword pythonExceptions	TimeoutError
    297  " builtin exceptions deprecated/removed in Python 3
    298  syn keyword pythonExceptions	IOError VMSError WindowsError
    299  " builtin warnings
    300  syn keyword pythonExceptions	BytesWarning DeprecationWarning FutureWarning
    301  syn keyword pythonExceptions	ImportWarning PendingDeprecationWarning
    302  syn keyword pythonExceptions	RuntimeWarning SyntaxWarning UnicodeWarning
    303  syn keyword pythonExceptions	UserWarning Warning
    304  " builtin warnings in Python 3
    305  syn keyword pythonExceptions	ResourceWarning
    306 endif
    307 
    308 if exists("python_space_error_highlight")
    309  " trailing whitespace
    310  syn match   pythonSpaceError	display excludenl "\s\+$"
    311  " mixed tabs and spaces
    312  syn match   pythonSpaceError	display " \+\t"
    313  syn match   pythonSpaceError	display "\t\+ "
    314 endif
    315 
    316 " Do not spell doctests inside strings.
    317 " Notice that the end of a string, either ''', or """, will end the contained
    318 " doctest too.  Thus, we do *not* need to have it as an end pattern.
    319 if !exists("python_no_doctest_highlight")
    320  if !exists("python_no_doctest_code_highlight")
    321    syn region pythonDoctest
    322   \ start="^\s*>>>\s" end="^\s*$"
    323   \ contained contains=ALLBUT,pythonDoctest,pythonFunction,@Spell
    324    syn region pythonDoctestValue
    325   \ start=+^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\++ end="$"
    326   \ contained
    327  else
    328    syn region pythonDoctest
    329   \ start="^\s*>>>" end="^\s*$"
    330   \ contained contains=@NoSpell
    331  endif
    332 endif
    333 
    334 " Sync at the beginning of class, function, or method definition.
    335 syn sync match pythonSync grouphere NONE "^\%(def\|class\)\s\+\h\w*\s*[(:]"
    336 
    337 " The default highlight links.  Can be overridden later.
    338 hi def link pythonStatement		Statement
    339 hi def link pythonConditional		Conditional
    340 hi def link pythonRepeat		Repeat
    341 hi def link pythonOperator		Operator
    342 hi def link pythonException		Exception
    343 hi def link pythonInclude		Include
    344 hi def link pythonAsync			Statement
    345 hi def link pythonDecorator		Define
    346 hi def link pythonDecoratorName		Function
    347 hi def link pythonFunction		Function
    348 hi def link pythonComment		Comment
    349 hi def link pythonTodo			Todo
    350 hi def link pythonString		String
    351 hi def link pythonRawString		String
    352 hi def link pythonQuotes		String
    353 hi def link pythonTripleQuotes		pythonQuotes
    354 hi def link pythonEscape		Special
    355 hi def link pythonUnicodeEscape		pythonEscape
    356 if !exists("python_no_number_highlight")
    357  hi def link pythonNumber		Number
    358 endif
    359 if !exists("python_no_builtin_highlight")
    360  hi def link pythonBuiltin		Function
    361 endif
    362 if !exists("python_no_exception_highlight")
    363  hi def link pythonExceptions		Structure
    364 endif
    365 if exists("python_space_error_highlight")
    366  hi def link pythonSpaceError		Error
    367 endif
    368 if !exists("python_no_doctest_highlight")
    369  hi def link pythonDoctest		Special
    370  hi def link pythonDoctestValue	Define
    371 endif
    372 
    373 let b:current_syntax = "python"
    374 
    375 let &cpo = s:cpo_save
    376 unlet s:cpo_save
    377 
    378 " vim:set sw=2 sts=2 ts=8 noet: