The whole layouting is split up into several, fairly simple passes, which are
executed one after the other. See the
notes in hacking.* for a discussion of
this approach.
If not compiled with -DXHTML_ONLY, an additional pass is inserted after element
parsing: In sgml_rework(), the
syntax tree is modified to fix the wrong element nesting caused by missing end
tags in SGML documents.
dump_tree() can be used again to dump all element and attribute types as found
in the lookup, and the possibly modified tree structure.
All of the passes mentioned above are necessary to prepare the rendering, and
are executed from layout().
The actual rendering is done in render.c. However, this isn't done for the
whole page like the other layouting passes. Instead, every time some region of
the output page needs to be displayed,
render() is called to render exactly that
region.
Alternatively, The whole page can be dumped to the terminal line by line, using
dump().
This file forms the framework for the layouting process. It contains functions
to load a file and prepare it for rendering, but also to free the memory used
by a document when it is no longer needed.
Before starting parsing, we have to create the tree top. (We call it the global
element.) This is done by setting "cur_el" to NULL and calling add_element().
Parsing
The parser itself works in a very simple way. It is some kind of state machine.
For every input character, one action is taken, selected by a dispatcher
depending on the current state (stored in "parse_mode") and the input char
itself. Several combinations (e.g. tag start) change the current state, thus
the following character(s) are parsed in a different mode. (Other actions are
taken.)
Sometimes a character that causes a mode switch has to be parsed in the new
mode itself. In this case the flag "recycle" is set after the mode change,
causing the dispatch to be repeated for the same char, but in the new mode.
Again, the parsing is not very efficient in the present implementation. (In
fact, it is by far the most time consuming part of the whole layouting.)
Especially the huge switch is quite slow. (Good compilers have a fairly
efficient implementation of the switch itself; however, it still causes many
unpredictable branches.) There are some possibilities to optimize this. The
bigger problem is that the inner loop is quite big, and may not fit into the
processor's instruction cache, thus making it terribly slow. Maybe splitting
the parsing into several simpler passes would help. However, we are planning to
switch to a completely different, (hopefully) much more efficient parser system
in the next major release...
The default parsing mode is "PM_CONTENT", which is the mode for parsing element
content. Any normal character encountered in this mode is simply added to
"text_buf" by "buf_add_char()". A ' ', '\t', '\n', '\r' or '\f' aren't stored;
we switch to "PM_BLANK" instead. Any following blank space is ignored. As soon
as a normal character occurs again, we store a single ' ' and swich back to
"PM_CONTENT".
input:
first paragraph of text;
includes multiple spaces and newlines,
^
file position
text_buf: " first paragraph of text; includes mul"
<pre> Blocks
After a <pre> tag, the mode isn't switched back to "PM_CONTENT", but to
"PM_PRE". In this mode all blank space characters are stored to "text_buf"
as non-breakable spaces, except newlines which are stored directly.
The mode is ended and switched to "PM_CONTENT" again when a closing "</pre>"
tag is encountered.
References
An '&' indicates a character reference (unicode escape) or entity reference
(named escape), and starts the reference parsing mode "PM_AMP". On entering
this mode, the current write position in "text_buf" is saved to "amp_pos".
input: [...] < [...]
^
text_buf: "[...] &"
^^
text_buf_len
amp_pos
In this mode characters are added to "text_buf", too. The mode is switched back
to the previous mode (saved in "prev_mode_amp") when a ';' occurs.
input: [...] < [...]
^
text_buf: "[...] <"
^ ^
text_buf_len
amp_pos
The text between the saved start position of the escape sequence and the
current positon is converted then. First the string is looked up in
"ref_table[]", which is a table of named characters, defined in facilities.c. If it
isn't there, but it seems to be a numerical character reference, it is
converted to an integer (ASCII value). If a replacement char was found either
in the table or by the number conversion, the reference is removed from
"text_buf" and the replacement char is inserted instead.
text_buf: "[...] <"
^
text_buf_len
If no replacement was found, the string is left unchanged. (We consider this
behaviour better then of some other browsers, which simply leave unknown
characters out, and the user only wonders that something is missing...)
Probably we will mark unknown escapes by some attribute in the future.
Tags
A '<' starts tag parsing. There is a a whole bunch of tag parsing modes. The
one entered after the '<' is "PM_TAG_START", which indicates that the tag name
should follow next.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: "[...] but also an anchor em"
tree:
+
+
+---+
-->| p |-. <== cur_el
+---+ | <+
| +
| +
v +
+--------+
| center |-. <++
+--------+ | +
v +
,----------------.
(" starting...tag,")
`--------+---+---' <-- last_el
| ? |->NULL
+---+
Start Tags
If the following character is an normal char, it's a start tag. (Or a single
tag, which is treated the same way for now.) "PM_TAG_NAME" is entered. A new
element node is created by
add_element(). Any content in front of
this new element, which was stored in "text_buf" up to now, is stored to the
new node's "text" field by "insert_buf".
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: ""
tree:
+
+---+
->| p |-. <++++++++++++++++++
+---+ | <+ +
| + <== +
| + ,----------.
v + (" this...em")
+--------+ `---+---+--' <--
| center |-. <++ ,->| |->NULL
+--------+ | + | +---+
v + |
,----------------. |
(" starting...tag,") |
`--------+---+---' |
| ? |------'
+---+
Normal characters encounterd in "PM_TAG_NAME" mode (including the one that
started the mode) are stored to "text_buf".
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: "a"
A blank space character ends "PM_TAG_NAME" and switches to "PM_TAG", which indicates that
attributes may follow. "text_buf" is stored as the element name.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: ""
tree:
+
+---+
->| p |-. <++++++++++++++++++
+---+ | <+ +
| + <== +
| + ,----------.
v + (" this...em")
+--------+ `---+---+--' <--
| center |-. <++ ,->| a |->NULL
+--------+ | + | +---+
v + |
,----------------. |
(" starting...tag,") |
`--------+---+---' |
| ? |------'
+---+
A following normal char is the beginning of an attribute name, and switches to
"PM_ATTR_NAME". Characters encounterd in "PM_ATTR_NAME" mode are also stored to "text_buf".
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: "name"
The attribute name ends with an '=' or a blank char. A new entry is created in the "attr[]"
array, and "text_buf" is stored as the attribute name. Mode is switched to
"PM_ATTR_NAME_END" first, which indicates that the attribue value should follow.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: ""
attr: name: data:
"name" ""
If the attribute name was ended by an '=', mode is switched immediately to
"PM_ATTR_VALUE", otherwise as soon as an '=' is encountered. (After any amount
of whitespace.)
White space in "PM_ATTR_VALUE" mode (after the '=') is ignored too.
Next char must be either a '"' or a '\'', and switches to "PM_ATTR_DATA_QUOT"
or "PM_ATTR_DATA_APOS", respectively. In this modes characters are stored to
"text_buf" again.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: "anchor"
attr: name: data:
"name" ""
A second '"' (or '\'', respectively) ends this mode. "text_buf" is stored as
the attribute value for the new "attr" entry.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: ""
attr: name: data:
"name" "anchor"
Mode is swiched back to "PM_TAG". Now blank space may follow (which is
ignored), followed by another attribute.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
In "PM_TAG" mode also a '>' may occur, ending tag parsing and switching back to
the mode before tag parsing had begun. (PM_CONTENT or PM_BLANK.) In this case,
"cur_el" is set to "last_el"; this means descending in the syntax tree to the
newly created node.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
text_buf: ""
attr: name: data:
"name" "anchor"
"href" ""
tree:
+
+---+
->| p |-. <++++++++++++++++++
+---+ | <+ +
| + +
| + ,----------.
v + (" this...em")
+--------+ `---+---+--' <==
| center |-. <++ ,->| a |->NULL <--
+--------+ | + | +---+
v + |
,----------------. |
(" starting...tag,") |
`--------+---+---' |
| ? |------'
+---+
A '>' may also occur in "PM_TAG_NAME" mode, meaning the element has no
attributes.
input: <html> <head> [...]
^
In this case creating the new node and storing the name, and descending into
the element are done in one step. (By "recycle".)
End Tags
If the first character after the '<' is a '/', the tag is an end tag, and we
switch to "PM_END_TAG_NAME". If any text is pending in "text_buf", we have to
store it somewhere. As an end tag normally does not create a new element node,
we have to create a dummy node for this. (Very inefficient, s.a.)
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
tree:
+
+---+
->| p |-. <++++++++++++++++++
+---+ | <+ +
| + +
| + ,----------.
v + (" this...em")
+--------+ `---+---+--' <==
| center |-. <++ ,->| a |-. <+
+--------+ | + | +---+ | +
v + | v +
,----------------. | ,---.+
(" starting...tag,") | ("bed")
`--------+---+---' | +---+ <--
| ? |------' | ? |->NULL
+---+ +---+
Normal chars in "PM_END_TAG_NAME" mode are stored to "text_buf", too.
"PM_END_TAG_NAME" can be ended immediately by a '>', or by blank space
(switching to "PM_END_TAG_SPACE") followed by '>'.
The tag name extracted to "text_buf" is compared against the element name of
the current element, to see if the end tag matches, and then abdannoned. The
element is closed by ascending to the parent.
input: [...] but also an anchor em<a name="anchor" href="">bed</a>ded inside a word
^
tree:
+
+---+
->| p |-. <++++++++++++++++++
+---+ | <+ +
| + <== +
| + ,----------.
v + (" this...em")
+--------+ `---+---+--'
| center |-. <++ ,->| a |-. <+
+--------+ | + | +---+ | +
v + | v +
,----------------. | ,---.+
(" starting...tag,") | ("bed")
`--------+---+---' | +---+ <--
| ? |------' | ? |->NULL
+---+ +---+
Single Tags
If a '/' appears instead of an attribute name in "PM_TAG" mode, "parse_mode" is
set to "PM_SINGLE_TAG", indicating an (XHTML) single tag.
input: [...] and finally a blank row <br /> (a single tag)
^
The '/' can also immediately follow the element name. (In "PM_TAG_NAME" mode.)
input: <hr/>
^
In this case, creating the node and switching to a single tag are done in one
step by "recycle".
In any case, a '>' has to follow, and switches back to normal mode just like in
a start tag, only it does not descend (set the new node as "cur_el") -- a
single tag has no content area; the content following a single tag still
belongs to the parent.
input: [...] and finally a blank row <br /> (a single tag)
^
tree:
+
+---+ <++++++++++++++++++++++++++++++++
->| p |-. <++++++++++++++++++ +
+---+ | <+ + +
| + <== + +
| + ,----------. ,---------.
v + (" this...em") ("ded...row")
+--------+ `---+---+--' `--+----+-' <--
| center |-. <++ ,->| a |-. <+ ,->| br |->NULL
+--------+ | + | +---+ | + | +----+
v + | v + |
,----------------. | ,---.+ |
(" starting...tag,") | ("bed") |
`--------+---+---' | +---+ |
| ? |------' | ? |--'
+---+ +---+
Comments
In "PM_TAG_START" mode (after the '<'), also an '!' can follow, indicating that
we have not any tag at all, but either a comment, a DOCTYPE declaration, or a
CDATA section. "parse_mode" is set to "PM_EXCLAM" in this case.
input: some text <!--a test-comment--> and more text
^
If a '-' follows, it's a comment. Mode is switched to "PM_COMMENT_START".
input: some text <!--a test-comment--> and more text
^
Now a second '-' has to follow, switching to "PM_COMMENT". In this mode any
characters but a '-' are simply ignored.
input: some text <!--a test-comment--> and more text
^
text_buf: "some text"
A '-' switches to "PM_COMMENT_END1", which means that it *may* be the comment end.
input: some text <!--a test-comment--> and more text
^
However, if it is followed by any other char than a second '-', mode is
switched back to "PM_COMMENT".
input: some text <!--a test-comment--> and more text
^
A second '-' in "PM_COMMENT_END1" switches to "PM_COMMENT_END2", which means
that now the comment really ends.
input: some text <!--a test-comment--> and more text
^
Now the '>' has to follow, and switches back to parsing mode before the
beginning of the comment ("prev_mode_tag").
input: some text <!--a test-comment--> and more text
^
DOCTYPE Declarations
If a normal char occurs in "PM_EXCLAM", we assume it is the "D" in "<!DOCTYPE".
input: garbage <!DOCTYPE somedoc> more garbage
^
We treat DOCTYPE declarations as comments. Any characters but '>' are ignored.
input: garbage <!DOCTYPE somedoc> more garbage
^
text_buf: "garbage"
A '>' returns to normal mode.
input: garbage <!DOCTYPE somedoc> more garbage
^
This isn't a very reliable detection, as according to the grammer, an unescaped
'>' may appear in some system literal inside the declaration. However, we
assume that this won't happen... (We would have to parse the whole declaration
otherwise.)
CDATA Sections
A '[' in "PM_EXCLAM" mode starts a CDATA section, indicated by
"PM_CDATA_START". If there is a pending blank ("prev_mode_tag" is "PM_BLANK"),
it has to be stored *before* the CDATA.
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text "
Following normal chars (should) belong to the "CDATA" string, and are ignored.
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text "
A second '[' in "PM_CDATA_START" mode switches to "PM_CDATA", indicating that
the actual data will follow.
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
Any characters in "PM_CDATA" mode but '>' are stored directly to "text_buf".
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text a tricky ]"
When a '>' occurs, the previous two chars (in "text_buf") are tested against
"]]". If they do not match, the '>' is simply stored just as any other
character.
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text a tricky ]>"
If they match, the last two characters are removed from "text_buf" (they belong
to the CDATA terminator), and mode is switched back to "PM_CONTENT". (It
doesn't need to be switched back to the mode before the CDATA section, as any
pending blanks already have been stored, and a CDATA section can't start in
other modes than "PM_TEXT" or "PM_BLANK".)
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text a tricky ]> CDATA section]]"
input: some text <![CDATA[a tricky ]> CDATA section]]> and more text
^
text_buf: "some text a tricky ]> CDATA section"
Processing Instructions
The '<' may also be followed by a '?', indicating a processing instruction.
Mode is switched from "PM_TAG_START" to "PM_INSTR".
input: some text <?a fake? processing instruction??> more text
^
Processing instructions are also treated as comments. Any chars but '?' are
ignored in "PM_INSTR".
input: some text <?a fake? processing instruction??> more text
^
text_buf: "some text"
A '?' switches to "PM_INSTR_END", indicating this *may* be the end of the
processing instruction.
input: some text <?a fake? processing instruction??> more text
^
If a normal char follows the '?', mode is switched back to "PM_INSTR".
input: some text <?a fake? processing instruction??> more text
^
If a second '?' follows, "PM_INSTR_END" is kept, as the first one isn't the end
of the processing instruction, but the new one could be.
input: some text <?a fake? processing instruction??> more text
^
A '>' in PM_INSTR_END really ends the processing instruction, and switches to
"prev_mode_tag".
input: some text <?a fake? processing instruction??> more text
^
SGML Mode
When compiled without the "-DXHTML_ONLY" option, a few cases more are possible.
Unclosed Tags
In SGML, not every element has to have an end tag.
When an end tag is encountered, we ascend in the syntax tree not only once, but
until an element is found that matches the end tag. Thus, all elements in
between are automatically closed.
input:
<body>
<p>
some text
<hr>
</p>
^
+------+
| body |-.<+
+------+ | +
v +
+---+
| p |-.<+
+---+ | +
v +
,-------.
(some text)
`-+----+'
--> | hr |->NULL
==> +----+
input:
<body>
<p>
some text
<hr>
</p>
^
+------+
| body |-.<+ <==
+------+ | +
v +
+---+
| p |-.<+
+---+ | +
v +
,-------.
(some text)
`-+----+'
--> | hr |->NULL
+----+
Unquoted Attribute Values
When a normal char occurs in "PM_ATTR_VALUE" mode, "PM_ATTR_DATA_NOQUOTE" is entered.
input: <sometag someattribute=somevalue minimized third="nothing">
^
This mode is just like "PM_ATTR_DATA_QUOT" or "PM_ATTR_DATA_APOS", only it
is ended by a blank or the tag end.
input: <sometag someattribute=somevalue minimized third="nothing">
^
Mimimized Attributes
In SGML, attributes without a value are possible. This is recognized when a
normal char or the tag end occurs in "PM_ATTR_NAME_END" mode instead of the
'='.
input: <sometag someattribute=somevalue minimized third="nothing">
^
The attribute is ended immediately. "text_buf[]" (which is empty in this case)
is stored just like at the end of an unquoted attribute value. Mode is set to
"PM_TAG", and the current character (the tag end or beginning of next
attribute) is processed in this mode.
SGML Comments
Comments also allow more complicated syntax. For one, blank space is possible between the "--" ending the comment string and the '>' ending the declaration. Thus, blank space in PM_COMMENT_END2 is ignored.
Moreover, another comment string may follow the end. Thus, a '-' in PM_COMMENT_END2 switches back to PM_COMMENT_START, similary to the '-' after the "<!".
input: <!--comment start-- --second comment string in same declaration-- >
^
Finally, SGML also allows empty declarations ("<!>"), which are also a kind of comment. Thus a '>' in PM_EXCLAM switches immediately to PM_COMMENT_END2 and recycles.
input: <!>
^
Parsing is ended by EOF. This should only appear in "PM_CONTENT" or "PM_BLANK"
mode (not inside some tag, comment, CDATA section or chracter/entity
reference), and only if the current element is the global one (not while
parsing some element's content).
The "list_next" pointer of the last node is set to point back to the tree top.
This faciliates easier processing in the following steps.
When using -DXHTML_ONLY, every syntax error encountered causes netrik to print
an error message and immediately quit. (The XML standard requires this.)
Without -DXHTML_ONLY, netrik is more tolerant.
Netrik uses simple workarounds for some of the most common cases of broken
HTML:
If some illegal char occurs in a entity/character reference, it's probably not
really a reference, but an unescaped '&'. We keep the whole sequence literally
and switch back to "prev_mode_amp".
Similar for illegal characters in "PM_TAG_START", which indicate an unescaped
'<'. We store a '<' and switch back to "prev_mode_tag".
As SGML comments have a quite complicated syntax, reasonable error handling is
also a bit more complicated.
If someting else then '>' (end of comment declaration), '-' (beginning of
second comment string), or blank space follows in PM_COMMENT_END2 (after a
"--"), then the "--" was probably not intended to have any special meaning, but
simply to be part of the comment. Thus, mode is switched back to PM_COMMENT.
The same is done for unexpected characters in PM_COMMENT_START mode, which is
most common for "---" inside a comment.
There is one exception to this, however: If a '>' follows in PM_COMMENT_START
mode, and it was preceeded not only by one '-' (the one which started
PM_COMMENT_START) but two or more, then the the '>' together with the last two
'-' was probably intended as as an XML-like "-->" comment end.
The "dash_count" variable keeps track of how many dashes have been encountered
in a row; it is incremented every time a '-' apprears in some of the comment
parsing modes, and is reset to 0 every time some other character is
encountered.
"dash_count" is also used in another situation: If a '>' follows in PM_COMMENT
or PM_COMMENT_END1, normally it is part of the comment. The '>' is ignored and
mode stays PM_COMMENT. (Or is switched back from PM_COMMENT_END1.)
However, if there were two or more dashes in front of the '>', this "-->"
combination was probably also intended as a comment end. A comment consisting
of a series of dashes is a typical example:
However, only a little warning can be printed in this case -- this is valid
SGML, and *has* to be treated as part of the comment, even if it's probably not
what the page author intended! Printing an error and using a workaround would
mean presumably to violate the standard in favour of broken pages, which is
probably not a very good idea...
All other syntax errors are simply ignored, hoping for the best.
Whenever some syntax error is detected (no matter whether workarounds are
available), html_error() is called, with several parameters describing the
error. This function is responsible for everything that needs to be done when
an error occurs.
First, it prints an error message. The message text is passed from
parse_syntax(), and used as the format string for printf(). If the error
message requires additional arguments, they are passed at the end of the
parameter list when calling html_error().
If the parsing mode requires that, it quits immediately afterwards. The mode is
determined by the config variable "cfg.parser", which is an "enum Parser_mode",
with the possible values CORRECT_HTML, NORMAL_HTML, BROKEN_HTML and
IGNORE_BROKEN. The parser quits only in CORRECT_HTML mode, or when -DXHTML_ONLY
is enabled. If the input resource from which the page is loaded is a pipe from
wget (see hacking-load.*), the pipe
is closed before quitting to assure a cleaner exit.
In all other modes, an additonal message passed from parse_syntax() is printed
afterwards, informing in which way netrik will handle the error. (workaround,
ignore etc.)
Finally the error level passed from parse_syntax() is compared against the
highest error level up to know, and the new higest level is returned.
$$
The last two aren't checked against the element name.
As soon as a match is found, the loop is left and the entry number is stored to
"syntax_tree" in place of the string. The entry number is an "enum
Element_type", defined in syntax.h; it tells the element type in the following
processing passes.
If none of the ordinary entries matched, the entry nuber, which now is ELEMENT_NO
(as this one follows after the ordinary entries), is stored anyhow, indicating
that the element is unknown. If no element name was stored ("cur_el->name.str"
is NULL), indicating a dummy tag, ELEMENT_NO is set also.
After the element name, all attribute names are processed in a loop. They are
looked up in "attr_table[]" the same way the element name is.
The attribute value isn't processed at all yet.
Note that there are no actual sizes or postions for the items, and no line
breaks inside the text items; this is all done in a later processing step
(pre-render.c). The item tree at this point only represents the structure of
the output page. (The line breaks in the fifth text block aren't really there;
we have inserted them in the figure because the text block is a bit too long to
put in a single line...)
The item tree looks complicated at first, but it's a quite trivial example when
taking a closer look. (This is becuase at the time of creating the 0.html file
used here, netrik wasn't able to do anything more complicated...) However, it
should be sufficient to get the idea...
Every node of the item tree consists of an "Item" structure. This structure is
declared in "items.h". It contains:
New items are created by add_item(). This function allocates a new "Item"
structure, and sets some pointers. The item isn't inserted into the tree
directly; it's only inserted into a list of all items at the current tree
depth. This is a single linked list maintained by the "first_item" and
"last_item" pointers of "state" (there is one such list for each tree depth),
and the "next" pointers of the item structures. The only other pointers set are
"list_next". The "parent" and "first_child" pointers aren't set; this is done
later when the items are actually inserted into the tree, while ascending from
the current depth. (For the first item in every tree depth the "parent" is
explicitly set to NULL, indicating that there is no parent yet.)
This function is called directly to create box items, and from add_string() to
create text items. Under certain conditions it also creates a blank item before
the actual text item or box item; more on this later, under
Blank Lines.
When called with the "virtual" flag, this function behaves slightly different:
No line break/blank line handling is done; the status remains unchanged. This
is for creating the Virtual Boxes used for
anchors.
The actual text data of text items is stored in a different place. Every text
item points to a "String" structure (also declared in "items.h"). This
structure consists of a normal C-string containing the text itself, and an
array of "Div" structures, containing all attribute information. (Color etc.) A
"String" can consist of several divisions with different attributes. Every
"Div" structure stores the attributes for one such division, and the ending
position of the division inside the string. (More exactly: the position *after*
the end of the div -- which is the starting position of the next div.) The end
of the last division is also used to find out the string length. This is quite
inefficient...
The "String" structure also contains "line_table[]", which holds the positions
of all line breaks inside the string; more on this in 7. pre-render.c.
Processing
Many properties of the various element types are data-driven. This presently
includes the line break/blank line handling, and elements creating a box around
all children. This properties are stored to the same
"element_table[]" as the name strings used
by parse_elements(). In future probably more properties will be data driven,
making the code simpler, and also necessary for handling style sheets, which
allow changing of almost all formatting properties.
The item tree is generated while traversing the element tree. Processing of
each element is done in two steps: One step is done before entering an element
(descending in the element tree), and the second step is done after leaving the
element (ascending). Between those two steps, the same is done for all
sub-elements. You guess it: This is a recursive algorithm. Only we haven't
implemented it recursively, as mentioned in chapter 0. In this function the
pseudo-recursive implementation is most evident; we even have to use a
pseudo-stack.
The processing could also be split into a couple of much simpler passes using
some temporary data structures, e.g. one generating the "normal" items, one
generating blank items, one generating the strings, one "optimizing" the tree
(lifting items where possible). This would be much easier to understand, and
probably it would have been a good idea for the beginning. However, it would be
much less efficient; that's why we won't step back to such an implementation
after already having the present one.
Pre-processing
The first action in every iteration of the outer loop is to do the first
processing step (s.a.) for the current element ("cur_el") -- in every iteration
exactly one element is pre-processed.
++>NULL
+
+---+
| ! |-. <++
+---+ | +
v +
,-----------.
("header text")
`-+------+--' <-- cur_el <== depth
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+
| head |->| body |-.
+------+ +------+ |
First, we store any text from the current element node to the current open text
item by add_string().
state[0]->first_item -->NULL (depth 0)
state[0]->last_item **>NULL
---
+------+ <-- first_item
| text |-->NULL <** last_item <== depth=1
+----*-+==>NULL
x *
v *
NULL *
v
,-----------.
("header text")
`-----------'
The next thing is processing of line breaks and paragraph breaks, depending
what kind of element we have. More on this later, in Text Blocks and Blank Lines.
Recursing
Then we recurse into the element (descend in the element tree).
++>NULL
+
+---+
| ! |-. <++
+---+ | +
v +
,-----------.
("header text")
`-+------+--' <-- cur_el
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+
| head |->| body |-. <== depth
+------+ +------+ |
state[0]->first_item -->NULL (depth 0)
state[0]->last_item **>NULL
---
+------+ <-- state[1].first_item (depth 1)
| text |-->NULL <** state[1].last_item
+----*-+==>NULL
x *
v *
NULL *
v
,-----------.
("header text")
`-----------'
---
first_item -->NULL <== depth=2
last_item **>NULL
This is done by push_state(). This function doubles the top of stack, and
returns a pointer to the newly created entry, which is used as the current
state. ("first_item" and "last_item" aren't copied, but set to NULL; "id_attr"
and "link_type" are set to -1.)
The stack stores all variables which are specific to every tree depth. Note
that the stack uses the depths from the element tree, not from the item tree.
The depths in the item tree are completely different, and change while
processing -- which is one of the most tricky parts about parse_struct().
Currently the data stored is:
-
Text attributes ("text_mode" and "high").
-
The nesting depth "list_depth" of item lists. (Determines the indent of list
items.)
-
The two pointers "first_item" and "last_item", necessary to maintain the list
of all items at a given depth.
-
The type of the link or form control created by the element in the
"link_type" enum (a value of -1 indicates there is no link at all)
-
The URL of links or value of form elements in the "link_value" string
-
The "form_enabled" flag indicates whether a form element is to be submitted to the
server
-
The name of a possible <select> element, bequeathed to its <option> elements
-
The kind of the <select> element, also bequeathed
-
"link_start" stores the position where a link or inline anchor beginns inside
the current string
-
"link_item" stores the text item in which a link/anchor beginns
-
For elements with an anchor, "id_attr" stores which attribute contains the
anchor id (or name)
After descending, first "link_start" is set to the current string end, so any
text generated inside this element will become part of the link or anchor, if
the element creates one. If there is no string item open, 0 is stored, so the
link will begin at the start of the string if a new string beginns inside the
element.
Aferwards, some element type specific handling is done. Mostly this is
outputing of special element indicators. (This could be made data-driven, and
probably it will do so soon.)
For some element types, also values of the current state are modified; this
would be the argument passing in a real recursive implementation.
Ascending
The last step of every outer loop iteration is returning from recursion
(ascending in the element tree). But in contrast to descending, ascending isn't
done once per outer loop iteration. Instead, there is an inner loop, that
ascends as often as needed to reach the level of the next element -- this can
be zero, once or several times.
We know how long we need to ascend by starting at the level of the current
element and looking for the parent of the new element; as soon as we find it,
we know we needn't ascend any more. "depth" is adjusted every time we ascend,
and all actions for leaving the element (unrecursing) are taken. ("depth" is
always one below the depth of "new_el".)
If the next element is a child of the current one, no ascending is necessary.
We have descended one step in the pre-processing step of the current iteration,
and this is ok; we keep it. ("cur_el" is alredy the parent of "list_next".)
,-----------.
("header text")
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+
| head |->| body |-. <++++++++++++++
+------+ +------+ | <+ +
v + +
+----++ +---+
cur_el --> | h1 |-. <+ ,->| p |->
new_el xx> +----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' | <== depth
list_next **> | ? |----'
+---+
If the next element is at the same level as the current one (single tags or
other elements with no sub-elements), we need to ascend exactly one time, to
get back to the level of the current element, after we have descended in the
pre-processing step.
,-----------.
("header text")
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+ <**
--> | head |->| body |-. <++++++++++++++
xx> +------+ +------+ | <+ +
v + +
+----++ +---+
| h1 |-. <+ ,->| p |-> <==
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
| ? |----'
+---+
,-----------.
("header text") <xx
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+ <**
--> | head |->| body |-. <++++++++++++++ <==
+------+ +------+ | <+ +
v + +
+----++ +---+
| h1 |-. <+ ,->| p |->
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
| ? |----'
+---+
Of course it's a bit of overhead first to descend into an element, just to
ascend from it right after. But it saves a lot of code for special handling of
such childless elements. Many of the actions of both the first step and the
second step have to be done for them also -- putting them together and leaving
out the descending and ascending wouldn't save that much, while complicating
the code quite a lot. We may consider some way in the future if profiling shows
this would be rewarding.
If the next element is above the current one, we have to ascend more than once.
(Once to get back to the level of the current one, the others to ascend to the
new level.)
,-----------.
("header text")
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+
| head |->| body |-. <++++++++++++++
+------+ +------+ | <+ +
v + +
+----++ +---+
| h1 |-. <+ ,->| p |-> <**
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
--> | ? |----'
xx> +---+
<==
,-----------.
("header text")
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+
| head |->| body |-. <++++++++++++++
+------+ +------+ | <+ +
v + +
+----++ +---+
xx> | h1 |-. <+ ,->| p |-> <**
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' | <==
--> | ? |----'
+---+
,-----------.
("header text")
`-+------+--'
| html |-. <++++++++
+------+ | <+ +
v + +
+------+ +------+ <xx
| head |->| body |-. <++++++++++++++
+------+ +------+ | <+ +
v + +
+----++ +---+
| h1 |-. <+ ,->| p |-> <** <==
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
--> | ? |----'
+---+
In every ascending iteration, first we do some element type specific handling
again, mostly outputing element end indicators. Then we pop the previous state
from the stack.
++>NULL
+
+ .--------------------------------.
+ v |
+---+ <xx |
| ! |-. <++ <** |
+---+ | + |
v + |
,-----------. |
("header text") | <==
`-+------+--' |
| html |-. <+++++++++++ |
+------+ | + |
| [...] [...]
[...] + |
| ,---------------. |
| (" (a single tag)") |
| `-----+---+-----' | <--
`--------->| ? |--------'
+---+
state[0]->first_item -->NULL (depth 0)
state[0]->last_item **>NULL
--- ,-- first_item
+------+ <--' +------+ +------+ <** last_item
| text |--[...]-->| text |-->| text |-->NULL <== depth=1
+----*-+==[...]==>+----*-+==>+----*-+==>NULL
x * x * x *
v * v * v * ,--------------.
NULL * NULL * NULL **>("(a single tag)")
v * `--------------'
,-----------. * ,----------------.
("header text") **>("this...blank row")
`-----------' `----------------'
++>NULL <xx
+
+ .--------------------------------.
+ v |
+---+ |
| ! |-. <++ <** | <==
+---+ | + |
v + |
,-----------. |
("header text") |
`-+------+--' |
| html |-. <+++++++++++ |
+------+ | + |
| [...] [...]
[...] + |
| ,---------------. |
| (" (a single tag)") |
| `-----+---+-----' | <--
`--------->| ? |--------'
+---+
first_item -->NULL <== depht=0
last_item **>NULL
--- ,-- state[1].first_item
+------+ <--' +------+ +------+ <** state[1].last_item (depth 1)
| text |--[...]-->| text |-->| text |-->NULL
+----*-+==[...]==>+----*-+==>+----*-+==>NULL
x * x * x *
v * v * v * ,--------------.
NULL * NULL * NULL **>("(a single tag)")
v * `--------------'
,-----------. * ,----------------.
("header text") **>("this...blank row")
`-----------' `----------------'
Inserting into Item Tree
Afterwards, the probably most interesting part follows: The sub-items created
inside the element we are just leaving, are inserted into the item tree
properly.
If the element we are leaving enforces a box (looked up in "element_table[]"), a new
box item is created. (Box items are always created when leaving the element,
and thus *after* all items inside the box.)
--> +-----+
**> ,->| box |-->NULL <== depht=0
| +-----+==>NULL
|
|
|
|
|
|
+------+ <-- +------+ +------+ | <** (depth 1)
| text |--[...]-->| text |-->| text |-'
+----*-+==[...]==>+----*-+==>+----*-+==>NULL
x * x * x *
v * v * v * ,--------------.
NULL * NULL * NULL **>("(a single tag)")
v * `--------------'
,-----------. * ,----------------.
("header text") **>("this...blank row")
`-----------' `----------------'
The "parent" pointers of all immediate children are set to the new box item,
and "first_child" of the new item is set to the first of them.
--> +-----+
**> ,->| box |-->NULL <== depht=0
| +-----+==>NULL
| x ^
xxxxxxxx[...]xxxxxxxxxxxxxxxxxxxxxxxxxxx +
x | +
x +++++[...]++++++++++++++++++++++++++++++
x + + + |
v + + + |
+------+ <-- +------+ +------+ | <** (depth 1)
| text |--[...]-->| text |-->| text |-'
+----*-+==[...]==>+----*-+==>+----*-+==>NULL
x * x * x *
v * v * v * ,--------------.
NULL * NULL * NULL **>("(a single tag)")
v * `--------------'
,-----------. * ,----------------.
("header text") **>("this...blank row")
`-----------' `----------------'
If the element does not create a box, things are more tricky: We have to "lift"
all sub-elements to the new level. This is done by concatenating the list of
elements of the depth we are leaving to the list of elements of the depth we
are entering.
state[0]->first_item -->NULL (depth 0)
state[0]->last_item **>NULL
---
+------+ <-- state[1].first_item (depth 1)
| text |-->NULL <** state[1].last_item
+----*-+==>NULL
x *
v *
NULL *
v
,-----------.
("header text")
`-----------'
---
state[2]->first_item -->NULL (depth 2)
state[2]->last_item **>NULL
--- ,-- state[3].first_item
+------+<-'+-------+ <** state[3].last_item (depth 3)
| text |-->| blank |-->NULL
+----*-+==>+-------+==>NULL
x * x
v * v
NULL * NULL
v
,-------.
("heading")
`-------'
---
+------+ <-- first_item
| text |-->NULL <** last_item <== depth=4
+----*-+==>NULL
x *
v *
NULL *
v
,------------.
("first...text")
`------------'
+------+ <+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
->| body |-. <++++++++++++++ +
+------+ | <+ + +
xx^ v + + +
+----++ +---+ <++++++++++++++++++++ +---+
==> | h1 |-. <+ ,->| p |---. <++ + **> ,->| p |->
depth=3 +----+ | + | +---+ | + + | +---+
v + | v + + |
,--------. | ,------------------. ,----. |
(" heading") | (" first...newlines,") (" and") |
`--+---+-' | `-----+----+-------' +-+----+-+ |
| ? |----' | em |-. <++ ,->| strong |-. <++ |
+---+ +----+ | + | +--------+ | + |
v + | v + |
,----------------. | ,------------. |
(" emphasized text") | (" strong text") |
`--------+---+---' | `-----+---+--' |
| ? |------' --> | ? |-----'
+---+ +---+
state[0]->first_item -->NULL (depth 0)
state[0]->last_item **>NULL
---
+------+ <-- state[1].first_item (depth 1)
| text |-->NULL <** state[1].last_item
+----*-+==>NULL
x *
v *
NULL *
v
,-----------.
("header text")
`-----------'
---
state[2]->first_item -->NULL (depth 2)
state[2]->last_item **>NULL
--- ,-- first_item
+------+<-'+-------+ +------+ <** last_item
| text |-->| blank |-->| text |-->NULL <== depth=3
+----*-+==>+-------+==>+----*-+==>NULL
x * x x *
v * v v *
NULL * NULL NULL *
v v
,-------. ,------------.
("heading") ("first...text")
`-------' `------------'
In the second case, we need an additional step if the element we are leaving
was a <center> element (or some element with an align="center" attribute): In
this case all sub-elements have to be centered one by one. (Elements creating a
box are centered as a whole.)
Finally, we have to do some more line break/blank line handling.
As soon as an element forcing a line break is either entered or left (there are
no elements creating a break only before or only behind it), "string_item" is
set to NULL, indicating that no more text can be added to the last text item,
and new text has to create a new one.
Blank Lines
Probably the most tricky part is handling of blank lines. Similar to line
breaks, items needing blank lines have them before *and* after them. However,
when two such items meet, they have only *one* blank line between them.
Furthermore, a blank line is *never* inserted before the first or after the
last item inside a box. That's why blank lines cannot be simply inserted when
entering an element causing blank lines, or when leaving it. Instead, only
"requests" for blank lines are stored in "para_blank", and if certain
conditions are met, a blank line is inserted before the next item (inside
add_item()).
Actually, the blank line is inserted not in front of the new item, but after
the last item, at the same tree depth as that one. This is important, to ensure
that a blank line generated in front of a box is actually inserted *outside* of
the box, not inside it, as would be the case if it was inserted at the current
depth. The global "blank_depth" variable is responsible for this, and is set to
the current depth every time a blank line request is generated. The blank item
is then inserted directly to the "state" structure at "blank_depth" in
add_item(). This is surely very bad programming style ;-)
The blank line requests are managed by the global "para_blank" variable. A
value of 1 indicates that a blank line is needed, and will be generated by the
next add_item(). A value of 0 indicates that no blank line is needed in any
case; this situation can only occur when there are no items inside the current
box yet. A value of -1 indicates that a blank line *may* be necessary. That is
the case when we already have some items inside the current box, but the last
item does not need a blank line; a blank line needs to be inserted only when
the following item wants one.
When entering an element needing a blank line, a request is generated
("para_blank" set to 1 and "blank_depth" is stored) if "para_blank" was -1,
indicating that there are already items in the current box.
+
+------+
->| body |-. <++++++++++++++
+------+ | <+ +
v + +
+----++ +---+
--> | h1 |-. <+ ,->| p |->
cur_ +----+ | + | +---+
tag v + |
,--------. |
(" heading") |
`--+---+-' |
| ? |----'
+---+
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
??? (para_blank=-1)
+
+------+
->| body |-. <++++++++++++++
+------+ | <+ +
v + +
+----++ +---+
--> | h1 |-. <+ ,->| p |->
==> +----+ | + | +---+
blank_ v + |
depth ,--------. |
(" heading") |
`--+---+-' |
**> | ? |----'
list_next +---+
(new "cur_el")
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
| (para_blank=1) |
...
|+-------+ | (will be created later)
||heading| |
|+-------+ |
If "para_blank" is already 1, the request is left unchanged; a blank line will
be inserted already.
| |
|+-------+ |
||heading| |
|+-------+ |
| (para_blank=1) |
|
v
+----+ <== +---+ <--
| h1 |-. <+ ,->| p |---. <++
+----+ | + | +---+ | +
v + | v +
,--------. | ,------------------.
(" heading") | (" first...newlines,")
`--+---+-' | `-----+----+-------'
| ? |----' **> | em |-.
+---+ +----+ |
| |
|+-------+ |
||heading| |
|+-------+ |
| (para_blank=1) |
...
|+------------+ |
||first...text| |
|+------------+ |
If "para_blank" is 0 nothing is done, even if the element would normally need a
blank line: No blank line is ever inserted in front of the first item inside a
box.
+-----------+
(para_blank=0)
+---+
| ! |-. <+
+---+ | +
v +
+---++
--> | p |-. <+
+---+ | +
v +
,---------.
("some text")
`--+---+--'
**> | ? |->
+---+
+-----------+
...
|+---------+|
||some text||
|+---------+|
When some item (text or box) is inserted by add_item(), "para_blank" is always
set to -1, as now there is at least one item in the current box.
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
| (para_blank=1) |
+
+------+
->| body |-. <++++++++++++++
+------+ | <+ +
v + +
+----++ +---+
| h1 |-. <+ ,->| p |->
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
--> | ? |----'
+---+
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
| |
|+-------+ |
||heading| |
|+-------+ |
??? (para_blank=-1)
When leaving an element needing a blank line, a request is generated also, and
will be handled in the next add_item(). Otherwise, the current state is kept.
+
+------+
->| body |-. <++++++++++++++
+------+ | <+ +
v + +
+----++ +---+
xx> | h1 |-. <+ ,->| p |-> <**
new_el +----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
--> | ? |----'
+---+
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
| |
|+-------+ |
||heading| |
|+-------+ |
??? (para_blank=-1)
+
+------+ <xx
->| body |-. <++++++++++++++
+------+ | <+ +
v + +
+----++ +---+
==> | h1 |-. <+ ,->| p |-> <**
+----+ | + | +---+
v + |
,--------. |
(" heading") |
`--+---+-' |
--> | ? |----'
+---+
+------------------+
|+-----------+ |
||header text| |
|+-----------+ |
| |
|+-------+ |
||heading| |
|+-------+ |
| (para_blank=1) |
When entering an element generating a box, "para_blank" is reset to 0.
| |
|+---------+ |
||some text| |
|+---------+ |
??? (para_blank=-1)
+--------+ +------+
->| center |-. ,->| form |-. <--
+--------+ | | +------+ |
v | |
,---------. | |
("some text") | v
`--+---+--' | +---+
| ? |-----' **> | p |->
+---+ +---+
| |
|+---------+ |
||some text| |
|+---------+ |
|+--------------+|
(para_blank=0)
However, it's left unchanged if there is already a request, indicating that a
blank line will be inserted *in front* of the box by the next add_item().
| |
|+---------+ |
||some text| |
|+---------+ |
| (para_blank=1) |
+---+ +------+
->| p |-. <== ,->| form |-. <--
+---+ | | +------+ |
v | |
,---------. | |
("some text") | v
`--+---+--' | +---+
| ? |-----' **> | p |->
+---+ +---+
| |
|+---------+ |
||some text| |
|+---------+ |
| (para_blank=1) |
|+--------------+|
When leaving a box creating element, any request generated inside the box is
discarded. We never insert a blank line after the last item of a box.
++>NULL
+ .--------------------------------.
+ v |
+---+ <xx |
| ! |-. <++ <** |
+---+ | + |
v + |
,-----------. |
("header text") |
`-+------+--' |
| html |-. <+++++++++++ |
+------+ | + |
| [...] [...]
[...] + |
| ,---------------. |
| (" (a single tag)") |
| `-----+---+-----' | <--
`--------->| ? |--------'
+---+
|+--------------+ |
||(a single tag)| |
|+--------------+ |
| (para_blank=1) |
++>NULL <xx
+ .--------------------------------.
+ v |
+---+ |
| ! |-. <++ <** |
+---+ | + |
v + |
,-----------. |
("header text") |
`-+------+--' |
| html |-. <+++++++++++ |
+------+ | + |
| [...] [...]
[...] + |
| ,---------------. |
| (" (a single tag)") |
| `-----+---+-----' | <--
`--------->| ? |--------'
+---+
|+--------------+ |
||(a single tag)| |
|+--------------+ |
+------------------+
??? (para_blank=-1)
However, if the last request was generated *before* descending into the element
creating the box (only possible if the box is empty), it is kept, and the blank
is inserted when the box is added.
| |
|+---------+ |
||some text| |
|+---------+ |
| (para_blank=1) |
|+--------------+|
+---+ +------+ <xx +---+
->| p |-. <== ,->| form |-. ,->| p |-> <**
+---+ | | +------+ | | +---+
v | | |
,---------. | | |
("some text") | v |
`--+---+--' | +------+ |
| ? |-----' --> | span |-'
+---+ +------+
| |
|+---------+ |
||some text| |
|+---------+ |
| |
|+--------------+|
|+--------------+|
<br> elements
<br> elements used to break text blocks as described above. This however turned
out to be a bug: some elements (e.g. <a>) can span over a <br>, and these were
handled incorrectly with that approach.
Now simply a '\n' is added to the text block when <br> is encountered, and then
correctly handled while Breaking String into
Lines.
Form elements are handled very similar, and by the same code. The only
difference is that "link_type" is set to some form type instead of FORM_NO, and
the initial "value" of the element is stored in the structure tree so it will
be submitted to the server, and (for some form control types) displayed on the
page via set_form() (see
hacking-links.*).
Also, "form_enabled" is set for all elements that will be submitted to the
server. It is always set for elements that are submitted unconditionally
(text/password/hidden input fields), and set to the initial state for elements
that are submitted depending on their state (radio buttons, checkboxes,
<select> options). Submit buttons initially aren't enabled.
Some special handling is necessary for <select> options: They do not have an
own "name" attribute to store in "Link->name" like other form elements; the
"name" for all options is given in the <select> element instead. Thus it needs
to be passed to all the options by the state stack, in "select_name". The same
for the link type (FORM_OPTION or FORM_MULTIOPTION) of the option links: It
depends on the presence of the "multiple" attribute in the <select> element,
and is passed in "select_type" for that reason.
After all elements of the syntax tree are traversed, the structure tree is
finalized by setting "next" of the tree top (the global item) to point back to
itself, and "parent" point to the first item.
parse_struct() returns a "struct Item" pointer to the tree top. This is passed
as argument to the following passes by main().
Is is a bit strange that "parent" of the tree top points to the first item.
However, it is important to have some simple way of accessing the first item,
as some of the following passes start with the fist item; but only the pointer
to the tree top is passed on the following passes. Maybe we should use some
function that finds the first item by following "first_child" instead -- as
this is done only once in every processing pass, it wouldn't be too big an
unefficiency.
assign_width()
The second pass assigns the x-coordinates (x_start and x_end) to all items.
(Presently, this is trivial: all items have the same coordinates as their
parent, which is the global item...) For text items, the positions of line
breaks are also calculated.
Traversing Item Tree Top to Bottom
In this pass, the tree is traversed top to bottom, as the coordinates of the
sub-items depend on the coordinates of the parent. This is a bit more
complicated than traversing bottom to top, as there is no equivalent of the
"list_next" pointer for this.
If the current item has children, we proceed with the first child. (Descend.)
<+++
+
+-----+
,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
cur_item xx> +-----+ +-----+ |
,->| box |-. ,->| box |-'
new cur_item | +-----+=|===========|=>+-----+==>NULL
| | x ^ | | x ^
xxxxxxxx|xxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++|+++++++++++++++++ | x ++++++++++++
v + | + | | v + |
+------+<-'+------+ | | +------+ |
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
If the current item has no children, we go to the "next" item.
<+++
+
+-----+
,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ +-----+ |
,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | <-- | +------+ |
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x ^xx x x
v v v
NULL NULL NULL
If there is no "next" item (we are already at the last item of this depth), we
have to ascend before we can go to the next item.
<+++
+
+-----+
,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ +-----+ |
--> ,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | <xx | +------+ |
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
<+++
+
+-----+
,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ --> +-----+ |
,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | <xx | +------+ |
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
If we still do not have a "next" item after ascending, we ascend again.
<+++
+
+-----+
,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ --> +-----+ |
,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | | +------+ | <xx
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
<+++
+
+-----+
--> ,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ +-----+ |
,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | | +------+ | <xx
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
After all items have been processed, we'll ascend until we get back to the top
item, which's "next" pointer points back to itself; Thus we stay at the tree
top after following "next", and the main loop is terminated.
<+++
+
+-----+
--> ,->| box |-->NULL
| +-----+<==#
| x ^ #===#
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx +
x +++++++++++++++++++++++++++++++++++
v + + |
+-----+ +-----+ |
,->| box |-. ,->| box |-'
| +-----+=|===========|=>+-----+==>NULL
| x ^ | | x ^
xxxxxxxxxxxxxxxxxxxxxxxx + | xxxxxxxxxxxxx +
x +++++++++++++++++++++++ | x ++++++++++++
v + + | | v + |
+------+ +------+ | | +------+ | <xx
| text |-->| text |-' `->| text |-'
+------+==>+------+==>NULL +------+==>NULL
x x x
v v v
NULL NULL NULL
Assigning x-Coordinates
When processing an item, not the coordinates of "cur_item" are assigned, but
the coordinates of its *sub-items*. "cur_item" has had its coodinates assigned
while its parent was processed. This is an exact reversal of calc_width(): Instead of "cur_item" getting
its size from its sub-items, the sub-items get their size from "cur_item".
The coordinates for the global item are assigned before calling assign_width().
x-start is set to 0, x-end is set to the output width passed from main(). (The
screen width when cfg.term_width is set; otherwise, either a constant value (in
--dump mode) or the maximum of screen width and page width.) Play around with
them if you like. (If set to a narrow box, you can see the word breaking work.)
##################################################################################
#------+ #
#header| #
#* #
#* #
[...]
#------------+ #
#parameters);| #
#------+ #
#single| #
^x_start=0 ^x_end=80
For box (and form) items, the coordinates of all immediate children are simply
set to the ones of the box. (This will have to change at some point, but it's
ok for now...) It's done in a simple loop processing the children by
"first_child" and "next", just as in
calc_width().
##################################################################################
+--------------------------------------------------------------------------------+
|header text |
**********************************************************************************
* *
[...]
+--------------------------------------------------------------------------------+
|this very long second paragraph contains some special characters (including a |
|simple space...): &; <>"=/ plus a big gap###and two unicode escapes (decimal: ¡ |
|and hexal: ¿) but also an anchor embedded inside a word (this anchor also is the|
|only tag with parameters); and finally a blank row |
+--------------------------------------------------------------------------------+
|(a single tag) |
Blank items have no children. Nothing has to be done. The same for anchor items.
Text items have no children, too; but they need to be broken into lines. (This
could be done in a seperate pass...)
Breaking String into Lines
The breaking into lines is a bit complicated, because netrik has the ability to
break words that do not fit on a single line. And: It does this smartly,
avoiding line breaks whenever possible.
The line breaking does not alter the string structure itself. The only output
is "line_table[]" (containing the positions of all line breaks inside the
string), and its length (The number of line breaks), which is stored as the
height of the text item in "y_end".
Before starting, some constants are calculated: The width of the text block is
the difference of x_end and x_start. The pointer to the start of the text
string is taken from the string structure and stored in "string_start".
The text block is processed word-wise. In each iteration of the outer loop one
word is processed.
First, "word_end" is retrieved. It points to the space, newline or string
terminator that ends the word to be processed. "next_word_start" is set to
"word_end+1", assuming that we will proceed with the next word (which starts
after the space); however, this may by altered later.
line_table[0]
v
string: "I am a very simple and stupid example sentence."
^ ^ ^ ^^
s l w en
string_start line_start next_word_start
word_end
word_start
output:
x_start x_end
|<- width ->|
v 12 v
+------------+
|I am a very |
|simple and stupid example sentence.
^ ^ ^^
l w en
Then we test if the whole word fits into the current open line (which's
starting position is stored in "line_start").
v
string: "I am a very simple and stupid example sentence."
^ ^ ^ ^^^
s l w enb
line_start+width (line end/Break position)
|<- width ->|
(12)
+------------+
|I am a very |
|simple and stupid example sentence.
^ ^ ^^^
l w enb
e<b -> no break
If it does, we do nothing, and simply proceed with the next word. "word_start"
is set to "next_word_start" before the next iteration.
v
string: "I am a very simple and stupid example sentence."
^ ^ ^
s l n
^
w
Otherwise, we have to generate a line break, and put the word on a new line.
v
string: "I am a very simple and stupid example sentence."
^ ^ ^^ ^^
s l wb en
+------------+
|I am a very |
|simple and stupid example sentence.
^ ^^ ^^
l wb en
e>=b -> break
Normally, we simply break the line at the current word, by setting "line_start"
to "word_start", and adding a line break at this position to "line_table[]".
line_table[1]
v v
string: "I am a very simple and stupid example sentence."
^ ^ ^^
s w en
^
l
+------------+
|I am a very |
|simple and |
|stupid example sentence.
^ ^^
w en
^
l
However, things are more complicated due to the ability of breaking too long
words. For this, we have to test whether the current word fits on one line. If
it does, we simlply insert a line break as described above.
v v
string: "I am a very simple and stupid example sentence."
^ ^ ^^ ^^ ^
s l wb en f
word_start+width (Fit on line)
|<- width ->|
+------------+
|I am a very |
|simple and stupid example sentence.
^ ^^ ^^ ^
l wb en f
e<f -> simple break
If it does not (if it's longer than the width of the text block), we have to
break the word.
v v v v
string: "I am a second example sentence with aVeryLongWord in me."
^ ^ ^ ^^^
l w b fen
+------------+
|I am a |
|second |
|example |
|sentence |
|with aVeryLongWord in me.
^ ^ ^ ^^^
l w b fen
e>=f -> break word
In this case, there are two possibilities: Either, we put the beginning of the
word on the current line, and the remainder on the next line(s). Or, we put the
first part to the new line already. This sometimes saves an unnecessary word
break:
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitL\|
|ongerWord in|
|me. |
+------------+
instead of:
+------------+
|I am a third|
|example |
|sentence, |
|with anEven\|
|ABitLongerW\|
|ord in me. |
+------------+
We decide which way to go, by truncating the word of as many whole line lengths
("width-1", because of the break chars) as possible, and testing if the
remaining part fits on the current line.
v v v v
string: "I am a second example sentence with aVeryLongWord in me."
^ ^ ^ ^ ^^
l w t b en
trunc_word_end=word_end-(width-1)
|<- ->|
width-1 (11)
+------------+
|I am a |
|second |
|example |
|sentence |
|with a\ |
^ ^ ^ ^
l w t b
t<=b -> fill line
|VeryLongWord| (truncated part)
^
e
Or:
v v v v v
string: "I am a third example sentence, with anEvenABitLongerWord in me."
^ ^ ^ ^ ^^
l w b t en
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitL\|
^ ^ ^ ^
l w t b
t<=b -> fill line
|itLongerWord|
^
e
For a longer word, the truncation is done more than once:
v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^ ^ ^ ^ ^ ^^
l w T b t t en
(final)
+------------+
|I am another|
|example |
|sentence, |
|with aTe\ |
^ ^ ^ ^
l w T b t<=b -> fill line
|rriblyLongW\|
^
t
|ordThatDoes\|
^
t
|n'tSeemToEnd in me.
^^
en
or:
v
string: "This example has again aTerriblyLongWordThatDoesn'tSeemToEnd in some other sentence."
^ ^ ^ ^ ^ ^ ^^
l w b T t t en
+------------+
|This example|
|has again aTe\
^ ^ ^ ^
l w b T
t>b -> don't fill (put first word part in new line)
This is done in a loop. We also could do it by a single expression, but
evaluating a quite complicated expression is probably less efficient than a
simple loop, which is almost always executed only once. (Very few words are
longer than two lines...) Also, it is easier to understand, isn't it?...
If we decide on the first way, we fill up the current line with the beginning
of the word. (The last char is kept empty for the word break indicator
displayed in the output.) The line break position and "line_start" are set
accordingly, so that the rest of the word will be put on the next line.
v v v v v
string: "I am a second example sentence with aVeryLongWord in me."
^ ^° ^^
w lb en
(old value)
+------------+
|I am a |
|second |
|example |
|sentence |
|with aVeryL\|
|ongWord in me.
^ ^^
l en
We also need to test if the remainder fits on the next line; if it does not, we
have to adjust "next_word_start" so that processing in the next loop iteration
will not continue with the next word, but with the part of the current word
that does not fit on the next line.
v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^° ^ ^^
w lb b en
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWordThatDoesn'tSeemToEnd in me.
^ ^ ^^
l b en
e>=b -> more breaks necessary
v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^ ^^ ^
w l nb e
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWordThatDoesn'tSeemToEnd in me.
^ ^^ ^
l nb e
If the second way was chosen, things are quite easy: The line break is inserted
at the beginning of the word, and "next_word_start" is *always* adjusted to the
end of the new line.
v v v v v
string: "I am a third example sentence, with anEvenABitLongerWord in me."
^ ^^ ^°
w nb en
^
l
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitLongerWord in me."
^ ^^ ^°
l nb en
In any case, if "next_line_start" was adjusted we will scan for the word end
again in the next iteration; but starting with the part of the word that does
not fit on the new line. (This is unefficient of course, but this case is quite
rare, and it's not worth adding special code for handling this.)
v v v v v
string: "I am a third example sentence, with anEvenABitLongerWord in me."
^ ^ ^^
l w en
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitLongerWord in me."
^ ^^ ^^
l wb en
As the new line is already filled up with the previous word part, another line
break will always be inserted just in front of the remainder, and the remainder
will be put into another line.
v v v v v
string: "I am a third example sentence, with anEvenABitLongerWord in me."
^ ^^ ^^
l wb en
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitLongerWord in me."
^ ^^ ^^
l wb en
e>b -> break
v v v v v
string: "I am a third example sentence, with anEvenABitLongerWord in me."
^° ^^
wb en
^
l
+------------+
|I am a third|
|example |
|sentence, |
|with |
|anEvenABitL\|
|ongerWord in me."
^ ^^
l en
Of course it's also possible that the remainder still doesn't fit on a line,
and has to be broken again.
v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^^ ^^
l wb en
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWordThatDoesn'tSeemToEnd in me.
^ ^^ ^^
l wb en
e>b -> break
v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^ ^ ^^
l w f en
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWordThatDoesn'tSeemToEnd in me.
^ ^ ^ ^^
l w f en
e>f -> word break
v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^^ ^ ^^
l wb t en
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWordThatDoes\|
^ ^^ ^
l wb t
t>b -> don't fill
v v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^^ ^
w nb e
^
l
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWord\|
|ThatDoesn'tSeemToEnd in me.
^ ^^ ^
l nb e
This will be repeated, until the whole word is stored.
v v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^^ ^^
l wb en
e>b -> break
v v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^ ^^
l w en
^
f
e<=f -> no word break
v v v v v v
string: "I am another example sentence, with aTerriblyLongWordThatDoesn'tSeemToEnd in me."
^ ^^
w en
^
l
+------------+
|I am another|
|example |
|sentence, |
|with aTerri\|
|blyLongWord\|
|ThatDoesn't\|
|SeemToEnd in me.
^ ^^
l en
Of course, a line break is always inserted in front of the word no matter if it
would fit on the old line, if the word follows a newline character.
v v v v v
string: "I am a stupid example sentence with a newline/in me."
^ ^ ^ ^^^
s l w enb
+------------+
|I am a |
[...]
|newline/in me.
^ ^ ^^^
l w enb
e<b, but w follows newline -> break
+------------+
|I am a |
[...]
|newline/ |
|in me.
^ ^^
w en
^
l
The third pass is simple again. calc_ywidth() calculates minimal heights
(y-widths) for all items.
Presently this is complete overkill; assign_ywidth() doesn't really need this.
However, it will be necessary as soon as interesting elements are
implemented (tables) -- which hopefully won't be too long now...
Blank lines always have the height of 1. Anchor items have no height. (They are virtual...)
The height of a box item is calculated by summing up the height of all its
sub-items. This is done by "first_child" and "next", just as seeking the widest
sub-item in calc_width().
The whole line map is allocated at the beginning. Afterwards, all items are
processed in a loop. For every item that is visible on the screen (presently
this are only text items), a reference to this item is stored to every line of
"page_map[]" between "y_start" and "y_end" of the item.
"page_map[]" is returned to pre_render(), and from there to main(), where it is
passed to dump() or to
render() (via
display(), see
hacking-pager.*) along with "item_tree".
dump()
The page is rendered line by line, using "page_map[]" to determine which items
we need to render in every line. Of course this isn't really necessary, as we
do not ever have more than one item in a line presently. However, using
"page_map[]" here is *not* overkill, just for a change ;-) On the contrary,
this is a pragmatic approach. Dumping the page item by item without using
"page_map[]" would be more efficient; however, it would be also more
complicated than dumping line by line.
In every line, we process all items (from "page_map[line]") one after the
other. If there is actually more then one item (which is impossible
presently...), they are printed one after the other. As long as they do not
overlap (they will at some point, but not too soon...), they shouldn't
interfere with each other.
At the beginning of processing an item, some constants are set. "item" and
"string" point to the processed item and its text area.
"string_line" is the line number inside the text block of the line we are just
printing. That is to say, it's the offset to the first line of the text block.
2 |[...] |
3 |+-----------------------------------------------+|
4 <-- item->y_start=4 0 ||first paragraph of text; includes multiple ||
5 <-- line=5 string_ --> 1 ||spaces and newlines, emphasized text and strong||
6 line=1 2 ||text ||
7 |+-----------------------------------------------+|
8 |[...] |
"text_start" tells where this line beginns inside the string. Normally, it is
taken directly from "line_table[string_line-1]", which is the position of the
line break at which the line starts.
line_table[0]
v
text: "first paragraph of text; includes multiple spaces and newlines, [...]"
^
text_start=line_table[string_line-1]
As line 0 of a text block doesn't start with a line break, its start isn't
stored in "line_table[]"; we have to test for this case and set "text_start" to
0.
v
text: "first paragraph of text; includes multiple spaces and newlines, [...]"
^
text_start
"text_end" tells where this line ends; it is set to the beginning of the next
line ("line_table[string_line]").
line_table[0] line_table[1]
v v
text: "[...]multiple spaces and newlines, emphasized text and strong text"
^ ^
text_start text_end=line_table[string_line]
As the last line does not end with a line break, we have to test for this case
end set "text_end" to the string end.
v v
text: "[...]multiple spaces and newlines, emphasized text and strong text"
^ ^
text_start text_end
Maybe we should store the beginning of the first line and the end of the last
line to "line_table[]" also. This would simplify the code (we wouldn't need the
tests), and the efficiency loss should be quite irrelevant.
"text_end" isn't declared as a constant, because it may be altered: If the last
character in the line turns out to be a blank (or newline), it isn't printed.
We accomplish this by decrementing "text_end" by one.
v v
text: "[...]multiple spaces and newlines, emphasized text and strong text"
^ ^
text_start text_end
After knowing start and end of the line, we calculate "x_start", which is the
screen column at which the line will start. Normally, this is equal to
"x_start" of the text item.
||spaces and newlines, emphasized text and strong||
^
x_start=item->x_start
If the text item is centered, we have to add an individual offset to each
line. The offset is half of the unused space inside the line, i.e. the
difference between the width of the text block and the width of the text in
this line.
text_start text_end
v v
||starting with an evil center tag, ||
^ ^
item->x_start item->x_end
|<---- text_end-text_start ----->|
|<--------------- x_end-x_start -------------->|
|<----------->|
unused
|<---->|
unused/2
v v
|| starting with an evil center tag, ||
^ ^ ^
item->x_start x_start=item->xstart+unused/2
|<---->|
unused/2
Then we set the cursor to the calculated col. This we do by a carrige return
(not really needed for the first item in a line...) and than going forward as
much character positions as needed.
Now we can output the text itself. We print all attribute divisions in a loop.
But first we have to find the first one that shows up in the current line.
div[0].end ... div[3].end
v v v v
text: "first[...]multiple spaces and newlines, emphasized text and strong text"
| ^ | ^
text_start
In every iteration we print all the text between "div_start" end "div_end",
which normally point to the start and end of the current division. For the
first iteration, "div_start" is set to "text_start" -- we only want the part of
the div that shows up in the current text line.
v v v v
text: "first[...]multiple spaces and newlines, emphasized text and strong text"
^ ^
div_start=text_start div_end=div[0].end
output:
first paragraph of text; contains multiple
spaces and newlines,
The next div starts where the current one ends.
v v v v
text: "first[...]multiple spaces and newlines, emphasized text and strong text"
^ ^ ^ ^
text_start div_start div_end
The last division is truncated to "text_end" -- as with the first one, we only
want the part that shows up in the current line.
v v v v
text: "first[...]multiple spaces and newlines, emphasized text and strong text"
^ ^ ^
div_start div_end
=text_end
Finally, we test if the line ends with a word break, and print the break
character if it does. We know it does when the character at the line end is a
word character (not a space, newline, or string end), because every word end is
followed by the space separating it from the next word; if there is no space at
the line end, we are inside a broken word.
v v
text "Some sentence containing aVeryLongAndThusBrokenWord."
^
output:
Some sentence
containing aVeryLongAn\
...
dThusBrokenWord.