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