gummibaum

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 18, 2020 License: Apache-2.0 Imports: 12 Imported by: 0

README

gummibaum

gummibaum is LaTeX template engine. Sometimes you just want a template with placeholders and fill those placeholders with actual content, for example using placeholders $name in your tex code and replace them with a constant "John". Or you have data in form of a csv and create LaTeX code based on that data, for example creating a dynamic table. gummibaum tries to be simple to use: It is not a LaTeX engine like LuaTeX but a simple static content creator that produces LaTeX output that can be compiled with pdflatex. It supports two different modes: Expansion mode and template mode.

Expansion Mode

The easiest mode to understand is the expansion mode. It takes a LaTeX file as input, replaces certain placeholders with values and and can be used to iterate over specific parts of the file. The advantage is that you can write a .tex file that you can compile with pdflatex and test how it looks like. Then use gummibaum to replace constant fields or use an easy way to iterate over content. It is not as flexible as the template mode though.

Template Mode

Using Golangs template system and some additional functionality you can write LaTeX files that contain directives such as loops. This way you need to execute your template first to create a valid LaTeX file that can be compiled with pdflatex. Expansion mode is more easy to understand but not as flexible as the template mode.

Usage

For usage information please see the Wiki and use ./gummibaum --help or ./gummibaum expand --help or ./gummibaum template --help.

Installation

From source

Requires a go compiler ≥ 1.9. Use go get -u github.com/FabianWe/gummibaum/.... Then you can go build cmd/gummibaum/gummibaum.go.

Binaries

Precompiled binaries are available in the releases section. Windows is not tested, for Linux: Place the executable gummibaum (rename togummibaum) somewhere and execute it. The best thing is probably to put it in /usr/local/bin.

For Developers

You can find the documentation on GoDoc.

License

Copyright 2018 Fabian Wenzelmann

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Index

Constants

View Source
const (
	// NoColEntry is returned by several methods of Column to indicate that a
	// key was not found.
	NoColEntry = "NO VALUE"
)

Variables

View Source
var (
	// DefaultReplacers describes the default replacer pairs. Note that certain
	// replacements like \textbackslash must have a leading space.
	DefaultReplacers = []string{
		"&", `\&`,
		"%", `\%`,
		"$", `\$`,
		"#", `\#`,
		"_", `\_`,
		"{", `\{`,
		"}", `\}`,
		"~", `\textasciitilde `,
		"^", `\textasciicircum `,
		`\`, `\textbackslash `,
	}
)

Functions

func ApplyExpandHandlers

func ApplyExpandHandlers(line string, handlers ...ExpandHandler) string

ApplyExpandHandlers applies the handlers one after the other to the original line.

func ExpandConfigFromJSONFile

func ExpandConfigFromJSONFile(file string) (map[string]string, map[string]string, error)

ExpandConfigFromJSONFile is like ExpandConfigJSON and reads the content from a file.

func ExpandConfigJSON

func ExpandConfigJSON(r io.Reader) (map[string]string, map[string]string, error)

ExpandConfigJSON parses a config file. The config files must be a dictionary mapping "const" to a dictionary of string variable / value pairs and mapping "rows" to a dictionary of string variable / value pairs.

func ExpandParseTex

func ExpandParseTex(r io.Reader) ([]string, []string, []string, error)

ExpandParseTex splits the tex file into the three parts: Head, everything before the line "%begin gummibaum repeat", body everything between "%begin gummibaum repeat" and "%end gummibaum repeat" and foot everything after "%end gummibaum repeat".

func IntMin

func IntMin(a, b int) int

IntMin returns the minimum of a and b.

func Join

func Join(replace LatexEscapeFunc) func(sep string, args ...interface{}) string

Join concatenates the elements of args to create a single string. The separator string sep is placed between elements in the resulting string. The function parameterized by a LatexEscapeFunc (that can be nil) that is used to prepare each arg.

func LatexEscaper

func LatexEscaper(replace LatexEscapeFunc) func(args ...interface{}) string

LatexEscaper returns a function that escapes an arbitrary number of arguments with the specified escaping function.

func LatexTemplate

func LatexTemplate(t *template.Template, replace LatexEscapeFunc) *template.Template

LatexTemplate adds the functions "latex", "verb", and "join" to the template. This function must be called before the template is parsed.

func MergeStringMaps

func MergeStringMaps(m1, m2 map[string]string) map[string]string

MergeStringMaps combines two string maps. The result is a new map (both maps are unchanged) containing all entries from m1 and m2. If a key is present in both maps the value from m2 is used.

func ParseTemplates

func ParseTemplates(replace LatexEscapeFunc, delimLeft, delimRight string, filenames ...string) (*template.Template, error)

ParseTemplates parses the templates specified by filenames. See Go template documentation for ParseTemplates for details. The functions "latex", "verb" and "join" are added. The replace function is used to escape special characters, if it is nil no replacement takes place. Delims defines which delimiters are used. The default {{ and }} are not nice for latex, so we replace them. #( and #) seem to be a good idea. This is what happens when you use the empty string as delims.

func ParseVarValList

func ParseVarValList(pairs []string) (map[string]string, error)

ParseVarValList parses a list of var=val pairs (each entry in pairs one such pair). The vars are mapped to the value. For syntax errors an error != nil is returned.

func ParseVarValPair

func ParseVarValPair(s string) (string, string, error)

ParseVarValPair parses a string of the form var=val. It returns var and val. For syntax errors an error != nil is returned.

func TemplateConstFromJSONFile

func TemplateConstFromJSONFile(file string) (map[string]string, error)

TemplateConstFromJSONFile is like TemplateConstJSON and reads the content from a file.

func TemplateConstJSON

func TemplateConstJSON(r io.Reader) (map[string]string, error)

TemplateConstJSON parses a constant json file, it must be a dictionary mapping strings (replace identifiers) by constant values.

func Verb

func Verb(del string, args ...interface{}) (string, error)

Verb returns a LaTeX verb environment with the given delimiter. For example Verb("|", "foo & bar") yields to \verb|foo & bar|. An error is returned if the delimiter is contained in the input string or if delimiter has a length != 1.

func WriteExpandHandlers

func WriteExpandHandlers(w io.Writer, line string, handlers ...ExpandHandler) (int, error)

WriteExpandHandlers works as ApplyExpandHandlers but writes the result to a writer. It returns the number of bytes written and any error that occurred.

Types

type CSVReader

type CSVReader struct {
	HeadContent    []string
	ColumnsContent [][]string
}

CSVReader implements CollectionSource by reading content as csv.

func NewCSVFileReader

func NewCSVFileReader(file string, sep rune, head bool) (*CSVReader, error)

NewCSVFileReader returns a new csv reader given a file path.

func NewCSVReader

func NewCSVReader(r io.Reader, sep rune, head bool) (*CSVReader, error)

NewCSVReader returns a new csv reader given the reader source and the separator (usually comma). If head is true the first column is assumed to be the head column and must be present.

This function exhaustively reads all data from the reader in memory.

func (*CSVReader) Entries

func (r *CSVReader) Entries() ([][]string, error)

Entries returns all columns.

func (*CSVReader) Head

func (r *CSVReader) Head() ([]string, error)

Head returns the head.

type ColKeyError added in v1.2.0

type ColKeyError struct {
	Message string
}

ColKeyError is an error returned by several methods of Column to indicate that a ky was not found.

func NewColKeyError added in v1.2.0

func NewColKeyError(msgTemplate string, a ...interface{}) ColKeyError

NewColKeyError returns a new ColKeyError.

func (ColKeyError) Error added in v1.2.0

func (err ColKeyError) Error() string

type Collection

type Collection struct {
	Head    []string
	Columns []*Column
}

Collection groups together several columns with the same head (row names).

func NewCollection

func NewCollection(source CollectionSource) (*Collection, error)

NewCollection returns a new Collection initialized with all entries from the source.

It returns any error from source.

type CollectionSource

type CollectionSource interface {
	Head() ([]string, error)
	Entries() ([][]string, error)
}

CollectionSource is everything that returns entries in the form of a column based data model.

Head describes the row names and can be nil in which case no names are given. Entries returns all columns.

For example Head might return ["first-name", "last-name"] and Entries might return [["John", "Doe"], ["Jane"]]. The second column does not have a field "last-name".

type Column

type Column struct {
	Head    []string
	Entries []string
	Map     map[string]string
}

Column represents a column in a collection. It has the head of the entries (that comes from the collection and all data entries as strings). Map is a mapping from head name (row names) to the data entry and is created in NewColumn.

Head and Entries should have the same size, but are allowed to have different sizes. In this case the map contains an entry for each row name in min(len(Head), mint(Entries)).

func NewColumn

func NewColumn(head, entries []string) *Column

NewColumn returns a new column and initializes the map m.

func (*Column) At

func (c *Column) At(i int) (string, error)

At returns the i-th entry. If i is not a valid position in entries an error of type ColKeyError is returned. GetPos is similar to At but does not return an error.

func (*Column) Element

func (c *Column) Element(key interface{}) (string, error)

Element returns either the element on position key if key is an int or the mapping at key if key is a string. If it is neither an of type ColKeyError error is returned. If the position / key is invalid an error of type ColKeyError is returned. Get is similar to Element but does not return an error if key is invalid.

func (*Column) Get

func (c *Column) Get(key interface{}) string

Get returns either the element on position key if key is an int or the mapping at key if key is a string. If it is neither NoColEntry is returned. If the position / key is invalid NoColEntry is returned. Element is similar to Get but returns an error if key is invalid.

func (*Column) GetKey

func (c *Column) GetKey(key string) string

GetKey returns the item with the given key where key is row name. If the key is not found NoColEntry is returned. Value is similar to GetKey but returns an error if key is not found.

func (*Column) GetPos

func (c *Column) GetPos(i int) string

GetPos returns the item on position i in Entries. If i is not a valid position in entries NoColEntry is returned. At is similar to GetPos but returns an error if i is invalid.

func (*Column) Value

func (c *Column) Value(key string) (string, error)

Value returns the item with the given key where key is row name. If the key is not found an error of type ColKeyError is returned. GetKey is similar to Value but does not return an error if key is invalid.

type ConstHandler

type ConstHandler struct {
	// contains filtered or unexported fields
}

ConstHandler replaces place holders with constant values.

func NewConstHandler

func NewConstHandler(mapper map[string]string, replaceFunc LatexEscapeFunc) *ConstHandler

NewConstHandler returns a new ConstHandler give the mapping place holder to constant value (for example "NAME" mapped to "John"). replaceFunc is a function to escape LaTeX special characters. If it is nil no replacements will take place.

func (*ConstHandler) HandleLine

func (h *ConstHandler) HandleLine(line string) string

type ExpandHandler

type ExpandHandler interface {
	HandleLine(line string) string
}

ExpandHandler is used for the expand mode to process a single line. A handler transforms a line and returns the new line.

type LatexEscapeFunc

type LatexEscapeFunc func(text string) string

LatexEscapeFunc is any function that replaces LaTeX special character within a text. Usually it should be clear how to do this, but LaTeX is a very rich language and I want to keep it extendable.

func EscapeWithDefaults

func EscapeWithDefaults(additional []string) LatexEscapeFunc

EscapeWithDefaults returns an escape function that uses the content from DefaultReplacers and combines it with the replacers from additional. Example: ["&", "\\&"] would replace each occurrence of & with \&. This replacement is already done by the DefaultReplacers though.

func LatexEscapeFromList

func LatexEscapeFromList(mapping []string) LatexEscapeFunc

LatexEscapeFromList returns a replacement function given a map of substitution pairs. Example: ["&", "\\&"] would replace each occurrence of & with \&. A list of default replacers can be found in DefaultReplacers, EscapeWithDefaults can be used to extend that list.

type MemoryCollection

type MemoryCollection struct {
	HeadContent    []string
	ColumnsContent [][]string
}

MemoryCollection implements CollectionSource with a predefined set of content.

func NewMemoryCollection

func NewMemoryCollection(head []string, columns [][]string) *MemoryCollection

NewMemoryCollection returns a new MemoryCollection given the data.

func (*MemoryCollection) Entries

func (c *MemoryCollection) Entries() ([][]string, error)

Entries returns all columns.

func (*MemoryCollection) Head

func (c *MemoryCollection) Head() ([]string, error)

Head returns the head.

type RowHandler

type RowHandler struct {
	// contains filtered or unexported fields
}

RowHandler replaces placeholders with values from a given column. It is not save for concurrent use with different columns, use WithColumn to create new RewHandlers with a new column and then run replacement on those instances concurrently. WithColumn must be called before using HandleLine.

func NewRowHandler

func NewRowHandler(replaceVarMap map[string]string, replaceFunc LatexEscapeFunc) *RowHandler

NewRowHandler returns a new RowHandler. replaceVarMap must be a mapping mapping replace names to row names, for example "REPL-TOKEN" --> "token". WithColumn must be called before HandleLine can be used.

func (*RowHandler) HandleLine

func (h *RowHandler) HandleLine(line string) string

HandleLine applies the actual replacement by substituting values for the current column. If the current column is nil this method panics, a column must be set before with WithColumn.

func (*RowHandler) WithColumn

func (h *RowHandler) WithColumn(c *Column) *RowHandler

WithColumn returns a new row handler with the column set.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL