@@ -0,0 +1,413 @@
1+{-
2+Copyright (C) 2010 John MacFarlane <jgm@berkeley.edu>
3+
4+This program is free software; you can redistribute it and/or modify
5+it under the terms of the GNU General Public License as published by
6+the Free Software Foundation; either version 2 of the License, or
7+(at your option) any later version.
8+
9+This program is distributed in the hope that it will be useful,
10+but WITHOUT ANY WARRANTY; without even the implied warranty of
11+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+GNU General Public License for more details.
13+
14+You should have received a copy of the GNU General Public License
15+along with this program; if not, write to the Free Software
16+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17+-}
18+
19+{- |
20+ Module : Text.Pandoc.Writers.Textile
21+ Copyright : Copyright (C) 2010 John MacFarlane
22+ License : GNU GPL, version 2 or above
23+
24+ Maintainer : John MacFarlane <jgm@berkeley.edu>
25+ Stability : alpha
26+ Portability : portable
27+
28+Conversion of 'Pandoc' documents to Textile markup.
29+
30+Textile: <http://thresholdstate.com/articles/4312/the-textile-reference-manual>
31+-}
32+module Text.Pandoc.Writers.Textile ( writeTextile ) where
33+import Text.Pandoc.Definition
34+import Text.Pandoc.Shared
35+import Text.Pandoc.Templates (renderTemplate)
36+import Text.Pandoc.XML ( escapeStringForXML )
37+import Data.List ( intercalate )
38+import Control.Monad.State
39+import Data.Char ( isSpace )
40+
41+data WriterState = WriterState {
42+ stNotes :: [String] -- Footnotes
43+ , stListLevel :: [Char] -- String at beginning of list items, e.g. "**"
44+ , stUseTags :: Bool -- True if we should use HTML tags because we're in a complex list
45+ }
46+
47+-- | Convert Pandoc to Textile.
48+writeTextile :: WriterOptions -> Pandoc -> String
49+writeTextile opts document =
50+ evalState (pandocToTextile opts document)
51+ (WriterState { stNotes = [], stListLevel = [], stUseTags = False })
52+
53+-- | Return Textile representation of document.
54+pandocToTextile :: WriterOptions -> Pandoc -> State WriterState String
55+pandocToTextile opts (Pandoc _ blocks) = do
56+ body <- blockListToTextile opts blocks
57+ notes <- liftM (unlines . reverse . stNotes) get
58+ let main = body ++ if null notes then "" else ("\n\n" ++ notes)
59+ let context = writerVariables opts ++ [ ("body", main) ]
60+ if writerStandalone opts
61+ then return $ renderTemplate context $ writerTemplate opts
62+ else return main
63+
64+withUseTags :: State WriterState a -> State WriterState a
65+withUseTags action = do
66+ oldUseTags <- liftM stUseTags get
67+ modify $ \s -> s { stUseTags = True }
68+ result <- action
69+ modify $ \s -> s { stUseTags = oldUseTags }
70+ return result
71+
72+-- | Escape one character as needed for Textile.
73+escapeCharForTextile :: Char -> String
74+escapeCharForTextile x = case x of
75+ '&' -> "&"
76+ '<' -> "<"
77+ '>' -> ">"
78+ '"' -> """
79+ '*' -> "*"
80+ '_' -> "_"
81+ '@' -> "@"
82+ '|' -> "|"
83+ c -> [c]
84+
85+-- | Escape string as needed for Textile.
86+escapeStringForTextile :: String -> String
87+escapeStringForTextile = concatMap escapeCharForTextile
88+
89+-- | Convert Pandoc block element to Textile.
90+blockToTextile :: WriterOptions -- ^ Options
91+ -> Block -- ^ Block element
92+ -> State WriterState String
93+
94+blockToTextile _ Null = return ""
95+
96+blockToTextile opts (Plain inlines) =
97+ inlineListToTextile opts inlines
98+
99+blockToTextile opts (Para [Image txt (src,tit)]) = do
100+ capt <- blockToTextile opts (Para txt)
101+ im <- inlineToTextile opts (Image txt (src,tit))
102+ return $ im ++ "\n" ++ capt
103+
104+blockToTextile opts (Para inlines) = do
105+ useTags <- liftM stUseTags get
106+ listLevel <- liftM stListLevel get
107+ contents <- inlineListToTextile opts inlines
108+ return $ if useTags
109+ then " <p>" ++ contents ++ "</p>"
110+ else contents ++ if null listLevel then "\n" else ""
111+
112+blockToTextile _ (RawHtml str) = return str
113+
114+blockToTextile _ HorizontalRule = return "<hr />\n"
115+
116+blockToTextile opts (Header level inlines) = do
117+ contents <- inlineListToTextile opts inlines
118+ let prefix = 'h' : (show level ++ ". ")
119+ return $ prefix ++ contents ++ "\n"
120+
121+blockToTextile _ (CodeBlock (_,classes,_) str) =
122+ return $ "bc" ++ classes' ++ dots ++ escapeStringForXML str ++ "\n"
123+ where classes' = if null classes
124+ then ""
125+ else "(" ++ unwords classes ++ ")"
126+ dots = if any isBlank (lines str)
127+ then ".. "
128+ else ". "
129+ isBlank = all isSpace
130+
131+blockToTextile opts (BlockQuote bs@[Para _]) = do
132+ contents <- blockListToTextile opts bs
133+ return $ "bq. " ++ contents
134+
135+blockToTextile opts (BlockQuote blocks) = do
136+ contents <- blockListToTextile opts blocks
137+ return $ "<blockquote>\n\n" ++ contents ++ "\n</blockquote>\n"
138+
139+blockToTextile opts (Table [] aligns widths headers rows') |
140+ all (==0) widths && all (`elem` [AlignLeft,AlignDefault]) aligns = do
141+ hs <- mapM (liftM (("_. " ++) . stripTrailingNewlines) . blockListToTextile opts) headers
142+ let cellsToRow cells = "|" ++ intercalate "|" cells ++ "|"
143+ let header = if all null headers then "" else cellsToRow hs
144+ let rowToCells = mapM (liftM stripTrailingNewlines . blockListToTextile opts)
145+ bs <- mapM rowToCells rows'
146+ let body = unlines $ map cellsToRow bs
147+ return $ header ++ "\n" ++ body ++ "\n"
148+
149+blockToTextile opts (Table capt aligns widths headers rows') = do
150+ let alignStrings = map alignmentToString aligns
151+ captionDoc <- if null capt
152+ then return ""
153+ else do
154+ c <- inlineListToTextile opts capt
155+ return $ " <caption>" ++ c ++ "</caption>\n"
156+ let percent w = show (truncate (100*w) :: Integer) ++ "%"
157+ let coltags = if all (== 0.0) widths
158+ then ""
159+ else unlines $ map
160+ (\w -> " <col width=\"" ++ percent w ++ "\" />") widths
161+ head' <- if all null headers
162+ then return ""
163+ else do
164+ hs <- tableRowToTextile opts alignStrings 0 headers
165+ return $ " <thead>\n" ++ hs ++ "\n </thead>\n"
166+ body' <- zipWithM (tableRowToTextile opts alignStrings) [1..] rows'
167+ return $ " <table>\n" ++ captionDoc ++ coltags ++ head' ++
168+ " <tbody>\n" ++ unlines body' ++ " </tbody>\n </table>\n"
169+
170+blockToTextile opts x@(BulletList items) = do
171+ oldUseTags <- liftM stUseTags get
172+ let useTags = oldUseTags || not (isSimpleList x)
173+ if useTags
174+ then do
175+ contents <- withUseTags $ mapM (listItemToTextile opts) items
176+ return $ " <ul>\n" ++ vcat contents ++ " </ul>\n"
177+ else do
178+ modify $ \s -> s { stListLevel = stListLevel s ++ "*" }
179+ contents <- mapM (listItemToTextile opts) items
180+ modify $ \s -> s { stListLevel = init (stListLevel s) }
181+ return $ vcat contents ++ "\n"
182+
183+blockToTextile opts x@(OrderedList attribs items) = do
184+ oldUseTags <- liftM stUseTags get
185+ let useTags = oldUseTags || not (isSimpleList x)
186+ if useTags
187+ then do
188+ contents <- withUseTags $ mapM (listItemToTextile opts) items
189+ return $ " <ol" ++ listAttribsToString attribs ++ ">\n" ++ vcat contents ++
190+ " </ol>\n"
191+ else do
192+ modify $ \s -> s { stListLevel = stListLevel s ++ "#" }
193+ contents <- mapM (listItemToTextile opts) items
194+ modify $ \s -> s { stListLevel = init (stListLevel s) }
195+ return $ vcat contents ++ "\n"
196+
197+blockToTextile opts (DefinitionList items) = do
198+ contents <- withUseTags $ mapM (definitionListItemToTextile opts) items
199+ return $ " <dl>\n" ++ vcat contents ++ " </dl>\n"
200+
201+-- Auxiliary functions for lists:
202+
203+-- | Convert ordered list attributes to HTML attribute string
204+listAttribsToString :: ListAttributes -> String
205+listAttribsToString (startnum, numstyle, _) =
206+ let numstyle' = camelCaseToHyphenated $ show numstyle
207+ in (if startnum /= 1
208+ then " start=\"" ++ show startnum ++ "\""
209+ else "") ++
210+ (if numstyle /= DefaultStyle
211+ then " style=\"list-style-type: " ++ numstyle' ++ ";\""
212+ else "")
213+
214+-- | Convert bullet or ordered list item (list of blocks) to Textile.
215+listItemToTextile :: WriterOptions -> [Block] -> State WriterState String
216+listItemToTextile opts items = do
217+ contents <- blockListToTextile opts items
218+ useTags <- get >>= return . stUseTags
219+ if useTags
220+ then return $ " <li>" ++ contents ++ "</li>"
221+ else do
222+ marker <- get >>= return . stListLevel
223+ return $ marker ++ " " ++ contents
224+
225+-- | Convert definition list item (label, list of blocks) to Textile.
226+definitionListItemToTextile :: WriterOptions
227+ -> ([Inline],[[Block]])
228+ -> State WriterState String
229+definitionListItemToTextile opts (label, items) = do
230+ labelText <- inlineListToTextile opts label
231+ contents <- mapM (blockListToTextile opts) items
232+ return $ " <dt>" ++ labelText ++ "</dt>\n" ++
233+ (intercalate "\n" $ map (\d -> " <dd>" ++ d ++ "</dd>") contents)
234+
235+-- | True if the list can be handled by simple wiki markup, False if HTML tags will be needed.
236+isSimpleList :: Block -> Bool
237+isSimpleList x =
238+ case x of
239+ BulletList items -> all isSimpleListItem items
240+ OrderedList (num, sty, _) items -> all isSimpleListItem items &&
241+ num == 1 && sty `elem` [DefaultStyle, Decimal]
242+ _ -> False
243+
244+-- | True if list item can be handled with the simple wiki syntax. False if
245+-- HTML tags will be needed.
246+isSimpleListItem :: [Block] -> Bool
247+isSimpleListItem [] = True
248+isSimpleListItem [x] =
249+ case x of
250+ Plain _ -> True
251+ Para _ -> True
252+ BulletList _ -> isSimpleList x
253+ OrderedList _ _ -> isSimpleList x
254+ _ -> False
255+isSimpleListItem [x, y] | isPlainOrPara x =
256+ case y of
257+ BulletList _ -> isSimpleList y
258+ OrderedList _ _ -> isSimpleList y
259+ _ -> False
260+isSimpleListItem _ = False
261+
262+isPlainOrPara :: Block -> Bool
263+isPlainOrPara (Plain _) = True
264+isPlainOrPara (Para _) = True
265+isPlainOrPara _ = False
266+
267+-- | Concatenates strings with line breaks between them.
268+vcat :: [String] -> String
269+vcat = intercalate "\n"
270+
271+-- Auxiliary functions for tables. (TODO: these are common to HTML, MediaWiki,
272+-- and Textile writers, and should be abstracted out.)
273+
274+tableRowToTextile :: WriterOptions
275+ -> [String]
276+ -> Int
277+ -> [[Block]]
278+ -> State WriterState String
279+tableRowToTextile opts alignStrings rownum cols' = do
280+ let celltype = if rownum == 0 then "th" else "td"
281+ let rowclass = case rownum of
282+ 0 -> "header"
283+ x | x `rem` 2 == 1 -> "odd"
284+ _ -> "even"
285+ cols'' <- sequence $ zipWith
286+ (\alignment item -> tableItemToTextile opts celltype alignment item)
287+ alignStrings cols'
288+ return $ "<tr class=\"" ++ rowclass ++ "\">\n" ++ unlines cols'' ++ "</tr>"
289+
290+alignmentToString :: Alignment -> [Char]
291+alignmentToString alignment = case alignment of
292+ AlignLeft -> "left"
293+ AlignRight -> "right"
294+ AlignCenter -> "center"
295+ AlignDefault -> "left"
296+
297+tableItemToTextile :: WriterOptions
298+ -> String
299+ -> String
300+ -> [Block]
301+ -> State WriterState String
302+tableItemToTextile opts celltype align' item = do
303+ let mkcell x = "<" ++ celltype ++ " align=\"" ++ align' ++ "\">" ++
304+ x ++ "</" ++ celltype ++ ">"
305+ contents <- blockListToTextile opts item
306+ return $ mkcell contents
307+
308+-- | Convert list of Pandoc block elements to Textile.
309+blockListToTextile :: WriterOptions -- ^ Options
310+ -> [Block] -- ^ List of block elements
311+ -> State WriterState String
312+blockListToTextile opts blocks =
313+ mapM (blockToTextile opts) blocks >>= return . vcat
314+
315+-- | Convert list of Pandoc inline elements to Textile.
316+inlineListToTextile :: WriterOptions -> [Inline] -> State WriterState String
317+inlineListToTextile opts lst =
318+ mapM (inlineToTextile opts) lst >>= return . concat
319+
320+-- | Convert Pandoc inline element to Textile.
321+inlineToTextile :: WriterOptions -> Inline -> State WriterState String
322+
323+inlineToTextile opts (Emph lst) = do
324+ contents <- inlineListToTextile opts lst
325+ return $ if '_' `elem` contents
326+ then "<em>" ++ contents ++ "</em>"
327+ else "_" ++ contents ++ "_"
328+
329+inlineToTextile opts (Strong lst) = do
330+ contents <- inlineListToTextile opts lst
331+ return $ if '*' `elem` contents
332+ then "<strong>" ++ contents ++ "</strong>"
333+ else "*" ++ contents ++ "*"
334+
335+inlineToTextile opts (Strikeout lst) = do
336+ contents <- inlineListToTextile opts lst
337+ return $ if '-' `elem` contents
338+ then "<del>" ++ contents ++ "</del>"
339+ else "-" ++ contents ++ "-"
340+
341+inlineToTextile opts (Superscript lst) = do
342+ contents <- inlineListToTextile opts lst
343+ return $ if '^' `elem` contents
344+ then "<sup>" ++ contents ++ "</sup>"
345+ else "^" ++ contents ++ "^"
346+
347+inlineToTextile opts (Subscript lst) = do
348+ contents <- inlineListToTextile opts lst
349+ return $ if '~' `elem` contents
350+ then "<sub>" ++ contents ++ "</sub>"
351+ else "~" ++ contents ++ "~"
352+
353+inlineToTextile opts (SmallCaps lst) = inlineListToTextile opts lst
354+
355+inlineToTextile opts (Quoted SingleQuote lst) = do
356+ contents <- inlineListToTextile opts lst
357+ return $ "'" ++ contents ++ "'"
358+
359+inlineToTextile opts (Quoted DoubleQuote lst) = do
360+ contents <- inlineListToTextile opts lst
361+ return $ "\"" ++ contents ++ "\""
362+
363+inlineToTextile opts (Cite _ lst) = inlineListToTextile opts lst
364+
365+inlineToTextile _ EmDash = return " -- "
366+
367+inlineToTextile _ EnDash = return " - "
368+
369+inlineToTextile _ Apostrophe = return "'"
370+
371+inlineToTextile _ Ellipses = return "..."
372+
373+inlineToTextile _ (Code str) =
374+ return $ if '@' `elem` str
375+ then "<tt>" ++ escapeStringForXML str ++ "</tt>"
376+ else "@" ++ escapeStringForXML str ++ "@"
377+
378+inlineToTextile _ (Str str) = return $ escapeStringForTextile str
379+
380+inlineToTextile _ (Math _ str) =
381+ return $ "<span class=\"math\">" ++ escapeStringForXML str ++ "</math>"
382+
383+inlineToTextile _ (TeX _) = return ""
384+
385+inlineToTextile _ (HtmlInline str) = return str
386+
387+inlineToTextile _ (LineBreak) = return "\n"
388+
389+inlineToTextile _ Space = return " "
390+
391+inlineToTextile opts (Link txt (src, _)) = do
392+ label <- case txt of
393+ [Code s] -> return s
394+ _ -> inlineListToTextile opts txt
395+ return $ "\"" ++ label ++ "\":" ++ src
396+
397+inlineToTextile opts (Image alt (source, tit)) = do
398+ alt' <- inlineListToTextile opts alt
399+ let txt = if null tit
400+ then if null alt'
401+ then ""
402+ else "(" ++ alt' ++ ")"
403+ else "(" ++ tit ++ ")"
404+ return $ "!" ++ source ++ txt ++ "!"
405+
406+inlineToTextile opts (Note contents) = do
407+ curNotes <- liftM stNotes get
408+ let newnum = length curNotes + 1
409+ contents' <- blockListToTextile opts contents
410+ let thisnote = "fn" ++ show newnum ++ ". " ++ contents' ++ "\n"
411+ modify $ \s -> s { stNotes = thisnote : curNotes }
412+ return $ "[" ++ show newnum ++ "]"
413+ -- note - may not work for notes with multiple blocks