-- © 2008 David Given.
-- WordGrinder is licensed under the MIT open source license. See the COPYING
-- file in this distribution for the full text.

local untextab = {
	["#"] = "\\#",
	["$"] = "\\$",
	["&"] = "\\&",
	["{"] = "\\{",
	["}"] = "\\}",
	["_"] = "\\_{}",
	["^"] = "\\^{}",
	["~"] = "\\~{}",
	["%"] = "\\%",
	["<"] = "$\\langle$",
	[">"] = "$\\rangle$",
	["\\"] = "$\\backslash$"
}

local function untex(s)
	s = s:gsub("[#$&{}\\_^~%%<>]", untextab)
	return s
end

local style_tab =
{
	["H1"] = {'\\section{',            '}'},
	["H2"] = {'\\subsection{',         '}'},
	["H3"] = {'\\subsubsection{',      '}'},
	["H4"] = {'\\paragraph{',          '}'},
	["P"] =  {'',                      '\n'},
	["L"] =  {'\\item[]{',             '}'},
	["LB"] = {'\\item[\\textbullet]{', '}'},
	["LN"] = {'\\item{',               '}'},
	["Q"] =  {'\\begin{quotation}\n',  '\n\\end{quotation}'},
	["V"] =  {'\\begin{quotation}\n',  '\n\\end{quotation}'},
	["RAW"] = {'', ''},
	["PRE"] = {'\\begin{verbatim}\n',  '\n\\end{verbatim}'}
}

local function callback(writer, document)
	return ExportFileUsingCallbacks(document,
	{
		prologue = function()
			writer('%% This document automatically generated by '..
				'WordGrinder '..VERSION..'.\n')
			writer('\\documentclass{article}\n')
			writer('\\usepackage{xunicode, setspace, xltxtra}\n')
			writer('\\sloppy\n')
			writer('\\onehalfspacing\n')
			writer('\\begin{document}\n')
			writer('\\title{', untex(Document.name), '}\n')
			writer('\\author{(no author)}\n')
			writer('\\maketitle\n')
		end,
		
		rawtext = function(s)
			writer(s)
		end,
		
		text = function(s)
			writer(untex(s))
		end,
		
		notext = function(s)
			writer('\\paragraph{}')
		end,
		
		italic_on = function()
			writer('\\textit{')
		end,
		
		italic_off = function()
			writer('}')
		end,
		
		bold_on = function()
			writer('\\textbf{')
		end,
		
		bold_off = function()
			writer('}')
		end,
		
		underline_on = function()
			writer('\\underline{')
		end,
		
		underline_off = function()
			writer('}')
		end,
		
		list_start = function()
			writer('\\begin{enumerate}\n')
		end,
		
		list_end = function()
			writer('\\end{enumerate}\n')
		end,
		
		paragraph_start = function(para)
			writer(style_tab[para.style][1] or "")
		end,		
		
		paragraph_end = function(para)
			writer(style_tab[para.style][2] or "")
			writer('\n')
		end,
		
		epilogue = function()
			writer('\\end{document}\n')	
		end
	})
end

function Cmd.ExportLatexFile(filename)
	return ExportFileWithUI(filename, "Export LaTeX File", ".tex",
		callback)
end

function Cmd.ExportToLatexString()
	return ExportToString(Document, callback)
end

