hscolour-1.20.3/0000755000000000000000000000000012022655553011626 5ustar0000000000000000hscolour-1.20.3/HsColour.hs0000644000000000000000000001626712022655553013734 0ustar0000000000000000{-# LANGUAGE CPP #-} module Main where import Language.Haskell.HsColour import qualified Language.Haskell.HsColour as HSColour import Language.Haskell.HsColour.Colourise (readColourPrefs) import Language.Haskell.HsColour.Options import Language.Haskell.HsColour.ACSS (breakS, srcModuleName) import System.Environment as System import System.Exit import System.IO hiding (withFile) import Control.Monad (when, forM_) import Data.List (intersperse, isSuffixOf) import Control.Exception (bracket) --import Debug.Trace -- Deal with UTF-8 I/O. #if __GLASGOW_HASKELL__ > 611 -- possibly if MIN_VERSION_base(4,2,0) import System.IO (hSetEncoding, utf8) #endif version :: String version = show MAJOR ++"."++show MINOR optionTable :: [(String,Option)] optionTable = [ ("help", Help) , ("version", Version) , ("print-css", Information) , ("html", Format HTML) , ("css", Format CSS) , ("icss", Format ICSS) , ("tty", Format TTY) , ("tty256", Format (TTYg XTerm256Compatible)) , ("latex", Format LaTeX) , ("mirc", Format MIRC) , ("lit", LHS True) , ("lit-tex",LHS True) , ("nolit", LHS False) , ("anchor", Anchors True) , ("noanchor", Anchors False) , ("partial", Partial True) , ("nopartial", Partial False) ] parseOption :: String -> Either String Option parseOption ('-':'o':s) = Right (Output s) parseOption ('-':'a':'n':'n':'o':'t':'=':s) = Right (Annot s) parseOption s@('-':_) = maybe (Left s) Right (lookup (dropWhile (== '-') s) optionTable) parseOption s = Right (Input s) main :: IO () main = do prog <- System.getProgName args <- System.getArgs pref <- readColourPrefs let options = map parseOption args bad = [ o | Left o <- options ] good = [ o | Right o <- options ] formats = [ f | Format f <- good ] outFile = [ f | Output f <- good ] annFile = [ f | Annot f <- good ] output = useDefault TTY id formats anchors = useDefault False id [ b | Anchors b <- good ] partial = useDefault False id [ b | Partial b <- good ] lhs = useDefault Nothing id [ Just b | LHS b<- good ] title = useDefault "Haskell code" id [ f | Input f <- good ] ioWrapper = useDefaults (ttyInteract outFile (guessLiterate lhs "")) (fileInteract outFile annFile) [(f, guessLiterate lhs f) | Input f <- good] when (not (null bad)) $ errorOut ("Unrecognised option(s): "++unwords bad++"\n"++usage prog) when (Help `elem` good) $ writeResult [] (usage prog) when (Version `elem` good) $ writeResult [] (prog++" "++version) when (Information `elem` good) $ writeResult outFile cssDefaults when (length formats > 1) $ errorOut ("Can only choose one output format at a time: " ++unwords (map show formats)) when (length outFile > 1) $ errorOut ("Can only have one output file at a time.") when (length annFile > 1) $ errorOut ("Can only use a single annotation file for annotated-CSS output") ioWrapper (HSColour.hscolour output pref anchors partial title) where writeResult outF s = do if null outF then putStrLn s else writeUTF8File (last outF) s exitSuccess fileInteract out ann inFs u = do h <- case out of [] -> return stdout [outF] -> openFile outF WriteMode >>= set_utf8_io_enc forM_ inFs $ \ (f, lit) -> do src <- readUTF8File f a <- readAnnots src ann hPutStr h $ u lit $ src ++ a hClose h ttyInteract [] lit u = do hSetBuffering stdout NoBuffering Prelude.interact (u lit) ttyInteract [outF] lit u = do c <- hGetContents stdin writeUTF8File outF (u lit c) exitSuccess = exitWith ExitSuccess errorOut s = hPutStrLn stderr s >> hFlush stderr >> exitFailure usage prog = "Usage: "++prog ++" options [file.hs]\n where\n options = [ " ++ (indent 15 . unwords . width 58 58 . intersperse "|" . ("-oOUTPUT":) . ("-annot=ANNOTATIONFILE":) . map (('-':) . fst)) optionTable ++ " ]\n" useDefault d f list | null list = d | otherwise = f (head list) useDefaults d f list | null list = d | otherwise = f list guessLiterate Nothing f = ".lhs" `isSuffixOf` f || ".ly" `isSuffixOf` f || ".lx" `isSuffixOf` f guessLiterate (Just b) _ = b readAnnots _ [] = return "" readAnnots src [annF] = do putStrLn $ "HsColour Annot on Module: " ++ mname annots <- readUTF8File annF return $ breakS ++ "\n" ++ mname ++ "\n" ++ annots where mname = srcModuleName src -- some simple text formatting for usage messages width n left [] = [] width n left (s:ss) = if size > left then "\n":s : width n n ss else s : width n (left-size-1) ss where size = length s indent n [] = [] indent n ('\n':s) = '\n':replicate n ' '++indent n s indent n (c:s) = c: indent n s -- Rather than have a separate .css file, define some reasonable defaults here. cssDefaults = concat [ ".hs-keyglyph, .hs-layout {color: red;}\n" , ".hs-keyword {color: blue;}\n" , ".hs-comment, .hs-comment a {color: green;}\n" , ".hs-str, .hs-chr {color: teal;}\n" , ".hs-keyword, .hs-conid, .hs-varid, .hs-conop, .hs-varop, .hs-num, " , ".hs-cpp, .hs-sel, .hs-definition {}\n" ] -- Deal with UTF-8 input and output. set_utf8_io_enc :: Handle -> IO Handle #if __GLASGOW_HASKELL__ > 611 -- possibly if MIN_VERSION_base(4,2,0) set_utf8_io_enc h = do hSetEncoding h utf8; return h #else set_utf8_io_enc h = return h #endif -- FILE I(unput) / O(utput) is in UTF8 -- TTY I(unput) / O(utput) is in locale -- ( may have problems with HsColour IFILE >OFILE -- , as it differs from HsColour IFILE -oOFILE) -- TTY stderr is always in locale (always used for user interaction) -- -- Some common use cases: -- File I / FILE O (HsColour -css -anchor -oOFILE IFILE) -- : are both always done in UTF8 mode (cabal hscolour mode) -- File I / TTY O (HsColour IFILE) -- : file is read in UTF-8 written in locale -- TTY I / TTY O (HsColour) -- : stdin/stdout are both in locale -- fully mimic Prelude analogues writeUTF8File f txt = withFile f WriteMode (\hdl -> do set_utf8_io_enc hdl hPutStr hdl txt) readUTF8File name = openFile name ReadMode >>= set_utf8_io_enc >>= hGetContents withFile :: FilePath -> IOMode -> (Handle -> IO r) -> IO r withFile name mode = bracket (openFile name mode) hClose hscolour-1.20.3/LICENCE-GPL0000644000000000000000000004311212022655553013234 0ustar0000000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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. Copyright (C) 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. , 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. hscolour-1.20.3/Setup.hs0000644000000000000000000000010512022655553013256 0ustar0000000000000000#!/usr/bin/env runghc import Distribution.Simple main = defaultMain hscolour-1.20.3/hscolour.cabal0000644000000000000000000000322012022655553014445 0ustar0000000000000000Name: hscolour Version: 1.20.3 Copyright: 2003-2012 Malcolm Wallace; 2006 Bjorn Bringert Maintainer: Malcolm Wallace Author: Malcolm Wallace Homepage: http://code.haskell.org/~malcolm/hscolour/ License: GPL License-file: LICENCE-GPL Synopsis: Colourise Haskell code. Description: hscolour is a small Haskell script to colourise Haskell code. It currently has six output formats: ANSI terminal codes (optionally XTerm-256colour codes), HTML 3.2 with tags, HTML 4.01 with CSS, HTML 4.01 with CSS and mouseover annotations, XHTML 1.0 with inline CSS styling, LaTeX, and mIRC chat codes. Category: Language Build-Type: Simple Data-files: hscolour.css, data/rgb24-example-.hscolour Cabal-version: >=1.6 Library Build-depends: base < 10, containers Exposed-Modules: Language.Haskell.HsColour Language.Haskell.HsColour.ANSI Language.Haskell.HsColour.Anchors Language.Haskell.HsColour.ACSS Language.Haskell.HsColour.CSS Language.Haskell.HsColour.Classify Language.Haskell.HsColour.ColourHighlight Language.Haskell.HsColour.Colourise Language.Haskell.HsColour.General Language.Haskell.HsColour.HTML Language.Haskell.HsColour.InlineCSS Language.Haskell.HsColour.LaTeX Language.Haskell.HsColour.MIRC Language.Haskell.HsColour.Options Language.Haskell.HsColour.Output Language.Haskell.HsColour.TTY --ghc-options: -O -W Extensions: Executable HsColour Build-depends: base < 10, containers Main-is: HsColour.hs --ghc-options: -O -W Extensions: CPP cpp-options: -DMAJOR=1 -DMINOR=20 Source-repository head Type : darcs Location: http://code.haskell.org/~malcolm/hscolour hscolour-1.20.3/hscolour.css0000644000000000000000000000157012022655553014201 0ustar0000000000000000.hs-keyglyph, .hs-layout {color: red;} .hs-keyword {color: blue;} .hs-comment, .hs-comment a {color: green;} .hs-str, .hs-chr {color: teal;} .hs-keyword,.hs-conid, .hs-varid, .hs-conop, .hs-varop, .hs-num, .hs-cpp, .hs-sel, .hs-definition {} /* For Mouseover Annotations */ a.annot{ position:relative; color:#000; text-decoration:none } a.annot:hover{z-index:25; background-color:#ff0} a.annot span.annottext{display: none} a.annot:hover span.annottext{ border-radius: 5px 5px; -moz-border-radius: 5px; -webkit-border-radius: 5px; box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.1); -webkit-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); -moz-box-shadow: 5px 5px rgba(0, 0, 0, 0.1); display:block; position: absolute; left: 1em; top: 2em; z-index: 99; margin-left: 5; background: #FFFFAA; border: 2px solid #FFAD33; padding: 0.8em 1em; } hscolour-1.20.3/Language/0000755000000000000000000000000012022655553013351 5ustar0000000000000000hscolour-1.20.3/Language/Haskell/0000755000000000000000000000000012022655553014734 5ustar0000000000000000hscolour-1.20.3/Language/Haskell/HsColour.hs0000644000000000000000000001152512022655553017032 0ustar0000000000000000-- | This is a library which colourises Haskell code. -- It currently has six output formats: -- -- * ANSI terminal codes -- -- * LaTeX macros -- -- * HTML 3.2 with font tags -- -- * HTML 4.01 with external CSS. -- -- * XHTML 1.0 with internal CSS. -- -- * mIRC chat client colour codes. -- module Language.Haskell.HsColour (Output(..), ColourPrefs(..), hscolour) where import Language.Haskell.HsColour.Colourise (ColourPrefs(..)) import qualified Language.Haskell.HsColour.TTY as TTY import qualified Language.Haskell.HsColour.HTML as HTML import qualified Language.Haskell.HsColour.CSS as CSS import qualified Language.Haskell.HsColour.ACSS as ACSS import qualified Language.Haskell.HsColour.InlineCSS as ICSS import qualified Language.Haskell.HsColour.LaTeX as LaTeX import qualified Language.Haskell.HsColour.MIRC as MIRC import Data.List(mapAccumL, isPrefixOf) import Data.Maybe import Language.Haskell.HsColour.Output --import Debug.Trace -- | Colourise Haskell source code with the given output format. hscolour :: Output -- ^ Output format. -> ColourPrefs -- ^ Colour preferences (for formats that support them). -> Bool -- ^ Whether to include anchors. -> Bool -- ^ Whether output document is partial or complete. -> String -- ^ Title for output. -> Bool -- ^ Whether input document is literate haskell or not -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour output pref anchor partial title False = (if partial then id else top'n'tail output title) . hscolour' output pref anchor hscolour output pref anchor partial title True = (if partial then id else top'n'tail output title) . concatMap chunk . joinL . classify . inlines where chunk (Code c) = hscolour' output pref anchor c chunk (Lit c) = c -- | The actual colourising worker, despatched on the chosen output format. hscolour' :: Output -- ^ Output format. -> ColourPrefs -- ^ Colour preferences (for formats that support them) -> Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour' TTY pref _ = TTY.hscolour pref hscolour' (TTYg tt) pref _ = TTY.hscolourG tt pref hscolour' MIRC pref _ = MIRC.hscolour pref hscolour' LaTeX pref _ = LaTeX.hscolour pref hscolour' HTML pref anchor = HTML.hscolour pref anchor hscolour' CSS _ anchor = CSS.hscolour anchor hscolour' ICSS pref anchor = ICSS.hscolour pref anchor hscolour' ACSS _ anchor = ACSS.hscolour anchor -- | Choose the right headers\/footers, depending on the output format. top'n'tail :: Output -- ^ Output format -> String -- ^ Title for output -> (String->String) -- ^ Output transformer top'n'tail TTY _ = id top'n'tail (TTYg _) _ = id top'n'tail MIRC _ = id top'n'tail LaTeX title = LaTeX.top'n'tail title top'n'tail HTML title = HTML.top'n'tail title top'n'tail CSS title = CSS.top'n'tail title top'n'tail ICSS title = ICSS.top'n'tail title top'n'tail ACSS title = CSS.top'n'tail title -- | Separating literate files into code\/comment chunks. data Lit = Code {unL :: String} | Lit {unL :: String} deriving (Show) -- Re-implementation of 'lines', for better efficiency (but decreased laziness). -- Also, importantly, accepts non-standard DOS and Mac line ending characters. -- And retains the trailing '\n' character in each resultant string. inlines :: String -> [String] inlines s = lines' s id where lines' [] acc = [acc []] lines' ('\^M':'\n':s) acc = acc ['\n'] : lines' s id -- DOS --lines' ('\^M':s) acc = acc ['\n'] : lines' s id -- MacOS lines' ('\n':s) acc = acc ['\n'] : lines' s id -- Unix lines' (c:s) acc = lines' s (acc . (c:)) -- | The code for classify is largely stolen from Language.Preprocessor.Unlit. classify :: [String] -> [Lit] classify [] = [] classify (x:xs) | "\\begin{code}"`isPrefixOf`x = Lit x: allProg xs where allProg [] = [] -- Should give an error message, -- but I have no good position information. allProg (x:xs) | "\\end{code}"`isPrefixOf`x = Lit x: classify xs allProg (x:xs) = Code x: allProg xs classify (('>':x):xs) = Code ('>':x) : classify xs classify (x:xs) = Lit x: classify xs -- | Join up chunks of code\/comment that are next to each other. joinL :: [Lit] -> [Lit] joinL [] = [] joinL (Code c:Code c2:xs) = joinL (Code (c++c2):xs) joinL (Lit c :Lit c2 :xs) = joinL (Lit (c++c2):xs) joinL (any:xs) = any: joinL xs hscolour-1.20.3/Language/Haskell/HsColour/0000755000000000000000000000000012022655553016472 5ustar0000000000000000hscolour-1.20.3/Language/Haskell/HsColour/ACSS.hs0000644000000000000000000001213412022655553017560 0ustar0000000000000000-- | Formats Haskell source code as HTML with CSS and Mouseover Type Annotations module Language.Haskell.HsColour.ACSS ( hscolour , hsannot , AnnMap (..) , Loc (..) , breakS , srcModuleName ) where import Language.Haskell.HsColour.Anchors import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.HTML (renderAnchors, renderComment, renderNewLinesAnchors, escape) import qualified Language.Haskell.HsColour.CSS as CSS import Data.Maybe (fromMaybe) import qualified Data.Map as M import Data.List (isSuffixOf, findIndex, elemIndices, intercalate) import Data.Char (isLower, isSpace, isAlphaNum) import Text.Printf import Debug.Trace newtype AnnMap = Ann (M.Map Loc (String, String)) newtype Loc = L (Int, Int) deriving (Eq, Ord, Show) -- | Formats Haskell source code using HTML and mouse-over annotations hscolour :: Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code, Annotations as comments at end -> String -- ^ Coloured Haskell source code. hscolour anchor = hsannot anchor . splitSrcAndAnns -- | Formats Haskell source code using HTML and mouse-over annotations hsannot :: Bool -- ^ Whether to include anchors. -> (String, AnnMap) -- ^ Haskell Source, Annotations -> String -- ^ Coloured Haskell source code. hsannot anchor = CSS.pre . (if anchor then -- renderNewLinesAnchors . concatMap (renderAnchors renderAnnotToken) . insertAnnotAnchors else concatMap renderAnnotToken) . annotTokenise annotTokenise :: (String, AnnMap) -> [(TokenType, String, Maybe String)] annotTokenise (src, Ann annm) = zipWith (\(x,y) z -> (x,y, snd `fmap` z)) toks annots where toks = tokenise src spans = tokenSpans $ map snd toks annots = map (`M.lookup` annm) spans tokenSpans :: [String] -> [Loc] tokenSpans = scanl plusLoc (L (1, 1)) plusLoc :: Loc -> String -> Loc plusLoc (L (l, c)) s = case '\n' `elemIndices` s of [] -> L (l, (c + n)) is -> L ((l + length is), (n - maximum is)) where n = length s renderAnnotToken :: (TokenType, String, Maybe String) -> String renderAnnotToken (x,y, Nothing) = CSS.renderToken (x, y) renderAnnotToken (x,y, Just ann) = printf template (escape ann) (CSS.renderToken (x, y)) where template = "%s%s" {- Example Annotation: x#agV:Int -> {VV_int:Int | (0 <= VV_int),(x#agV <= VV_int)} NOWTRYTHIS -} insertAnnotAnchors :: [(TokenType, String, a)] -> [Either String (TokenType, String, a)] insertAnnotAnchors toks = stitch (zip toks' toks) $ insertAnchors toks' where toks' = [(x,y) | (x,y,_) <- toks] stitch :: Eq b => [(b, c)] -> [Either a b] -> [Either a c] stitch xys ((Left a) : rest) = (Left a) : stitch xys rest stitch ((x,y):xys) ((Right x'):rest) | x == x' = (Right y) : stitch xys rest | otherwise = error "stitch" stitch _ [] = [] splitSrcAndAnns :: String -> (String, AnnMap) splitSrcAndAnns s = let ls = lines s in case findIndex (breakS ==) ls of Nothing -> (s, Ann M.empty) Just i -> (src, {- trace ("annm =" ++ show ann) -} ann) where (codes, _:mname:annots) = splitAt i ls ann = annotParse mname $ dropWhile isSpace $ unlines annots src = unlines codes -- mname = srcModuleName src srcModuleName :: String -> String srcModuleName = fromMaybe "Main" . tokenModule . tokenise tokenModule toks = do i <- findIndex ((Keyword, "module") ==) toks let (_, toks') = splitAt (i+2) toks j <- findIndex ((Space ==) . fst) toks' let (toks'', _) = splitAt j toks' return $ concatMap snd toks'' breakS = "MOUSEOVER ANNOTATIONS" annotParse :: String -> String -> AnnMap annotParse mname = Ann . M.fromList . parseLines mname 0 . lines parseLines mname i [] = [] parseLines mname i ("":ls) = parseLines mname (i+1) ls parseLines mname i (x:f:l:c:n:rest) | f /= mname -- `isSuffixOf` mname = {- trace ("wrong annot f = " ++ f ++ " mname = " ++ mname) $ -} parseLines mname (i + 5 + num) rest' | otherwise = (L (line, col), (x, anns)) : parseLines mname (i + 5 + num) rest' where line = (read l) :: Int col = (read c) :: Int num = (read n) :: Int anns = intercalate "\n" $ take num rest rest' = drop num rest parseLines _ i _ = error $ "Error Parsing Annot Input on Line: " ++ show i takeFileName s = map slashWhite s where slashWhite '/' = ' ' instance Show AnnMap where show (Ann m) = "\n\n" ++ (concatMap ppAnnot $ M.toList m) where ppAnnot (L (l, c), (x,s)) = x ++ "\n" ++ show l ++ "\n" ++ show c ++ "\n" ++ show (length $ lines s) ++ "\n" ++ s ++ "\n\n\n" hscolour-1.20.3/Language/Haskell/HsColour/ANSI.hs0000644000000000000000000000741112022655553017563 0ustar0000000000000000-- | Partially taken from Hugs AnsiScreen.hs library: module Language.Haskell.HsColour.ANSI ( highlightOnG,highlightOn , highlightOff , highlightG,highlight , cleareol, clearbol, clearline, clearDown, clearUp, cls , goto , cursorUp, cursorDown, cursorLeft, cursorRight , savePosition, restorePosition , Highlight(..) , Colour(..) , colourCycle , enableScrollRegion, scrollUp, scrollDown , lineWrap , TerminalType(..) ) where import Language.Haskell.HsColour.ColourHighlight import Language.Haskell.HsColour.Output(TerminalType(..)) import Data.List (intersperse,isPrefixOf) import Data.Char (isDigit) -- Basic screen control codes: type Pos = (Int,Int) at :: Pos -> String -> String -- | Move the screen cursor to the given position. goto :: Int -> Int -> String home :: String -- | Clear the screen. cls :: String at (x,y) s = goto x y ++ s goto x y = '\ESC':'[':(show y ++(';':show x ++ "H")) home = goto 1 1 cursorUp = "\ESC[A" cursorDown = "\ESC[B" cursorRight = "\ESC[C" cursorLeft = "\ESC[D" cleareol = "\ESC[K" clearbol = "\ESC[1K" clearline = "\ESC[2K" clearDown = "\ESC[J" clearUp = "\ESC[1J" -- Choose whichever of the following lines is suitable for your system: cls = "\ESC[2J" -- for PC with ANSI.SYS --cls = "\^L" -- for Sun window savePosition = "\ESC7" restorePosition = "\ESC8" -- data Colour -- imported from ColourHighlight -- data Highlight -- imported from ColourHighlight instance Enum Highlight where fromEnum Normal = 0 fromEnum Bold = 1 fromEnum Dim = 2 fromEnum Underscore = 4 fromEnum Blink = 5 fromEnum ReverseVideo = 7 fromEnum Concealed = 8 -- The translation of these depends on the terminal type, and they don't translate to single numbers anyway. Should we really use the Enum class for this purpose rather than simply moving this table to 'renderAttrG'? fromEnum (Foreground (Rgb _ _ _)) = error "Internal error: fromEnum (Foreground (Rgb _ _ _))" fromEnum (Background (Rgb _ _ _)) = error "Internal error: fromEnum (Background (Rgb _ _ _))" fromEnum (Foreground c) = 30 + fromEnum c fromEnum (Background c) = 40 + fromEnum c fromEnum Italic = 2 -- | = 'highlightG' 'Ansi16Colour' highlight :: [Highlight] -> String -> String highlight = highlightG Ansi16Colour -- | = 'highlightOn' 'Ansi16Colour' highlightOn :: [Highlight] -> String highlightOn = highlightOnG Ansi16Colour -- | Make the given string appear with all of the listed highlights highlightG :: TerminalType -> [Highlight] -> String -> String highlightG tt attrs s = highlightOnG tt attrs ++ s ++ highlightOff highlightOnG :: TerminalType -> [Highlight] -> String highlightOnG tt [] = highlightOnG tt [Normal] highlightOnG tt attrs = "\ESC[" ++ concat (intersperse ";" (concatMap (renderAttrG tt) attrs)) ++"m" highlightOff :: [Char] highlightOff = "\ESC[0m" renderAttrG :: TerminalType -> Highlight -> [String] renderAttrG XTerm256Compatible (Foreground (Rgb r g b)) = [ "38", "5", show ( rgb24bit_to_xterm256 r g b ) ] renderAttrG XTerm256Compatible (Background (Rgb r g b)) = [ "48", "5", show ( rgb24bit_to_xterm256 r g b ) ] renderAttrG _ a = [ show (fromEnum (hlProjectToBasicColour8 a)) ] -- | An infinite supply of colours. colourCycle :: [Colour] colourCycle = cycle [Red,Blue,Magenta,Green,Cyan] -- | Scrolling enableScrollRegion :: Int -> Int -> String enableScrollRegion start end = "\ESC["++show start++';':show end++"r" scrollDown :: String scrollDown = "\ESCD" scrollUp :: String scrollUp = "\ESCM" -- Line-wrapping mode lineWrap :: Bool -> [Char] lineWrap True = "\ESC[7h" lineWrap False = "\ESC[7l" hscolour-1.20.3/Language/Haskell/HsColour/Anchors.hs0000644000000000000000000001672312022655553020434 0ustar0000000000000000module Language.Haskell.HsColour.Anchors ( insertAnchors ) where import Language.Haskell.HsColour.Classify import Language.Haskell.HsColour.General import Data.List import Data.Char (isUpper, isLower, isDigit, ord, intToDigit) -- This is an attempt to find the first defining occurrence of an -- identifier (function, datatype, class) in a Haskell source file. -- Rather than parse the module properly, we try to get by with just -- a finite state automaton. Keeping a record of identifiers we -- have already seen, we look at the beginning of every line to see -- if it starts with the right tokens to introduce a defn. If so, -- we look a little bit further until we can be certain. Then plonk -- (or not) an anchor at the beginning of the line. type Anchor = String -- | 'insertAnchors' places an anchor marker in the token stream before the -- first defining occurrence of any identifier. Here, /before/ means -- immediately preceding its type signature, or preceding a (haddock) -- comment that comes immediately before the type signature, or failing -- either of those, before the first equation. insertAnchors :: [(TokenType,String)] -> [Either Anchor (TokenType,String)] insertAnchors = anchor emptyST -- looks at first token in the left-most position of each line -- precondition: have just seen a newline token. anchor :: ST -> [(TokenType, String)] -> [Either String (TokenType, String)] anchor st s = case identifier st s of Nothing -> emit st s Just v -> Left (escape v): emit (insertST v st) s -- some chars are not valid in anchor URIs: http://www.ietf.org/rfc/rfc3986 -- NOTE: This code assumes characters are 8-bit. -- Ideally, it should transcode to utf8 octets first. escape :: String -> String escape = concatMap enc where enc x | isDigit x || isURIFragmentValid x || isLower x || isUpper x = [x] | ord x >= 256 = [x] -- not correct, but better than nothing | otherwise = ['%',hexHi (ord x), hexLo (ord x)] hexHi d = intToDigit (d`div`16) hexLo d = intToDigit (d`mod`16) isURIFragmentValid x = x `elem` "!$&'()*+,;=/?-._~:@" -- emit passes stuff through until the next newline has been encountered, -- then jumps back into the anchor function -- pre-condition: newlines are explicitly single tokens emit :: ST -> [(TokenType, String)] -> [Either String (TokenType, String)] emit st (t@(Space,"\n"):stream) = Right t: anchor st stream emit st (t:stream) = Right t: emit st stream emit _ [] = [] -- Given that we are at the beginning of a line, determine whether there -- is an identifier defined here, and if so, return it. -- precondition: have just seen a newline token. identifier :: ST -> [(TokenType, String)] -> Maybe String identifier st t@((kind,v):stream) | kind`elem`[Varid,Definition] = case skip stream of ((Varop,v):_) | not (v`inST`st) -> Just (fix v) notVarop -- | typesig stream -> Nothing -- not a defn | v `inST` st -> Nothing -- already defined | otherwise -> Just v identifier st t@((Layout,"("):stream) = case stream of ((Varop,v):(Layout,")"):_) -- | typesig stream -> Nothing | v `inST` st -> Nothing | otherwise -> Just (fix v) notVarop -> case skip (munchParens stream) of ((Varop,v):_) | not (v`inST`st) -> Just (fix v) _ -> Nothing identifier st t@((Keyword,"foreign"):stream) = Nothing -- not yet implemented identifier st t@((Keyword,"data"):stream) = getConid stream identifier st t@((Keyword,"newtype"):stream) = getConid stream identifier st t@((Keyword,"type"):stream) = getConid stream identifier st t@((Keyword,"class"):stream) = getConid stream identifier st t@((Keyword,"instance"):stream)= getInstance stream identifier st t@((Comment,_):(Space,"\n"):stream) = identifier st stream identifier st stream = Nothing -- Is this really a type signature? (no longer used) typesig :: [(TokenType,String)] -> Bool typesig ((Keyglyph,"::"):_) = True typesig ((Varid,_):stream) = typesig stream typesig ((Layout,"("):(Varop,_):(Layout,")"):stream) = typesig stream typesig ((Layout,","):stream) = typesig stream typesig ((Space,_):stream) = typesig stream typesig ((Comment,_):stream) = typesig stream typesig _ = False -- throw away everything from opening paren to matching close munchParens :: [(TokenType, String)] -> [(TokenType, String)] munchParens = munch (0::Int) -- already seen open paren where munch 0 ((Layout,")"):rest) = rest munch n ((Layout,")"):rest) = munch (n-1) rest munch n ((Layout,"("):rest) = munch (n+1) rest munch n (_:rest) = munch n rest munch _ [] = [] -- source is ill-formed -- ensure anchor name is correct for a Varop fix :: String -> String fix ('`':v) = dropLast '`' v fix v = v -- look past whitespace and comments to next "real" token skip :: [(TokenType, t)] -> [(TokenType, t)] skip ((Space,_):stream) = skip stream skip ((Comment,_):stream) = skip stream skip stream = stream -- skip possible context up to and including "=>", returning next Conid token -- (this function is highly partial - relies on source being parse-correct) getConid :: [(TokenType, String)] -> Maybe String getConid stream = case skip stream of ((Conid,c):rest) -> case context rest of ((Keyglyph,"="):_) -> Just c ((Keyglyph,"=>"):more) -> case skip more of ((Conid,c'):_) -> Just c' v -> debug v ("Conid "++c++" =>") v -> debug v ("Conid "++c++" no = or =>") ((Layout,"("):rest) -> case context rest of ((Keyglyph,"=>"):more) -> case skip more of ((Conid,c'):_) -> Just c' v -> debug v ("(...) =>") v -> debug v ("(...) no =>") v -> debug v ("no Conid or (...)") where debug _ _ = Nothing -- debug (s:t) c = error ("HsColour: getConid failed: "++show s -- ++"\n in the context of: "++c) -- jump past possible class context context :: [(TokenType, String)] -> [(TokenType, String)] context stream@((Keyglyph,"="):_) = stream context stream@((Keyglyph,"=>"):_) = stream context stream@((Keyglyph,"⇒"):_) = stream context (_:stream) = context stream context [] = [] -- the anchor name for an instance is just the entire instance head, minus -- any extra context clause getInstance = Just . unwords . ("instance":) . words . concat . map snd . trimContext . takeWhile (/=(Keyword,"where")) where trimContext ts = if (Keyglyph,"=>") `elem` ts || (Keyglyph,"⇒") `elem` ts then tail . dropWhile (`notElem`[(Keyglyph,"=>") ,(Keyglyph,"⇒")]) $ ts else ts -- simple implementation of a string lookup table. -- replace this with something more sophisticated if needed. type ST = [String] emptyST :: ST emptyST = [] insertST :: String -> ST -> ST insertST k st = insert k st inST :: String -> ST -> Bool inST k st = k `elem` st hscolour-1.20.3/Language/Haskell/HsColour/CSS.hs0000644000000000000000000000442712022655553017465 0ustar0000000000000000-- | Formats Haskell source code as HTML with CSS. module Language.Haskell.HsColour.CSS ( hscolour , top'n'tail , renderToken , pre ) where import Language.Haskell.HsColour.Anchors import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.HTML (renderAnchors, renderComment, renderNewLinesAnchors, escape) -- | Formats Haskell source code as a complete HTML document with CSS. hscolour :: Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ An HTML document containing the coloured -- Haskell source code. hscolour anchor = pre . (if anchor then renderNewLinesAnchors . concatMap (renderAnchors renderToken) . insertAnchors else concatMap renderToken) . tokenise top'n'tail :: String -> String -> String top'n'tail title = (cssPrefix title ++) . (++cssSuffix) pre :: String -> String pre = ("
"++) . (++"
") renderToken :: (TokenType,String) -> String renderToken (cls,text) = before ++ (if cls == Comment then renderComment text else escape text) ++ after where before = if null cls2 then "" else "" after = if null cls2 then "" else "" cls2 = cssClass cls cssClass Keyword = "hs-keyword" cssClass Keyglyph = "hs-keyglyph" cssClass Layout = "hs-layout" cssClass Comment = "hs-comment" cssClass Conid = "hs-conid" cssClass Varid = "hs-varid" cssClass Conop = "hs-conop" cssClass Varop = "hs-varop" cssClass String = "hs-str" cssClass Char = "hs-chr" cssClass Number = "hs-num" cssClass Cpp = "hs-cpp" cssClass Error = "hs-sel" cssClass Definition = "hs-definition" cssClass _ = "" cssPrefix title = unlines ["" ,"" ,"" ,"" ,"" ,""++title++"" ,"" ,"" ,"" ] cssSuffix = unlines ["" ,"" ] hscolour-1.20.3/Language/Haskell/HsColour/Classify.hs0000644000000000000000000001156412022655553020612 0ustar0000000000000000module Language.Haskell.HsColour.Classify ( TokenType(..) , tokenise ) where import Data.Char (isSpace, isUpper, isLower, isDigit) import Data.List -- | Lex Haskell source code into an annotated token stream, without -- discarding any characters or layout. tokenise :: String -> [(TokenType,String)] tokenise str = let chunks = glue . chunk $ str in markDefs $ map (\s-> (classify s,s)) chunks markDefs :: [(TokenType, String)] -> [(TokenType, String)] markDefs [] = [] markDefs ((Varid, s) : rest) = (Definition, s) : continue rest markDefs ((Varop, ">") : (Space, " ") : (Varid, d) : rest) = (Varop, ">") : (Space, " ") : (Definition, d) : continue rest markDefs rest = continue rest continue rest = let (thisLine, nextLine) = span (/= (Space, "\n")) rest in case nextLine of [] -> thisLine ((Space, "\n"):nextLine') -> (thisLine ++ ((Space, "\n") : (markDefs nextLine'))) -- Basic Haskell lexing, except we keep whitespace. chunk :: String -> [String] chunk [] = [] chunk ('\r':s) = chunk s -- get rid of DOS newline stuff chunk ('\n':s) = "\n": chunk s chunk (c:s) | isLinearSpace c = (c:ss): chunk rest where (ss,rest) = span isLinearSpace s chunk ('{':'-':s) = let (com,s') = nestcomment 0 s in ('{':'-':com) : chunk s' chunk s = case Prelude.lex s of [] -> [head s]: chunk (tail s) -- e.g. inside comment ((tok@('-':'-':_),rest):_) | all (=='-') tok -> (tok++com): chunk s' where (com,s') = eolcomment rest ((tok,rest):_) -> tok: chunk rest isLinearSpace c = c `elem` " \t\f" -- " \t\xa0" -- Glue sequences of tokens into more useful blobs --glue (q:".":n:rest) | Char.isUpper (head q) -- qualified names -- = glue ((q++"."++n): rest) glue ("`":rest) = -- `varid` -> varop case glue rest of (qn:"`":rest) -> ("`"++qn++"`"): glue rest _ -> "`": glue rest glue (s:ss) | all (=='-') s && length s >=2 -- eol comment = (s++concat c): glue rest where (c,rest) = break ('\n'`elem`) ss --glue ("{":"-":ss) = ("{-"++c): glue rest -- nested comment -- where (c,rest) = nestcomment 0 ss glue ("(":ss) = case rest of ")":rest -> ("(" ++ concat tuple ++ ")") : glue rest _ -> "(" : glue ss where (tuple,rest) = span (==",") ss glue ("[":"]":ss) = "[]" : glue ss glue ("\n":"#":ss)= "\n" : ('#':concat line) : glue rest where (line,rest) = break ('\n'`elem`) ss glue (s:ss) = s: glue ss glue [] = [] -- Deal with comments. nestcomment :: Int -> String -> (String,String) nestcomment n ('{':'-':ss) | n>=0 = (("{-"++cs),rm) where (cs,rm) = nestcomment (n+1) ss nestcomment n ('-':'}':ss) | n>0 = (("-}"++cs),rm) where (cs,rm) = nestcomment (n-1) ss nestcomment n ('-':'}':ss) | n==0 = ("-}",ss) nestcomment n (s:ss) | n>=0 = ((s:cs),rm) where (cs,rm) = nestcomment n ss nestcomment n [] = ([],[]) eolcomment :: String -> (String,String) eolcomment s@('\n':_) = ([], s) eolcomment ('\r':s) = eolcomment s eolcomment (c:s) = (c:cs, s') where (cs,s') = eolcomment s eolcomment [] = ([],[]) -- | Classification of tokens as lexical entities data TokenType = Space | Keyword | Keyglyph | Layout | Comment | Conid | Varid | Conop | Varop | String | Char | Number | Cpp | Error | Definition deriving (Eq,Show) classify :: String -> TokenType classify s@(h:t) | isSpace h = Space | all (=='-') s = Comment | "--" `isPrefixOf` s && any isSpace s = Comment -- not fully correct | "{-" `isPrefixOf` s = Comment | s `elem` keywords = Keyword | s `elem` keyglyphs = Keyglyph | s `elem` layoutchars = Layout | isUpper h = Conid | s == "[]" = Conid | h == '(' && isTupleTail t = Conid | h == '#' = Cpp | isLower h = Varid | h `elem` symbols = Varop | h==':' = Conop | h=='`' = Varop | h=='"' = String | h=='\'' = Char | isDigit h = Number | otherwise = Error classify _ = Space isTupleTail [')'] = True isTupleTail (',':xs) = isTupleTail xs isTupleTail _ = False -- Haskell keywords keywords = ["case","class","data","default","deriving","do","else","forall" ,"if","import","in","infix","infixl","infixr","instance","let","module" ,"newtype","of","qualified","then","type","where","_" ,"foreign","ccall","as","safe","unsafe"] keyglyphs = ["..","::","=","\\","|","<-","->","@","~","=>","[","]"] layoutchars = map (:[]) ";{}()," symbols = "!#$%&*+./<=>?@\\^|-~" hscolour-1.20.3/Language/Haskell/HsColour/ColourHighlight.hs0000644000000000000000000000556012022655553022127 0ustar0000000000000000module Language.Haskell.HsColour.ColourHighlight ( Colour(..) , Highlight(..) , base256, unbase , rgb24bit_to_xterm256 , projectToBasicColour8 , hlProjectToBasicColour8 ) where import Data.Word -- | Colours supported by ANSI codes. data Colour = Black | Red | Green | Yellow | Blue | Magenta | Cyan | White | Rgb Word8 Word8 Word8 deriving (Eq,Show,Read) -- | Convert an integer in the range [0,2^24-1] to its base 256-triplet, passing the result to the given continuation (avoid unnecessary tupleism). base256 :: Integral int => (Word8 -> Word8 -> Word8 -> r) -> int -> r base256 kont x = let (r,gb) = divMod x 256 (g,b) = divMod gb 256 fi = fromIntegral in kont (fi r) (fi g) (fi b) -- | Convert a three-digit numeral in the given (as arg 1) base to its integer value. unbase :: Integral int => int -> Word8 -> Word8 -> Word8 -> int unbase base r g b = (fi r*base+fi g)*base+fi b where fi = fromIntegral -- | Approximate a 24-bit Rgb colour with a colour in the xterm256 6x6x6 colour cube, returning its index. rgb24bit_to_xterm256 :: (Integral t) => Word8 -> Word8 -> Word8 -> t rgb24bit_to_xterm256 r g b = let f = (`div` 43) in 16 + unbase 6 (f r) (f g) (f b) -- | Ap\"proxi\"mate a 24-bit Rgb colour with an ANSI8 colour. Will leave other colours unchanged and will never return an 'Rgb' constructor value. projectToBasicColour8 :: Colour -> Colour projectToBasicColour8 (Rgb r g b) = let f = (`div` 128) in toEnum ( unbase 2 (f r) (f g) (f b) ) projectToBasicColour8 x = x -- | Lift 'projectToBasicColour8' to 'Highlight's hlProjectToBasicColour8 :: Highlight -> Highlight hlProjectToBasicColour8 (Foreground c) = Foreground (projectToBasicColour8 c) hlProjectToBasicColour8 (Background c) = Background (projectToBasicColour8 c) hlProjectToBasicColour8 h = h instance Enum Colour where toEnum 0 = Black toEnum 1 = Red toEnum 2 = Green toEnum 3 = Yellow toEnum 4 = Blue toEnum 5 = Magenta toEnum 6 = Cyan toEnum 7 = White -- Arbitrary extension; maybe just 'error' out instead toEnum x = base256 Rgb (x-8) fromEnum Black = 0 fromEnum Red = 1 fromEnum Green = 2 fromEnum Yellow = 3 fromEnum Blue = 4 fromEnum Magenta = 5 fromEnum Cyan = 6 fromEnum White = 7 -- Arbitrary extension; maybe just 'error' out instead fromEnum (Rgb r g b) = 8 + unbase 256 r g b -- | Types of highlighting supported by ANSI codes (and some extra styles). data Highlight = Normal | Bold | Dim | Underscore | Blink | ReverseVideo | Concealed | Foreground Colour | Background Colour -- The above styles are ANSI-supported, with the exception of the 'Rgb' constructor for 'Colour's. Below are extra styles (e.g. for Html rendering). | Italic deriving (Eq,Show,Read) hscolour-1.20.3/Language/Haskell/HsColour/Colourise.hs0000644000000000000000000000550612022655553021000 0ustar0000000000000000{-# LANGUAGE ScopedTypeVariables #-} module Language.Haskell.HsColour.Colourise ( module Language.Haskell.HsColour.ColourHighlight , ColourPrefs(..) , readColourPrefs , defaultColourPrefs , colourise ) where import Language.Haskell.HsColour.ColourHighlight import Language.Haskell.HsColour.Classify (TokenType(..)) import System.IO (hPutStrLn,stderr) import System.Environment (getEnv) import Data.List import Prelude hiding (catch) import Control.Exception.Base (catch) -- | Colour preferences. data ColourPrefs = ColourPrefs { keyword, keyglyph, layout, comment , conid, varid, conop, varop , string, char, number, cpp , selection, variantselection, definition :: [Highlight] } deriving (Eq,Show,Read) defaultColourPrefs = ColourPrefs { keyword = [Foreground Green,Underscore] , keyglyph = [Foreground Red] , layout = [Foreground Cyan] , comment = [Foreground Blue, Italic] , conid = [Normal] , varid = [Normal] , conop = [Foreground Red,Bold] , varop = [Foreground Cyan] , string = [Foreground Magenta] , char = [Foreground Magenta] , number = [Foreground Magenta] , cpp = [Foreground Magenta,Dim] , selection = [Bold, Foreground Magenta] , variantselection = [Dim, Foreground Red, Underscore] , definition = [Foreground Blue] } -- NOTE, should we give a warning message on a failed reading? parseColourPrefs :: String -> String -> IO ColourPrefs parseColourPrefs file x = case reads x of (res,_):_ -> return res _ -> do hPutStrLn stderr ("Could not parse colour prefs from "++file ++": reverting to defaults") return defaultColourPrefs -- | Read colour preferences from .hscolour file in the current directory, or failing that, -- from \$HOME\/.hscolour, and failing that, returns a default set of prefs. readColourPrefs :: IO ColourPrefs readColourPrefs = catch (do val <- readFile ".hscolour" parseColourPrefs ".hscolour" val) (\ (_::IOError)-> catch (do home <- getEnv "HOME" val <- readFile (home++"/.hscolour") parseColourPrefs (home++"/.hscolour") val) (\ (_::IOError)-> return defaultColourPrefs)) -- | Convert token classification to colour highlights. colourise :: ColourPrefs -> TokenType -> [Highlight] colourise pref Space = [Normal] colourise pref Comment = comment pref colourise pref Keyword = keyword pref colourise pref Keyglyph = keyglyph pref colourise pref Layout = layout pref colourise pref Conid = conid pref colourise pref Varid = varid pref colourise pref Conop = conop pref colourise pref Varop = varop pref colourise pref String = string pref colourise pref Char = char pref colourise pref Number = number pref colourise pref Cpp = cpp pref colourise pref Error = selection pref colourise pref Definition = definition pref hscolour-1.20.3/Language/Haskell/HsColour/General.hs0000644000000000000000000000044712022655553020410 0ustar0000000000000000 module Language.Haskell.HsColour.General( dropLast, dropFirst ) where dropLast :: Eq a => a -> [a] -> [a] dropLast x [y] | x == y = [] dropLast x (y:ys) = y : dropLast x ys dropLast x [] = [] dropFirst :: Eq a => a -> [a] -> [a] dropFirst x (y:ys) | x == y = ys dropFirst x ys = ys hscolour-1.20.3/Language/Haskell/HsColour/HTML.hs0000644000000000000000000000667112022655553017604 0ustar0000000000000000-- | Formats Haskell source code using HTML with font tags. module Language.Haskell.HsColour.HTML ( hscolour , top'n'tail -- * Internals , renderAnchors, renderComment, renderNewLinesAnchors, escape ) where import Language.Haskell.HsColour.Anchors import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Data.Char(isAlphaNum) import Text.Printf -- | Formats Haskell source code using HTML with font tags. hscolour :: ColourPrefs -- ^ Colour preferences. -> Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour pref anchor = pre . (if anchor then renderNewLinesAnchors . concatMap (renderAnchors (renderToken pref)) . insertAnchors else concatMap (renderToken pref)) . tokenise top'n'tail :: String -> String -> String top'n'tail title = (htmlHeader title ++) . (++htmlClose) pre :: String -> String pre = ("
"++) . (++"
") renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken pref (t,s) = fontify (colourise pref t) (if t == Comment then renderComment s else escape s) renderAnchors :: (a -> String) -> Either String a -> String renderAnchors _ (Left v) = "" renderAnchors render (Right r) = render r -- if there are http://links/ in a comment, turn them into -- hyperlinks renderComment :: String -> String renderComment xs@('h':'t':'t':'p':':':'/':'/':_) = renderLink a ++ renderComment b where -- see http://www.gbiv.com/protocols/uri/rfc/rfc3986.html#characters isUrlChar x = isAlphaNum x || x `elem` ":/?#[]@!$&'()*+,;=-._~%" (a,b) = span isUrlChar xs renderLink link = "" ++ escape link ++ "" renderComment (x:xs) = escape [x] ++ renderComment xs renderComment [] = [] renderNewLinesAnchors :: String -> String renderNewLinesAnchors = unlines . map render . zip [1..] . lines where render (line, s) = "" ++ s -- Html stuff fontify :: [Highlight] -> String -> String fontify [] s = s fontify (h:hs) s = font h (fontify hs s) font :: Highlight -> String -> String font Normal s = s font Bold s = ""++s++"" font Dim s = ""++s++"" font Underscore s = ""++s++"" font Blink s = ""++s++"" font ReverseVideo s = s font Concealed s = s font (Foreground (Rgb r g b)) s = printf "%s" r g b s font (Background (Rgb r g b)) s = printf "%s" r g b s font (Foreground c) s = ""++s++"" font (Background c) s = ""++s++"" font Italic s = ""++s++"" escape :: String -> String escape ('<':cs) = "<"++escape cs escape ('>':cs) = ">"++escape cs escape ('&':cs) = "&"++escape cs escape (c:cs) = c: escape cs escape [] = [] htmlHeader :: String -> String htmlHeader title = unlines [ "" , "" , "" ,"" , ""++title++"" , "" , "" ] htmlClose :: String htmlClose = "\n\n" hscolour-1.20.3/Language/Haskell/HsColour/InlineCSS.hs0000644000000000000000000000541512022655553020622 0ustar0000000000000000-- | Formats Haskell source code as HTML with inline CSS. module Language.Haskell.HsColour.InlineCSS (hscolour,top'n'tail) where import Language.Haskell.HsColour.Anchors import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Language.Haskell.HsColour.HTML (renderAnchors, renderComment, renderNewLinesAnchors, escape) import Text.Printf -- | Formats Haskell source code as a complete HTML document with inline styling hscolour :: ColourPrefs -- ^ Preferences for styling. -> Bool -- ^ Whether to include anchors. -> String -- ^ Haskell source code. -> String -- ^ An HTML document containing the coloured -- Haskell source code. hscolour prefs anchor = pre . (if anchor then renderNewLinesAnchors . concatMap (renderAnchors (renderToken prefs)) . insertAnchors else concatMap (renderToken prefs)) . tokenise top'n'tail :: String -> String -> String top'n'tail title = (cssPrefix title ++) . (++cssSuffix) pre :: String -> String pre = ("
"++)
      . (++"
") renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken prefs (cls,text) = stylise (colourise prefs cls) $ if cls == Comment then renderComment text else escape text stylise :: [Highlight] -> String -> String stylise hs s = "" ++s++ "" cssPrefix title = unlines ["" ,"" ,"" ,"" ,"" ,""++title++"" ,"" ,"" ] cssSuffix = unlines ["" ,"" ] style :: Highlight -> String style Normal = "" style Bold = "font-weight: bold;" style Dim = "font-weight: lighter;" style Underscore = "text-decoration: underline;" style Blink = "text-decoration: blink;" style ReverseVideo = "" style Concealed = "text-decoration: line-through;" style (Foreground c) = "color: "++csscolour c++";" style (Background c) = "background-color: "++csscolour c++";" style Italic = "font-style: italic;" csscolour :: Colour -> String csscolour Black = "#000000" csscolour Red = "#ff0000" csscolour Green = "#00ff00" csscolour Yellow = "#ffff00" csscolour Blue = "#0000ff" csscolour Magenta = "#ff00ff" csscolour Cyan = "#00ffff" csscolour White = "#ffffff" csscolour (Rgb r g b) = printf "#%02x%02x%02x" r g b hscolour-1.20.3/Language/Haskell/HsColour/LaTeX.hs0000644000000000000000000001060412022655553020004 0ustar0000000000000000-- | Formats Haskell source code using LaTeX macros. module Language.Haskell.HsColour.LaTeX (hscolour, top'n'tail) where import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Language.Haskell.HsColour.General -- | Formats Haskell source code as a complete LaTeX document. hscolour :: ColourPrefs -- ^ Colour preferences. -> String -- ^ Haskell source code. -> String -- ^ A LaTeX document\/fragment containing the coloured -- Haskell source code. hscolour pref = concatMap (renderToken pref) . tokenise top'n'tail :: String -> String -> String top'n'tail title = (latexPrefix title++) . (++latexSuffix) -- | Wrap each lexeme in the appropriate LaTeX macro. -- TODO: filter dangerous characters like "{}_$" renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken pref (Space,text) = filterSpace text renderToken pref (cls,text) = let symb = case cls of String -> "``" ++ (dropFirst '\"' $ dropLast '\"' $ text) ++ "''" _ -> text style = colourise pref cls (pre, post) = unzip $ map latexHighlight style in concat pre ++ filterSpecial symb ++ concat post -- | Filter white space characters. filterSpace :: String -> String filterSpace ('\n':ss) = '\\':'\\':(filterSpace ss) filterSpace (' ':ss) = "\\hsspace "++(filterSpace ss) filterSpace ('\t':ss) = "\\hstab "++(filterSpace ss) filterSpace (c:ss) = c:(filterSpace ss) filterSpace [] = [] -- | Filters the characters "#$%&~_^\{}" which are special -- in LaTeX. filterSpecial :: String -- ^ The string to filter. -> String -- ^ The LaTeX-safe string. filterSpecial ('#':cs) = '\\':'#':(filterSpecial cs) filterSpecial ('$':cs) = '\\':'$':(filterSpecial cs) filterSpecial ('%':cs) = '\\':'%':(filterSpecial cs) filterSpecial ('&':cs) = '\\':'&':(filterSpecial cs) filterSpecial ('~':cs) = "\\tilde{ }"++(filterSpecial cs) filterSpecial ('_':cs) = '\\':'_':(filterSpecial cs) filterSpecial ('^':cs) = "\\ensuremath{\\hat{ }}"++(filterSpecial cs) filterSpecial ('\\':cs) = "$\\backslash$"++(filterSpecial cs) filterSpecial ('{':cs) = '\\':'{':(filterSpecial cs) filterSpecial ('}':cs) = '\\':'}':(filterSpecial cs) filterSpecial ('|':cs) = "\\ensuremath{|}"++(filterSpecial cs) filterSpecial ('<':'-':cs) = "\\ensuremath{\\leftarrow}"++(filterSpecial cs) filterSpecial ('<':cs) = "\\ensuremath{\\langle}"++(filterSpecial cs) filterSpecial ('-':'>':cs) = "\\ensuremath{\\rightarrow}"++(filterSpecial cs) filterSpecial ('>':cs) = "\\ensuremath{\\rangle}"++(filterSpecial cs) filterSpecial (c:cs) = c:(filterSpecial cs) filterSpecial [] = [] -- | Constructs the appropriate LaTeX macro for the given style. latexHighlight :: Highlight -> (String, String) latexHighlight Normal = ("{\\rm{}", "}") latexHighlight Bold = ("{\\bf{}", "}") latexHighlight Dim = ("", "") latexHighlight Underscore = ("\\underline{", "}") latexHighlight Blink = ("", "") latexHighlight ReverseVideo = ("", "") latexHighlight Concealed = ("\\conceal{", "}") latexHighlight (Foreground c) = ("\\textcolor{"++ latexColour c ++"}{", "}") latexHighlight (Background c) = ("\\colorbox{"++ latexColour c ++"}{", "}") latexHighlight Italic = ("{\\it{}", "}") -- | Translate a 'Colour' into a LaTeX colour name. latexColour :: Colour -> String latexColour Black = "black" latexColour Red = "red" latexColour Green = "green" latexColour Yellow = "yellow" latexColour Blue = "blue" latexColour Magenta = "magenta" latexColour Cyan = "cyan" latexColour White = "white" -- | TODO: How are these properly encoded in Latex? latexColour c@(Rgb _ _ _) = latexColour (projectToBasicColour8 c) -- | Generic LaTeX document preamble. latexPrefix title = unlines ["\\documentclass[a4paper, 12pt]{article}" ,"\\usepackage[usenames]{color}" ,"\\usepackage{hyperref}" ,"\\newsavebox{\\spaceb}" ,"\\newsavebox{\\tabb}" ,"\\savebox{\\spaceb}[1ex]{~}" ,"\\savebox{\\tabb}[4ex]{~}" ,"\\newcommand{\\hsspace}{\\usebox{\\spaceb}}" ,"\\newcommand{\\hstab}{\\usebox{\\tabb}}" ,"\\newcommand{\\conceal}[1]{}" ,"\\title{"++title++"}" ,"%% Generated by HsColour" ,"\\begin{document}" ,"\\maketitle" ,"\\noindent" ] -- | Generic LaTeX document postamble. latexSuffix = unlines ["" ,"\\end{document}" ] hscolour-1.20.3/Language/Haskell/HsColour/MIRC.hs0000644000000000000000000000447712022655553017574 0ustar0000000000000000-- | Formats Haskell source code using mIRC codes. -- (see http:\/\/irssi.org\/documentation\/formats) module Language.Haskell.HsColour.MIRC (hscolour) where import Language.Haskell.HsColour.Classify as Classify import Language.Haskell.HsColour.Colourise import Data.Char(isAlphaNum) -- | Formats Haskell source code using mIRC codes. hscolour :: ColourPrefs -- ^ Colour preferences. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour pref = concatMap (renderToken pref) . tokenise renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken pref (t,s) = fontify (colourise pref t) s -- mIRC stuff fontify hs = mircColours (joinColours hs) . highlight (filter (`elem`[Normal,Bold,Underscore,ReverseVideo]) hs) where highlight [] s = s highlight (h:hs) s = font h (highlight hs s) font Normal s = s font Bold s = '\^B':s++"\^B" font Underscore s = '\^_':s++"\^_" font ReverseVideo s = '\^V':s++"\^V" -- mIRC combines colour codes in a non-modular way data MircColour = Mirc { fg::Colour, dim::Bool, bg::Maybe Colour, blink::Bool} joinColours :: [Highlight] -> MircColour joinColours = foldr join (Mirc {fg=Black, dim=False, bg=Nothing, blink=False}) where join Blink mirc = mirc {blink=True} join Dim mirc = mirc {dim=True} join (Foreground fg) mirc = mirc {fg=fg} join (Background bg) mirc = mirc {bg=Just bg} join Concealed mirc = mirc {fg=Black, bg=Just Black} join _ mirc = mirc mircColours :: MircColour -> String -> String mircColours (Mirc fg dim Nothing blink) s = '\^C': code fg dim++s++"\^O" mircColours (Mirc fg dim (Just bg) blink) s = '\^C': code fg dim++',' : code bg blink++s++"\^O" code :: Colour -> Bool -> String code Black False = "1" code Red False = "5" code Green False = "3" code Yellow False = "7" code Blue False = "2" code Magenta False = "6" code Cyan False = "10" code White False = "0" code Black True = "14" code Red True = "4" code Green True = "9" code Yellow True = "8" code Blue True = "12" code Magenta True = "13" code Cyan True = "11" code White True = "15" code c@(Rgb _ _ _) b = code (projectToBasicColour8 c) b hscolour-1.20.3/Language/Haskell/HsColour/Options.hs0000644000000000000000000000127512022655553020466 0ustar0000000000000000module Language.Haskell.HsColour.Options ( Option(..) , Output(..) , TerminalType(..) ) where import Language.Haskell.HsColour.Output -- | Command-line options data Option = Help -- ^ print usage message | Version -- ^ report version | Information -- ^ report auxiliary information, e.g. CSS defaults | Format Output -- ^ what type of output to produce | LHS Bool -- ^ literate input (i.e. multiple embedded fragments) | Anchors Bool -- ^ whether to add anchors | Partial Bool -- ^ whether to produce a full document or partial | Input FilePath -- ^ input source file | Output FilePath -- ^ output source file | Annot FilePath -- ^ annotations file deriving Eq hscolour-1.20.3/Language/Haskell/HsColour/Output.hs0000644000000000000000000000164312022655553020332 0ustar0000000000000000module Language.Haskell.HsColour.Output(TerminalType(..),Output(..)) where data TerminalType = Ansi16Colour -- ^ @\\033[Xm@-style escape sequences (with /X/ =~ [34][0-7]) | XTerm256Compatible -- ^ 'Ansi16Colour', and also @\\033[Y8;5;Zm]@-style escape sequences (with /Y/ =~ [3,4] and /Z/ an integer in [0,255] with the XTerm colour cube semantics). deriving (Show,Eq,Ord) -- | The supported output formats. data Output = TTY -- ^ ANSI terminal codes. Equivalent to 'TTYg' 'Ansi16Colour' but left in for backwards compatibility. | TTYg TerminalType -- ^ Terminal codes appropriate for the 'TerminalType'. | LaTeX -- ^ TeX macros | HTML -- ^ HTML with font tags | CSS -- ^ HTML with CSS. | ACSS -- ^ HTML with CSS and mouseover types. | ICSS -- ^ HTML with inline CSS. | MIRC -- ^ mIRC chat clients deriving (Eq,Show) hscolour-1.20.3/Language/Haskell/HsColour/TTY.hs0000644000000000000000000000155512022655553017514 0ustar0000000000000000-- | Highlights Haskell code with ANSI terminal codes. module Language.Haskell.HsColour.TTY (hscolour,hscolourG) where import Language.Haskell.HsColour.ANSI as ANSI import Language.Haskell.HsColour.Classify import Language.Haskell.HsColour.Colourise import Language.Haskell.HsColour.Output(TerminalType(Ansi16Colour)) -- | = 'hscolourG' 'Ansi16Colour' hscolour :: ColourPrefs -- ^ Colour preferences. -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour = hscolourG Ansi16Colour -- | Highlights Haskell code with ANSI terminal codes. hscolourG terminalType pref = concatMap (renderTokenG terminalType pref) . tokenise renderToken :: ColourPrefs -> (TokenType,String) -> String renderToken = renderTokenG Ansi16Colour renderTokenG terminalType pref (t,s) = ANSI.highlightG terminalType (colourise pref t) s hscolour-1.20.3/data/0000755000000000000000000000000012022655553012537 5ustar0000000000000000hscolour-1.20.3/data/rgb24-example-.hscolour0000644000000000000000000000266512022655553016756 0ustar0000000000000000ColourPrefs { keyword = [Foreground (Rgb 255 255 150 ), Background (Rgb 0 0 0)] , keyglyph = [Foreground (Rgb 255 255 150 ), Background (Rgb 0 0 0)] , layout = [Foreground (Rgb 150 255 150 ), Background (Rgb 0 0 0 ), Bold] , comment = [Foreground (Rgb 0 0 0 ), Background (Rgb 150 255 150 ), Italic] , conid = [Foreground (Rgb 150 150 255 ), Background (Rgb 0 0 0 ), Bold] , varid = [Foreground (Rgb 150 150 255 ), Background (Rgb 0 0 0)] , conop = [Foreground (Rgb 255 150 150 ), Background (Rgb 0 0 0 ), Bold] , varop = [Foreground (Rgb 255 150 150 ), Background (Rgb 0 0 0)] , string = [Foreground (Rgb 0 0 0 ), Background (Rgb 150 150 255)] , char = [Foreground (Rgb 0 0 0 ), Background (Rgb 150 150 255)] , number = [Foreground (Rgb 255 255 150 ), Background (Rgb 0 0 0)] , cpp = [Foreground (Rgb 0 0 0 ), Background (Rgb 255 150 150)] , selection = [Foreground (Rgb 150 255 150 ), Background (Rgb 0 0 0)] , variantselection = [Dim, Foreground Red, Underscore] , definition = [Foreground (Rgb 150 255 150 ), Background (Rgb 0 0 0)] } -- This example configuration file would take effect if you moved it to ~/.hscolour. -- Note: Comments currently have to come *after* the above block -- vim: ft=haskell