python.vim 14KB

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