python.vim 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. " Vim syntax file
  2. " Language: Python
  3. " Maintainer: Zvezdan Petkovic <zpetkovic@acm.org>
  4. " Last Change: 2021 Dec 10
  5. " Credits: Neil Schemenauer <nas@python.ca>
  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. " quit when a syntax file was already loaded.
  39. if exists("b:current_syntax")
  40. finish
  41. endif
  42. " We need nocompatible mode in order to continue lines with backslashes.
  43. " Original setting will be restored.
  44. let s:cpo_save = &cpo
  45. set cpo&vim
  46. if exists("python_no_doctest_highlight")
  47. let python_no_doctest_code_highlight = 1
  48. endif
  49. if exists("python_highlight_all")
  50. if exists("python_no_builtin_highlight")
  51. unlet python_no_builtin_highlight
  52. endif
  53. if exists("python_no_doctest_code_highlight")
  54. unlet python_no_doctest_code_highlight
  55. endif
  56. if exists("python_no_doctest_highlight")
  57. unlet python_no_doctest_highlight
  58. endif
  59. if exists("python_no_exception_highlight")
  60. unlet python_no_exception_highlight
  61. endif
  62. if exists("python_no_number_highlight")
  63. unlet python_no_number_highlight
  64. endif
  65. let python_space_error_highlight = 1
  66. endif
  67. " Keep Python keywords in alphabetical order inside groups for easy
  68. " comparison with the table in the 'Python Language Reference'
  69. " https://docs.python.org/reference/lexical_analysis.html#keywords.
  70. " Groups are in the order presented in NAMING CONVENTIONS in syntax.txt.
  71. " Exceptions come last at the end of each group (class and def below).
  72. "
  73. " The list can be checked using:
  74. "
  75. " python3 -c 'import keyword, pprint; pprint.pprint(keyword.kwlist + keyword.softkwlist, compact=True)'
  76. "
  77. syn keyword pythonStatement False None True
  78. syn keyword pythonStatement as assert break continue del global
  79. syn keyword pythonStatement lambda nonlocal pass return with yield
  80. syn keyword pythonStatement class def nextgroup=pythonFunction skipwhite
  81. syn keyword pythonConditional elif else if
  82. syn keyword pythonConditional case match
  83. syn keyword pythonRepeat for while
  84. syn keyword pythonOperator and in is not or
  85. syn keyword pythonException except finally raise try
  86. syn keyword pythonInclude from import
  87. syn keyword pythonAsync async await
  88. " Decorators
  89. " A dot must be allowed because of @MyClass.myfunc decorators.
  90. syn match pythonDecorator "@" display contained
  91. syn match pythonDecoratorName "@\s*\h\%(\w\|\.\)*" display contains=pythonDecorator
  92. " Python 3.5 introduced the use of the same symbol for matrix multiplication:
  93. " https://www.python.org/dev/peps/pep-0465/. We now have to exclude the
  94. " symbol from highlighting when used in that context.
  95. " Single line multiplication.
  96. syn match pythonMatrixMultiply
  97. \ "\%(\w\|[])]\)\s*@"
  98. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  99. \ transparent
  100. " Multiplication continued on the next line after backslash.
  101. syn match pythonMatrixMultiply
  102. \ "[^\\]\\\s*\n\%(\s*\.\.\.\s\)\=\s\+@"
  103. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  104. \ transparent
  105. " Multiplication in a parenthesized expression over multiple lines with @ at
  106. " the start of each continued line; very similar to decorators and complex.
  107. syn match pythonMatrixMultiply
  108. \ "^\s*\%(\%(>>>\|\.\.\.\)\s\+\)\=\zs\%(\h\|\%(\h\|[[(]\).\{-}\%(\w\|[])]\)\)\s*\n\%(\s*\.\.\.\s\)\=\s\+@\%(.\{-}\n\%(\s*\.\.\.\s\)\=\s\+@\)*"
  109. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  110. \ transparent
  111. syn match pythonFunction "\h\w*" display contained
  112. syn match pythonComment "#.*$" contains=pythonTodo,@Spell
  113. syn keyword pythonTodo FIXME NOTE NOTES TODO XXX contained
  114. " Triple-quoted strings can contain doctests.
  115. syn region pythonString matchgroup=pythonQuotes
  116. \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  117. \ contains=pythonEscape,@Spell
  118. syn region pythonString matchgroup=pythonTripleQuotes
  119. \ start=+[uU]\=\z('''\|"""\)+ skip=+\\["']+ end="\z1" keepend
  120. \ contains=pythonEscape,pythonSpaceError,pythonDoctest,@Spell
  121. syn region pythonRawString matchgroup=pythonQuotes
  122. \ start=+[uU]\=[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  123. \ contains=@Spell
  124. syn region pythonRawString matchgroup=pythonTripleQuotes
  125. \ start=+[uU]\=[rR]\z('''\|"""\)+ end="\z1" keepend
  126. \ contains=pythonSpaceError,pythonDoctest,@Spell
  127. syn match pythonEscape +\\[abfnrtv'"\\]+ contained
  128. syn match pythonEscape "\\\o\{1,3}" contained
  129. syn match pythonEscape "\\x\x\{2}" contained
  130. syn match pythonEscape "\%(\\u\x\{4}\|\\U\x\{8}\)" contained
  131. " Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/
  132. syn match pythonEscape "\\N{\a\+\%(\s\a\+\)*}" contained
  133. syn match pythonEscape "\\$"
  134. " It is very important to understand all details before changing the
  135. " regular expressions below or their order.
  136. " The word boundaries are *not* the floating-point number boundaries
  137. " because of a possible leading or trailing decimal point.
  138. " The expressions below ensure that all valid number literals are
  139. " highlighted, and invalid number literals are not. For example,
  140. "
  141. " - a decimal point in '4.' at the end of a line is highlighted,
  142. " - a second dot in 1.0.0 is not highlighted,
  143. " - 08 is not highlighted,
  144. " - 08e0 or 08j are highlighted,
  145. "
  146. " and so on, as specified in the 'Python Language Reference'.
  147. " https://docs.python.org/reference/lexical_analysis.html#numeric-literals
  148. if !exists("python_no_number_highlight")
  149. " numbers (including longs and complex)
  150. syn match pythonNumber "\<0[oO]\=\o\+[Ll]\=\>"
  151. syn match pythonNumber "\<0[xX]\x\+[Ll]\=\>"
  152. syn match pythonNumber "\<0[bB][01]\+[Ll]\=\>"
  153. syn match pythonNumber "\<\%([1-9]\d*\|0\)[Ll]\=\>"
  154. syn match pythonNumber "\<\d\+[jJ]\>"
  155. syn match pythonNumber "\<\d\+[eE][+-]\=\d\+[jJ]\=\>"
  156. syn match pythonNumber
  157. \ "\<\d\+\.\%([eE][+-]\=\d\+\)\=[jJ]\=\%(\W\|$\)\@="
  158. syn match pythonNumber
  159. \ "\%(^\|\W\)\zs\d*\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>"
  160. endif
  161. " Group the built-ins in the order in the 'Python Library Reference' for
  162. " easier comparison.
  163. " https://docs.python.org/library/constants.html
  164. " http://docs.python.org/library/functions.html
  165. " Python built-in functions are in alphabetical order.
  166. "
  167. " The list can be checked using:
  168. "
  169. " python3 -c 'import builtins, pprint; pprint.pprint(dir(builtins), compact=True)'
  170. "
  171. " The constants added by the `site` module are not listed below because they
  172. " should not be used in programs, only in interactive interpreter.
  173. " Similarly for some other attributes and functions `__`-enclosed from the
  174. " output of the above command.
  175. "
  176. if !exists("python_no_builtin_highlight")
  177. " built-in constants
  178. " 'False', 'True', and 'None' are also reserved words in Python 3
  179. syn keyword pythonBuiltin False True None
  180. syn keyword pythonBuiltin NotImplemented Ellipsis __debug__
  181. " constants added by the `site` module
  182. syn keyword pythonBuiltin quit exit copyright credits license
  183. " built-in functions
  184. syn keyword pythonBuiltin abs all any ascii bin bool breakpoint bytearray
  185. syn keyword pythonBuiltin bytes callable chr classmethod compile complex
  186. syn keyword pythonBuiltin delattr dict dir divmod enumerate eval exec
  187. syn keyword pythonBuiltin filter float format frozenset getattr globals
  188. syn keyword pythonBuiltin hasattr hash 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 sum super
  193. syn keyword pythonBuiltin tuple type vars zip __import__
  194. " avoid highlighting attributes as builtins
  195. syn match pythonAttribute /\.\h\w*/hs=s+1
  196. \ contains=ALLBUT,pythonBuiltin,pythonFunction,pythonAsync
  197. \ transparent
  198. endif
  199. " From the 'Python Library Reference' class hierarchy at the bottom.
  200. " http://docs.python.org/library/exceptions.html
  201. if !exists("python_no_exception_highlight")
  202. " builtin base exceptions (used mostly as base classes for other exceptions)
  203. syn keyword pythonExceptions BaseException Exception
  204. syn keyword pythonExceptions ArithmeticError BufferError LookupError
  205. " builtin exceptions (actually raised)
  206. syn keyword pythonExceptions AssertionError AttributeError EOFError
  207. syn keyword pythonExceptions FloatingPointError GeneratorExit ImportError
  208. syn keyword pythonExceptions IndentationError IndexError KeyError
  209. syn keyword pythonExceptions KeyboardInterrupt MemoryError
  210. syn keyword pythonExceptions ModuleNotFoundError NameError
  211. syn keyword pythonExceptions NotImplementedError OSError OverflowError
  212. syn keyword pythonExceptions RecursionError ReferenceError RuntimeError
  213. syn keyword pythonExceptions StopAsyncIteration StopIteration SyntaxError
  214. syn keyword pythonExceptions SystemError SystemExit TabError TypeError
  215. syn keyword pythonExceptions UnboundLocalError UnicodeDecodeError
  216. syn keyword pythonExceptions UnicodeEncodeError UnicodeError
  217. syn keyword pythonExceptions UnicodeTranslateError ValueError
  218. syn keyword pythonExceptions ZeroDivisionError
  219. " builtin exception aliases for OSError
  220. syn keyword pythonExceptions EnvironmentError IOError WindowsError
  221. " builtin OS exceptions in Python 3
  222. syn keyword pythonExceptions BlockingIOError BrokenPipeError
  223. syn keyword pythonExceptions ChildProcessError ConnectionAbortedError
  224. syn keyword pythonExceptions ConnectionError ConnectionRefusedError
  225. syn keyword pythonExceptions ConnectionResetError FileExistsError
  226. syn keyword pythonExceptions FileNotFoundError InterruptedError
  227. syn keyword pythonExceptions IsADirectoryError NotADirectoryError
  228. syn keyword pythonExceptions PermissionError ProcessLookupError TimeoutError
  229. " builtin warnings
  230. syn keyword pythonExceptions BytesWarning DeprecationWarning FutureWarning
  231. syn keyword pythonExceptions ImportWarning PendingDeprecationWarning
  232. syn keyword pythonExceptions ResourceWarning RuntimeWarning
  233. syn keyword pythonExceptions SyntaxWarning UnicodeWarning
  234. syn keyword pythonExceptions UserWarning Warning
  235. endif
  236. if exists("python_space_error_highlight")
  237. " trailing whitespace
  238. syn match pythonSpaceError display excludenl "\s\+$"
  239. " mixed tabs and spaces
  240. syn match pythonSpaceError display " \+\t"
  241. syn match pythonSpaceError display "\t\+ "
  242. endif
  243. " Do not spell doctests inside strings.
  244. " Notice that the end of a string, either ''', or """, will end the contained
  245. " doctest too. Thus, we do *not* need to have it as an end pattern.
  246. if !exists("python_no_doctest_highlight")
  247. if !exists("python_no_doctest_code_highlight")
  248. syn region pythonDoctest
  249. \ start="^\s*>>>\s" end="^\s*$"
  250. \ contained contains=ALLBUT,pythonDoctest,pythonFunction,@Spell
  251. syn region pythonDoctestValue
  252. \ start=+^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\++ end="$"
  253. \ contained
  254. else
  255. syn region pythonDoctest
  256. \ start="^\s*>>>" end="^\s*$"
  257. \ contained contains=@NoSpell
  258. endif
  259. endif
  260. " Sync at the beginning of class, function, or method definition.
  261. syn sync match pythonSync grouphere NONE "^\%(def\|class\)\s\+\h\w*\s*[(:]"
  262. " The default highlight links. Can be overridden later.
  263. hi def link pythonStatement Statement
  264. hi def link pythonConditional Conditional
  265. hi def link pythonRepeat Repeat
  266. hi def link pythonOperator Operator
  267. hi def link pythonException Exception
  268. hi def link pythonInclude Include
  269. hi def link pythonAsync Statement
  270. hi def link pythonDecorator Define
  271. hi def link pythonDecoratorName Function
  272. hi def link pythonFunction Function
  273. hi def link pythonComment Comment
  274. hi def link pythonTodo Todo
  275. hi def link pythonString String
  276. hi def link pythonRawString String
  277. hi def link pythonQuotes String
  278. hi def link pythonTripleQuotes pythonQuotes
  279. hi def link pythonEscape Special
  280. if !exists("python_no_number_highlight")
  281. hi def link pythonNumber Number
  282. endif
  283. if !exists("python_no_builtin_highlight")
  284. hi def link pythonBuiltin Function
  285. endif
  286. if !exists("python_no_exception_highlight")
  287. hi def link pythonExceptions Structure
  288. endif
  289. if exists("python_space_error_highlight")
  290. hi def link pythonSpaceError Error
  291. endif
  292. if !exists("python_no_doctest_highlight")
  293. hi def link pythonDoctest Special
  294. hi def link pythonDoctestValue Define
  295. endif
  296. let b:current_syntax = "python"
  297. let &cpo = s:cpo_save
  298. unlet s:cpo_save
  299. " vim:set sw=2 sts=2 ts=8 noet: