]> git.armaanb.net Git - stagit.git/blobdiff - highlight
Ditch linguist and switch to python.
[stagit.git] / highlight
index 2b46f20fdd885d4c0df382109c7c818d51520d2c..cfcc452fb2862375aa073c4c5f2052514957f49d 100755 (executable)
--- a/highlight
+++ b/highlight
@@ -1,49 +1,33 @@
-#!/usr/bin/env ruby
-
-require 'linguist'
-require 'pygments'
-
-stdin = ARGF.file
-
-filename = stdin.readline.strip  # Read first line (filename).
-contents = stdin.read            # Read rest (code).
-
-class FakeBlob < Linguist::FileBlob
-  def initialize(path, content, base_bath=nil)
-    super(path, base_bath)
-    @content = content
-  end
-
-  def data
-    @content
-  end
-
-  def size
-    @content.bytesize
-  end
-end
-
-blob = FakeBlob.new(filename, contents)
-detected = if blob.language
-             blob.language.name
-           else
-             "Text only"
-           end
-
-# Debugging
-#puts "File #{filename}"
-#puts "Code:
-#{contents}"
-#print "Language: "
-#pp detected
-
-html = Pygments.highlight(contents,
-  :lexer => detected,
-  :formatter => 'html',
-  :options => {
-    :encoding => 'utf-8',
-    :linenos => 'table',
-    :lineanchors => 'loc',
-    :anchorlinenos => true})
-
-puts html
+#!/usr/bin/env python3
+
+import pygments
+from pygments import highlight
+from pygments.formatters import HtmlFormatter
+from pygments.lexers import guess_lexer, guess_lexer_for_filename
+
+from sys import stdin
+
+filename = stdin.readline().strip()
+contents = stdin.read()
+
+lexer=None
+
+try:
+    lexer = guess_lexer_for_filename(filename, contents)
+except pygments.util.ClassNotFound:
+    try:
+        lexer = guess_lexer(contents)
+    except pygments.util.ClassNotFound:
+        pass
+
+if lexer is None:
+    from pygments.lexers import TextLexer
+    lexer = TextLexer
+
+FORMAT = HtmlFormatter(
+    lineos='table',
+    lineanchors='loc',
+    anchorlinenos=True)
+
+print(highlight(contents, lexer, FORMAT))
+