modeline.py 986 B

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