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