summaryrefslogtreecommitdiff
path: root/lib/coderay/encoders/latex.demiurgo.rb
diff options
context:
space:
mode:
authorNathan Youngman <git@nathany.com>2012-10-27 14:22:18 -0600
committerNathan Youngman <git@nathany.com>2012-10-27 14:22:18 -0600
commit3a97b804e0c0df0693e34fb23fd16a65757636ef (patch)
tree25387d06433fd8121666f4f88b937d2c1d0079f7 /lib/coderay/encoders/latex.demiurgo.rb
parent3effca8291ed4941f7b3a1c2088b50274f28aa6f (diff)
downloadcoderay-latex-encoder.tar.gz
Latex encoder from Redminelatex-encoder
Diffstat (limited to 'lib/coderay/encoders/latex.demiurgo.rb')
-rw-r--r--lib/coderay/encoders/latex.demiurgo.rb79
1 files changed, 79 insertions, 0 deletions
diff --git a/lib/coderay/encoders/latex.demiurgo.rb b/lib/coderay/encoders/latex.demiurgo.rb
new file mode 100644
index 0000000..0a54872
--- /dev/null
+++ b/lib/coderay/encoders/latex.demiurgo.rb
@@ -0,0 +1,79 @@
+module CodeRay
+module Encoders
+
+ # = LaTeX Encoder
+ #
+ # Encoder producing LaTeX.
+ class Latex < Encoder
+
+ include Streamable
+ register_for :latex
+
+ FILE_EXTENSION = 'tex'
+
+ DEFAULT_OPTIONS = {
+ :wrap => true,
+ }
+
+ protected
+ def text_token text, kind
+ @out <<
+ if kind == :space
+ text
+ else
+ text = escape_latex(text)
+ "\\syn#{kind_to_command(kind)}{#{text}}"
+ end
+ end
+
+ def block_token action, kind
+ @out << super
+ end
+
+ def open_token kind
+ "\\syn#{kind_to_command(kind)}{"
+ end
+
+ def close_token kind
+ "}"
+ end
+
+ def kind_to_command kind
+ kind.to_s.gsub(/[^a-z0-9]/i, '').to_sym
+ end
+
+ def finish options
+ case options[:wrap]
+ when true, 1, :semiverbatim
+ @out = "\\begin{semiverbatim}\n#{@out}\n\\end{semiverbatim}\n"
+ when false, 0
+ # Nothing to do
+ else
+ raise ArgumentError, "Unknown :wrap option: '#{options[:wrap]}'"
+ end
+
+ super
+ end
+
+ # Escape text so it's interpreted literally by LaTeX compilers
+ def escape_latex string
+ string.to_s.gsub(/[$\\{}_%#&~^"]/) do |s|
+ case s
+ when '$'
+ '\$'
+ when '\\'
+ '\synbs{}'
+ when /[{}_%#&]/
+ "\\#{s}"
+ when /[~^]/
+ "\\#{s}{}"
+ when '"'
+ '"{}'
+ end
+ end
+ end
+
+ end
+
+end
+end