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