GAP (GAPDoc) - Chapter 5: The Converters

Goto Chapter: | Top | 1 | 2 | 3 | 4 | 5 | A | B | Bib | Ind

### 5. The Converters

The GAPDoc package contains a set of programs which allow us to convert a GAPDoc book into several output versions and to make them available to GAP's online help.

Currently the following output formats are provided: text for browsing inside a terminal running GAP, LaTeX with `hyperref`-package for cross references via hyperlinks and HTML for reading with a Web-browser.

#### 5.1 Producing Documentation from Source Files

Here we explain how to use the functions which are described in more detail in the following sections. We assume that we have the main file `MyBook.xml` of a book `"MyBook"` in the directory `/my/book/path`. This contains `<#Include ...>`-statements as explained in Chapter 4.. These refer to some other files as well as pieces of text which are found in the comments of some GAP source files `../lib/a.gd` and `../lib/b.gi` (relative to the path above). A BibTeX database `MyBook.bib` for the citations is also in the directory given above. We want to produce a text-, `dvi`-, `pdf-`, postscript- and HTML-version of the document.

All the commands shown in this Section are collected in the single function `MakeGAPDocDoc` (5.1-1).

First we construct the complete XML-document as a string with `ComposedXMLString` (4.2-1). This interprets recursively the `<#Include ...>`-statements.

    gap> path := Directory("/my/book/path");;
    gap> main := "MyBook.xml";;
    gap> files := ["../lib/a.gd", "../lib/b.gi"];;
    gap> bookname := "MyBook";;
    gap> str := ComposedXMLString(path, main, files);;

Then we parse the document and store its structure in a tree-like data structure. The commands for this are `ParseTreeXMLString` (5.2-1) and `CheckAndCleanGapDocTree` (5.2-4).

    gap> r := ParseTreeXMLString(str);;
    gap> CheckAndCleanGapDocTree(r);
    true

We first produce a LaTeX version of the document. `GAPDoc2LaTeX` (5.3-1) returns a string containing the LaTeX source. The utility function `FileString` (5.6-5) writes the content of a string to a file, we choose `MyBook.tex`.

    gap> l := GAPDoc2LaTeX(r);;
    gap> FileString(Filename(path, Concatenation(bookname, ".tex")), l);

Assuming that you have a sufficiently good installation of TeX available (see `GAPDoc2LaTeX` (5.3-1) for details) this can be processed with a series of commands like in the following example.

    cd /my/book/path
    latex MyBook
    bibtex MyBook
    latex MyBook
    makeindex MyBook
    latex MyBook
    mv MyBook.dvi manual.dvi
    dvips -o manual.ps manual.dvi
    rm MyBook.aux
    pdflatex MyBook
    pdflatex MyBook
    mv MyBook.pdf manual.pdf

After this we have a `dvi`-, `pdf`- and postscript version of the document in the files `manual.dvi`, `manual.pdf` and `manual.ps`. The first two versions contain hyperlink information which can be used with appropriate browsers for convenient reading of the document on screen (e.g., current versions of `xdvi`, respectively `xpdf` or `acroread`.

Furthermore we have produced a file `MyBook.pnr` which is GAP-readable and contains the page number information for each (sub-)section of the document. We will use this later.

Next we produce a text version which can be read in a terminal (window). The command is `GAPDoc2Text` (5.3-2). This produces a record with the actual text and some additional information. The text can be written chapter wise into files with `GAPDoc2TextPrintTextFiles` (5.3-3). The names of these files are `chap0.txt`, `chap1.txt` and so on. The text contains some color markup using ANSI escape sequences. One can use this with a terminal which interprets these sequences appropriately after setting the GAP variable `ANSI_COLORS` to `true`. For the bibliography we have to tell `GAPDoc2Text` (5.3-2) the location of the BibTeX database by specifying a `path` as second argument.

    gap> t := GAPDoc2Text(r, path);;
    gap> GAPDoc2TextPrintTextFiles(t, path);

This command constructs all parts of the document including table of contents, bibliography and index. The functions `FormatParagraph` (5.5-3) for formatting text paragraphs and `ParseBibFiles` (5.4-1) for reading BibTeX files with GAP may be of independent interest.

With the text version we have also produced the information which is used for searching with GAP's online help. We can add the page number information from the LaTeX version of the document and then print a `manual.six` file which is read by GAP when the document is loaded. This is done with `AddPageNumbersToSix` (5.3-4) and `PrintSixFile` (5.3-5).

    gap> AddPageNumbersToSix(r, Filename(path, "MyBook.pnr"));
    gap> PrintSixFile(Filename(path, "manual.six"), r, bookname);

Finally we produce an HTML version of the document and write it (chapter-wise) into files `chap0.html`, `chap1.html` and so on. They can be read with any Web-browser. The commands are `GAPDoc2HTML` (5.3-6) and `GAPDoc2HTMLPrintHTMLFiles` (5.3-7). We also add a link from `manual.html` to `chap0.html`. You may also add a file `manual.css`, see `GAPDoc2HTMLPrintHTMLFiles` (5.3-7) for more details. The argument `path` of `GAPDoc2HTML` (5.3-6) specifies the directory containing the BibTeX database files.

    gap> h := GAPDoc2HTML(r, path);;
    gap> GAPDoc2HTMLPrintHTMLFiles(h, path);

##### 5.1-1 MakeGAPDocDoc

`> MakeGAPDocDoc`( path, main, files, bookname[, gaproot] ) | ( function )

This function collects all the commands for producing a `dvi`-, `pdf`-, postscript-, text- and HTML-version of a GAPDoc document as described in Section 5.1.

Note: If this function works for you depends on your operating system and installed software. It will probably work on most `UNIX` systems with a standard LaTeX installation. If the function doesn't work for you look at the source code and adjust it to your system.

Here path must be the directory (as string or directory object) containing the main file main of the document (given with or without the `.xml` extension. The argument files is a list of (probably source code) files relative to path which contain pieces of documentation which must be included in the document, see Chapter 4.. And bookname is the name of the book used by GAP's online help. The optional argument gaproot must be a string which gives the relative path from path to the GAP root directory. If this is given, the HTML files are produced with relative paths to external books.

Experimental: `MakeGAPDocDoc` can be called with additional arguments `"Tth"` and/or `"MathML"`. If these are given additional variants of the HTML conversion are called, see `GAPDoc2HTML` (5.3-6) for details.

#### 5.2 Parsing XML Documents

Arbitrary well-formed XML documents can be parsed and browsed by the following functions.

##### 5.2-1 ParseTreeXMLString

`> ParseTreeXMLString`( str ) | ( function )

Returns: a record which is root of a tree structure

This function parses an XML-document stored in string str and returns the document in form of a tree.

A node in this tree corresponds to an XML element, or to some parsed character data. In the first case it looks as follows:

    rec( name := "Book",
         attributes := rec( Name := "EDIM" ),
         content := [ ... list of nodes for content ...],
         start := 312,
         stop := 15610,
         next := 15611     )

This means that `str{[312..15610]}` looks like `<Book Name="EDIM"> ... content ... </Book>`.

The leaves of the tree encode parsed character data as in the following example:

    rec( name := "PCDATA",
         content := "text without markup "     )

This function checks whether the XML document is well formed, see 2.1-13 for an explanation. If an error in the XML structure is found, a break loop is entered and the text around the position where the problem starts is shown. With `Show();` one can browse the original input in the `Pager` (Reference: Pager), starting with the line where the error occurred. All entities are resolved when they are either entities defined in the GAPDoc package (in particular the standard XML entities) or if their definition is included in the `<!DOCTYPE ..>` tag of the document.

Note that `ParseTreeXMLString` does not parse and interpret the corresponding document type definition (the `.dtd`-file given in the `<!DOCTYPE ..>` tag). Hence it also does not check the validity of the document (i.e., it is no validating XML parser).

If you are using this function to parse a GAPDoc document you can use `CheckAndCleanGapDocTree` (5.2-4) for some validation and additional checking of the document structure.

##### 5.2-2 DisplayXMLStructure

`> DisplayXMLStructure`( tree ) | ( function )

This utility displays the tree structure of an XML document as it is returned by `ParseTreeXMLString` (5.2-1) (without the `PCDATA` leaves).

Since this is usually quite long the result is shown using the `Pager` (Reference: Pager).

##### 5.2-3 ApplyToNodesParseTree

`> ApplyToNodesParseTree`( tree, fun ) | ( function )

`> AddRootParseTree`( tree ) | ( function )

`> RemoveRootParseTree`( tree ) | ( function )

The function `ApplyToNodesParseTree` applies a function fun to all nodes of the parse tree tree of an XML document returned by `ParseTreeXMLString` (5.2-1).

The function `AddRootParseTree` is an application of this. It adds to all nodes a component `.root` to which the top node tree tree is assigned. These components can be removed afterwards with `RemoveRootParseTree`.

And here are utilities for processing GAPDoc XML documents.

##### 5.2-4 CheckAndCleanGapDocTree

`> CheckAndCleanGapDocTree`( tree ) | ( function )

Returns: nothing

The argument tree of this function is a parse tree from `ParseTreeXMLString` (5.2-1) of some GAPDoc document. This function does an (incomplete) validity check of the document according to the document type declaration in `gapdoc.dtd`. It also does some additional checks which cannot be described in the DTD (like checking whether chapters and sections have a heading). For elements with element content the whitespace between these elements is removed.

In case of an error the break loop is entered and the position of the error in the original XML document is printed. With `Show();` one can browse the original input in the `Pager` (Reference: Pager).

##### 5.2-5 AddParagraphNumbersGapDocTree

`> AddParagraphNumbersGapDocTree`( tree ) | ( function )

Returns: nothing

The argument tree must be an XML tree returned by `ParseTreeXMLString` (5.2-1) applied to a GAPDoc document. This function adds to each node of the tree a component `.count` which is of form `[Chapter[, Section[, Subsection, Paragraph] ] ]`. Here the first three numbers should be the same as produced by the LaTeX version of the document. Text before the first chapter is counted as chapter `0` and similarly for sections and subsections. Some elements are always considered to start a new paragraph.

#### 5.3 The Converters

Here are more details about the conversion programs for GAPDoc XML documents.

##### 5.3-1 GAPDoc2LaTeX

`> GAPDoc2LaTeX`( tree ) | ( function )

Returns: LaTeX document as string

The argument tree for this function is a tree describing a GAPDoc XML document as returned by `ParseTreeXMLString` (5.2-1) (probably also checked with `CheckAndCleanGapDocTree` (5.2-4)). The output is a string containing a version of the document which can be written to a file and processed with LaTeX or pdfLaTeX (and probably BibTeX and `makeindex`).

The output uses the `report` document class and needs the following LaTeX packages: `a4wide`, `amssymb`, `isolatin1`, `makeidx`, `color`, `fancyvrb`, `pslatex` and `hyperref`. These are for example provided by the teTeX-1.0 distribution of TeX (which in turn is used for most TeX packages of current Linux distributions); see http://www.tug.org/tetex/.

In particular, the resulting `dvi`- or `pdf`-output contains (internal and external) hyperlinks which can be very useful for online browsing of the document.

The LaTeX processing also produces a file with extension `.pnr` which is GAP readable and contains the page numbers for all (sub)sections of the document. This can be used by GAP's online help; see `AddPageNumbersToSix` (5.3-4). There is support for two types or XML processing instructions which allow to change the options used for the document class or to add some extra lines to the preamble of the LaTeX document. They can be specified as in the following examples:

    <?LaTeX Options="12pt"?>
    <?LaTeX ExtraPreamble="\usepackage{blabla}
    \newcommand{\bla}{blabla}
    "?>

A hint for large documents: In many TeX installations one can easily reach some memory limitations with documents which contain many (cross-)references. In teTeX you can look for a file `texmf.cnf` which allows to enlarge certain memory sizes.

This function works by running recursively through the document tree and calling a handler function for each GAPDoc XML element. These handler functions are all quite easy to understand (the greatest complications are some commands for index entries, labels or the output of page number information). So it should be easy to adjust layout details to your own taste by slight modifications of the program.

##### 5.3-2 GAPDoc2Text

`> GAPDoc2Text`( tree[, bibpath][,][width] ) | ( function )

Returns: record containing text files as strings and other information

The argument tree for this function is a tree describing a GAPDoc XML document as returned by `ParseTreeXMLString` (5.2-1) (probably also checked with `CheckAndCleanGapDocTree` (5.2-4)). This function produces a text version of the document which can be used with GAP's online help (with the `"screen"` viewer, see `SetHelpViewer` (Reference: SetHelpViewer)). It includes title page, bibliography and index. The bibliography is made from BibTeX databases. Their location must be given with the argument bibpath (as string or directory object).

The output is a record with one component for each chapter (with names `"0"`, `"1"`, ..., `"Bib"` and `"Ind"`). Each such component is again a record with the following components:

`text`

  the text of the whole chapter as a string

`ssnr`

  list of subsection numbers in this chapter (like `[3, 2, 1]` for chapter 3, section 2, subsection 1)

`linenr`

  corresponding list of line numbers where the subsections start

`len`

  number of lines of this chapter

The result can be written into files with the command `GAPDoc2TextPrintTextFiles` (5.3-3).

As a side effect this function also produces the `manual.six` information which is used for searching in GAP's online help. This is stored in `tree.six` and can be printed into a `manual.six` file with `PrintSixFile` (5.3-5) (preferably after producing a LaTeX version of the document as well and adding the page number information to `tree.six`, see `GAPDoc2LaTeX` (5.3-1) and `AddPageNumbersToSix` (5.3-4)).

The text produced by this function contains color markup via ANSI escape sequences, see `TextAttr` (5.5-2). To view the colored text you need a terminal which interprets these escape sequences correctly and you have to set the variable `ANSI_COLORS` to `true` (a good place for doing this is your `.gaprc` file).

With the optional argument width a different length of the output text lines can be chosen. The default is 76 and all lines in the resulting text start with two spaces. This looks good on a terminal with a standard width of 80 characters and you probably don't want to use this argument.

##### 5.3-3 GAPDoc2TextPrintTextFiles

`> GAPDoc2TextPrintTextFiles`( t[, path] ) | ( function )

Returns: nothing

The first argument must be a result returned by `GAPDoc2Text` (5.3-2). The second argument is a path for the files to write, it can be given as string or directory object. The text of each chapter is written into a separate file with name `chap0.txt`, `chap1.txt`, ..., `chapBib.txt`, and `chapInd.txt`.

If you want to make your document accessible via the GAP online help you must put at least these files for the text version into a directory and use the name of this directory as an argument for one of the commands `DeclarePackageDocumentation` (Reference: DeclarePackageDocumentation) or `DeclarePackageAutoDocumentation` (Reference: DeclarePackageAutoDocumentation). Furthermore you need to put the file `manual.six` into this directory, see `PrintSixFile` (5.3-5).

Optionally you can add the `dvi`- and `pdf`-versions of the document which are produced with `GAPDoc2LaTeX` (5.3-1) to this directory. The files must have the names `manual.dvi` and `manual.pdf`, respectively. Also you can add the files of the HTML version produced with `GAPDoc2HTML` (5.3-6) to this directory, see `GAPDoc2HTMLPrintHTMLFiles` (5.3-7). The handler functions in GAP for this help format detect automatically which of the optional formats of a book are actually available.

##### 5.3-4 AddPageNumbersToSix

`> AddPageNumbersToSix`( tree, pnrfile ) | ( function )

Returns: nothing

Here tree must be the XML tree of a GAPDoc document, returned by `ParseTreeXMLString` (5.2-1). Running `latex` on the result of `GAPDoc2LaTeX` (5.3-1)`(tree)` produces a file pnrfile (with extension `.pnr`). The command `GAPDoc2Text` (5.3-2)`(tree)` creates a component `tree.six` which contains all information about the document for the GAP online help, except the page numbers in the `.dvi, .ps, .pdf` versions of the document. This command adds the missing page number information to `tree.six`.

##### 5.3-5 PrintSixFile

`> PrintSixFile`( tree, bookname, fname ) | ( function )

Returns: nothing

This function prints the `.six` file fname for a GAPDoc document stored in tree with name bookname. Such a file contains all information about the book which is needed by the GAP online help. This information must first be created by calls of `GAPDoc2Text` (5.3-2) and `AddPageNumbersToSix` (5.3-4).

##### 5.3-6 GAPDoc2HTML

`> GAPDoc2HTML`( tree[, bibpath[, gaproot]][,][mtrans] ) | ( function )

Returns: record containing HTML files as strings and other information

The argument tree for this function is a tree describing a GAPDoc XML document as returned by `ParseTreeXMLString` (5.2-1) (probably also checked with `CheckAndCleanGapDocTree` (5.2-4)). Without an mtrans argument this function produces an HTML version of the document which can be read with any Web-browser and also be used with GAP's online help (see `SetHelpViewer` (Reference: SetHelpViewer)). It includes title page, bibliography, and index. The bibliography is made from BibTeX databases. Their location must be given with the argument bibpath (as string or directory object, if not given the current directory is used). If the third argument gaproot is given and is a string then this string is interpreted as relative path to GAP's root directory. Reference-URLs to external HTML-books which begin with the GAP root path are then rewritten to start with the given relative path. This makes the HTML-documentation portable provided a package is installed in some standard location below the GAP root.

The output is a record with one component for each chapter (with names `"0"`, `"1"`, ..., `"Bib"`, and `"Ind"`). Each such component is again a record with the following components:

`text`

  the text of an HTML file containing the whole chapter (as a string)

`ssnr`

  list of subsection numbers in this chapter (like `[3, 2, 1]` for chapter 3, section 2, subsection 1)

Standard output format without mtrans argument

The HTML code produced with this converter conforms to the W3C specification "XHTML 1.0 strict", see http://www.w3.org/TR/xhtml1. First, this means that the HTML files are valid XML files. Secondly, the extension "strict" says in particular that the code doesn't contain any explicit font or color information.

Mathematical formulae are handled as in the text converter `GAPDoc2Text` (5.3-2). We don't want to assume that the browser can use symbol fonts. Some GAP users like to browse the online help with `lynx`, see `SetHelpViewer` (Reference: SetHelpViewer), which runs inside the same terminal windows as GAP.

Using a stylesheet file

The layout information for a browser should be specified in a cascading style sheet (CSS) file. The GAPDoc package contains an example of such a style sheet, see the file `gapdoc.css` in the root directory of the package. This file conforms to the W3C specification CSS 2.0, see http://www.w3.org/TR/REC-CSS2. You may just copy that file as `manual.css` into the directory which contains the HTML version of your documentation. But, of course, you are free to adjust it for your package, e.g., change colors or other layout details, add a background image, ... Each of the HTML files produced by the converters contains a link to this local style sheet file called `manual.css`.

Output format with mtrans argument

Currently, there are two experimental variants of this converter available which handle mathematical formulae differently. They are accessed via the optional last mtrans argument.

If this argument is set to `"Tth"` it is assumed that you have installed the LaTeX to HTML translation program `tth`. This is used to translate the contents of the `M`, `Math` and `Display` elements into HTML code. Note that the resulting code is not compliant with any standard. Formally it is "XHTML 1.0 Transitional", it contains explicit font specifications and the characters of mathematical symbols are included via their position in a "Symbol" font. Some graphical browsers can be configured to display this in a useful manner, check the Tth homepage for more details.

If the mtrans argument is set to `"MathML"` it is assumed that you have installed the translation program `ttm`, see also the Tth homepage). This is used to translate the contents of the `M`, `Math` and `Display` elements to MathML 2.0 markup. The resulting files should conform to the "XHTML 1.1 plus MathML 2.0" standard, see the W3C information for more details. It is expected that the next generation of graphical browsers will be able to render such files (try for example `Mozilla`, at least 0.9.9). You must copy the `.xsl` and `.css` files from GAPDocs `mathml` directory to the directory containing the output files. The translation with `ttm` is still experimental. The output of this converter variant is garbage for browsers which don't support MathML.

The result of this converter can be written to files with the command `GAPDoc2HTMLPrintHTMLFiles` (5.3-7).

##### 5.3-7 GAPDoc2HTMLPrintHTMLFiles

`> GAPDoc2HTMLPrintHTMLFiles`( t[, path] ) | ( function )

Returns: nothing

The first argument must be a result returned by `GAPDoc2HTML` (5.3-6). The second argument is a path for the files to write, it can be given as string or directory object. The text of each chapter is written into a separate file with name `chap0.html`, `chap1.html`, ..., `chapBib.html`, and `chapInd.html`.

The experimental versions which are produced with `tth` or `ttm` use different names for the files, namely `chap0_sym.html`, and so on for files which need symbol fonts and `chap0_mml.xml` for files with MathML translations.

You can make these files accessible via the GAP online help by putting them into a directory and using this as an argument for one of the commands `DeclarePackageDocumentation` (Reference: DeclarePackageDocumentation) or `DeclarePackageAutoDocumentation` (Reference: DeclarePackageAutoDocumentation). You may also want to put a file `manual.css` into that directory, see `GAPDoc2HTML` (5.3-6).

#### 5.4 Parsing BibTeX Files

Here are functions for parsing, normalizing and printing reference lists in BibTeX format. The reference describing this format is [L85, Appendix B].

##### 5.4-1 ParseBibFiles

`> ParseBibFiles`( bibfile ) | ( function )

Returns: list `[list of bib-records, list of abbrevs, list of expansions]`

This function parses a file bibfile (if this file does not exist the extension `.bib` is appended) in BibTeX format and returns a list as follows: `[entries, strings, texts]`. Here `entries` is a list of records, one record for each reference contained in bibfile. Then `strings` is a list of abbreviations defined by `@string`-entries in bibfile and `texts` is a list which contains in the corresponding position the full text for such an abbreviation.

The records in `entries` store key-value pairs of a BibTeX reference in the form `rec(key1 = value1, ...)`. The names of the keys are converted to lower case. The type of the reference (i.e., book, article, ...) and the citation key are stored as components `.Type` and `.Label`.

As an example consider the following BibTeX file.

    @string{ j  = "Important Journal" }
    @article{ AB2000, Author=  "Fritz A. First and Sec, X. Y.",
    TITLE="Short", journal = j, year = 2000 }

    gap> bib := ParseBibFiles("my.bib");
    [ [ rec( Type := "article", Label := "AB2000",
              author := "Fritz A. First and Sec, X. Y.", title := "Short",
              journal := "Important Journal", year := "2000" ) ],
      [ "j" ],
      [ "Important Journal" ] ]

##### 5.4-2 NormalizeNameAndKey

`> NormalizeNameAndKey`( r ) | ( function )

Returns: nothing

This function normalizes in a record describing a BibTeX reference (see `ParseBibFiles` (5.4-1)) the `author` and editor fields using the description in [L85, Appendix B 1.2]. The original entries are stored in `.authororig` and `.editororig`.

Furthermore a short and a long citation key is generated.

We continue the example from `ParseBibFiles` (5.4-1).

    gap> NormalizeNameAndKey(bib[1][1]);
    gap> bib[1][1];
    rec( Type := "article", Label := "AB2000",
      author := "First, F. A. and Sec, X. Y. ", title := "Short",
      journal := "Important Journal", year := "2000",
      authororig := "Fritz A. First and Sec, X. Y.", key := "FS00",
      keylong := "firstsec2000" )

##### 5.4-3 WriteBibFile

`> WriteBibFile`( bibfile, bib ) | ( function )

Returns: nothing

This is the converse of `ParseBibFiles` (5.4-1). Here bib must have a format as it is returned by `ParseBibFiles` (5.4-1). A BibTeX file bibfile is written and the entries are formatted in a uniform way. All given abbreviations are used while writing this file.

We continue the example from `NormalizeNameAndKey` (5.4-2). The command

    gap> WriteBibFile("nicer.bib", bib);

produces a file `nicer.bib` as follows:

    @string{j = "Important Journal" }

    @article{ AB2000,
      author =           {First, F. A. and Sec, X. Y.},
      title =            {Short},
      journal =          j,
      year =             {2000},
      key =              {FS00},
      authororig =       {Fritz A. First and Sec, X. Y.},
      keylong =          {firstsec2000}
    }

#### 5.5 Text Utilities

This section describes some utility functions for handling texts within GAP. They are used by the functions in the GAPDoc package but may be useful for other purposes as well. We start with some variables containing useful strings and go on with functions for parsing and reformatting text.

##### 5.5-1 WHITESPACE

`> WHITESPACE` | ( global variable )

`> CAPITALLETTERS` | ( global variable )

`> SMALLLETTERS` | ( global variable )

`> LETTERS` | ( global variable )

`> DIGITS` | ( global variable )

`> HEXDIGITS` | ( global variable )

These variables contain sets of characters which are useful for text processing. They are defined as follows.

WHITESPACE

  `" \n\t\r"`

CAPITALLETTERS

  `"ABCDEFGHIJKLMNOPQRSTUVWXYZ"`

SMALLLETTERS

  `"abcdefghijklmnopqrstuvwxyz"`

LETTERS

  concatenation of CAPITALLETTERS and SMALLLETTERS

DIGITS

  `"0123456789"`

HEXDIGITS

  `"0123456789ABCDEFabcdef"`

##### 5.5-2 TextAttr

`> TextAttr` | ( global variable )

The record `TextAttr` contains strings which can be printed to change the terminal attribute for the following characters. This only works with terminals which understand basic ANSI escape sequences. Try the following example to see if this is the case for the terminal you are using. It shows the effect of the foreground and background color attributes and of the `.bold`, `.blink`, `.normal`, `.reverse` and`.underscore` which can partly be mixed.

    extra := ["CSI", "reset", "delline", "home"];;
    for t in Difference(RecNames(TextAttr), extra) do
      Print(TextAttr.(t), "TextAttr.", t, TextAttr.reset,"\n");
    od;

The suggested defaults for colors `0..7` are black, red, green, brown, blue, magenta, cyan, white. But this may be different for your terminal configuration.

The escape sequence `.delline` deletes the content of the current line and `.home` moves the cursor to the beginning of the current line.

    for i in [1..5] do
      Print(TextAttr.home, TextAttr.delline, String(i,-6), "\c");
      Sleep(1);
    od;

Whenever you use this in some printing routines you should make it optional. Use these attributes only, when the variable `ANSI_COLORS` has the value `true`.

##### 5.5-3 FormatParagraph

`> FormatParagraph`( str[, len[, flush[, attr]]] ) | ( function )

Returns: the formatted paragraph as string

This function formats a text given in the string str as a paragraph. The optional arguments have the following meaning:

len

  the length of the lines of the resulting text (default is `78`)

flush

  can be `"left"`, `"right"`, `"center"` or `"both"`, telling that lines should be flushed left, flushed right, centered or left-right justified, respectively (default is `"both"`)

attr

  is a list of two strings; the first is prepended and the second appended to each line of the result (can for example be used for indenting, `[" ", ""]`, or some markup, `[TextAttr.bold, TextAttr.reset]`, default is `["", ""]`)

This function tries to handle markup with the escape sequences explained in `TextAttr` (5.5-2) correctly.

    gap> str := "One two three four five six seven eight nine ten eleven.";;
    gap> Print(FormatParagraph(str, 25, "left", ["/* ", " */"]));
    /* One two three four five */
    /* six seven eight nine ten */
    /* eleven. */

##### 5.5-4 SubstitutionSublist

`> SubstitutionSublist`( list, sublist, new[, flag] ) | ( function )

Returns: the changed list

This function looks for (non-overlapping) occurrences of a sublist sublist in a list list (compare `PositionSublist` (Reference: PositionSublist)) and returns a list where these are substituted with the list new.

The optional argument flag can either be `"all"` (this is the default if not given) or `"one"`. In the second case only the first occurrence of sublist is substituted.

If sublist does not occur in list then list itself is returned (and not a `ShallowCopy(list)`).

    gap> SubstitutionSublist("xababx", "ab", "a");
    "xaax"

##### 5.5-5 StripBeginEnd

`> StripBeginEnd`( list, strip ) | ( function )

Returns: changed string

Here list and strip must be lists. This function returns the sublist of list which does not contain the leading and trailing entries which are entries of strip. If the result is equal to list then list itself is returned.

    gap> StripBeginEnd(" ,a, b,c,   ", ", ");
    "a, b,c"

##### 5.5-6 StripEscapeSequences

`> StripEscapeSequences`( str ) | ( function )

Returns: string without escape sequences

This function returns the string one gets from the string str by removing all escape sequences which are explained in `TextAttr` (5.5-2). If str does not contain such a sequence then str itself is returned.

##### 5.5-7 RepeatedString

`> RepeatedString`( c, len ) | ( function )

Here c must be either a character or a string and len is a non-negative number. Then `RepeatedString` returns a string of length len consisting of copies of c.

    gap> RepeatedString('=',51);
    "==================================================="
    gap> RepeatedString("*=",51);
    "*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*"

##### 5.5-8 NumberDigits

`> NumberDigits`( str, base ) | ( function )

Returns: integer

`> DigitsNumber`( n, base ) | ( function )

Returns: string

The argument str of `NumberDigits` must be a string consisting only of an optional leading `'-'` and characters in `0123456789abcdefABCDEF`, describing an integer in base base with 2 <= base <= 16. This function returns the corresponding integer.

The function `DigitsNumber` does the reverse.

    gap> NumberDigits("1A3F",16);
    6719
    gap> DigitsNumber(6719, 16);
    "1A3F"

##### 5.5-9 PositionMatchingDelimiter

`> PositionMatchingDelimiter`( str, delim, pos ) | ( function )

Returns: position as integer or `fail`

Here str must be a string and delim a string with two different characters. This function searches the smallest position `r` of the character `delim[2]` in str such that the number of occurrences of `delim[2]` in str between positions `pos+1` and `r` is by one greater than the corresponding number of occurrences of `delim[1]`.

If such an `r` exists, it is returned. Otherwise `fail` is returned.

    gap> PositionMatchingDelimiter("{}x{ab{c}d}", "{}", 0);
    fail
    gap> PositionMatchingDelimiter("{}x{ab{c}d}", "{}", 1);
    2
    gap> PositionMatchingDelimiter("{}x{ab{c}d}", "{}", 6);
    11

##### 5.5-10 WordsString

`> WordsString`( str ) | ( function )

Returns: list of strings containing the words

This returns the list of words of a text stored in the string str. All non-letters are considered as word boundaries and are removed.

    gap> WordsString("one_two \n    three!?");
    [ "one", "two", "three" ]

#### 5.6 Print Utilities

The following printing utilities turned out to be useful for interactive work with texts in GAP. But they are more general and so we document them here.

##### 5.6-1 PrintTo1

`> PrintTo1`( filename, fun ) | ( function )

`> AppendTo1`( filename, fun ) | ( function )

The argument fun must be a function without arguments. Everything which is printed by a call fun() is printed into the file filename. As with `PrintTo` (Reference: PrintTo) and `AppendTo` (Reference: AppendTo) this overwrites or appends to, respectively, a previous content of filename.

These functions can be particularly efficient when many small pieces of text shall be written to a file, because no multiple reopening of the file is necessary.

    gap> f := function() local i;
    >   for i in [1..100000] do Print(i, "\n"); od; end;
    gap> PrintTo1("nonsense", f); # now check the local file `nonsense'

##### 5.6-2 StringPrint

`> StringPrint`( obj1[, obj2[, ...]] ) | ( function )

`> StringView`( obj ) | ( function )

These functions return a string containing the output of a `Print` or `ViewObj` call with the same arguments.

This should be considered as a (temporary?) hack. It would be better to have `String` (Reference: String) methods for all GAP objects and to have a generic `Print` (Reference: Print)-function which just interprets these strings.

##### 5.6-3 PrintFormattedString

`> PrintFormattedString`( str ) | ( function )

This function prints a string str. The difference to `Print(str);` is that no additional line breaks are introduced by GAP's standard printing mechanism. This can be used to print lines which are longer than the current screen width. In particular one can print text which contains escape sequences like those explained in `TextAttr` (5.5-2), where lines may have more characters than visible characters.

##### 5.6-4 Page

`> Page`( ... ) | ( function )

`> PageDisplay`( obj ) | ( function )

These functions are similar to `Print` (Reference: Print) and `Display` (Reference: Display), respectively. The difference is that the output is not sent directly to the screen, but is piped into the current pager; see `PAGER` (Reference: Pager).

    gap> Page([1..1421]+0);
    gap> PageDisplay(CharacterTable("Symmetric", 14));

##### 5.6-5 StringFile

`> StringFile`( filename ) | ( function )

`> FileString`( filename, str[, append] ) | ( function )

The function `StringFile` returns the content of file filename as a string. This works efficiently with arbitrary (binary or text) files. If something went wrong, this function returns `fail`.

Conversely the function `FileString` writes the content of a string str into the file filename. If the optional third argument append is given and equals `true` then the content of str is appended to the file. Otherwise previous content of the file is deleted. This function returns the number of bytes written or `fail` if something went wrong.

Both functions are quite efficient, even with large files.

Top of Book | Previous Chapter | Next Chapter

Goto Chapter: | Top | 1 | 2 | 3 | 4 | 5 | A | B | Bib | Ind

generated by GAPDoc2HTML