summaryrefslogtreecommitdiff
path: root/pandoc.rb
blob: 8c51cb492ce5dbffd5a85ea5693cebc4be8da41d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# coding: utf-8
require 'open3'
require 'json'

module Pandoc
	def self.prog
		@prog ||= 'pandoc'
	end
	def self.prog=(val)
		@prog = val
	end
	def self.load(fmt, input)
		cmd = Pandoc::prog + " -t json"
		unless fmt.nil?
			cmd += " -f " + fmt
		end
		str = input
		if str.respond_to? :read
			str = str.read
		end
		json = ''
		errors = ''
		Open3::popen3(cmd) do |stdin, stdout, stderr|
			stdin.puts(str)
			stdin.close
			json = stdout.read
			errors = stderr.read
		end
		unless errors.empty?
			raise errors
		end
		return Pandoc::AST::new(json)
	end

	class AST
		def initialize(json)
			@js = JSON::parse(json)
		end

		def [](key)
			Pandoc::AST::js2sane(@js["meta"][key])
		end

		def js
			@js
		end

		def to(format)
			cmd = Pandoc::prog + " -f json -t " + format.to_s
			output = ''
			errors = ''
			Open3::popen3(cmd) do |stdin, stdout, stderr|
				stdin.puts @js.to_json
				stdin.close
				output = stdout.read
				errors = stderr.read
			end
			unless errors.empty?
				raise errors
			end
			return output
		end

		def self.js2sane(js)
			if js.nil?
				return js
			end
			case js["t"]
			when "MetaMap"
				Hash[js["c"].map{|k,v| [k, js2sane(v)]}]
			when "MetaList"
				js["c"].map{|c| js2sane(c)}
			when "MetaBool"
				js["c"]
			when "MetaString"
				js["c"]
			when "MetaInlines"
				js["c"].map{|c| js2sane(c)}.join()
			when "MetaBlocks"
				js["c"].map{|c| js2sane(c)}.join("\n")
			when "Str"
				js["c"]
			when "Space"
				" "
			when "RawInline"
				js["c"][1]
			when "RawBlock"
				js["c"][1]
			when "Para"
				js["c"].map{|c| js2sane(c)}.join()
			else
				raise "Unexpected AST node type '#{js["t"]}'"
			end
		end
	end
end