python.vim 15KB

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