You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1010 B

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