PageRenderTime 69ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/bundle/extra-syntax/syntax/python.vim

https://github.com/hoelzro/vimfiles
Vim Script | 327 lines | 194 code | 21 blank | 112 comment | 22 complexity | 59de3736815e763ab580aa8878b73afd MD5 | raw file
Possible License(s): BSD-3-Clause, 0BSD
  1. " Vim syntax file
  2. " Language: Python
  3. " Maintainer: Zvezdan Petkovic <zpetkovic@acm.org>
  4. " Last Change: 2021 Feb 15
  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, 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 match case
  82. syn keyword pythonRepeat for while
  83. syn keyword pythonOperator and in is not or
  84. syn keyword pythonException except finally raise try
  85. syn keyword pythonInclude from import
  86. syn keyword pythonAsync async await
  87. " Decorators
  88. " A dot must be allowed because of @MyClass.myfunc decorators.
  89. syn match pythonDecorator "@" display contained
  90. syn match pythonDecoratorName "@\s*\h\%(\w\|\.\)*" display contains=pythonDecorator
  91. " Python 3.5 introduced the use of the same symbol for matrix multiplication:
  92. " https://www.python.org/dev/peps/pep-0465/. We now have to exclude the
  93. " symbol from highlighting when used in that context.
  94. " Single line multiplication.
  95. syn match pythonMatrixMultiply
  96. \ "\%(\w\|[])]\)\s*@"
  97. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  98. \ transparent
  99. " Multiplication continued on the next line after backslash.
  100. syn match pythonMatrixMultiply
  101. \ "[^\\]\\\s*\n\%(\s*\.\.\.\s\)\=\s\+@"
  102. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  103. \ transparent
  104. " Multiplication in a parenthesized expression over multiple lines with @ at
  105. " the start of each continued line; very similar to decorators and complex.
  106. syn match pythonMatrixMultiply
  107. \ "^\s*\%(\%(>>>\|\.\.\.\)\s\+\)\=\zs\%(\h\|\%(\h\|[[(]\).\{-}\%(\w\|[])]\)\)\s*\n\%(\s*\.\.\.\s\)\=\s\+@\%(.\{-}\n\%(\s*\.\.\.\s\)\=\s\+@\)*"
  108. \ contains=ALLBUT,pythonDecoratorName,pythonDecorator,pythonFunction,pythonDoctestValue
  109. \ transparent
  110. syn match pythonFunction "\h\w*" display contained
  111. syn match pythonComment "#.*$" contains=pythonTodo,@Spell
  112. syn keyword pythonTodo FIXME NOTE NOTES TODO XXX contained
  113. " Triple-quoted strings can contain doctests.
  114. syn region pythonString matchgroup=pythonQuotes
  115. \ start=+[uU]\=\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  116. \ contains=pythonEscape,@Spell
  117. syn region pythonString matchgroup=pythonTripleQuotes
  118. \ start=+[uU]\=\z('''\|"""\)+ end="\z1" keepend
  119. \ contains=pythonEscape,pythonSpaceError,pythonDoctest,@Spell
  120. syn region pythonRawString matchgroup=pythonQuotes
  121. \ start=+[uU]\=[rR]\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  122. \ contains=@Spell
  123. syn region pythonRawString matchgroup=pythonTripleQuotes
  124. \ start=+[uU]\=[rR]\z('''\|"""\)+ end="\z1" keepend
  125. \ contains=pythonSpaceError,pythonDoctest,@Spell
  126. " f-strings can contain expressions
  127. syn region pythonString matchgroup=pythonQuotes
  128. \ start=+[uU]\=f\z(['"]\)+ end="\z1" skip="\\\\\|\\\z1"
  129. \ contains=pythonEscape,pythonFStringExpr,@Spell
  130. syn region pythonFStringExpr matchgroup=Delimiter
  131. \ start="{" end="}"
  132. \ contained contains=ALLBUT,pythonDoctest,pythonFunction,@Spell
  133. syn match pythonEscape +\\[abfnrtv'"\\]+ contained
  134. syn match pythonEscape "\\\o\{1,3}" contained
  135. syn match pythonEscape "\\x\x\{2}" contained
  136. syn match pythonEscape "\%(\\u\x\{4}\|\\U\x\{8}\)" contained
  137. " Python allows case-insensitive Unicode IDs: http://www.unicode.org/charts/
  138. syn match pythonEscape "\\N{\a\+\%(\s\a\+\)*}" contained
  139. syn match pythonEscape "\\$"
  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/reference/lexical_analysis.html#numeric-literals
  154. if !exists("python_no_number_highlight")
  155. " numbers (including longs and complex)
  156. syn match pythonNumber "\<0[oO]\=[0-7_]\+[Ll]\=\>"
  157. syn match pythonNumber "\<0[xX][0-9a-fA-F_]\+[Ll]\=\>"
  158. syn match pythonNumber "\<0[bB][01_]\+[Ll]\=\>"
  159. syn match pythonNumber "\<\%([1-9][0-9_]*\|0\)[Ll]\=\>"
  160. syn match pythonNumber "\<[0-9_]\+[jJ]\>"
  161. syn match pythonNumber "\<[0-9_]\+[eE][+-]\=[0-9_]\+[jJ]\=\>"
  162. syn match pythonNumber
  163. \ "\<[0-9_]\+\.\%([eE][+-]\=[0-9_]\+\)\=[jJ]\=\%(\W\|$\)\@="
  164. syn match pythonNumber
  165. \ "\%(^\|\W\)\zs[0-9_]*\.[0-9_]\+\%([eE][+-]\=[0-9_]\+\)\=[jJ]\=\>"
  166. endif
  167. " Group the built-ins in the order in the 'Python Library Reference' for
  168. " easier comparison.
  169. " https://docs.python.org/library/constants.html
  170. " http://docs.python.org/library/functions.html
  171. " Python built-in functions are in alphabetical order.
  172. "
  173. " The list can be checked using:
  174. "
  175. " python3 -c 'import builtins, pprint; pprint.pprint(dir(builtins), compact=True)'
  176. "
  177. " The constants added by the `site` module are not listed below because they
  178. " should not be used in programs, only in interactive interpreter.
  179. " Similarly for some other attributes and functions `__`-enclosed from the
  180. " output of the above command.
  181. "
  182. if !exists("python_no_builtin_highlight")
  183. " built-in constants
  184. " 'False', 'True', and 'None' are also reserved words in Python 3
  185. syn keyword pythonBuiltin False True None
  186. syn keyword pythonBuiltin NotImplemented Ellipsis __debug__
  187. " constants added by the `site` module
  188. syn keyword pythonBuiltin quit exit copyright credits license
  189. " built-in functions
  190. syn keyword pythonBuiltin abs all any ascii bin bool breakpoint bytearray
  191. syn keyword pythonBuiltin bytes callable chr classmethod compile complex
  192. syn keyword pythonBuiltin delattr dict dir divmod enumerate eval exec
  193. syn keyword pythonBuiltin filter float format frozenset getattr globals
  194. syn keyword pythonBuiltin hasattr hash help hex id input int isinstance
  195. syn keyword pythonBuiltin issubclass iter len list locals map max
  196. syn keyword pythonBuiltin memoryview min next object oct open ord pow
  197. syn keyword pythonBuiltin print property range repr reversed round set
  198. syn keyword pythonBuiltin setattr slice sorted staticmethod str sum super
  199. syn keyword pythonBuiltin tuple type vars zip __import__
  200. " avoid highlighting attributes as builtins
  201. syn match pythonAttribute /\.\h\w*/hs=s+1
  202. \ contains=ALLBUT,pythonBuiltin,pythonFunction,pythonAsync
  203. \ transparent
  204. endif
  205. " From the 'Python Library Reference' class hierarchy at the bottom.
  206. " http://docs.python.org/library/exceptions.html
  207. if !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 LookupError
  211. " builtin exceptions (actually raised)
  212. syn keyword pythonExceptions AssertionError AttributeError EOFError
  213. syn keyword pythonExceptions FloatingPointError GeneratorExit ImportError
  214. syn keyword pythonExceptions IndentationError IndexError KeyError
  215. syn keyword pythonExceptions KeyboardInterrupt MemoryError
  216. syn keyword pythonExceptions ModuleNotFoundError NameError
  217. syn keyword pythonExceptions NotImplementedError OSError OverflowError
  218. syn keyword pythonExceptions RecursionError ReferenceError RuntimeError
  219. syn keyword pythonExceptions StopAsyncIteration StopIteration SyntaxError
  220. syn keyword pythonExceptions SystemError SystemExit TabError TypeError
  221. syn keyword pythonExceptions UnboundLocalError UnicodeDecodeError
  222. syn keyword pythonExceptions UnicodeEncodeError UnicodeError
  223. syn keyword pythonExceptions UnicodeTranslateError ValueError
  224. syn keyword pythonExceptions ZeroDivisionError
  225. " builtin exception aliases for OSError
  226. syn keyword pythonExceptions EnvironmentError IOError WindowsError
  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 TimeoutError
  235. " builtin warnings
  236. syn keyword pythonExceptions BytesWarning DeprecationWarning FutureWarning
  237. syn keyword pythonExceptions ImportWarning PendingDeprecationWarning
  238. syn keyword pythonExceptions ResourceWarning RuntimeWarning
  239. syn keyword pythonExceptions SyntaxWarning UnicodeWarning
  240. syn keyword pythonExceptions UserWarning Warning
  241. endif
  242. if exists("python_space_error_highlight")
  243. " trailing whitespace
  244. syn match pythonSpaceError display excludenl "\s\+$"
  245. " mixed tabs and spaces
  246. syn match pythonSpaceError display " \+\t"
  247. syn match pythonSpaceError display "\t\+ "
  248. endif
  249. " Do not spell doctests inside strings.
  250. " Notice that the end of a string, either ''', or """, will end the contained
  251. " doctest too. Thus, we do *not* need to have it as an end pattern.
  252. if !exists("python_no_doctest_highlight")
  253. if !exists("python_no_doctest_code_highlight")
  254. syn region pythonDoctest
  255. \ start="^\s*>>>\s" end="^\s*$"
  256. \ contained contains=ALLBUT,pythonDoctest,pythonFunction,@Spell
  257. syn region pythonDoctestValue
  258. \ start=+^\s*\%(>>>\s\|\.\.\.\s\|"""\|'''\)\@!\S\++ end="$"
  259. \ contained
  260. else
  261. syn region pythonDoctest
  262. \ start="^\s*>>>" end="^\s*$"
  263. \ contained contains=@NoSpell
  264. endif
  265. endif
  266. " Sync at the beginning of class, function, or method definition.
  267. syn sync match pythonSync grouphere NONE "^\%(def\|class\)\s\+\h\w*\s*[(:]"
  268. " The default highlight links. Can be overridden later.
  269. hi def link pythonStatement Statement
  270. hi def link pythonConditional Conditional
  271. hi def link pythonRepeat Repeat
  272. hi def link pythonOperator Operator
  273. hi def link pythonException Exception
  274. hi def link pythonInclude Include
  275. hi def link pythonAsync Statement
  276. hi def link pythonDecorator Define
  277. hi def link pythonDecoratorName Function
  278. hi def link pythonFunction Function
  279. hi def link pythonComment Comment
  280. hi def link pythonTodo Todo
  281. hi def link pythonString String
  282. hi def link pythonRawString String
  283. hi def link pythonQuotes String
  284. hi def link pythonTripleQuotes pythonQuotes
  285. hi def link pythonEscape Special
  286. if !exists("python_no_number_highlight")
  287. hi def link pythonNumber Number
  288. endif
  289. if !exists("python_no_builtin_highlight")
  290. hi def link pythonBuiltin Function
  291. endif
  292. if !exists("python_no_exception_highlight")
  293. hi def link pythonExceptions Structure
  294. endif
  295. if exists("python_space_error_highlight")
  296. hi def link pythonSpaceError Error
  297. endif
  298. if !exists("python_no_doctest_highlight")
  299. hi def link pythonDoctest Special
  300. hi def link pythonDoctestValue Define
  301. endif
  302. let b:current_syntax = "python"
  303. let &cpo = s:cpo_save
  304. unlet s:cpo_save
  305. " vim:set sw=2 sts=2 ts=8 noet: