Home
Guide2lhs2TeX - of Andres Löh
Contents
1. format times format A n f n f begin code ATTR Expr Factor numvars Int ATTR Expr Factor value Int SEM Expr Sum lhs value A left value A right value numvars A left numvars A right numvars SEM Factor Prod lhs value A left value A right value numvars A left numvars A right numvars end code produces the following output 29 ATTR Expr Factor numvars Int ATTR Expr Factor value Int SEM Expr Sum Ihs value left value right value numvars left numvars right numvars SEM Factor Prod Ihs value left value x right value numvars left numvars right numvars 11 4 Generic Haskell example Another example of a Haskell variant that can be typeset using 1hs2TeX using some annotations is Generic Haskell 5 This is a possible input file including the directives necessary to be able to process it in both newcode and poly style if style newcode format format format ti a I a I format ki a a helse format n format A format ti a Mty a rty format ki a Mki a rki newcommand lty mathopen mskip 3 4mu newcommand rty mathclose mskip 3 4mu newcommand 1ki mathopen mskip 3 5mu newcommand rki mathclose mskip 3 5mu format ti format t2 format al format a2 Y format r_ rho yformat s A
2. One can have different versions of one paper in one set of source file s De pending on a flag 1hs2TeX can produce either the one or the other Because the flag can be defined via a command line option cf Section 9 no modification of the source is necessary to switch versions Code that is needed to make the Haskell program work but that should not appear in the formatted article module headers auxiliary definitions can be enclosed between 4if False and endif directives Alternatively if Haskell code has to be annotated for 1hs2TeX to produce aes thetically pleasing output one can define different formatting directives for the annotation depending on style poly or newcode Both code and TEX file can then still be produced from a common source Section 11 4 contains an example that puts this technique to use The Ihs2TEX library files use conditionals to include different directives depending on the style selected but they also use conditionals to provide additional or modified behaviour if some flags are set These flags are underlineKeywords spacePreserving meta activate a number of additional formatting directives array use array envi ronment instead of tabular to format code blocks in math style use parray instead of pboxed in poly style latex209 adapt for use with ATEX 2 09 not supported any more euler and standardsymbols It is likely that these flags will be replaced by a selection of library files that c
3. definition of map 1 1 map 4 1 2 3 performing the addition on the head 2 map 1 2 3 recursive application of map 2 3 4 list syntactic sugar 2 3 4 12 Calling hugs or ghci It is possible to call ghci or hugs using the Zoptions directive In all but the two code styles 1hs2TeX looks for calls to the TEX commands eval and perform and feeds their arguments to the Haskell interpreter selected The current input file will be the active module This has a couple of consequences on the positive side values defined in the current source file may be used in the ex pressions on the negative side the feature will only work if the current file is accepted as legal input by the selected interpreter If the command line in the options directive starts with ghci then 1hs2TeX as sumes that ghci is called otherwise it assumes that hugs is called Depending on the interpreter 1hs2TeX will use some heuristics to extract the answer from the output of the interpreter After this extraction the result will either be printed as inline ver batim for a perform or as inline code for eval to which formatting directives apply WARNING This feature is somewhat fragile different versions of ghci and hugs show different behaviour and the extraction heuristics can sometimes fail Do not expect too much from this feature 12 1 Calling ghci example The following input shows an example of how to call
4. a right hand side can be used to easily format a frequently occurring special case only a variable or construc tor name that ends in a number or a prime can be used in an implicit formatting statement The prefix will then be formatted as determined by the formatting direc tives in the input so far The number will be added as an index the prime character as itself The following input contains some example format omega omega omega omegai3 omega13 par format omegai3 omega omega13 omegai3 par format omegai3 omega omegai3 omegai3 The corresponding output is w omega13 omega13 w w13 omega13 w 13 ws Another form of implicit formatting only takes place only if the token to be format ted does not end in primes and only if digits at the end are immediately preceded by an underscore The reason for these conditions is compatibility If the conditions are met then the token is split at underscores and the part to the right of an under score is typeset as subscript to the part on the left recursively Again let us look at an example 18 format a_i format a_j format left leftarrow format right rightarrow format a left format a right format a let format a where format a x 1 format a x 2 format y 1 format y 2 format a y 1 format a y 2 format a yl format a_i a i a j a left a right a let a where a x 1 a x 2 a y 1 a y 2
5. ghci 32 options ghci fglasgow exts gt fix forall a a gt a gt a gt fix f f fix f This function is of type eval t fix and take 10 fix x l evaluates to eval take 10 fix x The option fglasgow exts is necessary to make ghci accept the forall keyword it only serves as an example here how to pass options to the interpreter The output will look similar to this fix x Va a a3 a fix f f fix f This function is of type fix Va a a a and take 10 fix x evaluates to XXXXXXXXXX Note that it is possible to pass interpreter commands such as t to the external pro gram 12 2 Calling hugs example The same could be achieved using hugs instead of ghci For this simple example the output is almost indistinguishable only that hugs usually does not print type signatures using explicit quantification and tends to use different variable names options hugs 98 gt fix forall a a gt a gt a gt fix f f fix f This function is of type eval t fix and take 10 fix x l evaluates to eval take 10 fix x The input is the same except for the changed options directive The output now looks as follows fix x Va a a a fix f f fix f This function is of type hugs not found and take 10 fix x evaluates to 7hugs not found 33 12 3 Using a preprocessor The situation is more difficult if
6. intersperse sep x xs x sep intersperse sep xs end code As output we get intersperse x a gt a a intersperse intersperse x x The only really interesting case is the one for lists containing at least two elements intersperse sep x xs x sep intersperse sep xs Compare this to the output that would be generated without the savecolumns and restorecolumns commands 25 intersperse 4 a gt a intersperse intersperse _ x The only really interesting case is the one for lists containing at least two elements intersperse sep x xs x sep intersperse sep xs IMPORTANT If this feature is used it may require several runs of IAT X until all code blocks are correctly aligned Watch out for warnings of the polytable package that tell you to rerun ATEX 9 Defining variables One can define or define flags or variables by means of the 1et directive let varname expression expression application operator application application not atom atom varid True False string numeral expression operator s amp amp M e I e om e e Expressions are built from booleans either True or False numerals integers but also decimal numbers and previously defined variables using some fixed set of builtin operators The expression will be evaluated completely at the time the let directive is proces
7. on an input file 1hs2TeX classifies the source file into different blocks Lines indicating a Bird style literate program i e lines beginning with either gt or X are considered as code blocks Lines that are surrounded by begin code and end code statements or also by begin spec and end spec statements are considered as code blocks Note that Ihs2TeX does not care if both styles of a literate program are mixed in one file In this sense it is more liberal than Haskell However in code and newcode mode the initial characters gt and lt will be replaced by spaces so you have to indent code environments in order to create a properly indented Haskell module Text between two characters that is not in a code block is considered inline verbatim If a 0 is desired to appear in text it needs to be escaped There is no need to escape s in code blocks Text between two characters that is not in a code block is considered inline code Again characters that should appear literally outside of code blocks need to be escaped A 7 that is followed by the name of an 1hs2TeX directive is considered as a di rective and may cause 1hs2TeX to take special actions Directives are described in detail later Some constructs are treated specially such as occurrences of the TEX commands eval Nperform Nverb or of the IATEX environment verbatim All the rest is classified as plain text Depending on the
8. symbol is substituted usually a cdot but that is customizable cf Section 13 7 4 No nesting with parametrized directives You cannot use a parametrized directive on the right hand side of another directive In summary the right hand sides of formatting directives are processed as follows A string enclosed in will be reproduced literally without the quotes A name if it is the name of a parameter will be replaced by the actual format ted argument A name if it is the name of a non parametrized formatting directive will be replaced by that directive s replacement Any other name will be replaced by its standard formatting Note that the spaces between the tokens do not occur in the output If you want spaces insert them explicitly 7 5 Parentheses Sometimes due to formatting an identifier as a symbol parentheses around argu ments or the entire function become unnecessary Therefore 1hs2TeX can be in structed to drop parentheses around an argument by enclosing the argument on the left hand side of the directive in parentheses Parentheses around the entire function are dropped if the entire left hand side of the directive is enclosed in parentheses Let us look at another example format format ptest a b c ptest a b c begin code ptest abc ptest a b c ptest a b CODD end code The above input produces the following output 16 ptest a b c ptest a
9. the position of the include directive Because of that the included files may not only contain other sources but also other directives in particular an included file may contain an include directive again The 1hs2TeX is entirely independent of TEX or Haskell includes imports WARNING Although relative and absolute pathnames can be specified as part of a filename in an include directive the use of this feature is strongly discouraged Set the search path using the P command line option to detect files to include If the v command line flag is set 1hs2TeX will print the paths of the files it is reading on screen while processing a file 6 1 The 1hs2TeX prelude Several aspects of the behaviour of 1hs2TeX are not hardcoded but configurable via directives As a consequence a minimal amount of functionality has to be defined for 1hs2TeX to be able to operate normally Essential definitions are collected in the file 1hs2TeX fmt NOTE TO USERS OF PREVIOUS VERSIONS There used to be a file 1hs2TeX sty that also contained a part of the prelude declarations This file does still exist for compatibility reasons but is now deprecated It should not be included directly in any of your documents anymore 12 If you are using the poly or newcode styles some of the defaults in 1hs2TeX fmt are sub optimal In this case there is a better prelude polycode fmt which includes lhs2TeX fmt in turn One of the two files 1hs2TeX fmt or polycod
10. then n is an alignment column for the code block If a token starts in an alignment column n and is prefixed by at least latency spaces then the token is aligned at column n All tokens that are aligned at a specific column will appear aligned i e at the same horizontal position in the output Both latency and separation can be modified by means of associated directives separation natural latency natural It can occasionally be useful to increase the default settings of 2 and 2 for large code blocks where accidental alignments become very likely It does not really make sense to set latency to a value that is strictly smaller than the separation but you can do so there are no checks that the specified settings are sensible 21 8 4 Indentation in poly style Sometimes 1hs2TeX will insert additional space at the beginning of a line to reflect indentation The rule is described in the following If a line is indented in column n then the previous code line is taken into account If there is an aligned token at column r in the previous line then the indented line will be aligned normally Otherwise the line will be indented with respect to the first aligned token in the previous line to the left of column n The first example demonstrates the first case unionBy a gt a gt Bool gt a gt a gt al unionBy eq xs ys xs foldl flip deleteBy eq nubBy eq ys In this example ther
11. EX denote the current values of the environment variables HOME and LHS2TEX The double slash at the end of each dir means that subdirectories are also scanned If 1hs2TeX is installed to a non standard path you might want to set the environment variable LHS2TEX to point to the directory where 1hs2TeX fmt and the other library files have been installed to IMPORTANT To be able to use poly style the two ATEX packages polytable sty and lazylist sty are required Both are included in the 1hs2TeX distribution they are not part of standard ATEX distributions although they are available from CTAN 1 2 and are usually installed during the normal procedure The configure script will determine whether a suit ably recent version of polytable is installed on your system and if necessary install both polytable sty and lazylist sty to your TEX system If this is not desired or fails because the script cannot detect your TEX installation properly the instal lation of these files can be disabled by passing the option disable polytable to configure In this case the two files must be manually installed to a location where your TeX distribution will find them Assuming that you have a local TEX tree at usr local share texmf this can usually be achieved by placing the files in the di rectory usr local share texmf tex latex polytable and subsequently running mktexlsr to update the TEX filename database 3 lhs2TeX operation When run
12. Guide21hs2TeX for version 1 14 Ralf Hinze Computing Laboratory University of Oxford Wolfson Building Parks Road Oxford OX1 3QD England ralf hinze comlab ox ac uk Andres Loh Institute of Information and Computing Sciences Utrecht University P O Box 80 089 3508 TB Utrecht The Netherlands andres cs uu nl October 24 2008 Contents 1 About 1hs2TeX 2 Installing 1hs2TeX 2l aad Using Cabal togqnstall Ihe2TeX lt oo a ak c e ERR COn me oa Bs a PEU 3 lhs2TeX operation 4 Overview over the different styles 4 1 4 2 4 3 4 4 4 5 4 6 4 7 Verbatim verb Style o ea xo ko eR TA ME SEO RE RW Space preserving formatting with tt style Proportional vs Monospaced ocs se c cac l l em Alignment and formatting with math style Complex layouts poly style eee ni e ee me poly style is customizable ss e seme The code and neweode Styles eui ek Re eene wane Oe 5 Directives Hs ps o A POU OANA oc M M 6 Including files Bl Une a o A 7 Formatting Z1 Bormatting single tokens x sues enim temi n x m oae 72 Nested formating uos y edo dox dog E NURSE EAS queda s 7 3 Parametrized formatting directives 2 0 ane eee ee 74 No nesting with parametrized directives o o oo 7 dU uoi nr 7 6 Localformattingdirectives s risici ees Zu PUEDAS eese ee ee eas Roses e ole e cs s 7 8 Formatting behaviour
13. a how to format inlines TEX code how to format the Haskell keyword a how to format an already translated line a in one column in math style how to produce a horizontal skip of a units how to produce horizontal space of the width of the already translated texta how to format an already translated line a in three columns in math style how to format a column starting at label b ending at label e containing the already translated code a in poly style how to define a column of label n with already processed format string a in poly style the format string to use for a centered column the format string to use for a left aligned column the format string to use for the dummy column a column that does not contain any code needed due to deficiencies of the polytable imple mentation how to produce an indentation horizontal space of n units Table 3 A short description of the Zsubst directives 36 Because 1hs2TeX identifies both the beginning and end of inline code or inline ver batim via the same character one missing delimiter can confuse 1hs2TeX and cause large passages to be typeset in the wrong way You should locate the first position in the document where something goes wrong and look for a missing delimiter at the corresponding position in the source file ATEX complains about a nested fromto in poly style This usually is a prob lem with one of your formatting directives If you start a TEX group in on
14. a yi a i l And its output ai Aj 0 0 let where Ux 1 y 2 Uy yz 0 1 4 7 8 Formatting behaviour in different styles Formatting directives are applied in math poly and newcode styles In tt style only non parametrized directives apply In verb and code styles formatting directives are ignored A document can be prepared for processing in different styles using conditionals cf Section 10 8 Alignment in poly style The second important feature of 1hs2TeX next to the ability to change the appearance of tokens is the possibility to maintain alignment in the code while using a propor tional font Use of this feature is relatively simple Alignment is computed per code block All tokens that start on the same column and are preceded by at least 2 spaces are horizontally aligned in the output Using these simple rules almost everything is possible but it is very important to verify the results and watch out for accidental alignments i e tokens that get aligned against intention 19 8 1 An example The following example shows some of the potential This is the input gt rep_alg NN gt Wm gt Leaf m gt lfun rfun gt Nn gt let lt lfun m gt rt rfun m gt in Bin rt gt gt replace_min t cata_Tree rep_alg t cata_Tree min_alg t Look at the highlighted grey tokens The 1t will not appear aligned with the two equality symbols because it is preced
15. ame strings that one can use to format a column in a tabular environment using the IATEX array 4 package Table 2 has a short and not necessarily complete overview TODO ADD EXAMPLE 8 8 Saving and restoring column information It is possible to share alignment information between different code blocks This can be desirable especially when one wants to interleave the definition of a single func tion with longer comments This feature is implemented on the TEX level the com mands are defined in the Ihs2TEX prelude 24 1 left align column c center column r right align column p dimen make column of fixed width dimen tex can be used before or after the letter specifying alignment to suppress inter column space and typeset fex instead note that this is usually achieved using just one but as 1hs2TeX interprets the it must be es caped gt tex can be used before the letter specifying the alignment to insert fex di rectly in front of the entry of the column lt tex can be used after the letter specifying the alignment to insert tex directly after the entry of the column Table 2 Column specifiers for aligncolumn Here is an example of its use savecolumns begin code intersperse a gt a gt a intersperse _ 1 O intersperse _ x x end code The only really interesting case is the one for lists containing at least two elements restorecolumns begin code
16. an be selectively included in documents in future versions of 1hs2TeX 27 11 Typesetting code beyond Haskell 11 1 Spacing There is no full Haskell parser in 1hs2TeX Instead the input code is only lexed and subsequently parsed by an extremely simplified parser The main purpose of the parser is to allow a simple heuristic where to insert spaces into the output while in math or poly style The disadvantage is that in rare cases this default spacing produces unsatisfying results However there is also a big advantage dialects of Haskell can be processed by lhs2TeX too In theory even completely different languages can be handled The more difference between Haskell and the actual input language the more tweaking is probably necessary to get the desired result An easy trick to modify the behaviour of 1hs2TeX is to insert dummy operators that do not directly correspond to constructs in the input language but rather provide hints to 1hs2TeX on how to format something For instance spacing can be guided completely by the following two formatting directives format format Use everywhere where no space is desired but the automatic spacing of 1hs2TeX would usually place one Conversely use everywhere where a space is desired but 1hs2TeX does usually not place one As described in Section 10 one can use conditionals to format such annotated input code in both poly or math and newcode style to generate bo
17. b c ptest a b c Note that in this example a special purpose operator is used to facilitate the in sertion of spaces on the right hand side of a formatting directive Read more about influencing spacing using formatting directives in Section 11 1 Another example in volving parentheses the input format eval a llbracket a rrbracket begin code size eval 2 2 end code format eval a llbracket a rrbracket begin code size eval 2 2 end code results in size 2 2 size 2 2 7 6 Local formatting directives Usually formatting directives scope over the rest of the input If that is not desired formatting directives can be placed into groups Groups look as follows ht Formatting directives that are defined in a group scope only over the rest of the current group Groups can be nested Groups in 1hs2TeX do not interact with TEX groups so these different kinds of groups do not have to occur properly nested The effect of groups is made visible by the example input 17 In the beginning one par format one mathsf 1 Before the group one par t format one mathsf fone Inside the group one par l After the group lonel which appears as follows In the beginning one Before the group 1 Inside the group one After the group 1 7 7 Implicit formatting The third syntactic form of the formatting directive lacking
18. command plus mathbin If you are not satisfied with any of the default definitions just redefine them A format directive scopes over the rest of the input and if multiple directives for the same token are defined the last one is used Thus after format mathbin mathbf format undefined Varid undefined format not n n ou you get undefined and respectively Note that Varid is a macro defined in the Ihs2TEX prelude that can be used to typeset identifier names It is predefined to be the same as mathit but can be changed Do not use identifier names in TEX replacements directly For instance THE FOLLOWING IS BAD format undefined undefined will cause undefined to be typeset as undefined which looks by far less nice than undefined It is also possible to define a symbol for infix uses of a function The file lhs2TeX fmt contains format elem Nin This causes 2 elem 1 2 to be typeset as 2 1 2 whereas elem 2 1 2 will still be typeset as elem 2 1 2 14 7 2 Nested formatting The right hand sides of formatting directives are not restricted to TEX strings They can in fact be sequences of such strings or other tokens separated by space Such other tokens will be replaced by their formatting again For example if you have already defined a specific formatting format leadsto then you can later reuse that fo
19. d in a typewriter font using some special symbols to beautify some Haskell operators all spaces in code blocks are preserved plain text is copied unchanged 4 3 Proportional vs Monospaced Usually there is a tradeoff between restricting oneself to the use of a typewriter font and not using any formatting and using a proportional font at the same time replac ing operators with mathematical symbols using different font shapes to highlight keywords etc While the latter offers far more flexibility the proportional font might destroy at least part of the layout that the programmer has employed in order to make the source code more readable Compare for example the previous two examples with the following result this is a negative example 1hs2TeX can do far better than that zip a gt b a b zip zipWith Aa b a b zipWith a gt b c gt a b gt c zipWith z a as b bs 2 zab zipWith z as bs zipWith ___ partition a Bool a a a partition p xs foldr select xs where select x ts fs p x x ts fs otherwise ts x fs While the indentation is kept otherwise for the layout sensitive Haskell it would be even disastrous because the code might no longer be valid alignment that has been present in the code lines has been lost For example in the input the user had decided to align all equality symbols of all three function definit
20. e fmt should be included using include directly or indirectly in every file to be processed by lhs2TeX include lhs2TeX fmt It is perfectly possible to design own libraries that replace or extend these basic files and to include those own libraries instead It is not recommended though to edit these two files directly If you are not satisfied with some of the default definitions create your own file to redefine selected parts This way if lhs2TeX is updated you will still be able to benefit from improvements and changes in the prelude files It is possible to use Ihs2TeX in a setup where a TEX document is split into several files and each of the files should be processed separately by 1hs2TeX In this case just include 1hs2TeX fmt or polycode fmt in every single file source file WARNING Note that both 1hs2TeX fmt and polycode fmt contain 1hs2TeX directives and therefore cannot be included using TEX or ITpX include mechanisms such as input or usepackage 7 Formatting Using the format directive tokens can be given a different appearance The com plete syntax that is supported by 1hs2TeX is quite complex but we will look at many different cases in detail format token fmttoken format single tokens format lhs fmttoken parametrized formatting format name implicit formatting Ihs name arg name arg name varname conname arg varname C varna
21. e is an aligned token in the previous line at the same column so everything is normal The two highlighted parentheses are aligned causing the second line to be effectively indented unionBy a gt a Bool gt a a a unionBy eq xs ys xs foldl flip deleteBy eq nubBy eq ys The next example demonstrates the second case It is the same example with one space before the two previously aligned parentheses removed unionBy a gt a gt Bool gt a gt a gt a unionBy eq xs ys xs foldl flip deleteBy eq nubBy eq ys Here there is no aligned token in the previous line at the same column Therefore the third line is indented with respect to the first aligned token in the previous line to the left of that column which in this case happens to be the xs unionBy a a Bool a a a unionBy eq xs ys xs foldl flip deleteBy eq nubBy eq ys Sometimes this behaviour might not match the intention of the user especially in cases as above where there really starts a token at the same position in the previous line but is not preceded by enough spaces Always verify the output if the result looks as desired The amount of space that is inserted can be modified A call to the TEX control sequence hsindent is inserted at the appropriate position in the output which gets as argument the column difference in the source between the token that is indented and the base t
22. e of your directives but do not close it then this error arises You should not write such unbal anced formatting directives unless you make sure that they do never span an aligned column References 1 Andres L h The polytable package http ctan org tex archive macros latex contrib polytable 2 Alan Jeffrey The lazylist package http ctan org tex archive macros latex contrib lazylist 3 Arthur Baars S Doaitse Swierstra Andres L h The UU AG System User Manual http www cs uu nl arthurb data AG AGman pdf 4 Frank Mittelbach and David Carlisle The array package http www ctan org tex archive macros latex required tools array dtx 5 Andres L h Exploring Generic Haskell PhD Thesis Utrecht University 2004 37
23. ed by only one space Similarly the m in the first line after the Leaf constructor will not be aligned with the declarations and the body of the let statement because it is preceded by only one space Note furthermore that the equality symbols for the main functions rep_alg and replace_min are sur rounded by two spaces on both sides also on the right This causes the comma and the closing parenthesis to be aligned correctly Indeed the output looks as follows rep alg Az Am Leaf m Mfun rfun Am let It Ifun m rt rfun m in Bin It rt replace min t cata Tree rep alg t cata Tree min_alg t 8 2 Accidental alignment The main danger of the alignment heuristic is that it results in more alignments than are intended The following example input contains such a case format Mhd gt options String gt Class String gt options foldr D 0 0 gt where ds s as Dir Align S ds as gt ds as Dir Include s ds as gt ds as Dir Let S ds as gt ds as ds s as The grey tokens will be unintentionally aligned because they start on the same col umn with two or more preceding spaces each The output looks as follows options String Class String options foldr lt where align lt ds s as Dir Align s ds as i s ds as Dir Include s ds as 1 s ds as DirLet s ds as s l
24. erbatim and code blocks are all typeset completely verba tim using a typewriter font all spaces in code blocks are preserved plain text is copied unchanged 4 2 Space preserving formatting with tt style The tt style is very similar to verb style but applies a tiny bit of formatting to the code and allows for more customizabilty zip a gt b gt a b zip zipWith Aa b gt a b zipWith a9b2c gt al gt b 1 gt c zipWith z a as b bs z a b zipWith z as bs zipWith _ _ E partition a gt Bool gt a gt C al Lal partition p xs foldr select xs where select x ts fs p x x ts fs otherwise ts x fs By default some of the Haskell symbols are expressed more naturally For instance special symbols are being used for the arrows or the lambda In addition the user can specify additional formatting directives to affect the appearance of certain identifiers In this way keywords can be highlighted user defined Haskell infix operators can be replaced by more appropriate symbols etc In this style the layout and all spaces from the source file are still preserved and a non proportional font is used as in verb style Typewriter summary non recursive formatting directives are obeyed conditionals and includes are handled inline verbatim is typeset as verbatim whereas inline code and code blocks are typeset almost verbatim after formatting directives are applie
25. ers 35 thinspace space newline verbnl blankline dummy Spaces 4 speciala verba verbatima inlinea code a conida varida consym q varsyma backquoted a numeral a chara string a comment 4 nesteda pragma a texa keyword a columni a hskipa phantom a column3 a fromtobea column n a centered left dummycol indent n how to produce a small quantity of horizontal space how to produce a normal horizontal space how to produce a new line inside a code block how to produce a new line in 1hs2TeX generated verbatim how to translate a blank line in a code block how to display a missing argument in a formatted function how to format the whitespace contained in a how to format the special character a how to format the already translated inline verbatim text a how to format an already translated verbatim block a how to format already translated inline code a how to format an already translated code block a how to format an identifier starting with an upper case character a how to format an identifier starting with a lower case character a how to format a constructor symbol a how to format a variable symbol a how to format a backquoted operator a how to format a numeral a how to format a character literal a how to format a literal string a how to format an already translated one line comment a how to format an already translated nested comment a how to format an already translated compiler pragma
26. in different styles 8 Alignment in poly style 51 Anexample ieee bs bees theese RSA eee ES 9 des BO dicedentalalpnmeliE o ss db ed a SE Res Bo Thetullstory uou thea boda y som e Ree e OR es 84 Indestalonuan poly Style esie ook a orm 85 Interaction between alignment and indentation 8 6 Interaction between alignment and formatting 8 7 Centered and right aligned columns o o ooo ooo 8 8 Saving and restoring column information 9 Defining variables 9 1 Predefined variables eee 10 Conditionals 10 1 Uses ar conditionals e ome Rok RU RR Or exe mk Gee ae 11 Typesetting code beyond Haskell ILI Space oo wee on Ge EE ete RO e ec OE es ped cy co che he O 153 AGcOdePpXAQple 4 oe Pech eee Lad PERSE EAS OG eS 11 4 Generic Haskell example cte tcea aa e ees 115 Calculation example cms ker eem eem ege me Eee x 12 Calling hugs or ghci 121 Callinpphcei example ume Ue Bae REESE E xus 122 Calling bugs example 2r ee ae POR ES 123 Tsing a preprocessor eode ey cedem A xus o ey Re 13 Advanced customization 14 Pitfalls FAQ 1 About 1hs2TeX The program 1hs2TeX is a preprocessor that takes as input a literate Haskell source file or something sufficiently alike and produces as output a formatted file that can be further processed by BIFX For example consider the following input file documentclassf article include polycode f
27. ine Zinclude polycode fmt to the preamble of your document BTEX complains when using 1hs2TeX in poly style with the jfp class Add the line Zinclude jfpcompat fmt to the preamble of your document ETFX claims that the package polytable or lazylist cannot be found or that the version installed on your system is too old Did you install polytable sty or lazylist sty in your TEX system manually If you have absolutely no idea how to do this you may try to copy both polytable sty and lazylist sty from the 1hs2TeX distribution into your working directory Haskell strings are displayed without double quotes This is a result from using an old 1hs2TeX fmt file together with a new version of 1hs2TeX Usually this stems from the fact that there is an old version in the working directory Now Ihs2TeX maintains a search path for included files thus usually a local old copy of 1hs2TeX fmt can be removed In math style I have aligned several symbols on one column but 1hs2TeX still won t align the code block Did you set the alignment column correctly using the align directive Note also that 1hs2TeX starts counting columns beginning with 1 whereas some editors might start counting with 0 Large parts of the formatted file look completely garbled Passages are formatted as code or verbatim although they are plain text Conversely things supposed to be code or verbatim are typeset as text You probably forgot multiple or charact
28. ions and also align them with the has type operator Without support from a tool like 1hs2TeX the horizontal positions of the equality symbols in the formatted code are totally unrelated A solution to this problem is of course to put the Haskell code in a IATEX table Doing this manually though is very cumbersome and in some case still quite hard The task of the formatted styles of lhs2TeX is thus to spare the user the burden of cluttering up the code with formatting annotations Most of the time completely un annotated code can be used to achieve good results using the fonts you like while maintaining alignment information in the code 4 4 Alignment and formatting with math style In prior versions of 1hs2TeX math style was the mode to use for formatted Haskell code There is one alignment column often used to align the equality symbols of several equations Additionally indentation is handled automatically User defined formatting directives can be used to alter the formatting of identifiers operators and symbols in many places zip a gt b a b zip zipWith Aa b a b zipWith So a b c a b c zipWith z a as b bs zab zipWithz as bs zipWith _ _ _ partition a Bool gt a a a partition p xs foldr select xs where select x ts fs p x x ts fs otherwise ts x fs The example shows that there is still a loss of alignment informati
29. k that it might be useful for other purposes you are welcome to look at the documentation for polytable 1 also distributed with 1hs2TeX as polytable pdf in the polytable directory Beyond the advanced alignment options poly style has all the functionality of math style If poly style works for you you should use it poly summary all formatting directives are obeyed conditionals and includes are handled inline verbatim is typeset as verbatim whereas inline code and code blocks are typeset using a proportional font using mathematical symbols to represent many Haskell operators alignment can be flexibly specified complex layouts are possible plain text is copied unchanged 4 6 poly style is customizable The following example demonstrates that the visual appearance of poly style is in no way dictated by 1hs2TeX There are several possibilities to modify the output by means of formatting directives Here we try to mimic tt style by choosing a type writer font again and using the same symbols that are default in tt style zip a gt b gt a b zip zipWith Aa b gt a b zipWith a gt b gt c gt a gt b gt c zipWith z a as b bs z a b zipWith z as bs zipWith _ 7 partition i a gt gt a gt a a partition p xs foldr select xs where select x ts fs px x ts fs otherwise ts x fs 10 In contrast to the tt style e
30. me fmttoken text token There are three different forms of the formatting statement The first one can be used to change the appearance of most functions and operators and a few other symbols The second form is restricted to named identifiers both qualified and unqualified but no symbolic operators in turn such formatting directives can be parametrized Finally the third form provides a syntactically lightweight way of formatting certain identifiers using some heuristics But let us look at some common examples first 7 1 Formatting single tokens The most important use for format is to assign a symbol to an identifier or an oper ator The input 13 format alpha alpha begin code tan alpha sin alpha cos alpha end code produces output similar to the following tan x sin x cos a The occurrences of alpha within the Haskell code portions of the input file are re placed by the TEX command alpha and thus appear as a in the output A lot of formatting directives for frequently used identifiers or operators is already defined in the Ihs2TeX prelude For instance is formatted as undefined is formatted as 1 and not is formatted as If you look at 1hs2TeX fmt you will find the following directives that do the job format plus format undefined bot format not neg Here plus refers to a ATEX macro defined in the Ihs2TEX prelude new
31. me of the styles though Directives can occur on all non code lines and start with a the TEX comment character immediately followed by the name of the directive plus a list of potential arguments While 1hs2TeX will remove directives that it has interpreted it will simply ignore all normal TgXcomments that are no directives Therefore if a directive is accidentally misspelled no error message will be raised in general Table 1 is a complete list of the directives that Ihs2TeX knows about These direc tives will be explained in more or less detail in the following sections 6 Including files Other files can be included by 1hs2TeX This is what the include directive is for 11 include include a file format formatting directive for an identifer operator 4t begin of an 1hs2TeX group Y end of an 1hs2TeX group let set a toggle if test a condition helse second part of conditional felif else combined with if fendif end of a conditional latency tweak alignment in poly mode separation tweak alignment in poly mode align set alignment column in math mode options set options for call of external program subst primitive formatting directive file set filename Table 1 All 1hs2TeX directives include filename The specified file is searched for in the 1hs2TeX source path which can be modified using environment variables or the P command line option see also page 5 In cluded files are inserted literally at
32. mt begin document This is the famous Hello world example written in Haskell begin code main IO main putStrLn Hello world end code end document If we run the following two commands on it lhs2TeX o HelloWorld tex HelloWorld lhs pdflatex HelloWorld tex then the resulting PDF file will look similar to This is the famous Hello world example written in Haskell main IO main putStrLn Hello world The behaviour of 1hs2TeX is highly customizable For example the argument poly in the call above specifies one of several different styles Depending on the selected style 1hs2TeX can perform quite different tasks Here is a brief overview verb verbatim format code completely verbatim tt typewriter format code verbatim but allow special formatting of keywords characters some functions math mathematical formatting with basic alignment highly customizable poly mathematical formatting with mutliple alignments highly customizable supersedes math code delete all comments extract sourcecode newcode new code delete all comments extract sourcecode but allow for formatting supersedes code 2 Installing 1hs2TeX There are two possibilities to install 1hs2TeX Using Cabal Classic configure make 2 1 Using Cabal to install 1hs2TeX This requires Cabal 1 2 or later The process is then as usual runghc Setup configure runghc Setup build
33. oken In the situation of the above example the call is nsindent 12 22 The default definition in the Ihs2TEX prelude ignores the argument and inserts a fixed amount of space newcommand hsindent 1 quad Here is another example that shows indentation in action the Haskell standard function scanr1 written using only basic pattern matching scanri a gt a gt a gt a gt al scanri f xxs case xxs of X XS gt case xs of DO gt x let qs scanri f xs in case qs of q gt fxq qs And the associated output scanr1 s aa a a gt a scanrl f xxs case xxs of X Xs case xs of 0 gt x let qs scanr1 f xs in case qs of q f xq qs 8 5 Interaction between alignment and indentation In rare cases the indentation heuristic can lead to surprising results This is an exam ple format foo verylongfoo begin code test 1 foo bar 2 end code And its output test 1 verylongfoo bar 2 23 Here the large amount of space between test and 1 might be surprising However the 1 is aligned with the 2 but 2 is also indented with respect to bar so everything is according to the rules The solution is to verify if both the alignment between 1 and 2 and the indentation of the 2 are intended and to remove or add spaces accordingly 8 6 Interaction between alignment and formatting If a token at a specific column is typeset according to a formatting directi
34. on compared to the original verbatim example The three arguments of the zipWith function as well as the two guarded equations in the definition of select are not aligned At the moment math style exists mainly to maintain compatibility with old documents New features may be added to poly style only math summary all formatting directives are obeyed conditionals and includes are handled inline verbatim is typeset as verbatim whereas inline code and code blocks are typeset using a proportional font using mathematical symbols to represent many Haskell operators indentation in code blocks is preserved furthermore alignment on a single col umn is possible plain text is copied unchanged 4 5 Complex layouts poly style The poly style has been designed to lift the restrictions that math style still has Mul tiple alignments and thus complex layouts are possible zip a gt b a b zip zipWith Aa b a b zipWith abc a b c zipWith z a as b bs z a b zipWith z as bs zipWith _ _ 2 exp partition a Bool a a a partition p xs foldr select xs where select x ts fs p x x ts fs otherwise ts x fs If run in poly style 1hs2TeX produces I4TEX code that makes use of the polytable package a package that has been specifically designed to fit the needs that arise while formatting Haskell code If you are interested in the package or thin
35. rmatting while defining variants format gt x gt nen y As you can see in this definition we reuse both the current formatting for and for We now get gt for gt x but should we decide to define 4format star later we then also get Of course you can use the same mechanism for non symbolic identifiers mathbf new text text nu new wpe format new format textO format text new will cause textO to be typeset as text and text new will appear as textnew WARNING There is no check for recursion in the formatting directives Formatting directives are expanded on demand therefore a directive such as THE FOLLOWING IS BAD format text mathsf text will not produce text for text but rather cause an infinite loop in 1hs2TeX once used P P 7 3 Parametrized formatting directives Formatting directives can be parametrized The parameters may occur once or more on the right hand side This form of a formatting directive is only available for al phanumeric identifiers For example the input format abs a mathopen a mathclose format leadsto The abs function computes the absolute value of an integer begin code abs 2 gt 2 end code 15 produces output similar to The function computes the absolute value of an integer 2 2 If the function is used with too few arguments as in the text a default
36. runghc Setup install The third step requires write access to the installation location and the IATEX filename database 2 2 configure make The following instructions apply to Unix like environments However 1hs2TeX does run on Windows systems too If you would like to add installation instructions or facilitate the installation procedure for Windows systems please contact the authors Unpack the archive Assume that it has been unpacked into directory somewhere Then say cd somewhere lhs2TeX 1 14 configure make make install You might need administrator permissions to perform the make install step Al ternatively you can select your own installation location by passing the prefix argument to configure configure prefix my local programs With 1hs2TeX come a couple of library files containing basic 1hs2TeX formatting directives that need to be found by the 1hs2TeX binary The default search path is as follows HOME lhs2tex 1 14 HOME 1hs2tex HOME 1hs2TeX HOME 1hs2tex 1 14 HOME 1hs2tex HOME 1hs2TeX LHS2TEX usr local share lhs2tex 1 14 usr local share lhs2tex 1 14 usr local lib lhs2tex 1 14 usr share lhs2tex 1 14 usr lib lhs2tex 1 14 usr local share lhs2tex usr local lib lhs2tex usr share lhs2tex usr lib lhs2tex usr local share lhs2TeX usr local lib lhs2TeX usr share lhs2TeX usr lib lhs2TeX Here HOME and LHS2T
37. sed If an error occurs during evaluation 1hs2TeX will fail Variables can also be passed to 1hs2TeX from the operating system level by using the 1 or s command line options The main use of variables is in conditionals cf Section 10 At the moment there is no way to directly use the value of a variable in a format directive 9 1 Predefined variables In every run of 1hs2TeX the version of 1hs2TeX is available as a numerical value in the predefined variable version Similarly the current style is available as an integer in the predefined variable style There also are integer variables verb tt math poly code and newcode predefined that can be used to test style It is thus possible to write documents in a way that they can be processed beauti fully in different styles or to make safe use of new 1hs2TeX features by checking its version first 26 10 Conditionals Boolean expressions can be used in conditionals The syntax of an 1hs2TeX condi tional is if expression Jelif expression else Yendif where the Zelif and else directives are optional There may be arbitrarily many elif directives When an if directive is encountered the expression is evaluated and depending on the result of the evaluation of the expression only the then or only the else part of the conditional is processed by 1hs2TeX the other part is ignored 10 1 Uses of conditionals These are some of the most common uses of conditionals
38. sigma format k_ kappa format forall a forall a format si cde di format mapa map a format mapb map i b Zformat Ntimes endif begin code type Map ki ti t2 ti t2 type Map ki r gt s t1 t2 forall ai a2 Map ki r al a2 gt Map ki s ti a1 t2 a2 map ti t k_ Map ki k t t map ti Unit Unit Unit map ti Int i map ti Sum mapa mapb Inl a map ti Sum mapa mapb Inr b map ti Prod mapa mapb a b end code Inl mapa a Inr mapb b mapa a mapb b 30 Processed in poly style the output looks as follows type Map ty ta t1 gt b type Map o ol t to Vay a Mapl o a1 a2 Map e t a1 t2 a2 map t x Mapi x tt map Unit Unit Unit map Int i i map Sum map map Inl a Inl map a map Sum map map Inr b Inr map b map Prod map map a x b map a x map b 11 5 Calculation example The following example shows a calculational proof The input def commentbegin quad def commentend begin spec map 1 1 2 3 desugaring of map 1 1 2 3 definition of map 1 1 map 1 2 3 performing the addition on the head 2 map 1 2 3 recursive application of map 2 3 4 list syntactic sugar 2 3 4 end spec produces 31 map 1 1 2 3 desugaring of map 1 1 2 3
39. style in which it is called 1hs2TeX will treat these blocks in differ ent ways 4 Overview over the different styles In this section we will demonstrate on a common example how the different styles can be used For each style there will also be a short summary Some of the points listed in the summary are defaults for the particular style and can actually be changed 4 1 Verbatim verb style In verb style the code shows up in the formatted document exactly as it has been entered i e verbatim All spaces are preserved and a non proportional font is used zip a gt b gt a b zip zipWith Ma b gt a b zipWith a gt b gt c gt a gt b gt c zipWith z a as b bs z a b zipWith z as bs zipWith _ _ 2 partition a gt Bool gt a gt a Lal partition p xs foldr select xs where select x ts fs p x x ts fs otherwise ts x fs One does not need 1hs2TeX to achieve such a result This style however does not make use of an internal TEX verbatim construct The implementation of verbatim en vironments in TEX is somewhat restricted and the preprocessor approach may prove more flexible in some situations For example it is easier to apply additional for matting instructions to the output as a whole such as placing the code in a colored box Verbatim summary formatting directives are ignored conditionals and includes are handled inline code inline v
40. t ds as ds s as 20 The and the have been aligned with the declarations of the where clause This results in too much space between the two options tokens and the symbols Even worse in this case the centering of the two symbols is destroyed by the alignment cf Section 8 7 therefore and appear left aligned but not cleanly because TEX inserts a different amount of whitespace around the two symbols The solution to all this is surprisingly simple just insert extra spaces in the input to ensure that unrelated tokens start on different columns format lhd gt options String gt Class String gt options foldr D 0 0 gt where lt ds s as Dir Align S ds as gt ds as Dir Include s ds as gt ds as Dir Let S ds as ds as ds s as This input produces the correct output options String Class String options foldr lt where align lt ds s as Dir Align s ds as i s lt ds as Dir Includes ds as 7 1 s ds as Dir Let s ds as s lt ds as ds s as 8 3 The full story If you further want to customize the alignment behaviour you can Here is exactly what happens Alignment is computed per code block Per code block there are a number of alignment columns If a token starts in column 7 and is prefixed by at least separation spaces
41. th typeset document and code with annotation remove from a single source file For this to work correctly one would define if style newcode format format else format format endif Nen as an extended version of the above This instructs 1hs2TeX to ignore and replace by a single space while in newcode style and to adjust spacing in other styles as before The examples in the following subsections show these directives in use 11 2 Inline TEX Another possibility that can help to trick 1hs2TeX into doing things it normally doesn t want to is to insert inline TEX code directly into the code block by using a special form of Haskell comment 28 i tex If this construct appears in a code block then fex is inserted literally into the out put file The advantage of this construct over a dummy operator is that if the input language is indeed Haskell one does not need to sacrifice the syntactic validity of the source program for nice formatting On the other hand inline TEX tends to be more verbose than an annotation using a formatting directive 11 3 AG code example Here is an example that shows how one can typeset code of the Utrecht University At tribute Grammar UUAG 5 system which is based on Haskell but adds additional syntactic constructs The input fformat 4format format ATTR mathbf ATTR format SEM mathbf SEM format lhs mathbf lhs format
42. the current 1hs2TeX source file is not valid input to the interpreter because annotations were needed to format some Haskell extensions satisfactory The following input file makes use of Template Haskell and uses the formatting directives for both newcode and poly style The options directive in structs ghci to use 1hs2Tex itself as the literate preprocessor using the pgmL option of ghci The 1hs2TeX binary itself acts as a suitable literate preprocessor if the pre command line option is passed which is achieved using the optL pre option format SPL x x if style newcode format QU x ixi format else format QU x llbracket x rrbracket 4format MN o endif options ghci fth pgmL lhs2TeX optL pre This is a rather stupid way of computing 42 using Template Haskell gt answer SPL foldri Mx y gt QU SPL x SPL y replicate 21 QU 2 The answer is indeed eval answer This is the corresponding output This is a rather stupid way of computing 42 using Template Haskell answer foldr1 Ax y x y replicate 21 2 The answer is indeed 42 13 Advanced customization There is one directive that has not yet been described subst This directive is used by lhs2TeX to customize almost every aspect of its output The average user will and should not need to use a 4subst directive but if one wants to influence the very nature of the code generated b
43. ve then the first token of the replacement text inherits the column position of the original token The other tokens of the replacement text will never be aligned Actual arguments of parametrized formatting directives keep the column positions they have in the input 8 7 Centered and right aligned columns Under certain circumstances 1hs2TeX decides to typeset a column centered instead of left aligned This happens if the following two conditions hold There is at most one token per line that is associated with the column At least one of the tokens associated with the column is a symbol In most cases this matches the intention If it does not there still might be the possi bility to trick 1hs2TeX to do the right thing Change the alignment behaviour of the column using Naligncolumn see be low If the column is centered but should not be add extra tokens that are formatted as nothing that will be associated with the column see also Section 11 1 about spacing If the column should be centered but is left aligned it is sometimes possible to use a symbol instead of an alphanumeric identifier and add a formatting directive for that newly introduced symbol The syntax of the aligncolumn command is aligncolumn integer H column specifier The integer denotes the number i e as displayed by the editor of a column Note that 1hs2TeX starts counting columns at 1 As column specifier one can use about the s
44. xample here the spaces in the code are not preserved the alignment is generated by the polytable package 4 7 The code and newcode styles These two styles are not for producing a IATEX source file but rather produce a Haskell file again Everything that is not code is thrown away In addition newcode does a few things extra It applies formatting directives which can here be used as simple macros on the Haskell source level and it generates line pragmas for the Haskell compiler that will result in error messages pointing to the original file before pro cessing with 1hs2TeX The plain code style does not have this extra functionality Again code is mainly intended for compatibility with old documents You should use newcode code summary formatting directives are ignored conditionals and includes are handled code blocks that are not specifications are copied unchanged plain text inline code specification code and inline verbatim are discarded new code summary all formatting directives are obeyed conditionals and includes are handled code blocks that are not specifications are after applying formatting directives copied unchanged prefixed by a line pragma indicating the original source lo cation of the code block plain text inline code specification code and inline verbatim are discarded 5 Directives A number of directives are understood by 1hs2TeX Some of the are ignored in so
45. y 1hs2TexX the subst directives provide a way to do it If one would for instance want to generate output for another TEX format such as plain TEX or ConTpxt or if one would want to use a different package than polytable 34 to do the alignment on the TEX side then the subst directives are a good place to start The default definitions can be found in 1hs2TeX fmt Table 3 shows only a short description of the approximate use of each of the cate gories 14 Pitfalls FAQ The document consists of multiple files Can 1hs2TeX be used One option is to use include rather than ATEX commands to include all files in the master file The other is to process all files that contain code and the master file with lhs2TeX All files to be processed with 1hs2TeX must contain an include lhs2TeX fmt or include polycode fmt statement From version 1 11 on including 1hs2TeX sty is no longer necessary Yes but the master file should be pure ATEX Create a file mylhs2tex 1hs with just one line namely include lhs2TeX fmt Process that file with 1hs2TeX using the options you also use for the other included files Call the resulting file mylhs2tex sty and say usepackage mylhs2tex at the beginning of your master file The spacing around my code blocks is bad nonexistent in poly style Add the line hinclude polycode fmt to the preamble of your document ATEX complains when using 1hs2TeX in poly style with the beamer package Add the l
Download Pdf Manuals
Related Search
Related Contents
Hampton Bay 36LGM-L Use and Care Manual Samsung Galaxy Tab S2 (9.7) دليل المستخدم(Lollipop) BMC MyIT Next-Generation Self-Service 30 ateliers créatifs au choix cuisine mode design déco Département de Géographie et Aménagement 2001 / 2002 Tender for Electronics and Telecommunication Department for the user guide guide de l`utilisateur guía del usuario PDFファイル Operation Manual Copyright © All rights reserved.