robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
19.2 KiB467 linesraw
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.
58if exists("b:current_syntax")
59  finish
60endif
61
62" Use of Python 2 and 3.5 or lower requested.
63if exists("python_use_python2_syntax")
64  runtime! syntax/python2.vim
65  finish
66endif
67
68" We need nocompatible mode in order to continue lines with backslashes.
69" Original setting will be restored.
70let s:cpo_save = &cpo
71set cpo&vim
72
73if exists("python_no_doctest_highlight")
74  let python_no_doctest_code_highlight = 1
75endif
76
77if 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
95endif
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"
107syn keyword pythonBoolean	False True
108syn keyword pythonConstant	None
109syn keyword pythonStatement	as assert break continue del global
110syn keyword pythonStatement	lambda nonlocal pass return with yield
111syn keyword pythonStatement	class nextgroup=pythonClass skipwhite
112syn keyword pythonStatement	def nextgroup=pythonFunction skipwhite
113syn keyword pythonConditional	elif else if
114syn keyword pythonRepeat	for while
115syn keyword pythonOperator	and in is not or
116syn keyword pythonException	except finally raise try
117syn keyword pythonInclude	from import
118syn 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.
124syn match   pythonConditional   "^\s*\zscase\%(\s\+.*:.*$\)\@="
125syn match   pythonConditional   "^\s*\zsmatch\%(\s\+.*:\s*\%(#.*\)\=$\)\@="
126syn match   pythonInclude       "^\s*\zslazy\ze\s\+\%(from\|import\)\>"
127syn 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.
131syn keyword pythonClassVar	self cls
132
133" Decorators
134" A dot must be allowed because of @MyClass.myfunc decorators.
135syn match   pythonDecorator	"@" display contained
136syn 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.
142syn 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.
147syn 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.
153syn 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
158syn match   pythonClass		"\h\w*" display contained
159syn match   pythonFunction	"\h\w*" display contained
160syn match   pythonType		"\h\w*" display contained
161
162syn match   pythonComment	"#.*$" contains=pythonTodo,@Spell
163syn keyword pythonTodo		FIXME NOTE NOTES TODO XXX contained
164
165" Triple-quoted strings can contain doctests.
166syn region  pythonString matchgroup=pythonQuotes
167      \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
168      \ contains=pythonEscape,pythonUnicodeEscape,@Spell
169syn region  pythonString matchgroup=pythonTripleQuotes
170      \ start=+[uU]\=\z('''\|"""\)+ skip=+\\["']+ end="\z1" keepend
171      \ contains=pythonEscape,pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell
172syn region  pythonRawString matchgroup=pythonQuotes
173      \ start=+[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
174      \ contains=@Spell
175syn 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
183syn region  pythonFString
184      \ matchgroup=pythonQuotes
185      \ start=+\c[FT]\z(['"]\)+
186      \ end="\z1"
187      \ skip="\\\\\|\\\z1"
188      \ contains=pythonFStringField,pythonFStringSkip,pythonEscape,pythonUnicodeEscape,@Spell
189syn region  pythonFString
190      \ matchgroup=pythonTripleQuotes
191      \ start=+\c[FT]\z('''\|"""\)+
192      \ end="\z1"
193      \ keepend
194      \ contains=pythonFStringField,pythonFStringSkip,pythonEscape,pythonUnicodeEscape,pythonSpaceError,pythonDoctest,@Spell
195syn region  pythonRawFString
196      \ matchgroup=pythonQuotes
197      \ start=+\c\%([FT]R\|R[FT]\)\z(['"]\)+
198      \ end="\z1"
199      \ skip="\\\\\|\\\z1"
200      \ contains=pythonFStringField,pythonFStringSkip,@Spell
201syn 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
209syn region  pythonBytes
210      \ matchgroup=pythonQuotes
211      \ start=+\cB\z(['"]\)+
212      \ end="\z1"
213      \ skip="\\\\\|\\\z1"
214      \ contains=pythonEscape
215syn region  pythonBytes
216      \ matchgroup=pythonTripleQuotes
217      \ start=+\cB\z('''\|"""\)+
218      \ end="\z1"
219      \ keepend
220      \ contains=pythonEscape
221syn region  pythonRawBytes
222      \ matchgroup=pythonQuotes
223      \ start=+\c\%(BR\|RB\)\z(['"]\)+
224      \ end="\z1"
225      \ skip="\\\\\|\\\z1"
226syn 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"
240syn region  pythonFStringField
241    \ matchgroup=pythonFStringDelimiter
242    \ start=/{/
243    \ end=/\%(=\s*\)\=\%(!\a\s*\)\=\%(:\%({\_[^}]*}\|[^{}]*\)\+\)\=}/
244    \ contained
245    \ contains=ALLBUT,pythonFStringField,pythonClass,pythonFunction,pythonType,pythonDoctest,pythonDoctestValue,@Spell
246syn match   pythonFStringFieldSkip  /(\_[^()]*)\|\[\_[^][]*]\|{\_[^{}]*}/
247    \ contained
248    \ contains=ALLBUT,pythonFStringField,pythonClass,pythonFunction,pythonType,pythonDoctest,pythonDoctestValue,@Spell
249
250" Doubled braces are not replacement fields
251syn match   pythonFStringSkip	/{{/ transparent contained contains=NONE
252
253syn match   pythonEscape	+\\[abfnrtv'"\\]+ contained
254syn match   pythonEscape	"\\\o\{1,3}" contained
255syn match   pythonEscape	"\\x\x\{2}" contained
256syn 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
259syn match   pythonUnicodeEscape	"\\N{\a\+\%(\%(\s\a\+[[:alnum:]]*\)\|\%(-[[:alnum:]]\+\)\)*}" contained
260syn 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
276if !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]\=\>"
293endif
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"
310if !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
337endif
338
339" From the 'Python Library Reference' class hierarchy at the bottom.
340" http://docs.python.org/library/exceptions.html
341if !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
375endif
376
377if 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\+ "
383endif
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.
388if !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
404endif
405
406" Sync at the beginning of (async) function or class definitions.
407syn sync match pythonSync grouphere NONE "^\%(def\|class\|async\s\+def\)\s\+\h\w*\s*[(:]"
408
409" The default highlight links.  Can be overridden later.
410hi def link pythonBoolean		Statement
411hi def link pythonConstant		Statement
412hi def link pythonStatement		Statement
413hi def link pythonConditional		Conditional
414hi def link pythonRepeat		Repeat
415hi def link pythonOperator		Operator
416hi def link pythonException		Exception
417hi def link pythonInclude		Include
418hi def link pythonAsync			Statement
419hi def link pythonClassVar		Identifier
420hi def link pythonDecorator		Define
421hi def link pythonDecoratorName		Function
422hi def link pythonClass			Structure
423hi def link pythonFunction		Function
424hi def link pythonType			Type
425hi def link pythonComment		Comment
426hi def link pythonTodo			Todo
427hi def link pythonString		String
428hi def link pythonRawString		String
429hi def link pythonFString		String
430hi def link pythonRawFString		String
431hi def link pythonBytes 		String
432hi def link pythonRawBytes 		String
433hi def link pythonQuotes		String
434hi def link pythonTripleQuotes		pythonQuotes
435hi def link pythonEscape		Special
436hi def link pythonUnicodeEscape		pythonEscape
437hi def link pythonFStringDelimiter	Special
438if !exists("python_no_number_highlight")
439  hi def link pythonNumber		Number
440endif
441if !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
446endif
447if !exists("python_no_exception_highlight")
448  hi def link pythonExceptions		Structure
449endif
450if exists("python_space_error_highlight")
451  hi def link pythonSpaceError		Error
452endif
453if !exists("python_no_doctest_highlight")
454  hi def link pythonDoctest		Special
455  hi def link pythonDoctestValue	Define
456endif
457if exists("python_constant_highlight")
458  hi! def link pythonBoolean		Boolean
459  hi! def link pythonConstant		Constant
460endif
461
462let b:current_syntax = "python"
463
464let &cpo = s:cpo_save
465unlet s:cpo_save
466
467" vim:set sw=2 sts=2 ts=8 noet: