marxup (empty) → 1.0.0
raw patch · 11 files changed
+1229/−0 lines, 11 filesdep +basedep +filepathdep +labeled-treesetup-changed
Dependencies added: base, filepath, labeled-tree, mtl, parsec, pretty
Files
- LICENSE +340/−0
- Main.hs +171/−0
- MarXup/Beamer.hs +29/−0
- MarXup/DerivationTrees.hs +226/−0
- MarXup/Latex.hs +126/−0
- MarXup/MetaPost.hs +27/−0
- MarXup/Tex.hs +153/−0
- MarXup/Text.hs +43/−0
- Setup.hs +2/−0
- examples/LaTeX.hs +72/−0
- marxup.cabal +40/−0
+ LICENSE view
@@ -0,0 +1,340 @@+ GNU GENERAL PUBLIC LICENSE+ Version 2, June 1991++ Copyright (C) 1989, 1991 Free Software Foundation, Inc.+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+ Everyone is permitted to copy and distribute verbatim copies+ of this license document, but changing it is not allowed.++ Preamble++ The licenses for most software are designed to take away your+freedom to share and change it. By contrast, the GNU General Public+License is intended to guarantee your freedom to share and change free+software--to make sure the software is free for all its users. This+General Public License applies to most of the Free Software+Foundation's software and to any other program whose authors commit to+using it. (Some other Free Software Foundation software is covered by+the GNU Library General Public License instead.) You can apply it to+your programs, too.++ When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+this service if you wish), that you receive source code or can get it+if you want it, that you can change the software or use pieces of it+in new free programs; and that you know you can do these things.++ To protect your rights, we need to make restrictions that forbid+anyone to deny you these rights or to ask you to surrender the rights.+These restrictions translate to certain responsibilities for you if you+distribute copies of the software, or if you modify it.++ For example, if you distribute copies of such a program, whether+gratis or for a fee, you must give the recipients all the rights that+you have. You must make sure that they, too, receive or can get the+source code. And you must show them these terms so they know their+rights.++ We protect your rights with two steps: (1) copyright the software, and+(2) offer you this license which gives you legal permission to copy,+distribute and/or modify the software.++ Also, for each author's protection and ours, we want to make certain+that everyone understands that there is no warranty for this free+software. If the software is modified by someone else and passed on, we+want its recipients to know that what they have is not the original, so+that any problems introduced by others will not reflect on the original+authors' reputations.++ Finally, any free program is threatened constantly by software+patents. We wish to avoid the danger that redistributors of a free+program will individually obtain patent licenses, in effect making the+program proprietary. To prevent this, we have made it clear that any+patent must be licensed for everyone's free use or not licensed at all.++ The precise terms and conditions for copying, distribution and+modification follow.++ GNU GENERAL PUBLIC LICENSE+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION++ 0. This License applies to any program or other work which contains+a notice placed by the copyright holder saying it may be distributed+under the terms of this General Public License. The "Program", below,+refers to any such program or work, and a "work based on the Program"+means either the Program or any derivative work under copyright law:+that is to say, a work containing the Program or a portion of it,+either verbatim or with modifications and/or translated into another+language. (Hereinafter, translation is included without limitation in+the term "modification".) Each licensee is addressed as "you".++Activities other than copying, distribution and modification are not+covered by this License; they are outside its scope. The act of+running the Program is not restricted, and the output from the Program+is covered only if its contents constitute a work based on the+Program (independent of having been made by running the Program).+Whether that is true depends on what the Program does.++ 1. You may copy and distribute verbatim copies of the Program's+source code as you receive it, in any medium, provided that you+conspicuously and appropriately publish on each copy an appropriate+copyright notice and disclaimer of warranty; keep intact all the+notices that refer to this License and to the absence of any warranty;+and give any other recipients of the Program a copy of this License+along with the Program.++You may charge a fee for the physical act of transferring a copy, and+you may at your option offer warranty protection in exchange for a fee.++ 2. You may modify your copy or copies of the Program or any portion+of it, thus forming a work based on the Program, and copy and+distribute such modifications or work under the terms of Section 1+above, provided that you also meet all of these conditions:++ a) You must cause the modified files to carry prominent notices+ stating that you changed the files and the date of any change.++ b) You must cause any work that you distribute or publish, that in+ whole or in part contains or is derived from the Program or any+ part thereof, to be licensed as a whole at no charge to all third+ parties under the terms of this License.++ c) If the modified program normally reads commands interactively+ when run, you must cause it, when started running for such+ interactive use in the most ordinary way, to print or display an+ announcement including an appropriate copyright notice and a+ notice that there is no warranty (or else, saying that you provide+ a warranty) and that users may redistribute the program under+ these conditions, and telling the user how to view a copy of this+ License. (Exception: if the Program itself is interactive but+ does not normally print such an announcement, your work based on+ the Program is not required to print an announcement.)++These requirements apply to the modified work as a whole. If+identifiable sections of that work are not derived from the Program,+and can be reasonably considered independent and separate works in+themselves, then this License, and its terms, do not apply to those+sections when you distribute them as separate works. But when you+distribute the same sections as part of a whole which is a work based+on the Program, the distribution of the whole must be on the terms of+this License, whose permissions for other licensees extend to the+entire whole, and thus to each and every part regardless of who wrote it.++Thus, it is not the intent of this section to claim rights or contest+your rights to work written entirely by you; rather, the intent is to+exercise the right to control the distribution of derivative or+collective works based on the Program.++In addition, mere aggregation of another work not based on the Program+with the Program (or with a work based on the Program) on a volume of+a storage or distribution medium does not bring the other work under+the scope of this License.++ 3. You may copy and distribute the Program (or a work based on it,+under Section 2) in object code or executable form under the terms of+Sections 1 and 2 above provided that you also do one of the following:++ a) Accompany it with the complete corresponding machine-readable+ source code, which must be distributed under the terms of Sections+ 1 and 2 above on a medium customarily used for software interchange; or,++ b) Accompany it with a written offer, valid for at least three+ years, to give any third party, for a charge no more than your+ cost of physically performing source distribution, a complete+ machine-readable copy of the corresponding source code, to be+ distributed under the terms of Sections 1 and 2 above on a medium+ customarily used for software interchange; or,++ c) Accompany it with the information you received as to the offer+ to distribute corresponding source code. (This alternative is+ allowed only for noncommercial distribution and only if you+ received the program in object code or executable form with such+ an offer, in accord with Subsection b above.)++The source code for a work means the preferred form of the work for+making modifications to it. For an executable work, complete source+code means all the source code for all modules it contains, plus any+associated interface definition files, plus the scripts used to+control compilation and installation of the executable. However, as a+special exception, the source code distributed need not include+anything that is normally distributed (in either source or binary+form) with the major components (compiler, kernel, and so on) of the+operating system on which the executable runs, unless that component+itself accompanies the executable.++If distribution of executable or object code is made by offering+access to copy from a designated place, then offering equivalent+access to copy the source code from the same place counts as+distribution of the source code, even though third parties are not+compelled to copy the source along with the object code.++ 4. You may not copy, modify, sublicense, or distribute the Program+except as expressly provided under this License. Any attempt+otherwise to copy, modify, sublicense or distribute the Program is+void, and will automatically terminate your rights under this License.+However, parties who have received copies, or rights, from you under+this License will not have their licenses terminated so long as such+parties remain in full compliance.++ 5. You are not required to accept this License, since you have not+signed it. However, nothing else grants you permission to modify or+distribute the Program or its derivative works. These actions are+prohibited by law if you do not accept this License. Therefore, by+modifying or distributing the Program (or any work based on the+Program), you indicate your acceptance of this License to do so, and+all its terms and conditions for copying, distributing or modifying+the Program or works based on it.++ 6. Each time you redistribute the Program (or any work based on the+Program), the recipient automatically receives a license from the+original licensor to copy, distribute or modify the Program subject to+these terms and conditions. You may not impose any further+restrictions on the recipients' exercise of the rights granted herein.+You are not responsible for enforcing compliance by third parties to+this License.++ 7. If, as a consequence of a court judgment or allegation of patent+infringement or for any other reason (not limited to patent issues),+conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot+distribute so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you+may not distribute the Program at all. For example, if a patent+license would not permit royalty-free redistribution of the Program by+all those who receive copies directly or indirectly through you, then+the only way you could satisfy both it and this License would be to+refrain entirely from distribution of the Program.++If any portion of this section is held invalid or unenforceable under+any particular circumstance, the balance of the section is intended to+apply and the section as a whole is intended to apply in other+circumstances.++It is not the purpose of this section to induce you to infringe any+patents or other property right claims or to contest validity of any+such claims; this section has the sole purpose of protecting the+integrity of the free software distribution system, which is+implemented by public license practices. Many people have made+generous contributions to the wide range of software distributed+through that system in reliance on consistent application of that+system; it is up to the author/donor to decide if he or she is willing+to distribute software through any other system and a licensee cannot+impose that choice.++This section is intended to make thoroughly clear what is believed to+be a consequence of the rest of this License.++ 8. If the distribution and/or use of the Program is restricted in+certain countries either by patents or by copyrighted interfaces, the+original copyright holder who places the Program under this License+may add an explicit geographical distribution limitation excluding+those countries, so that distribution is permitted only in or among+countries not thus excluded. In such case, this License incorporates+the limitation as if written in the body of this License.++ 9. The Free Software Foundation may publish revised and/or new versions+of the General Public License from time to time. Such new versions will+be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the Program+specifies a version number of this License which applies to it and "any+later version", you have the option of following the terms and conditions+either of that version or of any later version published by the Free+Software Foundation. If the Program does not specify a version number of+this License, you may choose any version ever published by the Free Software+Foundation.++ 10. If you wish to incorporate parts of the Program into other free+programs whose distribution conditions are different, write to the author+to ask for permission. For software which is copyrighted by the Free+Software Foundation, write to the Free Software Foundation; we sometimes+make exceptions for this. Our decision will be guided by the two goals+of preserving the free status of all derivatives of our free software and+of promoting the sharing and reuse of software generally.++ NO WARRANTY++ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,+REPAIR OR CORRECTION.++ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE+POSSIBILITY OF SUCH DAMAGES.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++ If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++ To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+convey the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software; you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation; either version 2 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU General Public License for more details.++ You should have received a copy of the GNU General Public License+ along with this program; if not, write to the Free Software+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA+++Also add information on how to contact you by electronic and paper mail.++If the program is interactive, make it output a short notice like this+when it starts in an interactive mode:++ Gnomovision version 69, Copyright (C) year name of author+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.+ This is free software, and you are welcome to redistribute it+ under certain conditions; type `show c' for details.++The hypothetical commands `show w' and `show c' should show the appropriate+parts of the General Public License. Of course, the commands you use may+be called something other than `show w' and `show c'; they could even be+mouse-clicks or menu items--whatever suits your program.++You should also get your employer (if you work as a programmer) or your+school, if any, to sign a "copyright disclaimer" for the program, if+necessary. Here is a sample; alter the names:++ Yoyodyne, Inc., hereby disclaims all copyright interest in the program+ `Gnomovision' (which makes passes at compilers) written by James Hacker.++ <signature of Ty Coon>, 1 April 1989+ Ty Coon, President of Vice++This General Public License does not permit incorporating your program into+proprietary programs. If your program is a subroutine library, you may+consider it more useful to permit linking proprietary applications with the+library. If this is what you want to do, use the GNU Library General+Public License instead of this License.
+ Main.hs view
@@ -0,0 +1,171 @@+import Text.ParserCombinators.Parsec+-- import Text.PrettyPrint.HughesPJ hiding (char)+-- import qualified Text.PrettyPrint.HughesPJ as O+++import Data.Char+import Control.Applicative hiding (many, (<|>))+import Data.List+import System.IO+import System.Environment+import Control.Monad++-- todo: parse strings inside haskell code+-- todo: output line directives.++instance Applicative (GenParser Char st) where+ (<*>) = ap+ pure = return++----------+ +type Doc = String -> String+(<>) = (.)+text s = (s ++)+x <+> y = x <> text " " <> y +oChar c = (c:)+parens s = oChar '(' <> s <> oChar ')'+braces s = oChar '{' <> s <> oChar '}'+brackets s = oChar '[' <> s <> oChar ']'+doubleQuotes s = oChar '"' <> s <> oChar '"'++oEmpty = id+int x = text $ show x+hcat :: [Doc] -> Doc+hcat = foldr (<>) oEmpty+punctuate t = map (<> t)+render x = x ""++------------------------------------------+-- Output combinators+ +oPos :: SourcePos -> Doc+oPos p = text "{-# LINE" <+> int (sourceLine p) <+> text (show (sourceName p)) <+> text "#-}"+ +oText :: String -> Doc+oText x = text "textual" <+> text (show x)++oMappend :: [Doc] -> Doc+oMappend [] = text "(return ())"+oMappend [x] = parens x+oMappend l = text "do" <+> braces (text "rec" <+> braces (hcat (punctuate (text ";") binds)) <> text ";" <> ret)+ where binds = init l+ ret = last l+ ++oBraces :: Doc -> Doc+oBraces x = oText "{" <> text "*>" <> x <> text "<*" <> oText "}"+++----------------------------------------------+-- Parsing combinators+pChunk :: String -> Parser String+pChunk stops = many1 (noneOf stops)++pWPos :: Parser Doc +pWPos = do + char '\n'+ pos <- getPosition+ return $ oPos pos <> text "\n"++pTextChunk = (oText <$> pChunk "\n{}@")++pHaskChunk = (text <$> many1 (noneOf "\n\"{}[]()@" <|> try (char '@' <* notFollowedBy (oneOf "[({\""))))++pHaskLn = pWPos -- before each newline, tell GHC where we are.++pTextLn = do+ (oText "\n" <>) <$> pWPos + -- add code to output a newline; and insert a newline in the code.+ ++pQuote = do+ try (string "@\"")+ d <- pInText (string "@\"")+ return $ parens d++box x = [x]++pString = do+ char '"'+ result <- many (string "\\\"" <|> pChunk ['"'])+ char '"'+ return $ doubleQuotes . hcat . map text $ result++-- | Parse some Haskell code with markup inside. +pHask = hcat <$> many ((brackets <$> pArg "[]") <|> + (braces <$> pArg "{}") <|>+ (parens <$> pArg "()") <|> pQuote <|> pString <|> pHaskChunk <|> pHaskLn)++-- | Parse a text argument to an element+pTextArg :: Parser Doc+pTextArg = do+ char '{' + result <- pInText (char '}')+ return result+++pInText :: Parser a -> Parser Doc+pInText end = oMappend <$> manyTill (pTextChunk <|> pTextLn <|> pElement <|> (oBraces <$> pTextArg)) (try end)++pArg :: String -> Parser Doc+pArg [open,close] = do + char open+ result <- pHask+ char close+ return result++pArg1 [open,close] = do+ r <- pArg [open,close]+ return $ oChar open <> r <> oChar close++isIdentChar x = isAlphaNum x || x == '\''++-- | Either @fctName or @result<-fctName+pFctName :: Parser (Maybe Doc, Doc)+pFctName = do + x <- try (char '@' >> satisfy isIdentChar) -- this is to clash with @"+ xs' <- many1 (satisfy isIdentChar)+ let xs = x : xs'+ ys <- option Nothing (Just <$> (try (string "<-") >> many1 (satisfy isIdentChar)))+ return $ case ys of+ Nothing -> (Nothing, text xs)+ Just ys -> (Just (text xs), text ys)++pFct = (Nothing,) <$> parens <$> + (try (string "@{") *> pHask <* char '}')++pElement :: Parser Doc+pElement = do+ (result,function) <- pFctName <|> pFct+ args <- many (pArg "()" <|> pTextArg)+ let binder = maybe oEmpty (<+> text "<-") result+ return $ binder <> text "element" <+> parens (function <+> (hcat $ fmap parens args))+{-+pTop :: Parser Doc+pTop = do+ t <- pInText+ return (text "import Text" $$+ text "main =" <+> t)+-}+{-+main = do+ p <- parseFromFile pTop "Text.ths"+ case p of + Left err -> hPutStrLn stderr $ show err+ Right res -> putStrLn $ render res+ -}++main :: IO ()+main = do+ x : y : z : _ <- getArgs+ putStrLn x+ putStrLn y+ putStrLn z+ p <- parseFromFile pHask y+ case p of + Left err -> do+ hPutStrLn stderr $ show err+ Right res -> writeFile z $ + render res+
+ MarXup/Beamer.hs view
@@ -0,0 +1,29 @@+{-# LANGUAGE OverloadedStrings #-}+module MarXup.Beamer where++import Control.Applicative+import Data.Monoid+import MarXup.Tex++usetheme = cmd "usetheme" . tex++frame tit bod = env "frame" $ do+ cmd "frametitle" tit+ bod+ +pause :: TeX+pause = cmd "pause"$ mempty++note = cmd "note"++{-+preamble :: Tex ()+preamble = do + usepackage [] "bbm"+ usetheme "Malmoe"+ + title $ tex "Elements of Parametricity and Computational Irrelevance" + cmd' "author" ["JP Bernardy"] $ tex "Jean-Philippe Bernardy"+ cmd "institute" $ tex "Chalmers University of Technology and University of Gothenburg"+ cmd "date" $ cmd "today" mempty+-}
+ MarXup/DerivationTrees.hs view
@@ -0,0 +1,226 @@+{-# LANGUAGE DisambiguateRecordFields, NamedFieldPuns, RecordWildCards, PostfixOperators, LiberalTypeSynonyms, TypeOperators, OverloadedStrings #-}++module MarXup.DerivationTrees (+-- * Basics+module Data.Monoid,+module Data.LabeledTree,++-- * Derivation' building+-- axiom, rule, etc, aborted, +emptyDrv, haltDrv, haltDrv', abortDrv, delayPre, +dummy, rule, Derivation, Premise, Rule(..), ++-- * Links+Alignment(..), LineStyle(..),defaultLink,Link(..),++-- * Figure building+Figure(..),++-- * Engine+derivationTree++) where++-- import DerivationTrees.Basics+import Data.List+import Data.Traversable hiding (mapM)+import Control.Monad.Writer +import Control.Monad.State +import Control.Applicative +import System.IO.Unsafe+import Data.LabeledTree+-- import Control.Applicative.State+import Data.Monoid+import MarXup.Tex hiding (label)+import MarXup.MetaPost++------------------+--- Basics++data LineStyle = None | Simple | Double | Dotted | Dashed | Waved | TeXDotted + deriving (Enum,Show)++data Link = Link {label :: Tex (), linkStyle :: LineStyle, align :: Alignment, steps :: Int} -- ^ Regular link+ | Detached {label :: Tex ()} -- ^ Detach the derivation as another figure+ | Delayed {align :: Alignment} -- ^ automatic delaying+-- deriving Show++defaultLink :: Link+defaultLink = Link mempty Dotted CenterA 0++data Alignment = LeftA | CenterA | RightA+instance Show Alignment where + show LeftA = "l"+ show CenterA = "c"+ show RightA = "r"+++-------------------++data Rule tag = Rule {tag :: tag, ruleStyle :: LineStyle, delimiter :: Tex (), ruleLabel :: Tex (), conclusion :: Tex ()}+-- deriving Show++{-+instance Monoid t => Applicative (Writer t) where+ pure = return+ (<*>) = ap+-}++type Premise = Link ::> Derivation' ()+type Derivation' tag = Tree Link (Rule tag) +type Derivation = Derivation' ()++data Figure tag = Figure {figureTag :: Label, contents :: Derivation' tag}++------------------------------------------------------------+-- Phase 1: Detach++type Detach x = x -> WriterT [Figure ()] Tex x++detachP :: Detach Premise+detachP (Detached{..} ::> d) = do+ d'@(Node r ps) <- detachD d+ figureTag <- lift $ newLabel + tell [Figure {contents = Node r {delimiter = label} ps,..}]+ return $ (defaultLink ::> haltDrv label d)+detachP (l ::> d) = (l ::>) <$> detachD d++detachD :: Detach Derivation+detachD (Node n ps) = Node n <$> for ps detachP++detachF :: Figure () -> WriterT [Figure ()] Tex ()+detachF Figure{..} = do+ contents <- detachD contents+ tell [Figure{..}]++detachTop :: [Figure ()] -> Tex [Figure ()]+detachTop fs = do + figs <- runWriterT $ for fs detachF+ return $ snd $ figs++--------------------------------------------------+-- Phase 2: Delay++insertAt n x xs = take n xs ++ x : drop n xs++rm idx [] = []+rm 0 (x:xs) = xs+rm n (x:xs) = x : rm (n-1) xs++depth (Detached{} ::> _) = 2+depth (Link{steps} ::> Node _ ps) = 1 + steps + maximum (0 : map depth ps)++isDelayed :: Premise -> Bool+isDelayed (Delayed{} ::> _) = True+isDelayed _ = False++delayPre a s (Link {..} ::> j) = Link {steps = s, align = a, ..} ::> j++delayD :: Derivation -> Derivation+delayD (Node r ps0) = Node r (map delayP ps)+ where ps = fmap (fmap delayD) ps0+ ps' = filter (not . isDelayed) ps+ delayP (Delayed{..} ::> d) = Link{..} ::> d+ where steps = 1 + maximum (0 : map depth ps')+ label = mempty+ linkStyle = Dotted+ delayP p = p++delayF :: Figure () -> Figure ()+delayF (Figure{..}) = Figure{contents = delayD contents,..}++delayTop = map delayF++++---------------------------------------------------------+-- Phase 3: Tag++type Tag x = x () -> Tex (x Int)++tagify :: Tag Rule+tagify (Rule {..}) = do+ tag <- newLabel+ return $ Rule {..}++tagifyFig :: Tag Figure+tagifyFig (Figure {..}) = Figure figureTag <$> traverse tagify contents++tagifyTop :: [Figure ()] -> Tex [Figure Int]+tagifyTop = mapM tagifyFig++----------------------------------------------------------+-- Phase 4: Texify++mpQuote :: Tex () -> Tex ()+mpQuote t = Tex "\"" >> t >> Tex "\""++mkTuple :: [Tex ()] -> Tex ()+mkTuple l = Tex " (" >> sequence_ (intersperse "," l) >> Tex ") "++link (Link {..} ::> Node (Rule{tag}) _) + | steps == 0 = sho tag+ | otherwise = Tex "MVD " >> sho tag >> Tex " " >>+ mkTuple [sho steps,sho "",mpQuote label,sho align,sho (fromEnum linkStyle)]++type Stringize x = x Int -> Tex ()++stringize :: Derivation' Label -> Tex ()+stringize (Node Rule {tag = t, ..} premises) = do+ traverse (traverse stringize) premises+ Tex "jgm " >> reference t >> Tex " " >> mpQuote conclusion >> Tex ";\n"+ Tex "Nfr " >> reference t >> mkTuple (map link premises) >> Tex " " >>+ mkTuple [mpQuote ruleLabel,mpQuote delimiter,mpQuote (Tex ""),sho (fromEnum ruleStyle)] >> Tex ";\n"++stringizeFig :: Figure Label -> Tex () +stringizeFig (Figure {..}) = metapostFigure figureTag $ do+ stringize contents+ texLn "draw drv_tree;"+ ++------------------------------------------+-- Pipeline++derivationTree :: Derivation -> Tex Label+derivationTree j = do + f <- newLabel+ a <- delayTop <$> detachTop [Figure f j]+ bz <- tagifyTop a + Metapost $ mapM stringizeFig bz+ cmd "includegraphics" (MPFigure f)+ return f++-----------------------++rule ruleLabel conclusion = Rule {tag = (), delimiter = mempty, ruleStyle = Simple, ..}++dummy :: Rule ()+dummy = (rule mempty mempty) {ruleStyle = None}+emptyDrv = Node dummy []++abortDrv (Node Rule {..} _) = Node Rule {ruleStyle = Waved, ..} []++-- | Used when the rest of the derivation is known.+haltDrv' :: Tex () -> Derivation -> Derivation+haltDrv' tex (Node r _) = Node r {ruleStyle = None} + [defaultLink {linkStyle = TeXDotted, steps = 1, label = tex} ::> emptyDrv]++-- | More compact variant+haltDrv :: Tex () -> Derivation -> Derivation+haltDrv t (Node r _) = Node r [defaultLink ::> Node dummy {conclusion = cmd "vdots" nil >> cmd "hspace" (Tex "2pt") >> t} []]+++{-------------------------+brace :: TeX -> TeX+brace (TeX x) = TeX $ '{' : x ++ ['}']+paren (TeX x) = TeX $ '(' : x ++ [')']+brack (TeX x) = TeX $ "[" ++ x ++ "]"++tex :: String -> [TeX] -> TeX+tex macro args = TeX ('\\' : macro) <> mconcat (map brace args)+text x = tex "text" [TeX x]++f ! x = brace f <> TeX "_" <> brace x+++-}
+ MarXup/Latex.hs view
@@ -0,0 +1,126 @@+{-# LANGUAGE OverloadedStrings #-}+module MarXup.Latex where++import Control.Applicative+import MarXup.Tex+import MarXup.MetaPost+import Data.List (intersperse)+import Data.Monoid++-- Separate the arguments with '\\'+mkrows :: [TeX] -> TeX+mkrows ls = sequence_ $ intersperse newline ls ++-- Separate the arguments with '&'+mkcols = sequence_ . intersperse newcol++vspace = cmd "vspace"+title = cmd "title"++newline = backslash <> backslash+newcol = tex "&"+newpara = texLines ["",""]++maketitle :: Tex ()+maketitle = cmd "maketitle" $ return ()++ldots = cmd "ldots" (return ())++section s = + do cmd "section" s+ label++subsection s = + do cmd "subsection" s+ label++color :: String -> Tex a -> Tex a+color col bod = do + [_,x] <- cmdn' "textcolor" [] [tex col >> return undefined, bod]+ return x++----------------+-- Preamble stuff++usepackage opts name = cmd' "usepackage" opts (Tex name)++stdPreamble = do + usepackage [] "graphicx"+ usepackage ["mathletters"] "ucs"+ usepackage ["utf8x"] "inputenc"+ return ()++latexDocument :: String -> [String] -> Tex a -> Tex a -> Tex ()+latexDocument docClass options pre body = do+ preamble+ Metapost $ metaPostPreamble preamble+ env "document" body+ Metapost $ metaPostEpilogue+ where + preamble = do+ cmd' "documentclass" options (Tex docClass)+ pre+ ++----------+-- Fonts++sf, em :: Tex a -> Tex a+sf = cmd "textsf"+em = cmd "emph"++----------+-- Math++align = env "align*" . mkrows . map mkcols ++block bod = do+ cmdn' "begin" [] [tex "array", tex "l"]+ mkrows $ bod+ cmdn' "end" [] [tex "array"]++math = cmd "ensuremath"+mbox = cmd "mbox"++displayMath body = Tex "\\[" *> body <* Tex "\\]"++paren bod = do+ tex "("+ bod+ tex ")"++brack bod = do+ tex "["+ bod+ tex "]"++brac bod = do+ backslash >> tex "{"+ bod+ backslash >> tex "}"+++mathsf = cmd "mathsf"++instance Eq TeX where+instance Show TeX where+ ++instance Fractional TeX where+ a / b = cmdn_ "frac" [a,b]++instance Floating TeX where+ pi = cmd "pi" nil+ exp x = "e^" <> braces x+ sqrt = cmd "sqrt"++instance Num TeX where+ fromInteger x = text $ show x+ (+) = binop $ text "+"+ (-) = binop $ text "-"+ (*) = binop $ text "*"+ negate x = "-" <> x++binop :: TeX -> TeX -> TeX -> TeX+binop op a b = a <> op <> b+
+ MarXup/MetaPost.hs view
@@ -0,0 +1,27 @@++module MarXup.MetaPost where++import MarXup.Tex++ +metaPostPreamble :: Tex a -> Tex ()+metaPostPreamble texPreamble = do+ texLines ["outputtemplate := \"%j-%c.mps\";",+ "input drv;",+ "verbatimtex %&latex",+ ""]+ texPreamble+ texLines ["",+ "\\begin{document}",+ "etex;",+ "prologues:=3;"] + +metaPostEpilogue = texLn "end"+ ++metapostFigure :: Label -> Tex a -> Tex ()+metapostFigure lab t = Metapost $ do+ Tex "beginfig(" >> Refer lab >> Tex ")\n"+ t+ texLn "endfig;"+
+ MarXup/Tex.hs view
@@ -0,0 +1,153 @@+module MarXup.Tex where++import Control.Monad.Fix+import Control.Monad.RWS.Lazy+import Control.Applicative+import Data.Either+import GHC.Exts( IsString(..) )+import System.FilePath+import System.Environment+import Data.List (intersperse)++---------------------------------+-- Marchup interface+textual = Tex -- TODO: escape \, &, etc.+text = textual +++element :: Tex a -> Tex a+element = id++-----------------------------------+-- Basic datatype and semantics+type Label = Int++data Tex a where+ Return :: a -> Tex a+ Bind :: Tex a -> (a -> Tex b) -> Tex b++ Tex :: String -> Tex () -- ^ raw TeX code++ -- Reference management+ Label :: Tex Label+ Refer :: Label -> Tex Label+ MFix :: (a -> Tex a) -> Tex a ++ -- MetaPOST+ Metapost :: Tex a -> Tex a -- the output should go in the metapost file+ MPFigure :: Label -> Tex () -- inclusion of a metapost figure+ +tex = Tex+type TeX = Tex ()++newLabel = Label +reference = Refer++instance MonadFix Tex where+ mfix = MFix++instance Monad Tex where+ (>>=) = Bind+ return = Return+ +instance Applicative Tex where+ (<*>) = ap+ pure = Return+ +instance Functor Tex where+ fmap = liftM+ +instance Monoid (Tex ()) where + mempty = Tex ""+ mappend = (>>)+ +(<>) :: Monoid a => a -> a -> a+(<>) = mappend+ +instance IsString (Tex ()) where + fromString = Tex+ +type References = Int -- how many labels have been allocated+emptyRefs :: References+emptyRefs = 0+ +select :: Bool -> a -> Either a a+select True x = Left x+select False x = Right x+ +-- | Produces a list of strings (either for LaTeX or MetaPOST).+display :: String -> Bool -> Tex a -> RWS () [Either String String] References a+display fname mp t = case t of+ (Tex s) -> tell' s+ (Return a) -> return a+ (Bind k f) -> rec k >>= (rec . f)+ Label -> do x <- get; put $ x + 1; return x+ (Refer x) -> do tell [select mp $ show x]; return x+ (MFix f) -> mfix (rec . f)+ (Metapost x) -> display fname True x + (MPFigure l) -> tell' $ fname ++ "-" ++ show l ++ ".mps"+ where tell' s = tell [select mp s] + rec = display fname mp+ +sho :: Show a => a -> Tex ()+sho = Tex . show+ +render :: Tex a -> IO () +render t = do + fname <- getProgName+ let (_,xs) = evalRWS (display fname False t) () emptyRefs + (mp,tex) = partitionEithers xs+ writeFile (fname <.> "tex") (concat tex)+ writeFile (fname <.> "mp") (concat mp)+ ++texLn :: String -> Tex () +texLn s = Tex s >> Tex "\n"++texLines :: [String] -> Tex ()+texLines = mapM_ texLn++genParen :: String -> Tex a -> Tex a+genParen [l,r] x = Tex [l] *> x <* Tex [r]++braces :: Tex a -> Tex a+braces = genParen "{}"+brackets = genParen "[]"++backslash = Tex ['\\']++nil = braces (Tex "")++cmd c = cmd' c []++cmd' cmd options arg = do+ [x] <- cmdn' cmd options [arg]+ return x++cmdn' :: String -> [String] -> [Tex a] -> Tex [a]+cmdn' cmd options args = do + backslash >> Tex cmd+ when (not $ null options) $ brackets $ sequence_ $ map tex $ intersperse "," options+ res <- sequence $ map braces args+ when (null args) $ Tex "{}" -- so that this does not get glued with the next thing.+ return res++cmdn'_ :: String -> [String] -> [Tex a] -> Tex ()+cmdn'_ cmd options args = cmdn' cmd options args >> return ()++cmdn cmd args = cmdn' cmd [] args+cmdn_ cmd args = cmdn'_ cmd [] args++env :: String -> Tex a -> Tex a+env e body = do+ cmd "begin" $ Tex e+ x <- body+ cmd "end" $ Tex e+ return x++label = do+ l <- Label+ cmd "label" (Refer l)+ +xref l = do+ cmd "ref" (Refer l)
+ MarXup/Text.hs view
@@ -0,0 +1,43 @@+module MarXup.Text (Text(..), textual, element, module Data.Monoid, linearize) where++import Data.Monoid+import Data.Traversable+import Data.Foldable+import Control.Applicative+import Control.Monad+import Control.Monad.Fix+import Control.Monad.Writer++data Text a where+ Return :: a -> Text a + Text :: String -> Text () + (:>>=) :: Text a -> (a -> Text b) -> Text b + MFix :: (a -> Text a) -> Text a++textual = Text++element :: Show a => a -> Text ()+element = Text . show++instance MonadFix Text where+ mfix = MFix++instance Monad Text where+ (>>=) = (:>>=)+ return = Return+ +instance Applicative Text where+ (<*>) = ap+ pure = Return+ +instance Functor Text where+ fmap = liftM++run :: Text a -> Writer [String] a+run (Return x) = return x+run (Text x) = tell [x]+run (k :>>= f) = run k >>= run . f+run (MFix f) = mfix (run . f)++linearize :: Text a -> [String]+linearize t = snd $ runWriter $ run t
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ examples/LaTeX.hs view
@@ -0,0 +1,72 @@+{-# OPTIONS_GHC -XTypeSynonymInstances -XOverloadedStrings -XDoRec -pgmF marchup -F #-}++import MarXup.Latex+import MarXup.Tex+import MarXup.DerivationTrees+import Control.Applicative++preamble :: Tex ()+preamble = do+ usepackage ["mathletters"] "ucs"+ usepackage ["utf8x"] "inputenc"+++someTree = derivationTree $ Node (rule (mbox "who knows?") "A → B") []++(∶) = binop ":"+γ = cmd "Gamma" nil+(⊢) = binop $ cmd "vdash" nil++x = Tex "x"+y = Tex "y"+a = Tex "a"+b = Tex "b"++(≜) = binop "="++main = render $ latexDocument "article" ["11pt"] preamble $ @"+@section{Markup}++At-syntax is used to call a Haskell function. ++Here comes @sf{some sans-serif text with @em{emphasis}!}++Note that arguments put in braces are markup.+Arguments in parenthesis contain regular Haskell code.+So, we could also write it+@em(text "like this").+++@someSection<-section{References}++The result of a call can be bound.+For example, the @sf{section} command returns a label that can be used+for references.++This is section @xref(someSection). Note that cross-references are checked+at ``compile-time''. Forward references also work (see+sec. @xref(concl)).++++@section{Math}++Haskell syntax is somewhat more convenient than markup to +write math. Combined with unicode,+this can make writing all sorts of mathy stuff rather pleasant. For+example: @math(γ ⊢ x ∶ a).++The operators are overloaded to work on text as well:+@displayMath(b ≜ sqrt (a + x/y))+However you must insert parentheses yourself+(until the math sub-DSL is implemented):+@displayMath((x+x)*x)+++@concl<-section{Conclusion}+++Marχup is awesome. :)++@"+
+ marxup.cabal view
@@ -0,0 +1,40 @@+name: marxup+version: 1.0.0+category: Text+synopsis: Markup language preprocessor for Haskell+description:+ Markup syntax preprocessor for Haskell. Steals ideas from the Scribble project (in Scheme).+ The package also provides a DSL to output Latex seamlessly from MarXup output.+license: GPL+license-file: LICENSE+author: Jean-Philippe Bernardy+maintainer: jeanphilippe.bernardy@gmail.com+Cabal-Version: >= 1.8+tested-with: GHC==6.12.1+build-type: Simple+data-files:+ examples/LaTeX.hs++executable marxup+ extensions: FlexibleInstances, TupleSections+ main-is: Main.hs+ build-depends: base==4.*+ build-depends: pretty==1.0.*+ build-depends: parsec==2.1.*+ +library+ extensions: FlexibleInstances, TypeSynonymInstances, GADTs+ build-depends: base==4.*+-- build-depends: pandoc==1.5.* (broken)+ build-depends: mtl==2.0.*+ build-depends: labeled-tree==1.* + build-depends: filepath==1.1.* ++ exposed-modules: MarXup.Tex+ exposed-modules: MarXup.MetaPost+ exposed-modules: MarXup.Latex+ exposed-modules: MarXup.Beamer+ exposed-modules: MarXup.DerivationTrees + exposed-modules: MarXup.Text+-- exposed-modules: MarXup.Pandoc (broken)+