.\"Copyright (C) 2011, Kaz Kylheku . .\"All rights reserved. .\" .\"BSD License: .\" .\"Redistribution and use in source and binary forms, with or without 1\"modification, are permitted provided that the following conditions .\"are met: .\" .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in .\" the documentation and/or other materials provided with the .\" distribution. .\" 3. The name of the author may not be used to endorse or promote .\" products derived from this software without specific prior .\" written permission. .\" .\"THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR .\"IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED .\"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. .TH "txr" 1 2011-10-20 "Utility Commands" "Txr Text Extractor" "Kaz Kylheku" .SH NAME txr \- text extractor (version 040) .SH SYNOPSIS .B txr [ options ] query-file { data-file }* .sp .SH DESCRIPTION .B txr is a query tool for extracting pieces of text buried in one or more text file based on pattern matching. A .B txr query specifies a pattern which matches (a prefix of) an entire file, or multiple files. The pattern is matched against the material in the files, and free variables occurring in the pattern are bound to the pieces of text occurring in the corresponding positions. If the overall match is successful, then .B txr can do one of two things: it can report the list of variables which were bound, in the form of a set of variable assignments which can be evaluated by the .B eval command of the POSIX shell language, or generate a custom report according to special directives in the query. In addition to embedded variables which implicitly match text, the .B txr query language supports a number of directives, for matching text using regular expressions, for continuing a match in another file, for searching through a file for the place where an entire sub-query matches, for collecting lists, and for combining sub-queries using logical conjunction, disjunction and negation. When .B txr finds a match for a variable and binds it, if that variable occurs again later in the query, the variable's text is substituted, forcing a match for that exact text. Thus txr supports a rudimentary form of backreferencing unification, if you will. For example, the query @FOO=@FOO will match material from the start of the line until the first equal sign, and bind it to the variable .IR FOO. Then, the material which follows the equal sign to the end of the line must match the contents bound to FOO. Hence the line "abc=abc" will match, but "abc=xyz" will fail to match. Generally, the scope of a variable's binding extends from its first successful match where the binding is established, to the end of the query. Unsuccessful subqueries have no effect on the bindings. Even if a failed subquery is partially successful, all of its bindings are thrown away. Some directives treat the bindings emanating from their subqueries in special ways. .SH ARGUMENTS AND OPTIONS Options which don't take an argument may be combined together. The -v and -q options are mutually exclusive. Of these two, the one which occurs in the rightmost position in the argument list dominates. The -c and -f options are also mutually exclusive; if both are specified, it is a fatal error. .IP -Dvar=value Bind the variable .IR var to the value .IR value prior to processing the query. The name is in scope over the entire query, so that all occurrence of the variable are substituted and match the equivalent text. If the value contains commas, these are interpreted as separators, which give rise to a list value. For instance -Da,b,c creates a list of the strings "a", "b" and "c". (See Collect Directive bellow). List variables provide a multiple match. That is to say, if a list variable occurs in a query, a successful match occurs if any of its values matches the text. If more than one value matches the text, the first one is taken. .IP -Dvar Binds the variable .IR var to an empty string value prior to processing the query. .IP -q Quiet operation during matching. Certain error messages are not reported on the standard error device (but the if the situations occur, they still fail the query). This option does not suppress error generation during the parsing of the query, only during its execution. .IP -v Verbose operation. Detailed logging is enabled. .IP -b Suppresses the printing of variable bindings for a successful query, and the word . IR false for a failed query. The program still sets an appropriate termination status. .IP -a num Specifies the maximum number of array dimensions to use for variables arising out of collect. The default is 1. Additional dimensions are expressed using numeric suffixes in the generated variable names. For instance, consider the three-dimensional list arising out of a triply nested collect: ((("a" "b") ("c" "d")) (("e" "f") ("g" "h"))). Suppose this is bound to a variable V. With -a 1, this will be reported as: V_0_0[0]="a" V_0_1[0]="b" V_1_0[0]="c" V_1_1[0]="d" V_0_0[1]="e" V_0_1[1]="f" V_1_0[1]="g" V_1_1[1]="h" The leftmost bracketed index is the most major index. That is to say, the dimension order is: NAME_m_m+1_..._n[1][2]...[m-1]. .IP -c query Specifies the query in the form of a command line argument. If this option is used, the query-file argument is omitted. The first non-option argument, if there is one, now specifies the first input source rather than a query. Unlike queries read from a file, (non-empty) queries specified as arguments using -c do not have to properly end in a newline. Internally, txr adds the missing newline before parsing the query. Thus -c "@a" is a valid query which matches a line. Example: # read two lines "1" and "2" from standard input, # binding them to variables a and b. Standard # input is specified as - and the data # comes from shell "here document" redirection. txr -c "@a @b" - < twoline.txr #!/usr/bin/txr @a @b [Ctrl-D] $ chmod a+x twoline.txr $ ./twoline.txr - 1 2 [Ctrl-D] a=1 b=2 A script written in this manner will not pass options to txr. For instance, if the above script is invoked like this ./twoline.txr -Da=42 the -D option isn't passed down to txr; -Da=42 is an ordinary argument (which the script will try to open as an input file). This behavior is useful if the script author wants not to expose the txr options to the user of the script. However, if the hash bang line can use the -f option: #!/usr/bin/txr -f Now, the name of the script is passed as an argument to the -f option, and txr will look for more options after that. .SS Whitespace Outside of directives, whitespace is significant in TXR queries, and represents a pattern match for whitespace in the input. An extent of text consisting of an undivided mixture of tabs and spaces is a whitespace token. Whitespace tokens match a precisely identical piece of whitespace in the input, with one exception: a whitespace token consisting of precisely one space has a special meaning. It is equivalent to the regular expression @/[ ]+/: match an extent of one or more spaces (but not tabs!) Thus, the query line "a b" (one space) matches texts like "a b", "a b", et cetera (arbitrary number of tabs and spaces between a and b). However "a b" (two spaces) matches only "a b" (two spaces). For matching a single space, the syntax @\ can be used (backslash-escaped space). It is more often necessary to match multiple spaces, than to exactly match one space, so this rule simplifies many queries and adds inconvenience to only few. In output clauses, string and character literals and quasiliterals, a space token denotes a space. .SS Text Query material which is not escaped by the special character @ is literal text, which matches input character for character. Text which occurs at the beginning of a line matches the beginning of a line. Text which starts in the middle of a line, other than following a variable, must match exactly at the current position, where the previous match left off. Moreover, if the text is the last element in the line, its match is anchored to the end of the line. An empty query line matches an empty line in the input. Note that an empty input stream does not contain any lines, and therefore is not matched by an empty line. An empty line in the input is represented by a newline character which is either the first character of the file, or follows a previous newline-terminated line. Input streams which end without terminating their last line with a newline are tolerated, and are treated as if they had the terminator. Text which follows a variable has special semantics, discussed in the section Variables below. A query may not leave unmatched material in a line which is covered by the query. However, a query may leave unmatched lines. In the following example, the query matches the text, even though the text has an extra line. Query: Four score and seven years ago our Text: Four score and seven years ago our forefathers In the following example, the query .B fails to match the text, because the text has extra material on one line. Query: I can carry nearly eighty gigs in my head Text: I can carry nearly eighty gigs of data in my head Needless to say, if the text has insufficient material relative to the query, that is a failure also. To match arbitrary material from the current position to the end of a line, the "match any sequence of characters, including empty" regular expression @/.*/ can be used. Example: Query: I can carry nearly eighty gigs@/.*/ Text: I can carry nearly eighty gigs of data In this example, the query matches, since the regular expression matches the string "of data". (See Regular Expressions section below). Another way to do this is: Query: I can carry nearly eighty gigs@(skip) .SS Special Characters in Text Control characters may be embedded directly in a query (with the exception of newline characters). An alternative to embedding is to use escape syntax. The following escapes are supported: .IP @\e A backslash immediately followed by a newline introduces a physical line break without breaking up the logical line. Material following this sequence continues to be interpreted as a continuation of the previous line, so that indentation can be introduced to show the continuation without appearing in the data. .IP @\e A backslash followed by a space encodes a space. This is useful in line continuations when it is necessary for leading spaces to be preserved. For instance the two line sequence abcd@\ @\ efg is equivalent to the line abcd efg The two spaces before the @\ in the second line are consumed. The spaces after are preserved. .IP @\ea Alert character (ASCII 7, BEL). .IP @\eb Backspace (ASCII 8, BS). .IP @\et Horizontal tab (ASCII 9, HT). .IP @\en Line feed (ASCII 10, LF). Serves as abstract newline on POSIX systems. .IP @\ev Vertical tab (ASCII 11, VT). .IP @\ef Form feed (ASCII 12, FF). This character clears the screen on many kinds of terminals, or ejects a page of text from a line printer. .IP @\er Carriage return (ASCII 13, CR). .IP @\ee Escape (ASCII 27, ESC) .IP @\exHEX A @\ex followed by a sequence of hex digits is interpreted as a hexadecimal numeric character code. For instance @\ex41 is the ASCII character A. .IP @\eOCTAL A @\e followed by a sequence of octal digits (0 through 7) is interpreted as an octal character code. For instance @\e010 is character 8, same as @\eb. .PP Note that if a newline is embedded into a query line with @\en, this does not split the line into two; it's embedded into the line and thus cannot match anything. However, @\en may be useful in the @(cat) directive and in @(output). .SS International Characters .B txr represents text internally using wide characters, which are used to represent Unicode code points. The query language, as well as all data sources, are assumed to be in the UTF-8 encoding. In the query language, extended characters can be used directly in comments, literal text, string literals, quasiliterals and regular expressions. Extended characters can also be expressed indirectly using hexadecimal or octal escapes. On some platforms, wide characters may be restricted to 16 bits, so that .B txr can only work with characters in the BMP (Basic Multilingual Plane) subset of Unicode. .B txr does not use the localization features of the system library; its handling of extended characters is not affected by environment variables like LANG and L_CTYPE. The program reads and writes only the UTF-8 encoding. If .B txr encounters an invalid bytes in the UTF-8 input, what happens depends on the context in which this occurs. In a query, comments are read without regard for encoding, so invalid encoding bytes are not detected. A comment is simply a sequence of bytes terminated by a newline. Invalid encoding bytes in significant query text are diagnosed as syntax errors. When the scanner is faced with input that isn't a valid multibyte character, it issues an error message, skips one byte, and resumes scanning. Invalid bytes in data are treated as follows: when an invalid byte is encountered in the middle of a multibyte character, or if the input ends in the middle of a multibyte character, the UTF-8 decoder returns to the starting byte of the ill-formed multibyte character, and decodes just that byte, by mapping it to the Unicode character range U+DC00 through U+DCFF. The decoding resumes at the following character, expecting that byte to be the start of another multibyte character. .SS Regular Expression Directives In place of a piece of text (see section Text above), a regular expression directive may be used, which has the following syntax: @/RE/ where the RE part enclosed in slashes represents regular expression syntax (described in the section Regular Expressions below). Long regular expressions can be broken into multiple lines using a backslash-newline sequence. Whitespace before the sequence or after the sequence is not significant, so the following two are equivalent: @/reg \e ular/ @/regular/ There may not be whitespace between the backslash and newline. Whereas literal text simply represents itself, regular expression denotes a (potentially infinite) set of texts. The regular expression directive matches the longest piece of text (possibly empty) which belongs to the set denoted by the regular expression. The match is anchored to the current position; thus if the directive is the first element of a line, the match is anchored to the start of a line. If the regular expression directive is the last element of a line, it is anchored to the end of the line also: the regular expression must match the text from the current position to the end of the line. Even if the regular expression matches the empty string, the match will fail if the input is empty, or has run out of data. For instance suppose the third line of the query is the regular expression @/.*/, but the input is a file which has only two lines. This will fail: the data has line for the regular expression to match. A line containing no characters is not the same thing as the absence of a line, even though both abstractions imply an absence of characters. Like text which follows a variable, a regular expression directive which follows a variable has special semantics, discussed in the section Variables below. .SS Variables Much of the query syntax consists of arbitrary text, which matches file data character for character. Embedded within the query may be variables and directives which are introduced by a @ character. Two consecutive @@ characters encode a literal @. A variable matching or substitution directive is written in one of several ways: @NAME @{NAME} @*NAME @*{NAME} @{NAME /RE/} @{NAME NUMBER} The forms with an * indicate a long match, see Longest Match below. The last two forms with the embedded regexp /RE/ or number have special semantics, see Positive Match below. The name itself may consist of any combination of one or more letters, numbers, and underscores, and must begin with a letter or underscore. Case is sensitive, so that @FOO is different from @foo, which is different from @Foo. The braces around a name can be used when material which follows would otherwise be interpreted as being part of the name. For instance @FOO_bar introduces the name "FOO_bar", whereas @{FOO}_bar means the variable named "FOO" followed by the text "_bar". There may be whitespace between the @ and the name, or opening brace. Whitespace is also allowed in the interior of the braces. It is not significant. If a variable has no prior binding, then it specifies a match. The match is determined from some current position in the data: the character which immediately follows all that has been matched previously. If a variable occurs at the start of a line, it matches some text at the start of the line. If it occurs at the end of a line, it matches everything from the current position to the end of the line. The extent of the matched text (the text bound to the variable) is determined by looking at what follows the variable. A variable may be followed by a piece of text, a regular expression directive, another variable, or nothing (i.e. occurs at the end of a line). If the variable is followed by nothing, the match extends from the current position in the data, to the end of the line. Example: pattern: "a b c @FOO" data: "a b c defghijk" result: FOO="defghijk" If the variable is followed by text (all non-directive material extending to the end of the line, or to the start of another directive), then the extent of the match is determined by searching for the first occurrence of that text within the line, starting at the current position. The variable matches everything between the current position and the matching position (not including the matching position). Any whitespace which follows the variable (and is not enclosed inside braces that surround the variable name) is part of the text. For example: pattern: "a b @FOO e f" data: "a b c d e f" result: FOO="c d" In the above example, the pattern text "a b " matches the data "a b ". So when the @FOO variable is processed, the data being matched is the remaining "c d e f". The text which follows @FOO is " e f". This is found within the data "c d e f" at position 3 (counting from 0). So positions 0-2 ("c d") constitute the matching text which is bound to FOO. If the variable is followed by a regular expression directive, the extent is determined by finding the closest match for the regular expression. (See Regular Expressions section below). To match successfully, .SS Special Symbols Just like in the programming language Lisp, the names nil and t cannot be used as variables. They always represent themselves, and have many uses, internal to the program as well as externally visible. The nil symbol stands for the empty list object, an object which marks the end of a list, and boolean false. It is synonymous with the syntax () which may be used interchangeably with nil in most constructs. Names whose names begin with the : character are keyword symbols. These also may not be used as variables either and stand for themselves. Keywords are useful for labeling information and situations. .SS Consecutive Variables If an unbound variable specified a fixed-width match or a regular expression, then the issue of consecutive variables does not arise. Such a variable consumes text regardless of any context which follows it. However, what if an unbound variable with no modifier is followed by another variable? The behavior depends on the nature of the other variable. If the other variable also has no modifier, this is a semantic error which will cause the query to fail. A diagnostic message will be issued, unless operating in quiet mode via -q. The reason is that there is no way to bind two consecutive variables to an extent of text; this is an ambiguous situation, since there is no matching criterion for dividing the text between two variables. (In theory, a repetition of the same variable, like @FOO@FOO, could find a solution by dividing the match extent in half, which would work only in the case when it contains an even number of characters. This behavior seems to have dubious value). An unbound variable may be followed by one which is bound. The bound variable is replaced by the text which it denotes, and the logic proceeds accordingly. Variables are never bound to regular expressions, so the regular expression match does not arise in this case. The @* syntax for longest match is available. Example: pattern: "@FOO:@BAR@FOO" data: "xyz:defxyz" result: FOO=xyz, BAR=def Here, FOO is matched with "xyz", based on the delimiting around the colon. The colon in the pattern then matches the colon in the data, so that BAR is considered for matching against "defxyz". BAR is followed by FOO, which is already bound to "xyz". Thus "xyz" is located in the "defxyz" data following "def", and so BAR is bound to "def". If an unbound variable is followed by a variable which is bound to a list, or nested list, then each character string in the list is tried in turn to produce a match. The first match is taken. An unbound variable may be followed by another unbound variable which specifies a regular expression match. This is a special case called a "double variable match". What happens is that the text is searched using the regular expression. If the search fails, than neither variable is bound: it is a matching failure. If the search succeeds, than the first variable is bound to the text which is skipped by the regular expression search. The second variable is bound to the text matched by the regular expression. .SS Longest Match The closest-match behavior for text and regular expressions can be overridden to longest match behavior. A special syntax is provided for this: an asterisk between the @ and the variable, e.g: pattern: "a @*{FOO}cd" data: "a b cdcdcdcd" result: FOO="b cdcdcd" pattern: "a @{FOO}cd" data: "a b cdcdcd" result: FOO="b " In the former example, the match extends to the rightmost occurrence of "cd", and so FOO receives "b cdcdcd". In the latter example, the * syntax isn't used, and so a leftmost match takes place. The extent covers only the "b ", stopping at the first "cd" occurrence. .SS Positive Match The syntax variants @{NAME /RE/} @{NAME NUMBER} specify a variable binding that is driven by a positive match derived from a regular expression or character count, rather than from trailing material (which may be regarded as a "negative" match, since the variable is bound to material which is .B skipped in order to match the trailing material). In the /RE/ form, the match extends over all characters from the current position which match the regular expression RE. (see Regular Expressions section below). In the NUMBER form, the match processes a field of text which consists of the specified number of characters, which must be nonnegative number. If the data line doesn't have that many characters starting at the current position, the match fails. A match for zero characters produces an empty string. The text which is actually matched by this construct is all text within the specified field, but excluding leading and trailing whitespace. If the field contains only spaces, then an empty string is extracted. A number is made up of digits, optionally preceded by a + or - sign. This syntax is processed without consideration of what other syntax follows. A positive match may be directly followed by an unbound variable. .SS Regular Expressions Regular expressions are a language for specifying sets of character strings. Through the use of pattern matching elements, regular expression is able to denote an infinite set of texts. .B txr contains an original implementation of regular expressions, which supports the following syntax: .IP . (period) is a "wildcard" that matches any character. .IP [] Character class: matches a single character, from the set specified by special syntax written between the square brackets. Supports basic regexp character class syntax; no POSIX notation like [:digit:]. The class [a-zA-Z] means match an uppercase or lowercase letter; the class [0-9a-f] means match a digit or a lowercase letter; the class [^0-9] means match a non-digit, et cetera. A ] or - can be used within a character class, but must be escaped with a backslash. A ^ in the first position denotes a complemented class, unless it is escaped by backslash. In any other position, it denotes itself. Two backslashes code for one backslash. So for instance [\e[\e-] means match a [ or - character, [^^] means match any character other than ^, and [\e^\e\e] means match either a ^ or a backslash. Regex operators such as *, + and & appearing in a character class represent ordinary characters. The characters -, ] and ^ occurring outside of a character class are ordinary. Unescaped / characters can appear within a character class. The empty character class [] matches no character at all, and its complement [^] matches any character, and is treated as a synonym for the . (period) wildcard operator. .IP empty An empty expression is a regular expression. It represents the set of strings consisting of the empty string; i.e. it matches just the empty string. The empty regex can appear alone as a full regular expression (for instance the .B txr syntax @// with nothing between the slashes) and can also be passed as a subexpression to operators, though this may require the use of parentheses to make the empty regex explicit. For example, the expression a| means: match either a, or nothing. The forms * and (*) are syntax errors; though not useful, the correct way to match the empty expression zero or more times is the syntax ()*. .IP nomatch The nomatch regular expression represents the empty set: it matches no strings at all, not even the empty string. There is no dedicated syntax to directly express nomatch in the regex language. However, the empty character class [] is equivalent to nomatch, and may be considered to be a notation for it. Other representations of nomatch are possible: for instance, the regex ~.* which is the complement of the regex that denotes the set of all possible strings, and thus denotes the empty set. A nomatch has uses; for instance, it can be used to temporarily "comment out" regular expressions. The regex ([]abc|xyz) is equivalent to (xyz), since the []abc branch cannot match anything. Using [] to "block" a subexpression allows you to leave it in place, then enable it later by removing the "block". .IP (R) If R is a regular expression, then so is (R). The contents of parentheses denote one regular expression unit, so that for instance in (RE)*, the * operator applies to the entire parenthesized group. The syntax () is valid and equivalent to the empty regular expression. .IP R? optionally match the preceding regular expression R. .IP R* match the expression R zero or more times. This operator is sometimes called the "Kleene star", or "Kleene closure". The Kleene closure favors the longest match. Roughly speaking, if there are two or more ways in which R1*R2 can match, than that match occurs in which R1* matches the longest possible text. .IP R+ match the preceding expression R one or more times. Like R*, this favors the longest possible match: R+ is equivalent to RR*. .IP R1%R2 match R1 zero or more times, then match R2. If this match can occur in more than one way, then it occurs such that R1 is matched the fewest number of times, which is opposite from the behavior of R1*R2. Repetitions of R1 terminate at the earliest point in the text where a non-empty match for R2 occurs. Because it favors shorter matches, % is termed a non-greedy operator. If R2 is the empty expression, or equivalent to it, then R1%R2 reduces to R1*. So for instance (R%) is equivalent to (R*), since the missing right operand is interpreted as the empty regex. Note that whereas the expression (R1*R2) is equivalent to (R1*)R2, the expression (R1%R2) is .B not equivalent to (R1%)R2. .IP ~R match the opposite of the following expression R; i.e. match exactly those texts that R does not match. This operator is called complement, or logical not. .IP R1R2 Two consecutive regular expressions denote catenation: the left expression must match, and then the right. .IP R1|R2 match either the expression R1 or R2. This operator is known by a number of names: union, logical or, disjunction, branch, or alternative. .IP R1&R2 match both the expression R1 and R2 simultaneously; i.e. the matching text must be one of the texts which are in the intersection of the set of texts matched by R1 and the set matched by R2. This operator is called intersection, logical and, or conjunction. .PP Any of the special characters, including the delimiting /, can be escaped with a backslash to suppress its meaning and denote the character itself. Furthermore, all of the same escapes are as described in the section Special Characters in Text above---the difference is that in regular expressions, the @ character is not required, so for example a tab is coded as \et rather than @\e\t. Any escaped character which does not fall into the above escaping conventions, or any unescaped character which is not a regular expression operator, denotes one-position match of that character itself. Precedence table, highest to lowest: .TS tab(!); l l l. operators!class!associativity (R) []!primary! R? R+ R* R%...!postfix!left-to-right R1R2!catenation!left-to-right ~R ...%R!unary!right-to-left R1&R2!intersection!left-to-right R1|R2!union!left-to-right .TE The % operator is like a postfix operator with respect to its left operand, but like a unary operator with respect to its right operand. Thus a~b%c~d is a(~(b%(c(~d)))), demonstrating right-to-left associativity, where all of b% may be regarded as a unary operator being applied to c~d. Similarly, a?*+%b means (((a?)*)+)%b, where the trailing %b behaves like a postfix operator. In .B txr, regular expression matches do not span multiple lines. The regex language has no feature for multi-line matching. However, the @(freeform) directive allows the remaining portion of the input to be treated as one string in which line terminators appear as explicit characters. Regular expressions may freely match through this sequence. It's possible for a regular expression to match an empty string. For instance, if the next input character is z, facing a the regular expression /a?/, there is a zero-character match: the regular expression's state machine can reach an acceptance state without consuming any characters. Examples: pattern: @A@/a?/@/.*/ data: zzzzz result: A="" pattern: @{A /a?/}@B data: zzzzz result: A="", B="zzzz" pattern: @*A@/a?/ data: zzzzz result: A="zzzzz" In the first example, variable @A is followed by a regular expression which can match an empty string. The expression faces the letter "z" at position 0 in the data line. A zero-character match occurs there, therefore the variable A takes on the empty string. The @/.*/ regular expression then consumes the line. Similarly, in the second example, the /a?/ regular expression faces a "z", and thus yields an empty string which is bound to A. Variable @B consumes the entire line. The third example requests the longest match for the variable binding. Thus, a search takes place for the rightmost position where the regular expression matches. The regular expression matches anywhere, including the empty string after the last character, which is the rightmost place. Thus variable A fetches the entire line. For additional information about the advanced regular expression operators, NOTES ON EXOTIC REGULAR EXPRESSIONS below. .SS Directives The general syntax of a directive is: @EXPR where expr is a parenthesized list of subexpressions. A subexpression is an symbol, number, string literal, character literal, quasiliteral, regular expression, or a parenthesized expression. So, examples of syntactically valid directives are: @(banana) @(a b c (d e f)) @( a (b (c d) (e ) )) @("apple" 'b' 3) @(a /[a-z]*/ b) @(_ `@file.txt`) A symbol is lexically the same thing as a variable and the same rules apply. Tokens that look like numbers are treated as numbers. String and character literals are delimited by double and single quotes, respectively, and may not span multiple lines. Character literals must contain exactly one character. Character and numeric escapes may be used within literals to escape the quotes, and to denote control characters. Quasiliterals are similar to string literals, except that they may contain variable references denoted by the usual @ syntax. The quasiliteral represents a string formed by substituting the values of those variables into the literal template. If a is bound to "apple" and b to "banana", the quasiliteral `one@a and two @{b}s` represents the string "one apple and two bananas". A backquote escaped by a backslash represents itself, and two consecutive @ characters code for a literal @. There is no \e@ escape. Some directives are involved in structuring the overall syntax of the query. There are syntactic constraints that depend on the directive. Some directives are "vertical only". They must occur on a line by themselves. If they are involved in additional syntax, it is line-oriented. Others work horizontally. They can occur anywhere in a line, and if they are involved in syntax, it hs character-oriented. Some work in both modes, with slightly different semantics. A summary of the available directives follows: .IP @(eof) Explicitly match the end of file. Fails if unmatched data remains in the input stream. .IP @(eol) Explicitly match the end of line. Fails if the the current position is not the end of a line. Also Fails if no data remains (there is no current line). .IP @(next) Continue matching in another file or other data source. .IP @(block) The remaining query is treated as an anonymous or named block. Blocks may be referenced by @(accept) and @(fail) directives. Blocks are discussed in the section BLOCKS below. .IP @(skip) Treat the remaining query as a subquery unit, and search the lines (or characters) of the input file until that subquery matches somewhere. A skip is also an anonymous block. .IP @(trailer) Treat the remaining query or subquery as a match for a trailing context. That is to say, if the remainder matches, the data position is not advanced. .IP @(freeform) Treat the remainder of the input as one big string, and apply the following query line to that string. The newline characters (or custom separators) appear explicitly in that string. .IP @(some) Multiple clauses are each applied to the same input. Succeeds if at least one of the clauses matches the input. The bindings established by earlier successful clauses are visible to the later clauses. .IP @(all) Multiple clauses are applied to the same input. Succeeds if and only if each one of the clauses matches. The clauses are applied in sequence, and evaluation stops on the first failure. The bindings established by earlier successful clauses are visible to the later clauses. .IP @(none) Multiple clauses are applied to the same input. Succeeds if and only if none of them match. The clauses are applied in sequence, and evaluation stops on the first success. No bindings are ever produced by this construct. .IP @(maybe) Multiple clauses are applied to the same input. No failure occurs if none of them match. The bindings established by earlier successful clauses are visible to the later clauses. .IP @(cases) Multiple clauses are applied to the same input. Evaluation stops on the first successful clause. .IP @(choose) Multiple clauses are applied to the same input. The one whose effect persists is the one which maximizes or minimizes the length of a particular variable. .IP @(define\ NAME\ (\ ARGUMENTS\ ...)) Introduces a function. Functions are discussed in the FUNCTIONS section below. .IP @(collect) Search the data for multiple matches of a clause. Collect the bindings in the clause into lists, which are output as array variables. The @(collect) directive is line oriented. It works with a multi-line pattern and scans line by line. A similar directive called @(coll) works within one line. A collect is an anonymous block. .IP @(and) Separator of clauses for @(some), @(all), @(none), @(maybe) and @(cases). Equivalent to @(or). Choice is stylistic. .IP @(or) Separator of clauses for @(some), @(all), @(none), @(maybe) and @(cases). Equivalent to @(and). Choice is stylistic. .IP @(end) Required terminator for @(some), @(all), @(none), @(maybe), @(cases), @(collect), @(coll), @(output), and @(repeat). .IP @(fail) Terminate the processing of a block, as if it were a failed match. Blocks are discussed in the section BLOCKS below. .IP @(accept) Terminate the processing of a block, as if it were a successful match. What bindings emerge may depend on the kind of block: collect has special semantics. Blocks are discussed in the section BLOCKS below. .IP @(try) Indicates the start of a try block, which is related to exception handling, discussed in the EXCEPTIONS section below. .IP @(catch),\ @(finally) Special clauses within @(try). See EXCEPTIONS below. .IP @(defex),\ @(throw) Define custom exception types; throw an exception. See EXCEPTIONS below. .IP @(flatten) Normalizes a set of specified variables to one-dimensional lists. Those variables which have scalar value are reduced to lists of that value. Those which are lists of lists (to an arbitrary level of nesting) are converted to flat lists of their leaf values. .IP @(merge) Binds a new variable which is the result of merging two or more other variables. Merging has somewhat complicated semantics. .IP @(cat) Decimates a list (any number of dimensions) to a string, by catenating its constituent strings, with an optional separator string between all of the values. .IP @(bind) Binds one or more variables against another variable using a structural pattern. A limited form of unification takes place which can cause a match to fail. .IP @(set) Destructively assigns one or more existing variables using a structural pattern, using syntax similar to bind. Assignment to unbound variables triggers an error. .IP @(output) A directive which encloses an output clause in the query. An output section does not match text, but produces text. The directives above are not understood in an output clause. .IP @(repeat) A directive understood within an @(output) section, for repeating multi-line text, with successive substitutions pulled from lists. The directive @(rep) produces iteration over lists horizontally within one line. .IP @(deffilter) This directive is used for defining named filters, which are useful for filtering variable substitutions in output blocks. Filters are useful when data must be translated between different representations that have different special characters or other syntax, requiring escaping or similar treatment. Note that it is also possible to use a function as a filter. See Function Filters below. .IP @(filter) The filder directive passes one or more variables through a given filter or chain or filters, updating them with the filtered values. .PP .SS The Next Directive The next directive comes in two forms, one of which is obsolescent syntax. The directive indicates that the remainder of the query is to be applied to a new input source. In the first form, it can occur by itself as the only element in a query line, with, or without arguments: @(next) @(next SOURCE) @(next SOURCE :nothrow) @(next :args) @(next :list EXPR) @(next :string EXPR) The lone @(next) without arguments switches to the next file in the argument list which was passed to the .B txr utility. If SOURCE is given, it must be text-valued expression which denotes an input source; it may be a string literal, quasiliteral or a variable. For instance, if variable A contains the text "data", then @(next A) means switch to the file called "data", and @(next `@A.txt`) means to switch to the file "data.txt". If the input source cannot be opened for whatever reason, .B txr throws an exception (see EXCEPTIONS below). An unhandled exception will terminate the program. Often, such a drastic measure is inconvenient; if @(next) is invoked with the :nothrow keyword, then if the input source cannot be opened, the situation is treated as a simple match failure. The variant @(next :args) means that the remaining command line arguments are to be treated as a data source. For this purpose, each argument is considered to be a line of text. If an argument is currently being processed as an input source, that argument is included. Note that if the first entry in the argument list does not name an input source, then the query should begin with @(next :args) or some other form of next directive, to prevent an attempt to open the input source named by that argument. If the very first directive of a query is any variant of the next directive, then .B txr avoids opening the first input source, but it does open the input source for any other directive, even one which does not consume any data. The syntax @(next :list EXPR) treats the expression as a source of text. The value of the expression is flattened to a list in a way similar to the @(flatten) directive. The resulting list is treated as if it were the lines of a text file: each element of the list is a line. If the lines happen contain embedded newline characters, they are a visible constituent of the line, and do not act as line separators. The syntax @(next :string EXPR) treats the expression as a source of text. The value of the expression must be a string. Newlines in the string are interpreted as line terminators. A string which is not terminated by a newline is tolerated, so that: @(next :string "abc") @a binds a to "abc". Likewise, this is also the case with input files and other streams whose last line is not terminated by a newline. However, watch out for empty strings, which are analogous to a correctly formed empty file which contains no lines: @(next :string "") @a This will not bind a to ""; it is a matching failure. The behavior of :list is different. The query @(next :list "") @a binds a to "". The reason is that under :list the string "" is flattened to the list ("") which is not an empty input stream, but a stream consisting of one empty line. Note that "remainder of the query" which is applied to the stream opened by @(next) refers to the subquery in which the next directive appears, not necessarily the entire query. For example, the following query looks for the line starting with "xyz" at the top of the file "foo.txt", within a some directive. After the @(end) which terminates the @(some), the "abc" is matched in the previous file again. @(some) @(next "foo.txt") xyz@suffix @(end) abc However, if the @(some) subquery successfully matched "xyz@suffix" within the file foo.text, there is now a binding for the suffix variable, which is visible to the remainder of the entire query. The variable bindings survive beyond the clause, but the data stream does not. The @(next) directive supports the file name conventions as the command line. The name - means standard input. Text which starts with a ! is interpreted as a shell command whose output is read like a file. These interpretations are applied after variable substitution. If the file is specified as @a, but the variable a expands to "!echo foo", then the output of the "echo foo" command will be processed. .SS The Skip Directive The skip directive considers the remainder of the query as a search pattern. The remainder is no longer required to strictly match at the current line in the current file. Rather, the current file is searched, starting with the current line, for the first line where the entire remainder of the query will successfully match. If no such line is found, the skip directive fails. If a matching position is found, the remainder of the query is understood to be processed there. Of course, the remainder of the query can itself contain skip directives. Each such directive performs a recursive subsearch. Skip comes in vertical and horizontal flavors. For instance, skip and match the last line: @(skip) @last @(eof) Skip and match the last character of the line: @(skip)@{last 1}@(eol) The skip directive has two optional arguments. If the first argument is a number, its value limits the range of lines scanned for a match. Judicious use of this feature can improve the performance of queries. Example: scan until "size: @SIZE" matches, which must happen within the next 15 lines: @(skip 15) size: @SIZE Without the range limitation skip will keep searching until it consumes the entire input source. While sometimes this is what is intended, often it is not. Sometimes a skip is nested within a collect, or following another skip. For instance, consider: @(collect) begin @BEG_SYMBOL @(skip) end @BEG_SYMBOL @(end) The collect iterates over the entire input. But, potentially, so does the skip. Suppose that "begin x" is matched, but the data has no matching "end x". The skip will search in vain all the way to the end of the data, and then the collect will try another iteration back at the beginning, just one line down from the original starting point. If it is a reasonable expectation that an "end x" occurs 15 lines of a "begin x", this can be written instead: @(collect) begin @BEG_SYMBOL @(skip 15) end @BEG_SYMBOL @(end) If the symbol nil is used in place of a number, it means to scan an unlimited range of lines; thus, @(skip nil) is equivalent to @(skip). If the symbol :greedy is used, it changes the semantics of the skip to longest match semantics, like the regular expression * operator. For instance, match the last three space-separated tokens of the line: @(skip :greedy) @a @b @c Without :greedy, the variable @c will can match multiple tokens, and end up with spaces in it, because nothign follows @c and so it matches from any position which follows a space to the end of the line. Also note the space in front of @a. Without this space, @a will get an empty string. A line oriented example of greedy skip: match the last line without using @eof: @(skip :greedy) @last_line There may be a second numeric argument. This specifies a minimum number of lines to skip before looking for a match. For instance, skip 15 lines and then search indefinitely for "begin ...": @(skip nil 15) begin @BEG_SYMBOL The two arguments may be used together. For instance, the following matches if, and only if, the 15th line of input starts with "begin ": @(skip 1 15) begin @BEG_SYMBOL Essentially, @(skip 1 ) means "hard skip by " lines, then match the query without scanning. @(skip 1 0) is the same as @(skip 1), which is a noop, because it means: "the remainder of the query must match starting on the very next line", or, more briefly, "skip exactly zero lines", which is the behavior if the skip directive is omitted altogether. Here is one trick for grabbing the fourth line from the bottom of the input: @(skip) @fourth_from_bottom @(skip 1 3) @(eof) Or using greedy skip: @(skip :greedy) @fourth_from_bottom @(skip 1 3) Nongreedy skip with the @(eof) has a slight advantage because the greedy skip will keep scanning even though it has found the correct match, then backtrack to the last good match once it runs out of data. The regular skip with explicit @(eof) will stop when the @(eof) matches. .SS The Trailer Directive The trailer directive introduces a trailing portion of a query or subquery which matches input material normally, but in the event of a successful match, does not advance the current position. This can be used, for instance, to cause @(collect) to match partially overlapping regions. Example: @(collect) @line @(trailer) @(skip) @line @(end) This script collects each line which has a duplicate somewhere later in the input. Without the @(trailer) directive, this does not work properly for inputs like: 111 222 111 222 Without @(trailer), the first duplicate pair constitutes a match which spans over the 222. After that pair is found, the matching continues after the second 111. With the @(trailer) directive in place, the collect body, on each iteration, only consumes the lines matched prior to @(trailer). .SS The Freeform Directive The freeform directive provides a useful alternative to .B txr's line-oriented matching discipline. The freeform directive treats all remaining input from the current input source as one big line. The query line which immediately follows freeform is applied to that line. The syntax variations are: @(freeform) ... query line .. @(freeform NUMBER) ... query line .. @(freeform STRING) ... query line .. @(freeform NUMBER STRING) ... query line .. The string and numeric arguments, if both are present, may be given in either order. If a numeric argument is given, it limits the range of lines which are combined together. For instance @(freeform 5) means to only consider the next five lines to to be one big line. Without a numeric argument, freeform is "bottomless". It can match the entire file, which creates the risk of allocating a large amount of memory. If a string argument is given, it specifies a custom line terminator. The default terminator is "\en". The terminator does not have to be one character long. Freeform does not convert the entire remainder of the input into one big line all at once, but does so in a dynamic, lazy fashion, which takes place as the data is accessed. So at any time, only some prefix of the data exists as a flat line in which newlines are replaced by the terminator string, and the remainder of the data still remains as a list of lines. After the subquery is applied to the virtual line, the unmatched remainder of that line is broken up into multiple lines again, by looking for and removing all occurences of the terminator string within the flattened portion. Care must be taken if the terminator is other than the default "\en". All occurences of the terminator string are treated as line terminators in the flattened portion of the data, so extra line breaks may be introduced. Likewise, in the yet unflattened portion, no breaking takes place, even if the text contains occurences of the terminator string. The extent of data which is flattened, and the amount of it which remains, depends entirely on the query line underneath @(flatten). In the following example, lines of data are flattened using $ as the line terminator. Query: @(freeform "$") @a$@b: @c @d Data: 1 2:3 4 Output: a="1" b="2" c="3" d="4" The data is turned into the virtual line 1$2:3$4$. The @a$@b: subquery matches the 1$2: portion, binding a to 1, and b to 2. The remaining portion 3$4$ is then split into separate lines again according to the line terminator $: 3 4 Thus the remainder of the query @c @d faces these lines, binding c to 3 and d to 4. Note that since the data does not contain dollar signs, there is no ambiguity; the meaning may be understood in terms of the entire data being flattened and split again. In the following example, freeform is used to solve a tokenizing problem. The Unix password file has fields separated by colons. Some fields may be empty. Using freeform, we can join the password file using ":" as a terminator. By restricting freeform to one line, we can obtain each line of the password file with a terminating ":", allowing for a simple tokenization, because now the fields are colon-terminated rather than colon-separated. Example: @(next "/etc/passwd") @(collect) @(freeform 1 ":") @(coll)@{token /[^:]*/}:@(end) @(end) .SS The Some, All, None, Maybe, Cases and Choose directives These directives, called the parallel directives, combine multiple subqueries, which are applied at the same input position, rather than to consecutive input. They come in vertical (line mode) and horizontal (character mode) flavors. In horizontal mode, the current position is understood to be a character position in the line being processed. The clauses advance this character position by moving it to the right. In vertical mode, the current position is understood to be a line of text within the stream. A clause advances the position by some whole number of lines. The syntax of these parallel directives follows this example: @(some) subquery1 . . . @(and) subquery2 . . . @(and) subquery3 . . . @(end) And in horizontal mode: @(some)subquery1...@(and)subquery2...@(and)subquery3...@(end) Long horizontal lines can be broken up with line continuations, allowing the above example to be written like this, which is considered a single logical line: @(some)@\ subquery1...@\ @(and)@\ subquery2...@\ @(and)@\ subquery3...@\ @(end) The @(some), @(all), @(none), @(maybe), @(cases) or @(choose) must be followed by at least one subquery clause, and be terminated by @(end). If there are two or more subqueries, these additional clauses are indicated by @(and) or @(or), which are interchangeable. The separator and terminator directives also must appear as the only element in a query line. The choose directive requires keyword arguments. See below. The syntax supports arbitrary nesting. For example: QUERY: SYNTAX TREE: @(all) all -+ @ (skip) +- skip -+ @ (some) | +- some -+ it | | +- TEXT @ (and) | | +- and @ (none) | | +- none -+ was | | | +- TEXT @ (end) | | | +- end @ (end) | | +- end a dark | +- TEXT @(end) *- end nesting can be indicated using whitespace between @ and the directive expression. Thus, the above is an @(all) query containing a @(skip) clause which applies to a @(some) that is followed by the the text line "a dark". The @(some) clause combines the text line "it", and a @(none) clause which contains just one clause consisting of the line "was". The semantics of the parallel directives is: .IP @(all) Each of the clauses is matched at the current position. If any of the clauses fails to match, the directive fails (and thus does not produce any variable bindings). Clauses following the failed directive are not evaluated. Bindings extracted by a successful clause are visible the clauses which follow, and if the directive succeeds, all of the combined bindings emerge. .IP @(some) Each of the clauses is matched at the current position. If any of the clauses succeed, the directive succeeds, retaining the bindings accumulated by the successully matching clauses. Evaluation does not stop on the first successful clause. Bindings extracted by a successful clause are visible to the clauses which follow. .IP @(none) Each of the clauses is matched at the current position. The directive succeeds only if all of the clauses fail. If any clause succeeds, the directive fails, and subsequent clauses are not evaluated. Thus, this directive never produces variable bindings, only matching success or failure. .IP @(maybe) Each of the clauses is matched at the current position. The directive always succeeds, even if all of the clauses fail. Whatever bindings are found in any of the clauses are retained. Bindings extracted by any successful clause are visible the clauses which follow. .IP @(cases) Each of the clauses is matched at the current position. The The clauses are matched, in order, at the current position. If any clause matches, the matching stops and the bindings collected from that clause are retained. Any remaining clauses after that one are not processed. If no clause matches, the directive fails, and produces no bindings. .IP @(choose { :longest | :shortest }) Each of the clauses is matched at the current position in order. In this construct, bindings established an earlier clause are not visible to later clauses. Although any or all of the clauses can potentially match, the clause which succeeds is the one which maximizes or minimizes the length of the text bound to the specified variable. The other clauses have no effect. For all of the parallel directives other than @(none) and @(choose), the query advances the input position by the greatest number of lines that match in any of the successfully matching subclauses that are evaluated. The @(none) directive does not advance the input position. For instance if there are two subclauses, and one of them matches three lines, but the other one matches five lines, then the overall clause is considered to have made a five line match at its position. If more directives follow, they begin matching five lines down from that position. .SS The Collect Directive The syntax of the collect directive is: @(collect) ... lines of subquery @(end) or with an until or last clause: @(collect) ... lines of subquery: main clause @(until) ... lines of subquery: until clause @(end) @(collect) ... lines of subquery: main clause @(last) ... lines of subquery: last clause @(end) The subquery is matched repeatedly, starting at the current line. If it fails to match, it is tried starting at the subsequent line. If it matches successfully, it is tried at the line following the entire extent of matched data, if there is one. Thus, the collected regions do not overlap. Unless certain keywords are specified, or unless the collect is explicitly failed with @(fail), it always succeeds, even if it collects nothing, and even if the until/last clause never finds a match. If no until/last clause is specified, and the collect is not limited using parameters, the collect is unbounded. It consumes the entire data file. If any query material follows such the collect clause, it will fail if it tries to match anything in the current file; but of course, it is possible to continue matching in another file by means of @(next). If an until/last clause is specified, the collection stops when that clause matches at the current position. If it is an until clause, no bindings are collected at that position, even if the main clause matches at that position also. Moreover, the position is not advanced. The remainder of the query begins matching at that position. If it is a last clause matches, the behavior is different. Any bindings captured by the main clause thrown away, just like with the until clause. However, the bindings in the last clause itself survive, and the position is advanced to skip over that material. Example: Query: @(collect) @a @(until) 42 @b @(end) @c Data: 1 2 3 42 5 6 Output: a[0]="1" a[1]="2" a[2]="3" c="42" The line 42 is not collected, even though it matches @a. Furthermore, the until does not advance the position, so variable c takes 42. If the @(until) is changed to @(last) the output will be different: Output: a[0]="1" a[1]="2" a[2]="3" b=5 c=6 The 42 is not collected into the a list, just like before. But now the binding captured by @b emerges. Furthermore, the position advances so variable now takes 6. The binding variables within the clause of a collect are treated specially. The multiple matches for each variable are collected into lists, which then appear as array variables in the final output. Example: Query: @(collect) @a:@b:@c @(end) Data: John:Doe:101 Mary:Jane:202 Bob:Coder:313 Output: a[0]="John" a[1]="Mary" a[2]="Bob" b[0]="Doe" b[1]="Jane" b[2]="Coder" c[0]="101" c[1]="202" c[2]="313" The query matches the data in three places, so each variable becomes a list of three elements, reported as an array. Variables with list bindings may be referenced in a query. They denote a multiple match. The -D command line option can establish a one-dimensional list binding. Collect clauses may be nested. Variable matches collated into lists in an inner collect, are again collated into nested lists in the outer collect. Thus an unbound variable wrapped in N nestings of @(collect) will be an N-dimensional list. A one dimensional list is a list of strings; a two dimensional list is a list of lists of strings, etc. It is important to note that the variables which are bound within the main clause of a collect---i.e. the variables which are subject to collection---appear, within the collect, as normal one-value bindings. The collation into lists happens outside of the collect. So for instance in the query: @(collect) @x=@x @(end) The left @x establishes a binding for some material preceding an equal sign. The right @x refers to that binding. The value of @x is different in each iteration, and these values are collected. What finally comes out of the collect clause is list variable called x which holds each value that was ever instantiated under that name within the collect clause. Also note that the until clause has visibility over the bindings established in the main clause. This is true even in the terminating case when the until clause matches, and the bindings of the main clause are discarded. .SS Collect Keyword Parameters By default, collect searches the rest of the input indefinitely, or until the @(until) clause matches. It skips arbitrary amounts of nonmatching material before the first match, and between matches. Within the @(collect) syntax, it is possible to specify some useful keyword parameters for additional control of the behavior. For instance @(collect :maxgap 5) means that the collect will terminate if it does not find a match within five lines of the starting position, or if more than five lines are skipped since any successful match. A :maxgap of 0 means that the collected regions must be adjacent. For instance: @(collect :maxgap 0) M @a @(end) means: from here, collect consecutive lines of the form "M ...". This will not search for the first such line, nor will it skip lines which do not match this form. Other keywords are :mingap, and :gap. The :mingap keyword specifies a minimum gap between matches, but has no effect on the distance to the first match. The :gap keyword specifies :mingap and :maxgap at the same time, and can only be used if these other two are not used. Thus: @(collect :gap 1) @a @(end) means collect every other line starting with the current line. Several other supported keywords are :times, :mintimes, :maxtimes and lines. The shorthand :times N means the same thing as :mintimes N :maxtimes N. These specify how many matches should be collected. If there are fewer than mintimes matches, the collect fails. If maxtimes matches are collected, collect stops collecting immediately. Example: @(collect :times 3) @a @b @(end) This will collect a match for "@a @b" exactly three times. If three matches are not found, it will fail. The :lines parameter specifies the upper bound on how many lines should be scanned by collect, measuring from the starting position. The extent of the collect body is not counted. Example: @(collect :lines 2) foo: @a bar: @b baz: @c @(end) The above collect will look for a match only twice: at the current position, and one line down. There is one more keyword, :vars, discussed in the following section. .SS Specifying Variables in Collect Normally, any variable for which a new binding occurs in a collect is collected. A collect clause may be sloppy: it can neglect to collect some variables on some iterations, or bind some variables which behave like local temporaries, but end up collated into lists. Another issue is that the collect clause might not match anything at all, and then none of the variables are bound. The :vars keyword allows the query writer to add discipline the collect body. The argument to :vars is a list of variable specs. A variable spec is either a symbol, or a ( ) pair, where the expression specifies a default value. When a :vars list is specified, it means that only the given variables can emerge from the successful collect. Any newly introduced bindings for other variables do not propagate. Furthermore, for any variable which is not specified with a default value, the collect body, whenever it matches successfully, must bind that variable. If it neglects to bind the variable, an exception of type query_error is thrown. For any variable which does have a default value, if the collect body neglects to bind that variable, the behavior is as if the collect did bind that variable to that default value. The default values are expressions, and so can be quasiliterals. Lastly, if in the event that the collect does not match anything, the variables specified in vars (whether or not they have a default value) are all bound to empty lists. (These bindings are established after the processing of the until/last clause, if present.) Example: @(collect :vars (a b (c "foo"))) @a @c @(end) Here, if the body "@a @c" matches, an error will be thrown because one of the mandatory variables is b, and the body neglects to produce a binding for b. Example: @(collect :vars (a (c "foo"))) @a @b @(end) Here, if "@a @b" matches, only a will be collected, but not b, because b is not in the variable list. Furthermore, because there is no binding for c in the body, a binding is created with the value "foo", exactly as if c matched such a piece of text. In the following example, the assumption is that THIS NEVER MATCHES is not found anywhere in the input but the line THIS DOES MATCH is found and has a successor which is bound to a. Because the body did not match, the :vars a and b should be bound to empty lists. But a is bound by the last clause to some text, so this takes precedence. Only b is bound to a an empty list. @(collect :vars (a b) THIS NEVER MATCHES @(last) THIS DOES MATCH @a @(end) .SS The Coll Directive The coll directive is a kind of miniature version of the collect directive. Whereas the collect directive works with multi-line clauses on line-oriented material, coll works within a single line. With coll, it is possible to recognize repeating regularities within a line and collect lists. Regular-expression based Positive Match variables work well with coll. Example: collect a comma-separated list, terminated by a space. pattern: @(coll)@{A /[^, ]+/}@(until) @(end)@B data: foo,bar,xyzzy blorch result: A[0]="foo" A[1]="bar" A[2]="xyzzy" B=blorch Here, the variable A is bound to tokens which match the regular expression /[^, ]+/: non-empty sequence of characters other than commas or spaces. Like its big cousin, the coll directive searches for matches. If no match occurs at the current character position, it tries at the next character position. Whenever a match occurs, it continues at the character position which follows the last character of the match, if such a position exists. If not bounded by an until clause, it will exhaust the entire line. If the until clause matches, then the collection stops at that position, and any bindings from that iteration are discarded. Like collect, coll also supports a last clause, which propagates varaible bindings and advances the position. Coll clauses nest, and variables bound within a coll are available to within the rest of the coll clause, including the until clause, and appear as single values. The final list aggregation is only visible after the coll clause. The behavior of coll is troublesome, when delimited variables are used, because in text file formats, the material which separates items is not repeated after the last item. For instance, a comma-separated list usually not appear as "a,b,c," but rather "a,b,c". There might not be any explicit termination---the last item might be at the very end of the line. So for instance, the following result is not satisfactory: pattern: @(coll)@a @(end) data: 1 2 3 4 5 result: a[0]="1" a[1]="2" a[2]="3" a[3]="4" What happened to the 5? After matching "4 ", coll continues to look for matches. It tries "5", which does not match, because it is not followed by a space. Then the line is consumed. So in this sequence, a valid item is either followed by a space, or by nothing. So it is tempting to try this: pattern: @(coll)@a@/ ?/@(end) data: 1 2 3 4 5 result: a[0]="" a[1]="" a[2]="" a[3]="" a[4]="" a[5]="" a[6]="" a[7]="" a[8]="" however, the problem is that the regular expression / ?/ (match either a space or nothing), matches at any position. So when it is used as a variable delimiter, it matches at the current position, which binds the empty string to the variable, the extent of the match being zero. In this situation, the coll directive proceeds character by character. The solution is to use positive matching: specify the regular expression which matches the item, rather than a trying to match whatever follows. The collect directive will recognize all items which match the regular expression. pattern: @(coll)@{a /[^ ]+/}@(end) data: 1 2 3 4 5 result: a[0]="1" a[1]="2" a[2]="3" a[3]="4" a[4]="5" The until clause can specify a pattern which, when recognized, terminates the collection. So for instance, suppose that the list of items may or may not be terminated by a semicolon. We must exclude the semicolon from being a valid character inside an item, and add an until clause which recognizes a semicolon: pattern: @(coll)@{a /[^ ;]+/}@(until);@(end); data: 1 2 3 4 5; result: a[0]="1" a[1]="2" a[2]="3" a[3]="4" a[4]="5" data: 1 2 3 4 5; result: a[0]="1" a[1]="2" a[2]="3" a[3]="4" a[4]="5" Semicolon or not, the items are collected properly. Note that the @(end) is followed by a semicolon. That's because when the @(until) clause meets a match, the matching material is not consumed. Instead of regular expression hacks, this problem can be nicely solved with cases: pattern: @(coll)@(cases)@a @(or)@a@(end)@(end) data: 1 2 3 4 5 result: a[0]="1" a[1]="2" a[2]="3" a[3]="4" a[4]="5" .SS Coll Keyword Parameters The @(coll) directive takes most of the same parameters as @(collect). See the section Collect Keyword Parameters above. So for instance @(coll :gap 0) means that the collects must be consecutive, and @(coll :maxtimes 2) means that at most two matches will be collected. The :lines keyword does not exist, but there is an analogous :chars keyword. .SS The Flatten Directive. The flatten directive can be used to convert variables to one dimensional lists. Variables which have a scalar value are converted to lists containing that value. Variables which are multidimensional lists are flattened to one-dimensional lists. Example (without @(flatten)) pattern: @b @(collect) @(collect) @a @(end) @(end) data: 0 1 2 3 4 5 result: b="0" a_0[0]="1" a_1[0]="2" a_2[0]="3" a_3[0]="4" a_4[0]="5" Example (with flatten): pattern: @b @(collect) @(collect) @a @(end) @(end) @(flatten a b) data: 0 1 2 3 4 5 result: b[0]="0" a[0]="1" a[1]="2" a[2]="3" a[3]="4" a[4]="5" .SS The Merge Directive The merge directive provides a way of combining two or more variables in a somewhat complicated but very useful way. To understand what merge does we first have to define a property called depth. The depth of an atom such as a string is defined as 1. The depth of an empty list is 0. The depth of a nonempty list is one plus the depth of its deepest element. So for instance "foo" has depth 1, ("foo") has depth 2, and ("foo" ("bar")) has depth three. We can now define the binary (two argument) merge operation as follows. (merge A B) first normalizes the values A and B such that they have normal depth. 1. A value which has depth zero is put into a one element list. 2. If either value has a smaller depth than the other, it is wrapped in a list as many times as needed to give it equal depth. Finally, the values are appended together. Merge takes more than two arguments. These are merged by a left reduction. The leftmost two values are merged, and then this result is merged with the third value, and so on. Merge is useful for combining the results from collects at different levels of nesting such that elements are at the appropriate depth. .SS The Cat Directive The @(cat) directive converts a list variable into a single piece of text. The syntax is: @(cat VAR [ SEP ]) The SEP argument specifies a separating piece of text. If no separator is specified, then a single space is used. Example: pattern: @(coll)@{a /[^ ]+/}@(end) @(cat a ":") data: 1 2 3 4 5 result: a="1:2:3:4:5" .SS The Bind Directive The syntax of the @(bind) directive is: @(bind pattern expression { keyword value }*) The @(bind) directive is a kind of pattern match, which matches one or more variables on in the left hand side pattern to the value of a variable on the right hand side. The right hand side variable must have a binding, or else the directive fails. Any variables on the left hand side which are unbound receive a matching piece of the right hand side value. Any variables on the left which are already bound must match their corresponding value, or the bind fails. Any variables which are already bound and which do match their corresponding value remain unchanged (the match can be inexact). The simplest bind is of one variable against itself, for instance bind A against A: @(bind A A) This will fail if A is not bound, (and complain loudly). If A is bound, it succeeds, since A matches A. The next simplest bind binds one variable to another: @(bind A B) Here, if A is unbound, it takes on the same value as B. If A is bound, it has to match B, or the bind fails. Matching means that either .IP - A and B are the same text .IP - A is text, B is a list, and A occurs within B. .IP - vice versa: B is text, A is a list, and B occurs within A. .IP - A and B are lists and are either identical, or one is found as substructure within the other. .PP The right hand side does not have to be a variable. It may be some other object, like a string, quasiliteral, regexp, or list of strings, et cetera. For instance @(bind A "ab\tc") will bind the string "ab\tc" (the letter a, b, a tab character, and c) to the variable A if A is unbound. If A is bound, this will fail unless A already contains an identical string. However, the right hand side of cannot be an unbound variable, nor a complex expression that contains unbound variables. The left hand side of a bind can be a nested list pattern containing variables. The last item of a list at any nesting level can be preceded by a dot, which means that the variable matches the rest of the list from that position. Example: suppose that the list A contains ("now" "now" "brown" "cow"). Then the directive @(bind (H N . C) A), assuming that H, N and C are unbound variables, will bind H to "how", N to "now", and C to the remainder of the list ("brown" "cow"). Example: suppose that the list A is nested to two dimensions and contains (("how" "now") ("brown" "cow")). Then @(bind ((H N) (B C)) A) binds H to "how", N to "now", B to "brown" and C to "cow". The dot notation may be used at any nesting level. it must be preceded and followed by a symbol: the forms (.) (. X) and (X .) are invalid. The number of items in a left pattern match must match the number of items in the corresponding right side object. So the pattern () only matches an empty list. The notation () and nil means exactly the same thing. The symbols nil, t and keyword symbols may be used on either side. They represent themselves. For example @(bind :foo :bar) fails, but @(bind :foo :foo) succeeds since the two sides denote the same keyword symbol object. .SS Keyword in The Bind Directive The Bind directive accepts these keywords .IP :lfilt The argument to :lfilt is a filter specification. When the left side pattern contains a binding which is therefore matched against its counterpart from the right side expression, the left side is filtered through the filter specified by :lfilt for the purposes of the comparison. For example: @(bind "a" "A" :lfilt :upcase) produces a match, since the left side is the same as the right after filtering through the :upcase filter. .IP :rfilt The argument to :rfilt is a filter specification. The specified filter is applied to the right hand side material prior to matching it against the left side. The filter is not applied if the left side is a variable with no binding. It is only applied to determine a match. Binding takes place the unmodified right hand side object. Example, the following produces a match: @(bind "A" "a" :rfilt :upcase) .IP :filter This keyword is a shorthand to specify both filters to the same value. So for instance :filter :upcase is equivalent to :lfilt :upcase :rfilt :upcase. For a description of filters, see Output Filtering below. Of course, compound filters like (:from_html :upcase) are supported with all these keywords. The filters apply across arbitrary patterns and nested data. Example: @(bind (a b c) ("A" "B" "C")) @(bind (a b c) (("z" "a") "b" "c") :rfilt :upcase) Here, the first bind establishes the values for a, b and c, and the second bind succeeds, because the value of a matches the second element of the list ("z" "a") if it is upcased, and likewise b matches "b" and c matches "c" if these are upcased. .SS The Set Directive The @(set) directive resembles bind, but is not a pattern match. It overwrites the previous values of variables with new values from the right hand side. Each variable that is assigned must have an existing binding. Examples follow. Store the value of A back into A, achieving nothing: @(set A A) Exchange the values of A and B: @(set (A B) (B A)) Store a string into A: @(set A "text") Store a list into A: @(set A ("line1" "line2")) Destructuring assignment. D assumed to contain the list @(bind D ("A" ("B1" "B2") "C1" "C2")) @(bind (A B C) (() () ())) @(set (A B . C) D) A ends up with "A", B ends up with ("B1" "B2") and C gets ("C1" and "C2"). .SH BLOCKS .SS Introduction Blocks are sections of a query which are denoted by a name. Blocks denoted by the name nil are understood as anonymous. The @(block NAME) directive introduces a named block, except when the name is the word nil. The @(block) directive introduces an unnamed block, equivalent to @(block nil). The @(skip) and @(collect) directives introduce implicit anonymous blocks, as do function bodies. .SS Block Scope The names of blocks are in a distinct namespace from the variable binding space. So @(block foo) has no interaction with the variable @foo. A block extends from the @(block ...) directive which introduces it, to the end of the subquery in which that directive is contained. For instance: @(some) abc @(block foo) xyz @(end) Here, the block foo occurs in a @(some) clause, and so it extends to the @(end) which terminates that clause. After that @(end), the name foo is not associated with a block (is not "in scope"). A block which is not contained in any subquery extends to the end of the overall query. Blocks are never terminated by @(end). The implicit anonymous block introduced by @(skip) has the same scope as the @(skip): they extends over all of the material which follows the skip, to the end of the containing subquery. .SS Block Nesting Blocks may nest, and nested blocks may have the same names as blocks in which they are nested. For instance: @(block) @(block) ... is a nesting of two anonymous blocks, and @(block foo) @(block foo) is a nesting of two named blocks which happen to have the same name. When a nested block has the same name as an outer block, it creates a block scope in which the outer block is "shadowed"; that is to say, directives which refer to that block name within the nested block refer to the inner block, and not to the outer one. A more complicated example of nesting is: @(skip) abc @(block) @(some) @(block foo) @(end) Here, the @(skip) introduces an anonymous block. The explicit anonymous @(block) is nested within skip's anonymous block and shadows it. The foo block is nested within both of these. .SS Block Semantics A block normally does nothing. The query material in the block is evaluated normally. However, a block serves as a termination point for @(fail) and @(accept) directives which are in scope of that block and refer to it. The precise meaning of these directives is: .IP @(fail\ NAME) Immediately terminate the enclosing query block called NAME, as if that block failed to match anything. If more than one block by that name encloses the directive, the inner-most block is terminated. No bindings emerge from a failed block. .IP @(fail) Immediately terminate the innermost enclosing anonymous block, as if that block failed to match. If the implicit block introduced by @(skip) is terminated in this manner, this has the effect of causing the skip itself to fail. I.e. the behavior is as if skip search did not find a match for the trailing material, except that it takes place prematurely (before the end of the available data source is reached). If the implicit block associated with a @(collect) is terminated this way, then the entire collect fails. This is a special behavior, because a collect normally does not fail, even if it matches and collects nothing! To prematurely terminate a collect by means of its anonymous block, without failing it, use @(accept). .IP @(accept\ NAME) Immediately terminate the enclosing query block called NAME, as if that block successfully matched. If more than one block by that name encloses the directive, the inner-most block is terminated. Any bindings established within that block until this point emerge from that block. .IP @(accept) Immediately terminate the innermost enclosing anonymous block, as if that block successfully matched. Any bindings established within that block until this point emerge from that block. If the implicit block introduced by @(skip) is terminated in this manner, this has the effect of causing the skip itself to succeed, as if all of the trailing material successfully matched. If the implicit block associated with a @(collect) is terminated this way, then the collection stops. All bindings collected in the current iteration of the collect are discarded. Bindings collected in previous iterations are retained, and collated into lists in accordance with the semantics of collect. Example: alternative way to @(until) termination: @(collect) @ (maybe) --- @ (accept) @ (end) @LINE @(end) This query will collect entire lines into a list called LINE. However, if the line --- is matched (by the embedded @(maybe)), the collection is terminated. Only the lines up to, and not including the --- line, are collected. The effect is identical to: @(collect) @LINE @(until) --- @(end) The difference (not relevant in these examples) is that the until clause has visibility into the bindings set up by the main clause. However, the following example has a different meaning: @(collect) @LINE @ (maybe) --- @ (accept) @ (end) @(end) Now, lines are collected until the end of the data source, or until a line is found which is followed by a --- line. If such a line is found, the collection stops, and that line is not included in the collection! The @(accept) terminates the process of the collect body, and so the action of collecting the last @LINE binding into the list is not performed. .SS Data Extent of Terminated Blocks A query block may have matched some material prior to being terminated by accept. In that case, it is deemed to have only matched that material, and not any material which follows. This may matter, depending on the context in which the block occurs. Example: Query: @(some) @(block foo) @first @(accept foo) @ignored @(end) @second Data: 1 2 3 Output: first="1" second="2" At the point where the accept occurs, the foo block has matched the first line, bound the text "1" to the variable @first. The block is then terminated. Not only does the @first binding emerge from this terminated block, but what also emerges is that the block advanced the data past the first line to the second line. So next, the @(some) directive ends, and propagates the bindings and position. Thus the @second which follows then matches the second line and takes the text "2". In the following query, the foo block occurs inside a maybe clause. Inside the foo block there is a @(some) clause. Its first subclause matches variable @first and then terminates block foo. Since block foo is outside of the @(some) directive, this has the effect of terminating the @(some) clause: Query: @(maybe) @(block foo) @ (some) @first @ (accept foo) @ (or) @one @two @three @four @ (end) @(end) @second Data: 1 2 3 4 5 Output: first="1" second="2" The second clause of the @(some) directive, namely: @one @two @three @four is never processed. The reason is that subclauses are processed in top to bottom order, but the processing was aborted within the first clause the @(accept foo). The @(some) construct never had the opportunity to match four lines. If the @(accept foo) line is removed from the above query, the output is different: Query: @(maybe) @(block foo) @ (some) @first @# <-- @(accept foo) removed from here!!! @ (or) @one @two @three @four @ (end) @(end) @second Data: 1 2 3 4 5 Output: first="1" one="1" two="2" three="3" four="4" second="5" Now, all clauses of the @(some) directive have the opportunity to match. The second clause grabs four lines, which is the longest match. And so, the next line of input available for matching is 5, which goes to the @second variable. .SH FUNCTIONS .SS Introduction .B txr functions allow a query to be structured to avoid repetition. On a theoretical note, because .B txr functions support recursion, functions enable txr to match some kinds of patterns which exhibit self-embedding, or nesting, and thus cannot be matched by a regular language. Functions in .B txr are not exactly like functions in mathematics or functional languages, and are not like procedures in imperative programming languages. They are not exactly like macros either. What it means for a .B txr function to take arguments and produce a result is different from the conventional notion of a function. A .B txr function may have one or more parameters. When such a function is invoked, an argument must be specified for each parameter. However, a special behavior is at play here. Namely, some or all of the argument expressions may be unbound variables. In that case, the corresponding parameters behave like unbound variables also. Thus .B txr function calls can transmit the "unbound" state from argument to parameter. It should be mentioned that functions have access to all bindings that are visible in the caller; functions may refer to variables which are not mentioned in their parameter list. With regard to returning, .B txr functions are also unconventional. If the function fails, then the function call is considered to have failed. The function call behaves like a kind of match; if the function fails, then the call is like a failed match. When a function call succeeds, then the bindings emanating from that function are processed specially. Firstly, any bindings for variables which do not correspond to one of the function's parameters are thrown away. Functions may internally bind arbitrary variables in order to get their job done, but only those variables which are named in the function argument list may propagate out of the function call. Thus, a function with no arguments can only indicate matching success or failure, but not produce any bindings. Secondly, variables do not propagate out of the function directly, but undergo a renaming. For each parameter which went into the function as an unbound variable (because its corresponding argument was an unbound variable), if that parameter now has a value, that value is bound onto the corresponding argument. Example: @(define collect_words (list)) @(coll)@{list /[^ \t]/}@(end) @(end) The above function "collect_words" contains a query which collects words from a line (sequences of characters other than space or tab), into the list variable called "list". This variable is named in the parameter list of the function, therefore, its value, if it has one, is permitted to escape from the function call. Suppose the input data is: Fine summer day and the function is called like this: @(collect_words wordlist) The result is: wordlist[0]=Fine wordlist[1]=summer wordlist[1]=day How it works is that in the function call @(collect_words wordlist), "wordlist" is an unbound variable. The parameter corresponding to that unbound variable is the parameter "list". Therefore, that parameter is unbound over the body of the function. The function body collects the words of "Fine summer day" into the variable "list", and then yields the that binding. Then the function call completes by noticing that the function parameter "list" now has a binding, and that the corresponding argument "wordlist" has no binding. The binding is thus transferred to the "wordlist" variable. After that, the bindings produced by the function are thrown away. The only enduring effects are: .IP - the function matched and consumed some input; and .IP - the function succeeded; and .IP - the wordlist variable now has a binding. .PP Another way to understand the parameter behavior is that function parameters behave like proxies which represent their arguments. If an argument is an established value, such as a character string or bound variable, the parameter is a proxy for that value and behaves just like that value. If an argument is an unbound variable, the function parameter acts as a proxy representing that unbound variable. The effect of binding the proxy is that the variable becomes bound, an effect which is settled when the function goes out of scope. Within the function, both the original variable and the proxy are visible simultaneously, and are independent. What if a function binds both of them? Suppose a function has a parameter called P, which is called with an argument A, and then in the function @A and @P are bound. This is permitted, and they can even be bound to different values. However, when the function terminates, the local binding of A simply disappears (because, remember, the symbol A is not a member of the list of parameters). Only the value bound to P emerges, and is bound to A, which still appears unbound at that point. .SS Definition Syntax A function definition begins with a @(define ...) directive which must be the only element in its line. The define must be followed by a symbol, which is the name of the function being defined. After the symbol, there is a parenthesized optional argument list. If there is no such list, or if the list is specified as () or the symbol "nil" then the function has no parameters. Examples of valid define syntax are: @(define foo) @(define bar ()) @(define match (a b c)) The define directive may be followed directly by the @(end) directive, also on a line by itself, in which case the function has an empty body. Or it may be followed by one or more query lines and then @(end). What is between a @(define ...) and its matching @(end) constitutes the function body. Functions may be nested within function bodies. Such local functions have dynamic scope. They are visible in the function body in which they are defined, and in any functions invoked from that body. The body of a function is an anonymous block. (See BLOCKS above). The following trivial function b produces no bindings and has a body which simply matches the line "begin". @(define b) begin @(end) Thus the call: @(b) matches an input line "begin". .SS Call Syntax A function is invoked by compound directive whose first symbol is the name of that function. Additional elements in the directive are the arguments. Arguments may be symbols, or other objects like string and character literals, quasiliterals ore regular expressions. Example: Query: @(define pair (a b)) @a @b @(end) @(pair first second) @(pair "ice" cream) Data: one two ice milk Output: first="one" second="two" cream="milk" The first call to the function takes the line "one two". The parameter "a" takes "one" and parameter b takes "two". These are rebound to the arguments first and second. The second call to the function binds the a parameter to the word "ice", and the b is unbound, because the corresponding argument "cream" is unbound. Thus inside the function, @a is forced to match "ice". Then a space is matched and @b collects the text "milk". When the function returns, the unbound "cream" variable gets this value. If a symbol occurs multiple times in the argument list, it constrains both parameters to bind to the same value. That is to say, all parameters which, in the body of the function, bind a value, and which are all derived from the same argument symbol must bind to the same value. This is settled when the function terminates, not while it is matching. Example: Query: @(define pair (a b)) @a @b @(end) @(pair same same) Data: one two Output: [query fails, prints "false"] .SS Nested Functions Function definitions may appear in a function. Such definitions are visible in all functions which are invoked from the body (and not necessarily enclosed in the body). In other words, the scope is dynamic, not lexical. Inner definitions shadow outer definitions. This means that a caller can redirect the function calls that take place in a callee, by defining local functions which capture the references. Example: Query: @(define which) @ (fun) @(end) @(define fun) @ (output) toplevel fun! @ (end) @(end) @(define callee) @ (define fun) @ (output) local fun! @ (end) @ (end) @ (which) @(end) @(callee) @(which) Output: local fun! toplevel fun! Here, the function "which" is defined which calls "fun". A toplevel definition of "fun" is introduced which outputs "toplevel fun!". The function "callee" provides its own local definition of "fun" which outputs "local fun!" before calling "which". When callee is invoked, it calls @(which), whose @(fun) call is routed to callee's local definition. When @(which) is called directly from the top level, its @(fun) call goes to the toplevel definition. .SH OUTPUT .SS Introduction A .B txr query may perform custom output. Output is performed by @(output) clauses, which may be embedded anywhere in the query, or placed at the end. Output occurs as a side effect of producing a part of a query which contains an @(output) directive, and is executed even if that part of the query ultimately fails to find a match. Thus output can be useful for debugging. An output clause specifies that its output goes to a file, pipe, or (by default) standard output. If any output clause is executed whose destination is standard output, .B txr makes a note of this, and later, just prior to termination, suppresses the usual printing of the variable bindings or the word false. .SS The Output Directive The syntax of the @(output) directive is: @(output [ DESTINATION ] { bool-keyword | keyword value }* ) . . one or more output directives or lines . @(end) The optional destination is a filename, the special name, - which redirects to standard output, or a shell command preceded by the ! symbol. In the first form, the destination may be specified as a variable which holds text, a string literal or a quasiliteral The keyword list consists of a mixture of boolean keywords which do not have an argument, or keywords with arguments. The following boolean keywords are supported: .IP :nothrow The output directive throws an exception if the output destination cannot be opened, unless the :nothrow keyword is present, in which case the situation is treated as a match failure. Note that since command pipes are processes that report errors asynchronously, a failing command will not throw an immediate exception that can be suppressed with :nothrow. This is for synchronous errors, like trying to open a destination file, but not having permissions, etc. .IP :append This keyword is meaningful for files, specifying append mode: the output is to be added to the end of the file rather than overwriting the file. The following value keywords are supported: .IP :filter The argument can be a symbol, which specifies a filter to be applied to the variable substitutions occuring within the output clause. The argument can also be a list of filter symbols, which specifies that multiple filters are to be applied, in left to right order. See the later sections Output Filtering below, and The Deffilter Directive. .IP :into The argument of :into is a symbol which denotes a variable. The output will go into that variable. If the variable is unbound, it will be created. Otherwise, its contents are overwritten unless the :append keyword is used. If :append is used, then the new content will be appened to the previous content of the variable, after flattening the content to a list, as if by the @(flatten) directive. .SS Output Text Text in an output clause is not matched against anything, but is output verbatim to the destination file, device or command pipe. .SS Output Variables Variables occurring in an output clause do not match anything, but instead their contents are output. A variable being output must be a simple string, not a list. Lists may be output within @(repeat) or @(rep) clauses. A list variable must be wrapped in as many nestings of these clauses as it has dimensions. For instance, a two-dimensional list may be mentioned in output if it is inside a @(rep) or @(repeat) clause which is itself wrapped inside another @(rep) or @(repeat) clause. In an output clause, the @{NAME NUMBER} variable syntax generates fixed-width field, which contains the variable's text. The absolute value of the number specifies the field width. For instance -20 and 20 both specify a field width of twenty. If the text is longer than the field, then it overflows the field. If the text is shorter than the field, then it is left-adjusted within that field, if the width is specified as a positive number, and right-adjusted if the width is specified as negative. An output variable may specify a filter which overrides any filter established for the output clause. The syntax for this is @(NAME :filter }. The filter specification syntax is the same as in the output clause. See Output Filtering below. .SS The Repeat Directive The repeat directive is generates repeated text from a ``boilerplate'', by taking successive elements from lists. The syntax of repeat is like this: @(repeat) . . main clause material, required . . special clauses, optional . . @(end) Repeat has four types of special clauses, any of which may be specified with empty contents, or omitted entirely. They are explained below. All of the material in the main clause and optional clauses is examined for the presence of variables. If none of the variables hold lists which contain at least one item, then no output is performed, (unless the repeat specifies an @(empty) clause, see below). Otherwise, among those variables which contain non-empty lists, repeat finds the length of the longest list. This length of this list determines the number of repetitions, R. If the repeat contains only a main clause, then the lines of this clause is output R times. Over the first repetition, all of the variables which, outside of the repeat, contain lists are locally rebound to just their first item. Over the second repetition, all of the list variables are bound to their second item, and so forth. Any variables which hold shorter lists than the longest list eventually end up with empty values over some repetitions. Example: if the list A holds "1", "2" and "3"; the list B holds "A", "B"; and the variable C holds "X", then @(repeat) >> @C >> @A @B @(end) will produce three repetitions (since there are two lists, the longest of which has three items). The output is: >> X >> 1 A >> X >> 2 B >> X >> 3 The last line has a trailing space, since it is produced by "@A @B", where @B has an empty value. Since C is not a list variable, it produces the same value in each repetition. The special clauses are: .IP @(single) If the repeat produces exactly one repetition, then the contents of this clause are processed for that one and only repetition, instead of the main clause or any other clause which would otherwise be processed. .IP @(first) The body of this clause specifies an alternative body to be used for the first repetition, instead of the material from the main clause. .IP @(last) The body of this clause is used instead of the main clause for the last repetition. .IP @(empty) If the repeat produces no repetitions, then the body of this clause is output. If this clause is absent or empty, the repeat produces no output. .PP The precedence among the clauses which take an iteration is: single > first > last > main. That is if two or more of these clauses can apply to a repetition, then the leftmost one in this precedence list applies. For instance, if there is just a single repetition, then any of these special clause types can apply to that repetition, since it is the only repetition, as well as the first and last one. In this situation, if there is a single clause present, then the repetition is processed using that clause. Otherwise, if there is a first clause present, that clause is used. Failing that, a last clause applies. Only if none of these clauses are present will the repetition be processed using the main clause. .SS Nested Repeats If a repeat clause encloses variables which holds multidimensional lists, those lists require additional nesting levels of repeat (or rep). It is an error to attempt to output a list variable which has not been decimated into primary elements via a repeat construct. Suppose that a variable X is two-dimensional (contains a list of lists). X must be twice nested in a repeat. The outer repeat will walk over the lists contained in X. The inner repeat will walk over the elements of each of these lists. A nested repeat may be embedded in any of the clauses of a repeat, not only the main clause. .SS The Rep Directive The @(rep) directive is similar to @(repeat), but whereas @(repeat) is line oriented, @(rep) generates material within a line. It has all the same clauses, but everything is specified within one line: @(rep)... main material ... .... special clauses ...@(end) More than one @(rep) can occur within a line, mixed with other material. A @(rep) can be nested within a @(repeat) or within another @(rep). .SS Repeat and Rep Examples Example 1: show the list L in parentheses, with spaces between the elements, or the symbol NIL if the list is empty: @(output) @(rep)@L @(single)(@L)@(first)(@L @(last)@L)@(empty)NIL@(end) @(end) Here, the @(empty) clause specifies NIL. So if there are no repetitions, the text NIL is produced. If there is a single item in the list L, then @(single)(@L) produces that item between parentheses. Otherwise if there are two or more items, the first item is produced with a leading parenthesis followed by a space by @(first)(@L , and the last item is produced with a closing parenthesis: @(last)@L). All items in between are emitted with a trailing space by the main clause: @(rep)@L . Example 2: show the list L like Example 1 above, but the empty list is (). @(output) (@(rep)@L @(last)@L@(end)) @(end) This is simpler. The parentheses are part of the text which surrounds the @(rep) construct, produced unconditionally. If the list L is empty, then @(rep) produces no output, resulting in (). If the list L has one or more items, then they are produced with spaces each one, except the last which has no space. If the list has exactly one item, then the @(last) applies to it instead of the main clause: it is produced with no trailing space. .SS Output Filtering Often it is necessary to transform the output to preserve its meaning under the convention of a given data format. For instance, if a piece of text contains the characters < or >, then if that text is being substituted into HTML, these should be replaced by < and >. This is what filtering is for. Filtering is applied to the contents of output variables, not to any template text. .B txr implements named filters. Built-in filters are named by keywords, given below. User-defined filters are possible, however. See notes on the deffilter directive below. Built-in filters: .IP :to_html Filter text to HTML, representing special characters using HTML ampersand sequences. For instance '>' is replaced by '>'. .IP :from_html Filter text with HTML codes into text in which the codes are replaced by the corresponding characters. For instance '>' is replaced by '>'. .IP :upcase Convert the 26 lower case letters of the English alphabet to upper case. .IP :downcase Convert the 26 upper case letters of the English alphabet to lower case. Example: to escape HTML characters in all variable substitutions occuring in an output clause, specify :filter :to_html in the directive: @(output :filter :to_html) ... @(end) To filter an individual variable, add the syntax to the variable spec: @(output) @{x :filter :to_html} @(end) Multiple filters can be applied at the same time. For instance: @(output) @{x :filter (:upcase :to_html)} @(end) This will fold the contents of x to upper case, and then encode any special characters into HTML. Beware of combinations that do not make sense. For instance, suppose the original text is HTML, containing codes like '"'. The compound filter (:upcase :from_html) will not work because '"' will turn to '"' which no longer be recognized by the :from_html filter, because the entity names in HTML codes are case-sensitive. Instead of a filter name, the syntax (fun NAME) can be used. This denotes that the function called NAME is to be used as a filter. This is discussed in the next section Function Filters below. .SS Function Filters A function can be used as a filter. For this to be possible, the function must conform to certain rules: .IP 1. The function must take two special arguments, which may be followed by additional arguments. .IP 2. When the function is called, the first argument will be bound to a string, and the second argument will be unbound. The function must produce a value by binding it to the second argument. If the filter is to be used as the final filter in a chain, it must produce a string. For instance, the following is a valid filter function: @(define foo_to_bar (in out) @ (next :string in) @ (cases) foo @ (bind out "bar") @ (or) @ (bind out in) @ (end) @(end) This function binds the out parameter to "bar" if the in parameter is "foo", otherwise it binds the out parameter to a copy of the in parameter. This is a simple filter. To use the filter, use the syntax (:fun foo_to_bar) in place of a filter name. For instance in the bind directive: @(bind "foo" "bar" :lfilt (:fun foo_to_bar)) The above should succeed since the left side is filtered from "foo" to "bar", so that there is a match. Of course, function filters can be used in a chain: @(output :filter (:downcase (:fun foo_to_bar) :upcase)) ... @(end) Here is a split function which takes an extra argument. @(define split (in out sep)) @ (next :list in) @ (coll)@(maybe)@token@sep@(or)@token@(end)@(end) @ (bind out token) @(end) Furthermore, note that it produces a list rather than a string. This function separates the argument in into tokens according to the separator text sep. Here is another function, join, which catenates a list: @(define join (in out sep)) @ (output :into out) @ (rep)@in@sep@(last)@in@(end) @ (end) @(end) Now here is these two being used in a chain: @(bind text "how,are,you") @(output :filter (:fun split ",") (:fun join "-")) @text @(end) Output: how-are-you When the filter invokes a function, it generates the first two arguments internally to pass in the input value and capture the output. The remaining arguments from the (:fun ...) construct are also passed to the function. Thus the "," and "-" are passed as the sep argument to split and join. Note that split puts out a list, which join accepts. So the overall filter chain operates on a string: a string goes into split, and a string comes out of join. .SS The Deffilter Directive The deffilter directive allows a query to define a custom filter, which can then be used in @(output) clauses to transform substituted data. This directive's syntax is illustrated in this example: Query: @(deffilter rot13 ("a" "n") ("b" "o") ("c" "p") ("d" "q") ("e" "r") ("f" "s") ("g" "t") ("h" "u") ("i" "v") ("j" "w") ("k" "x") ("l" "y") ("m" "z") ("n" "a") ("o" "b") ("p" "c") ("q" "d") ("r" "e") ("s" "f") ("t" "g") ("u" "h") ("v" "i") ("w" "j") ("x" "k") ("y" "l") ("z" "m")) @(collect) @line @(end) @(output :filter rot13) @(repeat) @line @(end) @(end) Input: hey there! Output: url gurer! The deffilter symbol must be followed by the name of the filter to be defined, followed by tuples of strings. Each tuple specifies one or more texts which are mapped to a replacement text. For instance, the following specifies a telephone keypad mapping from upper case letters to digits. @(deffilter alpha_to_phone ("E" "0") ("J" "N" "Q" "1") ("R" "W" "X" "2") ("D" "S" "Y" "3") ("F" "T" "4") ("A" "M" "5") ("C" "I" "V" "6") ("B" "K" "U" "7") ("L" "O" "P" "8") ("G" "H" "Z" "9")) Filtering works using a longest match algorithm. The input is scanned from left to right, and the longest piece of text is identified at every character position which matches a string on the left hand side, and that text is replaced with its associated replacement text. The scanning then continues at the first character after the matched text. If none of the strings matches at a given character position, then that character is passed through the filter untranslated, and the scan continues at the next character in the input. Filtering is not in-place but rather instantiates a new text, and so replacement text is not re-scanned for more replacements. If a filter definition accidentally contains two or more repetitions of the same left hand string with different right hand translations, the later ones take precedence. No warning is issued. .SS The Filter Directive The syntax of the filter directive is: @(filter FILTER { VAR }+ } A filter is specified, followed by one or more variables whose values are filtered and stored back into each variable. Example: convert a, b, and c to upper case and HTML encode: @(filter (:upcase :to_html) a b c) .SH EXCEPTIONS .SS Introduction The exceptions mechanism in .B txr is another disciplined form of non-local transfer, in addition to the blocks mechanism (see BLOCKS above). Like blocks, exceptions provide a construct which serves as the target for a dynamic exit. Both blocks and exceptions can be used to bail out of deep nesting when some condition occurs. However, exceptions provide more complexity. Exceptions are useful for error handling, and txr in fact maps certain error situations to exception control transfers. However, exceptions are not inherently an error-handling mechanism; they are a structured dynamic control transfer mechanism, one of whose applications is error handling. An exception control transfer (simply called an exception) is always identified by a symbol, which is its type. Types are organized in a subtype-supertype hierarchy. For instance, the file_error exception type is a subtype of the error type. This means that a file error is a kind of error. An exception handling block which catches exceptions of type error will catch exceptions of type file_error, but a block which catches file_error will not catch all exceptions of type error. A query_error is a kind of error, but not a kind of file_error. The symbol t is the supertype of every type: every exception type is considered to be a kind of t. (Mnemonic: t stands for type, as in any type). Exceptions are handled using @(catch) clauses within a @(try) directive. In addition to being useful for exception handling, the @(try) directive also provides unwind protection by means of a @(finally) clause, which specifies query material to be executed unconditionally when the try clause terminates, no matter how it terminates. .SS The Try Directive The general syntax of the try directive is @(try) ... main clause, required ... ... optional catch clauses ... ... optional finally clause @(end) A catch clause looks like: @(catch TYPE) . . . and also the this form, equivalent to @(catch (t)): @(catch) . . . which catches all exceptions. A finally clause looks like: @(finally) ... . . The main clause may not be empty, but the catch and finally may be. A try clause is surrounded by an implicit anonymous block (see BLOCKS section above). So for instance, the following is a no-op (an operation with no effect, other than successful execution): @(try) @(accept) @(end) The @(accept) causes a successful termination of the implicit anonymous block. Execution resumes with query lines or directives which follow, if any. Try clauses and blocks interact. For instance, a block accept from within a try clause invokes a finally. Query: @(block foo) @ (try) @ (accept foo) @ (finally) @ (output) bye! @ (end) @ (end) Output: bye! How this works: the try block's main clause is @(accept foo). This causes the enclosing block named foo to terminate, as a successful match. Since the try is nested within this block, it too must terminate in order for the block to terminate. But the try has a finally clause, which executes unconditionally, no matter how the try block terminates. The finally clause performs some output, which is seen. .SS The Finally Clause A try directive can terminate in one of three ways. The main clause may match successfully, and possibly yield some new variable bindings. The main clause may fail to match. Or the main clause may be terminated by a non-local control transfer, like an exception being thrown or a block return (like the block foo example in the previous section). No matter how the try clause terminates, the finally clause is processed. Now, the finally clause is itself a query which binds variables, which leads to the question: what happens to such variables? What if the finally block fails as a query? Another question is: what if a finally clause itself initiates a control transfer? Answers follow. Firstly, a finally clause will contribute variable bindings only if the main clause terminates normally (either as a successful or failed match). If the main clause successfully matches, then the finally block continues matching at the next position in the data, and contributes bindings. If the main clause fails, then the finally block matches at the same position. The overall try directive succeeds as a match if either the main clause or the finally clause succeed. If both fail, then the try directive is a failed match. The subquery in which it is located fails, et cetera. Example: Query: @(try) @a @(finally) @b @(end) @c Data: 1 2 3 Output: a=1 b=2 c=3 In this example, the main clause of the try captures line "1" of the data as variable a, then the finally clause captures "2" as b, and then the query continues with the @c variable after try block, and captures "3". Example: Query: @(try) hello @a @(finally) @b @(end) @c Data: 1 2 Output: b=1 c=2 In this example, the main clause of the try fails to match, because the input is not prefixed with "hello ". However, the finally clause matches, binding b to "1". This means that the try block is a successful match, and so processing continues with @c which captures "2". When finally clauses are processed during a non-local return, they have no externally visible effect if they do not bind variables. However, their execution makes itself known if they perform side effects, such as output. A finally clause guards only the main clause and the catch clauses. It does not guard itself. Once the finally clause is executing, the try block is no longer guarded. This means if a nonlocal transfer, such as a block accept or exception, is initiated within the finally clause, it will not re-execute the finally clause. The finally clause is simply abandoned. The disestablishment of blocks and try clauses is properly interleaved with the execution of finally clauses. This means that all surrounding exit points are visible in a finally clause, even if the finally clause is being invoked as part of a transfer to a distant exit point. The finally clause can make a control transfer to an exit point which is more near than the original one, thereby "hijacking" the control transfer. Also, the anonymous block established by the try directive is visible in the finally clause. Example: @(try) @ (try) @ (next "nonexistent-file") @ (finally) @ (accept) @ (end) @(catch file_error) @ (output) file error caught @ (end) @(end) In this example, the @(next) directive throws an exception of type file_error, because the given file does not exist. The exit point for this exception is the @(catch file_error) clause in the outer-most try block. The inner block is not eligible because it contains no catch clauses at all. However, the inner try block has a finally clause, and so during the processing of this exception which is headed for the @(catch file_error), the finally clause performs an anonymous accept. The exit point for the accept is the anonymous block surrounding the inner try. So the original transfer to the catch clause is forgotten. The inner try terminates successfully, and since it constitutes the main clause of the outer try, that also terminates successfully. The "file error caught" message is never printed. .SS Catch Clauses Catch clauses establish a try block as a potential exit point for an exception-induced control transfer (called a ``throw''). A catch clause specifies an optional list of symbols which represent the exception types which it catches. The catch clause will catch exceptions which are a subtype of any one of those exception types. If a try block has more than one catch clause which can match a given exception, the first one will be invoked. The exception protection of a try block does not extend over the catch clauses. Once a catch clause is being executed, if it throws an exception, that exception will not re-enter any catch within the same try block, even if it matches one. Catches are processed prior to finally. When a catch is invoked, it is of course understood that the main clause did not terminate normally, and so the main clause could not have produced any bindings. So the success or failure of the try block depends on the behavior of the catch clause or the finally, if there is one. If either of them succeed, then the try block is considered a successful match. Example: Query: @(try) @ (next "nonexistent-file") @ x @ (catch file_error) @a @(finally) @b @(end) @c Data: 1 2 3 Output: a=1 b=2 c=3 Here, the try block's main clause is terminated abruptly by a file_error exception from the @(next) directive. This is handled by the catch clause, which binds variable a to the input line "1". Then the finally clause executes, binding b to "2". The try block then terminates successfully, and so @c takes "3". .SS Catch Clauses with Parameters A catch may have parameters following the type name, like this: @(catch pair (a b)) To write a catch-all with parameters, explicitly write the master supertype t: @(catch t (arg ...)) Parameters are useful in conjunction with throw. The built-in error exceptions generate one argument, which is a string containing the error message. Using throw, arbitrary parameters can be passed from the throw site to the catches. .SS The Throw Directive The throw directive generates an exception. A type must be specified, followed by optional arguments. For example, @(throw pair "a" `@file.txt`) throws an exception of type pair, with two arguments, being "a" and the expansion of the quasiliteral `@file.txt`. The selection of the target catch is performed purely using the type name; the parameters are not involved in the selection. Binding takes place between the arguments given in throw, and the target catch. If any catch parameter, for which a throw argument is given, is a bound variable, it has to be identical to the argument, otherwise the catch fails. (Control still passes to the catch, but the catch is a failed match). Query: @(bind a "apple") @(try) @(throw e "banana") @(catch e (a)) @(end) Output: false If any argument is an unbound variable, the corresponding parameter in the catch is left alone: if it is an unbound variable, it remains unbound, and if it is bound, it stays as is. Query: @(try) @(trow e "honda" unbound) @(catch e (car1 car2)) @car1 @car2 @(end) Data: honda toyota Output: car1="honda" car2="toyota" If a catch has fewer parameters than there are throw arguments, the excess arguments are ignored. Query: @(try) @(throw e "banana" "apple" "pear") @(catch e (fruit)) @(end) Output: fruit="banana" If a catch has more parameters than there are throw arguments, the excess parameters are left alone. They may be bound or unbound variables. Query: @(try) @(trow e "honda") @(catch e (car1 car2)) @car1 @car2 @(end) Data: honda toyota Output: car1="honda" car2="toyota" A throw argument passing a value to a catch parameter which is unbound causes that parameter to be bound to that value. Throw arguments are evaluated in the context of the throw, and the bindings which are available there. Consideration of what parameters are bound is done in the context of the catch. Query: @(bind c "c") @(try) @(forget c) @(bind (a c) ("a" "lc")) @(throw e a c) @(catch e (b a)) @(end) Output: c="c" b="a" a="lc" In the above example, c has a toplevel binding to the string "c", but is then unbound within the try construct, and rebound to the value "c". Since the try construct is terminated by a throw, these modifications of the binding environment are discarded. Hence, at the end of the query, variable c ends up bound to the original value "c". The throw still takes place within the scope of the bindings set up by the try clause, so the values of a and c that are thrown are "a" and "lc". However, at the catch site, variable a does not have a binding. At that point, the binding to "a" established in the try has disappeared already. Being unbound, the catch parameter a can take whatever value the corresponding throw argument provides, so it ends up with "lc". .SS The Defex Directive The defex directive allows the query writer to invent custom exception types, which are arranged in a type hierarchy (meaning that some exception types are considered subtypes of other types). Subtyping means that if an exception type B is a subtype of A, then every exception of type B is also considered to be of type A. So a catch for type A will also catch exceptions of type B. Every type is a supertype of itself: an A is a kind of A. This of course implies that ever type is a subtype of itself also. Furthermore, every type is a subtype of the type t, which has no supertype other than itself. Type nil is is a subtype of every type, including itself. The subtyping relationship is transitive also. If A is a subtype of B, and B is a subtype of C, then A is a subtype of C. Defex may be invoked with no arguments, in which case it does nothing: @(defex) It may be invoked with one argument, which must be a symbol. This introduces a new exception type. Strictly speaking, such an introduction is not necessary; any symbol may be used as an exception type without being introduced by @(defex): @(defex a) Therefore, this also does nothing, other than document the intent to use a as an exception. If two or more argument symbols are given, the symbols are all introduced as types, engaged in a subtype-supertype relationship from left to right. That is to say, the first (leftmost) symbol is a subtype of the next one, which is a subtype of the next one and so on. The last symbol, if it had not been already defined as a subtype of some type, becomes a direct subtype of the master supertype t. Example: @(defex d e) @(defex a b c d) The fist directive defines d as a subtype of e, and e as a subtype of t. The second defines a as a subtype of b, b as a subtype of c, and c as a subtype of d, which is already defined as a subtype of e. Thus a is now a subtype of e. It should be obvious that the above could be condensed to: @(defex a b c d e) Example: Query: @(defex gorilla ape primate) @(defex monkey primate) @(defex human primate) @(collect) @(try) @(skip) @(cases) gorilla @name @(throw gorilla name) @(or) monkey @name @(throw monkey name) @(or) human @name @(throw human name) @(end)@#cases @(catch primate (name)) @kind @name @(output) we have a primate @name of kind @kind @(end)@#output @(end)@#try @(end)@#collect Input: gorilla joe human bob monkey alice Output: we have a primate joe of kind gorilla we have a primate bob of kind human we have a primate alice of kind monkey Exception types have a pervasive scope. Once a type relationship is introduced, it is visible everywhere. Moreover, the defex directive is destructive, meaning that the supertype of a type can be redefined. This is necessary so that something like the following works right. @(defex gorilla ape) @(defex ape primate) These directives are evaluated in sequence. So after the first one, the ape type has the type t as its immediate supertype. But in the second directive, ape appears again, and is assigned the primate supertype, while retaining gorilla as a subtype. This situation could instead be diagnosed as an error, forcing the programmer to reorder the statements, but instead txr obliges. However, there are limitations. It is an error to define a subtype-supertype relationship between two types if they are already connected by such a relationship, directly or transitively. So the following definitions are in error: @(defex a b) @(defex b c) @(defex a c)@# error: a is already a subtype of c, through b @(defex x y) @(defex y x)@# error: circularity; y is already a supertype of x. .SH NOTES ON EXOTIC REGULAR EXPRESSIONS Users familiar with regular expressions may not be familiar with the complement and intersection operators, which are often absent from text processing tools that support regular expressions. The following remarks are offered in hope that they are of some use. .SS Equivalence to Sets Regexp intersection is not essential; it may be obtained from complement and union as follows, since De Morgan's law applies to regular expression algebra: (R1)&(R2) = ~(~(R1)|~(R2)). (The complement of the union of the complements of R1 and R2 constitutes the intersection.) This law works because the regular expression operators denote set operations in a straightforward way. A regular expression denotes a set of strings (a potentially infinite one) in a condensed way. The union of two regular expressions R1 | R2 denotes the union of the set of texts denoted by R1 and that denoted by R2. Similarly R1 & R2 denotes a set intersection, and ~R denotes a set complement. Thus algebraic laws that apply to set operations apply to regular expressions. It's useful to keep in mind this relationship between regular expressions and sets in understanding intersection and complement. Given a finite set of strings, like the set { "abc", "def" }, which corresponds to the regular expression (abc|def), the complement is the set which contains an infinite number of strings: it consists of all possible strings except "abc" and "def". It includes the empty string, all strings of length 1, all strings of length 2, all strings of length 3 other than "abc" and "def", all strings of length 4, etc. This means that a "harmless looking" expression like ~(abc|def) can actually match arbitrarily long inputs. .SS Set Difference How about matching only three-character-long strings other than "abc" or "def"? To express this, regex intersection can be used: these strings are the intersection of the set of all three-character strings, and the set of all strings which are not "abc" or "def". The straightforward set-based reasoning leads us to this: ...&~(abc|def). This A&~B idiom is also called set difference, sometimes notated with a minus sign: A-B (which is not supported in .B txr regular expression syntax). Elements which are in the set A, but not B, are those elements which are in the intersection of A with the complement of B. This is similar to the arithmetic rule A - B = A + -B: subtraction is equivalent to addition of the additive inverse. Set difference is a useful tool: it enables us to write a positive match which captures a more general set than what is intended (but one whose regular expression is far simpler than a positive match for the exact set we want), then we can intersect this over-generalized set with the complemented set of another regular expression which matches the particulars that we wish excluded. .SS Expressivity versus Power It turns out that regular expressions which do not make use of the complement or intersection operators are just as powerful as expressions that do. That is to say, with or without these operators, regular expressions can match the same sets of strings (all regular languages). This means that for a given regular expression which uses intersection and complement, it is possible to find a regular expression which doesn't use these operators, yet matches the same set of strings. But, though they exist, such equivalent regular expressions are often much more complicated, which makes them difficult to design. Such expressions do not necessarily . B express what it is they match; they merely capture the equivalent set. They perform a job, without making it obvious what it is they do. The use of complement and intersection leads to natural ways of expressing many kinds of matching sets, which not only demonstrate the power to carry out an operation, but also easily express the concept. .SS Example: Matching C Language Comments For instance, using complement, we can write a straightforward regular expression which matches C language comments. A C language comment is the digraph /*, followed by any string which does not contain the closing sequence */, followed by that closing sequence. Examples of valid comments are /**/, /* abc */ or /***/. But C comments do not nest (cannot contain comments), so that /* /* nested */ */ actually consists of the comment /* /* nested */, which is followed by the trailing junk */. Our simple characterization of interior part of a C comment as a string which does not contain the terminating digraph makes use of the complement, and can be expressed using the complemented regular expression like this: (~.*[*][/].*). That is to say, strings which contain */ are matched by the expression .*[*][/].*: zero or more arbitrary characters, followed by */, followed by zero or more arbitrary characters. Therefore, the complement of this expression matches all other strings: those which do not contain */. These strings up the inside of a C comment between the /* and */. The equivalent simple regex is quite a bit more complicated. Without complement, we must somehow write a positive match for all strings such that we avoid matching */. Obviously, sequences of characters other than * are included: [^*]*. Occurrences of * are also allowed, but only if followed by something other than a slash, so let's include this via union: ([^*]|[*][^/])*. Alas, already, we have a bug in this expression. The subexpression [*][^/] can match "**", since a * is not a /. If the next character in the input is /, we missed a comment close. To fix the problem we revise to this: ([^*]|[*][^*/])* (The interior of a C language comment is a any mixture of zero or more non-asterisks, or digraphs consisting of an asterisk followed by something other than a slash or another asterisk). Oops, now we have a problem again. What if two asterisks occur in a comment? They are not matched by [^*], and they are not matched by [*][^*/]. Actually, our regex must not simply match asterisk-non-asterisk digraphs, but rather sequences of one or more asterisks followed by a non-asterisk: ([^*]|[*]*[^*/])* This is still not right, because, for instance, it fails to match the interior of a comment which is terminated by asterisks, including the simple test cases where the comment interior is nothing but asterisks. We have no provision in our expression for this case; the expression requires all runs of asterisks to be followed by something which is not a slash or asterisk. The way to fix this is to add on a subexpression which optionally matches a run of zero or more interior asterisks before the comment close: ([^*]|[*]*[^*/])*[*]* Thus our the semi-final regular expression is [/][*]([^*]|[*]*[^*/])*[*]*[*][/] (A C comment is an interior string enclosed in /* */, where this interior part consists of a mixture of non-asterisk characters, as well as runs of asterisk characters which are terminated by a character other than a slash, except for possibly one rightmost run of asterisks which extends to the end of the interior, touching the comment close. Phew!) One final simplification is possible: the tail part [*]*[*][/] can be reduced to [*]+[/] such that the final run of asterisks is regarded as part of an extended comment terminator which consists of one or more asterisks followed by a slash. The regular expression works, but it's cryptic; to someone who has not developed it, it isn't obvious what it is intended to match. Working out complemented matching without complement support from the language is not impossible, but it may be difficult and error-prone, possibly requiring multiple iterations of trial-and-error development involving numerous test cases, resulting in an expression that doesn't have a straightforward relationship to the original idea. .SS The Non-Greedy Operator The non-greedy operator % is actually defined in terms of a set difference, which is in turn based on intersection and complement. The uninteresting case (R%) where the right operand is empty reduces to (R*): if there is no trailing context, the non-greedy operator matches R as far as possible, possibly to the end of the input, exactly like the greedy Kleene. The interesting case (R%T) is defined as a "syntactic sugar" for the equivalent expression ((R*)&(~.*(T&.+).*))T which means: match the longest string which is matched by R*, but which does not contain a non-empty match for T; then, match T. This is a useful and expressive notation. With it, we can write the regular expression for matching C language comments simply like this: [/][*].%[*][/] (match the opening sequence /*, then match a sequence of zero or more characters non-greedily, and then the closing sequence */. With the non-greedy operator, we don't have to think about the interior of the comment as set of strings which excludes */. Though the non-greedy operator appears expressive, its apparent simplicity may be deceptive. It looks as if it works "magically" by itself; "somehow" this .% "knows" only to consume enough characters so that it doesn't swallow an occurrence of the trailing context. Care must be taken that the trailing context passed to the operator really is the correct text that should be excluded by the non-greedy match. For instance, take the expression .%abc. If you intend the trailing context to be merely a, you must be careful to write (.%a)bc. Otherwise the trailing context is abc, and this means that the .% match will consume the longest string that does not contain "abc", when in fact what was intended was to consume the longest string that does not contain a. The change in behavior of the % operator upon modifying the trailing context is not as intuitive as that of the * operator, because the trailing context is deeply involved in its logic. For single-character trailing contexts, it may be a good idea to use a complemented character class instead. That is to say, rather than (.%a)bc, consider [^a]*bc. The set of strings which don't contain the character a is adequately expressed by [^a]*. .SH NOTES ON FALSE The reason for printing the word .IR false on standard output when a query doesn't match, in addition to returning a failed termination status, is that the output of .B txr may be collected by a shell script, by the application of eval to command substitution syntax. Printing .IR false will cause eval to evaluate the .IR false command, and thus failed status will propagate from the eval itself. The eval command conceals the termination status of a program run via command substitution. That is to say, if a program fails, without producing output, its output is substituted into the eval command which then succeeds, masking the failure of the program. For example: eval "$(false)" appears successful: the false utility indicates a failed status, but produces no output. Eval evaluates an empty script and reports success; the failed status of the false program is forgotten. Note the difference between the above and this: eval "$(echo false)" This command has a failed status. The echo prints the word false and succeeds; this false word is then evaluated as a script, and thus interpreted as the false command which fails. This failure .B is propagated as the result of the eval command.