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