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