|
1 # -*- coding: utf-8 -*- |
|
2 """ |
|
3 pygments.modeline |
|
4 ~~~~~~~~~~~~~~~~~ |
|
5 |
|
6 A simple modeline parser (based on pymodeline). |
|
7 |
|
8 :copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS. |
|
9 :license: BSD, see LICENSE for details. |
|
10 """ |
|
11 |
|
12 import re |
|
13 |
|
14 __all__ = ['get_filetype_from_buffer'] |
|
15 |
|
16 |
|
17 modeline_re = re.compile(r''' |
|
18 (?: vi | vim | ex ) (?: [<=>]? \d* )? : |
|
19 .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ ) |
|
20 ''', re.VERBOSE) |
|
21 |
|
22 |
|
23 def get_filetype_from_line(l): |
|
24 m = modeline_re.search(l) |
|
25 if m: |
|
26 return m.group(1) |
|
27 |
|
28 |
|
29 def get_filetype_from_buffer(buf, max_lines=5): |
|
30 """ |
|
31 Scan the buffer for modelines and return filetype if one is found. |
|
32 """ |
|
33 lines = buf.splitlines() |
|
34 for l in lines[-1:-max_lines-1:-1]: |
|
35 ret = get_filetype_from_line(l) |
|
36 if ret: |
|
37 return ret |
|
38 for i in range(max_lines, -1, -1): |
|
39 if i < len(lines): |
|
40 ret = get_filetype_from_line(lines[i]) |
|
41 if ret: |
|
42 return ret |
|
43 |
|
44 return None |