summaryrefslogtreecommitdiff
path: root/pygments/modeline.py
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2013-05-19 09:02:27 +0200
committerGeorg Brandl <georg@python.org>2013-05-19 09:02:27 +0200
commit4275413185f40b6dac9f0ca42679a8b464185c27 (patch)
tree5b838dbbee7ef2f4f75a8caed062cb8328044cc7 /pygments/modeline.py
parent586387f82d5387f803473e9148c223c81325dfc6 (diff)
parenta9b99161513666939581b748a756e77fe8ea8bbf (diff)
downloadpygments-4275413185f40b6dac9f0ca42679a8b464185c27.tar.gz
merge with mgorny/pygments-vim-modelines-r1 (pull request #118)
Diffstat (limited to 'pygments/modeline.py')
-rw-r--r--pygments/modeline.py40
1 files changed, 40 insertions, 0 deletions
diff --git a/pygments/modeline.py b/pygments/modeline.py
new file mode 100644
index 00000000..cba1cab2
--- /dev/null
+++ b/pygments/modeline.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+"""
+ pygments.modeline
+ ~~~~~~~~~~~~~~~~~
+
+ A simple modeline parser (based on pymodeline).
+
+ :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import re
+
+__all__ = ['get_filetype_from_buffer']
+
+modeline_re = re.compile(r'''
+ (?: vi | vim | ex ) (?: [<=>]? \d* )? :
+ .* (?: ft | filetype | syn | syntax ) = ( [^:\s]+ )
+''', re.VERBOSE)
+
+def get_filetype_from_line(l):
+ m = modeline_re.search(l)
+ if m:
+ return m.group(1)
+
+def get_filetype_from_buffer(buf, max_lines=5):
+ """
+ Scan the buffer for modelines and return filetype if one is found.
+ """
+ lines = buf.splitlines()
+ for l in lines[-1:-max_lines-1:-1]:
+ ret = get_filetype_from_line(l)
+ if ret:
+ return ret
+ for l in lines[max_lines:0:-1]:
+ ret = get_filetype_from_line(l)
+ if ret:
+ return ret
+
+ return None