Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/pygments/modeline.py: 30%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

20 statements  

1""" 

2 pygments.modeline 

3 ~~~~~~~~~~~~~~~~~ 

4 

5 A simple modeline parser (based on pymodeline). 

6 

7 :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. 

8 :license: BSD, see LICENSE for details. 

9""" 

10 

11import re 

12 

13__all__ = ['get_filetype_from_buffer'] 

14 

15 

16modeline_re = re.compile(r''' 

17 (?: vi | vim | ex ) (?: [<=>]? \d* )? : 

18 .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ ) 

19''', re.VERBOSE) 

20 

21 

22def get_filetype_from_line(l): # noqa: E741 

23 m = modeline_re.search(l) 

24 if m: 

25 return m.group(1) 

26 

27 

28def 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 line in lines[-1:-max_lines-1:-1]: 

34 ret = get_filetype_from_line(line) 

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