python.vim (19601B)
1 " Vim syntax file 2 " Language: Python 3 " Maintainer: Zvezdan Petkovic <zpetkovic@acm.org> 4 " Last Change: 2025 Sep 08 5 " 2025 Sep 25 by Vim Project: fix wrong type highlighting #18394 6 " 2025 Dec 03 by Vim Project: highlight t-strings #18679 7 " 2026 Jan 26 by Vim Project: highlight constants #18922 8 " 2026 Mar 11 by Vim Project: fix number performance #19630 9 " 2026 May 27 by Vim Project: highlight `lazy` soft keyword (PEP 810) #20342 10 " 2026 Aug 30 by Vim Project: improve number and ellipsis performance 11 " 2026 Sep 10 by Vim Project: add new builtins #21254 12 " Credits: Neil Schemenauer <nas@python.ca> 13 " Dmitry Vasiliev 14 " Rob B 15 " Jon Parise 16 " 17 " This version is a major rewrite by Zvezdan Petkovic. 18 " 19 " - introduced highlighting of doctests 20 " - updated keywords, built-ins, and exceptions 21 " - corrected regular expressions for 22 " 23 " * functions 24 " * decorators 25 " * strings 26 " * escapes 27 " * numbers 28 " * space error 29 " 30 " - corrected synchronization 31 " - more highlighting is ON by default, except 32 " - space error highlighting is OFF by default 33 " 34 " Optional highlighting can be controlled using these variables. 35 " 36 " let python_no_builtin_highlight = 1 37 " let python_no_doctest_code_highlight = 1 38 " let python_no_doctest_highlight = 1 39 " let python_no_exception_highlight = 1 40 " let python_no_number_highlight = 1 41 " let python_space_error_highlight = 1 42 " let python_constant_highlight = 1 43 " 44 " All the options above can be switched on together. 45 " 46 " let python_highlight_all = 1 47 " 48 " The use of Python 2 compatible syntax highlighting can be enforced. 49 " The straddling code (Python 2 and 3 compatible), up to Python 3.5, 50 " will be also supported. 51 " 52 " let python_use_python2_syntax = 1 53 " 54 " This option will exclude all modern Python 3.6 or higher features. 55 " 56 57 " quit when a syntax file was already loaded. 58 if exists("b:current_syntax") 59 finish 60 endif 61 62 " Use of Python 2 and 3.5 or lower requested. 63 if exists("python_use_python2_syntax") 64 runtime! syntax/python2.vim 65 finish 66 endif 67 68 " We need nocompatible mode in order to continue lines with backslashes. 69 " Original setting will be restored. 70 let s:cpo_save = &cpo 71 set cpo&vim 72 73 if exists("python_no_doctest_highlight") 74 let python_no_doctest_code_highlight = 1 75 endif 76 77 if exists("python_highlight_all") 78 if exists("python_no_builtin_highlight") 79 unlet python_no_builtin_highlight 80 endif 81 if exists("python_no_doctest_code_highlight") 82 unlet python_no_doctest_code_highlight 83 endif 84 if exists("python_no_doctest_highlight") 85 unlet python_no_doctest_highlight 86 endif 87 if exists("python_no_exception_highlight") 88 unlet python_no_exception_highlight 89 endif 90 if exists("python_no_number_highlight") 91 unlet python_no_number_highlight 92 endif 93 let python_space_error_highlight = 1 94 let python_constant_highlight = 1 95 endif 96 97 " Keep Python keywords in alphabetical order inside groups for easy 98 " comparison with the table in the 'Python Language Reference' 99 " https://docs.python.org/reference/lexical_analysis.html#keywords. 100 " Groups are in the order presented in NAMING CONVENTIONS in syntax.txt. 101 " Exceptions come last at the end of each group (class and def below). 102 " 103 " The list can be checked using: 104 " 105 " python3 -c 'import keyword, pprint; pprint.pprint(keyword.kwlist + keyword.softkwlist, compact=True)' 106 " 107 syn keyword pythonBoolean False True 108 syn keyword pythonConstant None 109 syn keyword pythonStatement as assert break continue del global 110 syn keyword pythonStatement lambda nonlocal pass return with yield 111 syn keyword pythonStatement class nextgroup=pythonClass skipwhite 112 syn keyword pythonStatement def nextgroup=pythonFunction skipwhite 113 syn keyword pythonConditional elif else if 114 syn keyword pythonRepeat for while 115 syn keyword pythonOperator and in is not or 116 syn keyword pythonException except finally raise try 117 syn keyword pythonInclude from import 118 syn keyword pythonAsync async await 119 120 " Soft keywords 121 " These keywords do not mean anything unless used in the right context. 122 " See https://docs.python.org/3/reference/lexical_analysis.html#soft-keywords 123 " for more on this. 124 syn match pythonConditional "^\s*\zscase\%(\s\+.*:.*$\)\@=" 125 syn match pythonConditional "^\s*\zsmatch\%(\s\+.*:\s*\%(#.*\)\=$\)\@=" 126 syn match pythonInclude "^\s*\zslazy\ze\s\+\%(from\|import\)\>" 127 syn match pythonStatement "\<type\ze\s\+\h\w*" nextgroup=pythonType skipwhite 128 129 " These names are special by convention. While they aren't real keywords, 130 " giving them distinct highlighting provides a nice visual cue. 131 syn keyword pythonClassVar self cls 132 133 " Decorators 134 " A dot must be allowed because of @MyClass.myfunc decorators. 135 syn match pythonDecorator "@" display contained 136 syn match pythonDecoratorName "@\s*\h\%(\w\|\.\)*" display contains=pythonDecorator 137 138 " Python 3.5 introduced the use of the same symbol for matrix multiplication: 139 " https://www.python.org/dev/peps/pep-0465/. We now have to exclude the 140 " symbol from highlighting when used in that context. 141 " Single line multiplication. 142 syn match pythonMatrixMultiply 143 \ "\%(\w\|[])]\)\s*@" 144 \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonClass,pythonFunction,pythonType,pythonDoctestValue 145 \ transparent 146 " Multiplication continued on the next line after backslash. 147 syn match pythonMatrixMultiply 148 \ "[^\\]\\\s*\n\%(\s*\.\.\.\s\)\=\s\+@" 149 \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonClass,pythonFunction,pythonType,pythonDoctestValue 150 \ transparent 151 " Multiplication in a parenthesized expression over multiple lines with @ at 152 " the start of each continued line; very similar to decorators and complex. 153 syn match pythonMatrixMultiply 154 \ "^\s*\%(\%(>>>\|\.\.\.\)\s\+\)\=\zs\%(\h\|\%(\h\|[[(]\).\{-}\%(\w\|[])]\)\)\s*\n\%(\s*\.\.\.\s\)\=\s\+@\%(.\{-}\n\%(\s*\.\.\.\s\)\=\s\+@\)*" 155 \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonClass,pythonFunction,pythonType,pythonDoctestValue 156 \ transparent 157 158 syn match pythonClass "\h\w*" display contained 159 syn match pythonFunction "\h\w*" display contained 160 syn match pythonType "\h\w*" display contained 161 162 syn match pythonComment "#.*$" contains=pythonTodo,@Spell 163 syn keyword pythonTodo FIXME NOTE NOTES TODO XXX contained 164 165 " Triple-quoted strings can contain doctests. 166 syn region pythonString matchgroup=pythonQuotes 167 \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" 168 \ contains=pythonEscape,pythonUnicodeEscape,@Spell 169 syn region pythonString matchgroup=pythonTripleQuotes 170 \ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend 171 \ contains=pythonEscape,pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell 172 syn region pythonRawString matchgroup=pythonQuotes 173 \ start=+[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1" 174 \ contains=@Spell 175 syn region pythonRawString matchgroup=pythonTripleQuotes 176 \ start=+[rR]\z('''\|"""\)+ end="\z1" keepend 177 \ contains=pythonSpaceError,pythonDoctest,@Spell 178 179 " Formatted string literals (f-strings) 180 " https://docs.python.org/3/reference/lexical_analysis.html#f-strings 181 " Template string literals (t-strings) 182 " https://docs.python.org/3/reference/lexical_analysis.html#template-string-literals 183 syn region pythonFString 184 \ matchgroup=pythonQuotes 185 \ start=+\c[FT]\z(['"]\)+ 186 \ end="\z1" 187 \ skip="\\\\\|\\\z1" 188 \ contains=pythonFStringField,pythonFStringSkip,pythonEscape,pythonUnicodeEscape,@Spell 189 syn region pythonFString 190 \ matchgroup=pythonTripleQuotes 191 \ start=+\c[FT]\z('''\|"""\)+ 192 \ end="\z1" 193 \ keepend 194 \ contains=pythonFStringField,pythonFStringSkip,pythonEscape,pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell 195 syn region pythonRawFString 196 \ matchgroup=pythonQuotes 197 \ start=+\c\%([FT]R\|R[FT]\)\z(['"]\)+ 198 \ end="\z1" 199 \ skip="\\\\\|\\\z1" 200 \ contains=pythonFStringField,pythonFStringSkip,@Spell 201 syn region pythonRawFString 202 \ matchgroup=pythonTripleQuotes 203 \ start=+\c\%([FT]R\|R[FT]\)\z('''\|"""\)+ 204 \ end="\z1" 205 \ keepend 206 \ contains=pythonFStringField,pythonFStringSkip,pythonSpaceError,pythonDoctest,@Spell 207 208 " Bytes 209 syn region pythonBytes 210 \ matchgroup=pythonQuotes 211 \ start=+\cB\z(['"]\)+ 212 \ end="\z1" 213 \ skip="\\\\\|\\\z1" 214 \ contains=pythonEscape 215 syn region pythonBytes 216 \ matchgroup=pythonTripleQuotes 217 \ start=+\cB\z('''\|"""\)+ 218 \ end="\z1" 219 \ keepend 220 \ contains=pythonEscape 221 syn region pythonRawBytes 222 \ matchgroup=pythonQuotes 223 \ start=+\c\%(BR\|RB\)\z(['"]\)+ 224 \ end="\z1" 225 \ skip="\\\\\|\\\z1" 226 syn region pythonRawBytes 227 \ matchgroup=pythonTripleQuotes 228 \ start=+\c\%(BR\|RB\)\z('''\|"""\)+ 229 \ end="\z1" 230 \ keepend 231 232 " F-string replacement fields 233 " 234 " - Matched parentheses, brackets and braces are skipped 235 " - A bare = (followed by optional whitespace) enables debugging 236 " - A bare ! prefixes a conversion field (followed by optional whitespace) 237 " - A bare : begins a format specification 238 " - Matched braces inside a format specification are skipped 239 " 240 syn region pythonFStringField 241 \ matchgroup=pythonFStringDelimiter 242 \ start=/{/ 243 \ end=/\%(=\s*\)\=\%(!\a\s*\)\=\%(:\%({\_[^}]*}\|[^{}]*\)\+\)\=}/ 244 \ contained 245 \ contains=ALLBUT,pythonFStringField,pythonClass,pythonFunction,pythonType,pythonDoctest,pythonDoctestValue,@Spell 246 syn match pythonFStringFieldSkip /(\_[^()]*)\|\[\_[^][]*]\|{\_[^{}]*}/ 247 \ contained 248 \ contains=ALLBUT,pythonFStringField,pythonClass,pythonFunction,pythonType,pythonDoctest,pythonDoctestValue,@Spell 249 250 " Doubled braces are not replacement fields 251 syn match pythonFStringSkip /{{/ transparent contained contains=NONE 252 253 syn match pythonEscape +\\[abfnrtv'"\\]+ contained 254 syn match pythonEscape "\\\o\{1,3}" contained 255 syn match pythonEscape "\\x\x\{2}" contained 256 syn match pythonUnicodeEscape "\%(\\u\x\{4}\|\\U\x\{8}\)" contained 257 " Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/ 258 " The specification: https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-4/#G135165 259 syn match pythonUnicodeEscape "\\N{\a\+\%(\%(\s\a\+[[:alnum:]]*\)\|\%(-[[:alnum:]]\+\)\)*}" contained 260 syn match pythonEscape "\\$" 261 262 " It is very important to understand all details before changing the 263 " regular expressions below or their order. 264 " The word boundaries are *not* the floating-point number boundaries 265 " because of a possible leading or trailing decimal point. 266 " The expressions below ensure that all valid number literals are 267 " highlighted, and invalid number literals are not. For example, 268 " 269 " - a decimal point in '4.' at the end of a line is highlighted, 270 " - a second dot in 1.0.0 is not highlighted, 271 " - 08 is not highlighted, 272 " - 08e0 or 08j are highlighted, 273 " 274 " and so on, as specified in the 'Python Language Reference'. 275 " https://docs.python.org/reference/lexical_analysis.html#numeric-literals 276 if !exists("python_no_number_highlight") 277 " numbers (including complex) 278 syn match pythonNumber "\<0[oO]_\=\o\+\%(_\o\+\)*\>" 279 syn match pythonNumber "\<0[xX]_\=\x\+\%(_\x\+\)*\>" 280 syn match pythonNumber "\<0[bB]_\=[01]\+\%(_[01]\+\)*\>" 281 syn match pythonNumber "\<\%([1-9]\d*\%(_\d\+\)*\|0\+\%(_0\+\)*\)\>" 282 syn match pythonNumber "\<\d\+\%(_\d\+\)*[jJ]\>" 283 syn match pythonNumber "\<\d\+\%(_\d\+\)*[eE][+-]\=\d\+\%(_\d\+\)*[jJ]\=\>" 284 " \d\. 285 syn match pythonNumber 286 \ "\<\d\+\%(_\d\+\)*\.\%([eE][+-]\=\d\+\%(_\d\+\)*\)\=[jJ]\=\%(\W\|$\)\@=" 287 " \d\.\d 288 syn match pythonNumber 289 \ "\<\d\+\%(_\d\+\)*\.\d\+\%(_\d\+\)*\%([eE][+-]\=\d\+\%(_\d\+\)*\)\=[jJ]\=\>" 290 " \.\d -- \%#=1 selects the faster backtracking engine (leading look-behind) 291 syn match pythonNumber 292 \ "\%#=1\%(^\|\W\)\@1<=\.\d\+\%(_\d\+\)*\%([eE][+-]\=\d\+\%(_\d\+\)*\)\=[jJ]\=\>" 293 endif 294 295 " Group the built-ins in the order in the 'Python Library Reference' for 296 " easier comparison. 297 " https://docs.python.org/library/constants.html 298 " http://docs.python.org/library/functions.html 299 " Python built-in functions are in alphabetical order. 300 " 301 " The list can be checked using: 302 " 303 " python3 -c 'import builtins, pprint; pprint.pprint(dir(builtins), compact=True)' 304 " 305 " The constants added by the `site` module are not listed below because they 306 " should not be used in programs, only in interactive interpreter. 307 " Similarly for some other attributes and functions `__`-enclosed from the 308 " output of the above command. 309 " 310 if !exists("python_no_builtin_highlight") 311 " built-in constants 312 " 'False', 'True', and 'None' are also reserved words in Python 3 313 syn keyword pythonBoolean False True 314 syn keyword pythonConstant None NotImplemented Ellipsis __debug__ 315 " constants added by the `site` module 316 syn keyword pythonBuiltin quit exit copyright credits license 317 " built-in functions 318 syn keyword pythonBuiltin abs aiter all anext any ascii bin bool breakpoint bytearray 319 syn keyword pythonBuiltin bytes callable chr classmethod compile complex 320 syn keyword pythonBuiltin delattr dict dir divmod enumerate eval exec 321 syn keyword pythonBuiltin filter float format frozenset getattr globals 322 syn keyword pythonBuiltin hasattr hash help hex id input int isinstance 323 syn keyword pythonBuiltin issubclass iter len list locals map max 324 syn keyword pythonBuiltin memoryview min next object oct open ord pow 325 syn keyword pythonBuiltin print property range repr reversed round set 326 syn keyword pythonBuiltin setattr slice sorted staticmethod str sum super 327 syn keyword pythonBuiltin tuple vars zip __import__ 328 " only match `type` as a builtin when it's not followed by an identifier 329 syn match pythonBuiltin "\<type\>\ze\(\s\+\h\w*\)\@!" 330 " avoid highlighting attributes as builtins 331 syn match pythonAttribute /\.\h\w*/hs=s+1 332 \ contains=ALLBUT,pythonBuiltin,pythonClass,pythonFunction,pythonType,pythonAsync 333 \ transparent 334 " the ellipsis literal `...` can be used in multiple syntactic contexts 335 " \%#=1 selects the faster backtracking engine (leading look-behind) 336 syn match pythonEllipsis "\%#=1\.\@1<!\.\.\.\ze\.\@!" display 337 endif 338 339 " From the 'Python Library Reference' class hierarchy at the bottom. 340 " http://docs.python.org/library/exceptions.html 341 if !exists("python_no_exception_highlight") 342 " builtin base exceptions (used mostly as base classes for other exceptions) 343 syn keyword pythonExceptions BaseException Exception BaseExceptionGroup ExceptionGroup 344 syn keyword pythonExceptions ArithmeticError BufferError LookupError 345 " builtin exceptions (actually raised) 346 syn keyword pythonExceptions AssertionError AttributeError EOFError 347 syn keyword pythonExceptions FloatingPointError GeneratorExit ImportError 348 syn keyword pythonExceptions IndentationError IndexError KeyError 349 syn keyword pythonExceptions KeyboardInterrupt MemoryError 350 syn keyword pythonExceptions ModuleNotFoundError NameError 351 syn keyword pythonExceptions NotImplementedError OSError OverflowError 352 syn keyword pythonExceptions PythonFinalizationError RecursionError ReferenceError RuntimeError 353 syn keyword pythonExceptions StopAsyncIteration StopIteration SyntaxError 354 syn keyword pythonExceptions SystemError SystemExit TabError TypeError 355 syn keyword pythonExceptions UnboundLocalError UnicodeDecodeError 356 syn keyword pythonExceptions UnicodeEncodeError UnicodeError 357 syn keyword pythonExceptions UnicodeTranslateError ValueError 358 syn keyword pythonExceptions ZeroDivisionError 359 " builtin exception aliases for OSError 360 syn keyword pythonExceptions EnvironmentError IOError WindowsError 361 " builtin OS exceptions in Python 3 362 syn keyword pythonExceptions BlockingIOError BrokenPipeError 363 syn keyword pythonExceptions ChildProcessError ConnectionAbortedError 364 syn keyword pythonExceptions ConnectionError ConnectionRefusedError 365 syn keyword pythonExceptions ConnectionResetError FileExistsError 366 syn keyword pythonExceptions FileNotFoundError InterruptedError 367 syn keyword pythonExceptions IsADirectoryError NotADirectoryError 368 syn keyword pythonExceptions PermissionError ProcessLookupError TimeoutError 369 " builtin warnings 370 syn keyword pythonExceptions BytesWarning DeprecationWarning EncodingWarning FutureWarning 371 syn keyword pythonExceptions ImportWarning PendingDeprecationWarning 372 syn keyword pythonExceptions ResourceWarning RuntimeWarning 373 syn keyword pythonExceptions SyntaxWarning UnicodeWarning 374 syn keyword pythonExceptions UserWarning Warning 375 endif 376 377 if exists("python_space_error_highlight") 378 " trailing whitespace 379 syn match pythonSpaceError display excludenl "\s\+$" 380 " mixed tabs and spaces 381 syn match pythonSpaceError display " \+\t" 382 syn match pythonSpaceError display "\t\+ " 383 endif 384 385 " Do not spell doctests inside strings. 386 " Notice that the end of a string, either ''', or """, will end the contained 387 " doctest too. Thus, we do *not* need to have it as an end pattern. 388 if !exists("python_no_doctest_highlight") 389 if !exists("python_no_doctest_code_highlight") 390 syn region pythonDoctest 391 \ start="^\s*>>>\s" end="^\s*$" 392 \ contained contains=ALLBUT,pythonDoctest,pythonEllipsis,pythonClass,pythonFunction,pythonType,@Spell 393 syn region pythonDoctestValue 394 \ start=+^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\++ end="$" 395 \ contained contains=pythonEllipsis 396 " \%#=1 selects the faster backtracking engine (leading look-behind) 397 syn match pythonEllipsis "\%#=1\%(^\s*\)\@<!\.\@1<!\zs\.\.\.\ze\.\@!" display 398 \ contained containedin=pythonDoctest 399 else 400 syn region pythonDoctest 401 \ start="^\s*>>>" end="^\s*$" 402 \ contained contains=@NoSpell 403 endif 404 endif 405 406 " Sync at the beginning of (async) function or class definitions. 407 syn sync match pythonSync grouphere NONE "^\%(def\|class\|async\s\+def\)\s\+\h\w*\s*[(:]" 408 409 " The default highlight links. Can be overridden later. 410 hi def link pythonBoolean Statement 411 hi def link pythonConstant Statement 412 hi def link pythonStatement Statement 413 hi def link pythonConditional Conditional 414 hi def link pythonRepeat Repeat 415 hi def link pythonOperator Operator 416 hi def link pythonException Exception 417 hi def link pythonInclude Include 418 hi def link pythonAsync Statement 419 hi def link pythonClassVar Identifier 420 hi def link pythonDecorator Define 421 hi def link pythonDecoratorName Function 422 hi def link pythonClass Structure 423 hi def link pythonFunction Function 424 hi def link pythonType Type 425 hi def link pythonComment Comment 426 hi def link pythonTodo Todo 427 hi def link pythonString String 428 hi def link pythonRawString String 429 hi def link pythonFString String 430 hi def link pythonRawFString String 431 hi def link pythonBytes String 432 hi def link pythonRawBytes String 433 hi def link pythonQuotes String 434 hi def link pythonTripleQuotes pythonQuotes 435 hi def link pythonEscape Special 436 hi def link pythonUnicodeEscape pythonEscape 437 hi def link pythonFStringDelimiter Special 438 if !exists("python_no_number_highlight") 439 hi def link pythonNumber Number 440 endif 441 if !exists("python_no_builtin_highlight") 442 hi! def link pythonBoolean Function 443 hi! def link pythonConstant Function 444 hi def link pythonBuiltin Function 445 hi def link pythonEllipsis pythonBuiltin 446 endif 447 if !exists("python_no_exception_highlight") 448 hi def link pythonExceptions Structure 449 endif 450 if exists("python_space_error_highlight") 451 hi def link pythonSpaceError Error 452 endif 453 if !exists("python_no_doctest_highlight") 454 hi def link pythonDoctest Special 455 hi def link pythonDoctestValue Define 456 endif 457 if exists("python_constant_highlight") 458 hi! def link pythonBoolean Boolean 459 hi! def link pythonConstant Constant 460 endif 461 462 let b:current_syntax = "python" 463 464 let &cpo = s:cpo_save 465 unlet s:cpo_save 466 467 " vim:set sw=2 sts=2 ts=8 noet: