hscolour-1.24.2/0000755000000000000000000000000013204110137011614 5ustar0000000000000000hscolour-1.24.2/HsColour.hs0000644000000000000000000001633713204110137013720 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) , ("acss", Format ACSS) , ("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.24.2/LICENCE-LGPL0000644000000000000000000006363313204110137013350 0ustar0000000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 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. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, 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 library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete 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 distribute a copy of this License along with the Library. 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 Library or any portion of it, thus forming a work based on the Library, 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) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, 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 Library, 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 Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you 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. If distribution of 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 satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be 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. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library 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. 9. 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 Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library 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 with this License. 11. 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 Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library 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 Library. 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. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library 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. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library 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 Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, 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 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. 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 LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; 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. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! hscolour-1.24.2/Setup.hs0000644000000000000000000000010513204110137013244 0ustar0000000000000000#!/usr/bin/env runghc import Distribution.Simple main = defaultMain hscolour-1.24.2/hscolour.cabal0000644000000000000000000000322213204110137014435 0ustar0000000000000000Name: hscolour Version: 1.24.2 Copyright: 2003-2017 Malcolm Wallace; 2006 Bjorn Bringert Maintainer: Malcolm Wallace Author: Malcolm Wallace Homepage: http://code.haskell.org/~malcolm/hscolour/ License: LGPL License-file: LICENCE-LGPL 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=24 Source-repository head Type : darcs Location: http://code.haskell.org/~malcolm/hscolour hscolour-1.24.2/hscolour.css0000644000000000000000000000157013204110137014167 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.24.2/Language/0000755000000000000000000000000013204110137013337 5ustar0000000000000000hscolour-1.24.2/Language/Haskell/0000755000000000000000000000000013204110137014722 5ustar0000000000000000hscolour-1.24.2/Language/Haskell/HsColour.hs0000644000000000000000000001224213204110137017015 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 1 hscolour output pref anchor partial title True = (if partial then id else top'n'tail output title) . concat . chunk 1 . joinL . classify . inlines where chunk _ [] = [] chunk n (Code c: cs) = hscolour' output pref anchor n c : chunk (n + length (lines c)) cs chunk n (Lit c: cs) = c : chunk n cs -- | 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. -> Int -- ^ Starting line number (for line 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 n = HTML.hscolour pref anchor n hscolour' CSS _ anchor n = CSS.hscolour anchor n hscolour' ICSS pref anchor n = ICSS.hscolour pref anchor n hscolour' ACSS _ anchor n = ACSS.hscolour anchor n -- | 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 "code" xs classify (x:xs) | "\\begin{spec}"`isPrefixOf`x = Lit x: allProg "spec" xs classify (('>':x):xs) = Code ('>':x) : classify xs classify (x:xs) = Lit x: classify xs allProg name = go where end = "\\end{" ++ name ++ "}" go [] = [] -- Should give an error message, -- but I have no good position information. go (x:xs) | end `isPrefixOf `x = Lit x: classify xs go (x:xs) = Code x: go 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.24.2/Language/Haskell/HsColour/0000755000000000000000000000000013204110137016460 5ustar0000000000000000hscolour-1.24.2/Language/Haskell/HsColour/ACSS.hs0000644000000000000000000001236213204110137017551 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. -> Int -- ^ Starting line number (for line anchors). -> String -- ^ Haskell source code, Annotations as comments at end -> String -- ^ Coloured Haskell source code. hscolour anchor n = hsannot anchor n . splitSrcAndAnns -- | Formats Haskell source code using HTML and mouse-over annotations hsannot :: Bool -- ^ Whether to include anchors. -> Int -- ^ Starting line number (for line anchors). -> (String, AnnMap) -- ^ Haskell Source, Annotations -> String -- ^ Coloured Haskell source code. hsannot anchor n = CSS.pre . (if anchor then -- renderNewLinesAnchors n . 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.24.2/Language/Haskell/HsColour/ANSI.hs0000644000000000000000000000741113204110137017551 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.24.2/Language/Haskell/HsColour/Anchors.hs0000644000000000000000000002000513204110137020406 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"):(Space,_):(Keyword,"family"):stream) = getConid stream identifier st t@((Keyword,"data"):stream) = getConid stream identifier st t@((Keyword,"newtype"):stream) = getConid stream identifier st t@((Keyword,"type"):(Space,_):(Keyword,"family"):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 (not . terminator) where trimContext ts = if (Keyglyph,"=>") `elem` ts || (Keyglyph,"⇒") `elem` ts then tail . dropWhile (`notElem`[(Keyglyph,"=>") ,(Keyglyph,"⇒")]) $ ts else ts terminator (Keyword, _) = True terminator (Comment, _) = True terminator (Cpp, _) = True terminator (Keyglyph,"|") = True terminator (Layout, ";") = True terminator (Layout, "{") = True terminator (Layout, "}") = True terminator _ = False -- 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.24.2/Language/Haskell/HsColour/CSS.hs0000644000000000000000000000453413204110137017452 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. -> Int -- ^ Starting line number (for line anchors). -> String -- ^ Haskell source code. -> String -- ^ An HTML document containing the coloured -- Haskell source code. hscolour anchor n = pre . (if anchor then renderNewLinesAnchors n . 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.24.2/Language/Haskell/HsColour/Classify.hs0000644000000000000000000001157513204110137020602 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","family"] keyglyphs = ["..","::","=","\\","|","<-","->","@","~","=>","[","]"] layoutchars = map (:[]) ";{}()," symbols = "!#$%&*+./<=>?@\\^|-~" hscolour-1.24.2/Language/Haskell/HsColour/ColourHighlight.hs0000644000000000000000000000556013204110137022115 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.24.2/Language/Haskell/HsColour/Colourise.hs0000644000000000000000000000550613204110137020766 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.24.2/Language/Haskell/HsColour/General.hs0000644000000000000000000000044713204110137020376 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.24.2/Language/Haskell/HsColour/HTML.hs0000644000000000000000000000701413204110137017562 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. -> Int -- ^ Starting line number (for line anchors). -> String -- ^ Haskell source code. -> String -- ^ Coloured Haskell source code. hscolour pref anchor n = pre . (if anchor then renderNewLinesAnchors n . 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 :: Int -> String -> String renderNewLinesAnchors n = unlines . map render . zip [n..] . 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.24.2/Language/Haskell/HsColour/InlineCSS.hs0000644000000000000000000000552213204110137020607 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. -> Int -- ^ Starting line number (for line anchors). -> String -- ^ Haskell source code. -> String -- ^ An HTML document containing the coloured -- Haskell source code. hscolour prefs anchor n = pre . (if anchor then renderNewLinesAnchors n . 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.24.2/Language/Haskell/HsColour/LaTeX.hs0000644000000000000000000001060413204110137017772 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.24.2/Language/Haskell/HsColour/MIRC.hs0000644000000000000000000000451113204110137017547 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 = "01" code Red False = "05" code Green False = "03" code Yellow False = "07" code Blue False = "02" code Magenta False = "06" code Cyan False = "10" code White False = "00" code Black True = "14" code Red True = "04" code Green True = "09" code Yellow True = "08" 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.24.2/Language/Haskell/HsColour/Options.hs0000644000000000000000000000127513204110137020454 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.24.2/Language/Haskell/HsColour/Output.hs0000644000000000000000000000164313204110137020320 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.24.2/Language/Haskell/HsColour/TTY.hs0000644000000000000000000000155513204110137017502 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.24.2/data/0000755000000000000000000000000013204110137012525 5ustar0000000000000000hscolour-1.24.2/data/rgb24-example-.hscolour0000644000000000000000000000266513204110137016744 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