OODoc::Text(3pm)
okay bestie, welcome to the OODoc::Text(3pm) manual page โ it's giving text-processing main character energy, and we're gonna read every single line together. ๐
โจ
๐ NAME ๐
OpenOffice::OODoc::Text โ the text processing submodule of OpenOffice::OODoc ๐
๐ธ DESCRIPTION ๐ธ
okay so this manual chapter describes the text-oriented methods of OpenOffice::OODoc, implemented by the OpenOffice::OODoc::Text class, and inherited by the OpenOffice::OODoc::Document class. ๐
These methods are not essentially dedicated to string processing; they are more precisely focused on text containers. A text container is a document element which can (and must) be used in order to support a text and integrate it at the right place and according to the right presentation rules. The OpenDocument specification defines a lot of such containers, and the present API supports many of them, such as paragraphs, headings, tables (or spreadsheets), lists, sections, and draw pages. Some of these containers can host other containers: for example, a table contains rows, a row contains cells, a section can contain almost everything including other sections, etc. It's nesting-doll realness, no cap. ๐ช
These features are text-oriented, but can be used on documents of any class, such as spreadsheets or presentations as well as text documents. So, the 'Text' word doesn't mean that the features described in the present manual chapter are dedicated to OpenDocument Text (ODT) documents only. In the other hand, a few methods can't apply to any document class (ex: creating or retrieving draw pages makes sense with presentation and drawing documents only). ๐
OODoc::Text should not be explicitly used in an ordinary application, because all its features are available through the OpenOffice::OODoc::Document class, in combination with other features. Practically, the present manual is provided to describe the text-oriented features of OpenOffice::OODoc::Document (knowing that these features are technically supported by the OpenOffice::OODoc::Text component of the API).
The OpenOffice::OODoc::Text class is a specialist derivative of OpenOffice::OODoc::XPath for XML elements which describe the text content of OOo/ODF documents. Here, "text content" means containers that can host text containers (i.e. tables, lists...) as well as flat text. ๐
Knowing that the "styles.xml" member of an OpenDocument file can contain text (because some style definitions, such as page headers or footers, can contain text), the presently described features can be used against this member as well as the "content.xml" member.
This module should be used in combination with OpenOffice::OODoc::Styles, via the OpenOffice::OODoc::Document class, if the application has to handle detailed presentation parameters of text elements. This is because such parameters are held in styles elements and not in the text elements themselves, according to the principle of separation of content and presentation which is one of the foundations of the OpenDocument format. periodt. ๐
๐ง Methods ๐ง
Constructor : OpenOffice::OODoc::Text->new(<parameters>)
Short Form: odfText(<parameters>)
This constructor should not be explicitly used in ordinary applications knowing that all the features of the returned object are inherited by any Document object.
See OpenOffice::OODoc::XPath->new for common arguments.
Returns an OODoc::XPath OpenDocument connector with additional features mainly focused on text containers.
This constructor is generally not explicitly called, knowing that it's automatically triggered each time a Document object is created.
The XML member loaded by default is 'content.xml'. The most common creation method is like this:
my $doc = odfText(file => 'my_file.odt');
This constructor should generally not be called directly, because it's inherited by odfDocument().
Other parameters can be supplied as options (see the properties list at the end of the chapter).
Example:
my %delim =
(
'text:h' =>
{
begin => '\sect{',
end => '}'
},
'text:list-item' =>
{
begin => '\item'
}
'text:footnote-body' =>
{
begin => '\footnote{',
end => '}'
}
);
my $doc = odfText
(
file => 'filename.odt',
paragraph_style => 'My Paragraphs',
heading_style => 'My Headings',
delimiters => { %delim }
);
This technique gives the default styles to be used when creating new text elements. It also gives the particular delimiters (in this case LaTeX style markers) to be used at the beginning or end of some elements (in this case headings, list elements, footers) where the text is to be exported "as is". See the getText method of OODoc::Text for information about exporting text. ๐
appendDrawPage([options])
In a presentation or drawing document, appends a new page at the end of the document.
Possible options are:
nameโ page name (unique)idโ page numeric ID (unique)styleโ page style namemasterโ master page name
Returns the new draw page element if successful, undef if not.
appendHeading([options])
Creates a new heading of any level and appends it to the end of the document.
Options are given as a hash [key => value]:
'text' => <heading text>
'level' => heading level, default is 1
'style' => heading style, default is 'Heading 1'
Examples:
$doc->appendHeading(text => 'Next section');
adds the text 'Next section' as a level 1 heading.
$doc->appendHeading
(
text => 'Chapter Conclusion',
level => '2',
style => 'Heading_20_2'
);
adds a level 2 heading to the end of the text body. 'Heading_20_n' styles, where 'n' is the level number, are presently available by default in OpenOffice.org.
You can give any XML attribute to the new heading except for style or heading level. In this case, the program must construct a hash containing pairs of key-values for the attributes you want to create and pass it using the 'attribute' option. Example:
my %attr = ( 'att1' => 'value1', 'att2' => 'value2' );
$doc->appendHeading
(
text => 'Attributes are important',
level => '1',
style => 'Chapter heading',
attributes => {%attr}
);
If the 'text' option is empty, the heading is created with an empty content.
Caution, creating headings with level attributes is not always sufficient to produce the needed result. For example, in order to generate headings with appropriate levels of numbering, each one must be attached to the right position in a hierarchy of lists, in combination with appendItemList(), insertItemList(), and appendListItem().
Note: this method can only be used with a new header i.e. it adds while it creates. To add an already available element using getHeading() from the same document or from another document, use the appendElement() method instead which is inherited from OODoc::XPath.
appendItem(list [, text => text ,style => style ,[other_options]])
See appendListItem().
appendItemList([type => list_type, [style => style [, options]]])
Creates a new (empty) list and appends it to the end of the document.
In OpenOffice.org 1 documents, an unordered list is the default, and if the 'type' option is given with the value 'ordered', then an ordered list is created. In Open Documents, the 'type' option is ignored because there are generic lists only (a list is ordered or "bulleted" according to a style, and not natively).
The 'style' option controls the list's style (as opposed to each item's style). If absent, the list takes the default paragraph style (see appendParagraph).
Like appendParagraph, this method actually creates a new list element. To copy an existing list in the same document or in another, use appendElement or replicateElement instead.
appendListItem(list [, text => text ,style => style ,[other_options]])
Adds a new item to a list (ordered or unordered).
The first argument is the existing list element (created using getOrderedList or getUnorderedList, for example). Options are the same as for appendParagraph.
If the 'style' option is absent, the element is inserted according to the following rule:
- if the new item is not the first one of the list, it takes the same style as the first item;
- otherwise, it takes the default paragraph style of the document.
The new item is created as a paragraph container by default. A 'type' option may be provided in order to require another type. Possible values are 'header', 'paragraph' or the XML name of any OpenDocument-compliant text container.
If the type is provided and set to undef, the new item is created as an empty element, so it could/should receive a content later. An empty item could be used as the attachment point of another list, in order to create a hierarchy of lists.
appendParagraph(<options>)
Creates a new paragraph and appends it to the document.
Options:
'text' => <paragraph text>
'style' => <paragraph style>
An 'attribute' option is also available under the same conditions as for the appendHeading method (see above).
If the 'text' option is empty, calling this method is the equivalent of adding a line feed.
If the 'style' option is empty, we just borrow the style from the 'paragraph_style' property of the OODoc::Text instance. Reuse era ๐
By default your shiny new paragraph lands at the end of the document. But bestie, you can also attach it as the last child of an existing text container (think: a table cell ๐). To do that, hand over the container through an 'attachment' option. Like, say you wanna drop a fresh paragraph into a table cell:
my $cell = $doc->getTableCell("Table1", "B12");
$doc->appendParagraph
(
text => "The cell, reloaded",
attachment => $cell
);
Note: this method only works with a new paragraph, i.e. it adds while it creates. If you wanna add an already existing paragraph โ pulled viagetParagraphfrom this document or a whole other document โ then use theappendElement,insertElementorreplicateElementmethods instead. Those are inherited from OODoc::XPath. โจ
Note: repeated spaces are not properly processed ๐ญ so any sequence of spaces (no matter how long) in the'text'string gets squashed down to a single space in the target document. SeesetText()andextendText().
๐ appendRow(table [, options])
Appends a row to the end of the given table โ by reference, by logical name, or by sequential number, your call ๐ซถ By default the new row is just an exact copy of the preceding row (content AND presentation, copy-paste energy). You can pass an options hash to give the created row certain attributes, under the same conditions as for the appendElement method of OODoc::XPath. The returned value is the created row element. ๐
Example:
open SRC, '<', 'data.txt';
my $table = $doc->getTable("Table1");
my ($h, $l) = $doc->getTableSize($table);
for (my $i = 0 ; my $record = <SRC> ; $i++)
{
last unless $record;
chomp $record;
my @data = split ';', $record;
my $row = $i < $h ?
$doc->getRow($table, $i) :
$doc->appendRow($table);
for (my $j = 0 ; $j < $l ; $j++)
{
$doc->cellValue($row, $j, $data[$j]);
}
}
So what's happening here, bestie? The program above reads a CSV format data file sequentially (one record per line, comma-separated fields). Each record gets split and dropped into a row in table Table1. On reading each new record, the reference for the following row is loaded by getRow, until the total number of rows is reached (that total came from getTableSize earlier ๐). If the table is already full, it gets lengthened by a row using appendRow. The inner loop loads the read data into the row's cells (pre-existing or freshly created). Peep the sections on getTable, getRow, getTableSize and cellValue for a better understanding of this example. ๐
But โ and this is the important part โ if good performance is what you're after, do not spam this method massively (like, lengthening a table dynamically row by row while loading external data into it ๐ฅด). Rather than running dozens or hundreds of successive appendRows, it'd be way better for the application to read the total number of records to be loaded first (using, for example, select count if it's from a relational database, or otherwise preloading the data into an ordinary Perl table) and then create a table of the appropriate size in advance using insertTable() or appendTable(). Efficiency is the vibe. ๐
๐ง appendSection(name [, options])
Creates a new section with the given name, and appends it by default to the end of the document body. If the "attachment" option is provided, with an existing element as its value, the new section is appended in the context of that element. For example, if the value of "attachment" is an existing section, the new section gets appended as the last sub-section of the existing one. Nested sections, we love to see it ๐ธ
A section can either hold local content or insert a subdocument which can be reached through an external link. ๐
To insert a subdocument link instead of an ordinary section, the application must provide a "link" option whose value is either a local file path or an URL.
Example:
$doc->appendSection
(
"Article",
link => "http://mycompany.com/doc/article.odt"
);
Other possible options:
'style'โ lets the application explicitly select a style for the new section'protected'โ write-protects the section when the document is edited;"true"or"false", default"false"'key'โ in combination with"protected" => "true", write-protects the section by password (the value of"key"is not the real password, but an encrypted password, so the end-user will never remove the protection by simply typing the key as it is written in the program ๐); seelockSection(),unlockSection()andsectionProtectionKey()
โญ appendTable(name, rows, columns [, options])
Creates a new table with the given name, number of rows and number of columns, and appends it by default to the end of the document body. The name must be unique within the document (the call gets rejected if the name already exists, no duplicates allowed ๐ ). Returns the created table element if successful.
Beware: creating simple tables from scratch is very easy; however, for a realistic application, it's strongly recommended to replicate XML table templates previously created with an ODF-compatible editing software. A reasonably sophisticated table implies dozens of style definitions and would require a lot of Perl code plus a deep knowledge of the ODF specification โ while it could be created in a few minutes through a WYSIWYG tool. Save yourself, bestie. ๐ญ
'rows' and/or 'columns', if omitted, are replaced by the 'max_rows' and 'max_cols' properties of the document (see the properties below).
By default, the table is set to fit the entire width between the left and right margins, with equal sized columns, cells of type string, and no borders or background colour. Clean slate energy โจ
Possible options:
'table-style'โ table style'cell-type'โ default cell type'cell-style'โ default cell style'text-style'โ default cell text style
The first option is the name of a table style which defines certain global properties for the table (width, background colour, etc.). See the OpenOffice::OODoc::Styles manual for info about styles. ๐
The second option is the cells' default data type. The main types available are string, float, currency, date, percentage. Caution: to be properly treated as having a numeric format in OOo/ODF, a cell needs more than to be just marked 'numeric'. If the cell really needs to be treated properly as a number, you must also give it a cell style which itself refers to a number style. The cell-style parameter can do this. However, even though the OODoc::Styles module is there to otherwise help you create and add styles from a program, this type of exercise can become very labour-intensive. So we recommend using basic tables created in advance from document templates or style libraries created from an office application, rather than creating complex number tables from code. Fr fr, trust. ๐
The text-style option selects the paragraph style applicable to the text displayed in each cell.
Once the table is created, you can obviously modify each cell's type and style individually. Go off. ๐
Example:
my $table = $doc->appendTable
(
"Rate", 22, 5,
'table-style' => 'Table1',
'text-style' => 'Text body'
);
๐ฆ appendTableRow(table)
See appendRow.
๐ autoSheetNormalizationOff()
Deactivates the automatic sheet normalization.
See autoSheetNormalizationOn().
โจ autoSheetNormalizationOn('full')
โจ autoSheetNormalizationOn(height, width)
Activates the automatic normalization of any used table.
This method instructs the API to automatically normalize anything table or sheet as soon as it's reached through getTable() or another table-related access method. The automatic normalization is not activated by default. It can be deactivated at any time using autoSheetNormalizationOff().
See normalizeSheet() for details about the arguments and the effects.
๐ bibliographyEntryContent(id [, key1 => value1, key2 => value2, ...])
Gets โ and optionally sets โ the properties of a given (existing) bibliographic entry. The optionally updated properties are provided as a hash. The returned description is a hash. ๐
The first argument can be either the logical identifier of the entry (as it appears for the end-user) or a previously found bibliography entry element (see getBibliographyElements()).
Example:
my %desc = $doc->bibliographyEntryContent
(
"GEN99",
author => 'Genicorp',
pages => 62
);
This sequence updates the "Author" and "Pages" values of the "GEN99" entry, then returns all the content of the entry in %desc. Chef's kiss ๐
โ ๏ธ Caution: several bibliography entries can totally share the same identifier, bestie. And this method? It only handles one element at a time. In the example up above, only the first occurrence of the "GEN99" entries gets updated. So if you need every single entry with that same identifier to hold the same content, your code needs to look something like this:
my @entries = $doc->getBibliographyElements("^GEN99$");
foreach my $entry (@entries)
{
$doc->bibliographyEntryContent
(
$entry,
author => 'Genicorp',
pages => 62
)
}
โ ๏ธ Caution number two: this method lets you create any new property and drop any value into any property โ zero control, zero gatekeeping, no vibe check. For the legal and/or recommended properties, go read the OpenDocument specification and the OpenOffice.org bibliographic project (http://bibliographic.openoffice.org). ๐ซถ
bookmarkElement(element, name [, offset])
Just go see setBookmark(). That's it, that's the whole thing. ๐
cellCurrency(table, row, column [, currency]) / cellCurrency(cell [, currency])
Get or set the currency unit of a cell. ๐ช
If you hand it a currency, the cell's value type gets automatically switched to 'currency' โ no extra steps, it just does it.
cellFormula(table, row, column [, formula]) / cellFormula(cell [, formula])
An accessor that returns the formula (or function) sitting inside the given table cell. Returns undef if there's no formula in that cell, no cap. โจ
The cell address works exactly the same as for getCellValue().
If you pass a formula as the last argument, it gets put into the cell and overwrites any formula that was already there. And listen โ no syntax checking happens at all on the formula you insert. It's fully on your application to insert a formula that conforms to OOo/ODF syntax. Example:
$doc->cellFormula(1,3,2, "sum <C2:C5>");
Note 1: inserting or replacing a formula does not directly modify the value or the text of the cell. Proper interpretation of a formula doesn't happen until the fields get updated when the document is reloaded into the office software. So like, don't panic when nothing changes immediately. ๐ญ
Note 2: the syntax and functionality of cell formulae differ greatly between office applications. It's giving chaos, honestly.
cellSpan(table, row, column [, hspan [, vspan]]) / cellSpan(cell [, hspan [, vspan]])
In a spreadsheet document, get or set the span of a table cell โ and yes, that span can cover one or more columns. The cell addressing is the same as with getTableCell(). Example:
$doc->cellSpan($table, "B4", 3);
That creates a 3-cell span starting from B4 in a spreadsheet. Iconic.
With only one span argument, this method does horizontal, left-to-right expansion. Add one more argument and the expansion becomes bi-directional, covering one or more rows below the given cell. If you want a vertical span only, set the horizontal span to 1.
The text of the covered cells (if there is any) gets concatenated onto the original content of the expanded cell โ exactly like in OOo Writer or Calc. ๐ธ
Now, the part where you gotta be careful: make sure your cell expansion won't invade the span of another cell that was already expanded before. Say A is the target of cellSpan(), B is an existing expanded cell, and C is a covered cell inside the span of B. Here's how the rules shake out:
- If
Bis going to be covered by the span ofA, then the span ofBgets automatically reset to1, soCbecomes visible, and thenBis covered byA. - But if
Cis inside the target range ofcellSpan()whileBis not, the method produces an inconsistency in the table. (This inconsistency doesn't stop OpenOffice.org and KSpread from loading the file โ but the span ofAis just ignored. ๐)
In list context, the method returns the horizontal span, then the vertical span. In scalar context, it returns the horizontal span only.
โ ๏ธ Caution: when we're talking about table cells,"span"does not mean the same thing as it does for flat text. SeegetSpan()andsetTextSpan()for that other flavor.
cellStyle(table, row, column [, stylename]) / cellStyle(cell [, stylename])
Get or set the style of a table cell. Simple as that. ๐
cellValue(table, row, column [, value [, text]]) / cellValue(cell [, value [, text]])
No value argument? Then go see getCellValue().
Got a value (and optionally a text)? Then go see updateCell(). Easy.
cellValueType(table, row, column [, type]) / cellValueType(cell [, type])
Get or set the data type of a table cell.
The possible value types are 'string', 'float', 'percentage', 'currency', 'date', 'time', 'boolean'.
Note: if your application has to convert a'string'cell into a numeric one and fill it with a numeric value, you must callcellValueType()beforecellValue(). Order matters, bestie. Ex:
my $cell = $doc->getTableCell('Sheet1', 4, 8);
$doc->cellValueType($cell, 'float');
$doc->cellValue($cell, 12.34);
checkIndexMark(name, type [, context])
Checks whether an index mark exists and whether it's valid (peep setIndexMark() for the details on range index marks). The mandatory arguments are the index entry identifier and the index entry type โ namely 'toc' or 'alphabetical index'. You can also pass a context element if you want to restrict the search context. ๐
This method may return 1, 0 or undef.
1means the index mark is present and consistent. Slay.0means the index mark is present in the context but not valid.undefmeans the index mark doesn't exist in the context at all.
If the result is 0, there are 2 possible reasons: either the start point or the end point of the index mark was found but not both, or both were found but their relative positions are wrong (the end is sitting before the start ๐ญ). Whatever the explanation, this result means some cleaning should be done โ see deleteIndexMark().
checkRangeBookmark(name [, context])
Checks whether a range bookmark exists and whether it's valid (peep setBookmark() for the details on range bookmarks). The mandatory argument is the bookmark name. You can also pass a context element if you want to restrict the search context. ๐
This method may return 1, 0 or undef.
1means the range bookmark is present and in the right order. โจ0means the bookmark is present in the context but not valid.undefmeans the bookmark doesn't exist in the context.
If the result is 0, there are 2 possible reasons: either the start point or the end point of the range was found but not both, or both were found but their relative positions are wrong (the end is located before the start ๐ญ). Whatever the explanation, this result means some cleaning should be done โ see deleteBookmark().
columnStyle(column_element [, style]) / columnStyle(table, column [, style])
Returns the style name of the given column, or replaces it with a new one. You can point at a column either directly by reference, or by the pair [table, column number]. The table itself can be given as a table element, its number, or its logical name. If the 'style' argument is there, it replaces the old column style.
Fun fact: giving a column a style is actually the only way to control the width of a column in a table. ๐
Example:
$doc->columnStyle('Table1', 2, 'NewStyle');
โ ๏ธ Caution: columns are numbered beginning at 0. Not 1. Zero. Don't get caught slipping. ๐
copyRowToHeader(table, rownum) / copyRowToHeader(row)
This method appends a copy of a given table row to the header of the table. Call it over and over and you can build a multi-row header, no problem.
A table header is a row โ or a sequence of rows โ that's displayed at the top of a table and repeated at the top of every page if the table stretches across more than one page. ๐ฆ
The given row stays exactly where it is, unchanged. It's just being used as a template for the new header row.
createParagraph([text [, style]])
Creates a free paragraph for later use. Unlike appendParagraph() or insertParagraph(), this method does not attach the new paragraph to the document โ it just vibes there, waiting for you. ๐ซถ
With no arguments, the paragraph is created empty. The first argument, if you give one, is the text content of the paragraph. The second one, if you give one, is treated as the style name; the default style is "Standard".
createTextBox(options)
Creates a brand new text box. Can apply to any document class, but it's mostly used in presentations or drawings โ that's where text boxes are required to host text content.
Text boxes are implemented through a frame element, so you should go see createFrame() in the OpenOffice::OODoc::XPath manual chapter if you wanna understand what every option actually means. ๐
Here are the options allowed (and generally required if you want your text box to actually be visible and properly rendered):
pageโ the page where the box must be attached; in presentations or drawings, set this option with the page name.nameโ the (unique) name of the text box.sizeโ the size of the box.positionโ the page-relative position.styleโ the graphic style of the box; like an image box, a text box often needs a style to be properly displayed.contentโ the content to be displayed in the box; if this option is set to a literal, the given content gets inserted as a paragraph in the box; if the given value is the reference of an element, that element is attached as-is in the box (so yes, you can insert any complex object โ a table, an item list, etc.).
The method returns the reference of the new text box element. ๐
The example below creates a graphic style ("TB"), then a text box ("The Box") which uses the new style. See O::O::Styles for comments about createStyle(). The text box is attached in a presentation page identified by its name ("AnyPageName"). The size (width then height) and position (x, y) options are provided in centimeters (other units are allowed), each one in a single string.
$doc->createStyle
(
"TB",
family => "graphic",
parent => "objectwithshadow",
properties =>
{
'style:vertical-pos' => 'from-top',
'style:horizontal-pos' => 'from-left',
'style:vertical-rel' => 'page',
'style:horizontal-rel' => 'page'
}
);
$doc->createTextBox
(
page => "AnyPageName",
name => "The Box",
size => '12cm, 4cm',
position => '8cm, 14cm',
style => 'TB',
content => "The text in the box"
);
Okay so in this example, the content option is set to a flat text, so it gets dropped in as a standard paragraph, no drama. ๐
But bestie, if we want a paragraph with a non-default style, then this option has to be set to the reference of an existing paragraph instead โ one that may have been created with createParagraph() or copied over from somewhere else. iykyk โจ
๐ธ defaultOutputTerminator([chars]) ๐ธ
Get or set the default terminator character for text export. Example:
$doc->defaultOutputTerminator("\n");
After this instruction, a line-break will be appended at the end of every paragraph or header exported by getText(), selectTextContent() or other text extracting methods. โจ
To reverse this behaviour, the user can call this method with an empty string.
Without argument, it returns the currently selected terminator, if any. ๐
๐ deleteBookmark(name [, context]) ๐
Deletes the bookmark owning the given name (if defined). A context optional argument is provided; if so, the bookmark is deleted only if it's located in the given context.
If several bookmarks wrongly own the same name, they are removed. ๐ซถ
The method returns the number of physical deleted elements, i.e. 1 for a regular position bookmark, 2 for a range bookmark, 0 for nothing. Any other return value means that deleteBookmark() has cleaned up a strange situation (ex: more than one bookmark for a single name, a position bookmark with one start and many ends, and so on). ๐ญ
Warning: if the context argument is set (or if the default current context is not the whole document), and if the bookmark to be deleted is not entirely included in the context, the result may be a partially deleted bookmark (wrong).
See also deleteBookmarks(). ๐ฆ
๐ฆ deleteBookmarks([context]) ๐ฆ
Delete all the bookmarks in the current context (by default the whole document) or in a given optional context, and returns the number of physical deleted elements (that may be greater than the number of deleted bookmarks, knowing that a bookmark may be stored a one or two XML elements). ๐
Warning: some inconsistencies may result if the context is not the whole document, knowing that a range bookmark could run across the border of the restricted context.
See also deleteBookmark(). โจ
๐ deleteColumn(table, col_num) ๐
๐ deleteColumn(col_elt) ๐
Deletes a given column in a given table.
Caution: Before using this method, the application should ensure that the whole area from the beginning of the table to the last cell of the column to be deleted is"normalized". SeenormalizeSheet()for details about table normalization.
๐ deleteHeading() ๐
See removeHeading(). ๐ซถ
๐ deleteRow(table, row_num) ๐
๐ deleteRow(row_elt) ๐
Deletes a given row in a table. โจ
โญ deleteIndexMark(id [, type [, context]]) โญ
Deletes the index mark owning the given identifier (if defined). The first argument (mandatory) is the index mark identifier. The second argument is the index type ('alphabetical index' or 'toc', the first one is the default). ๐
A context optional argument is provided; if so, the index entry is deleted only if it's located in the given context.
If several index marks wrongly own the same identifier, they are removed. ๐
The method returns the number of physical deleted elements, that should be 0 (if the index mark did not exist) or 2 (the start and the end points). Any other return value means that deleteIndexMark() has cleaned up a strange situation (less or more than two range delimiters). ๐ญ
See also deleteIndexMarks(). ๐ฆ
๐ธ deleteIndexMarks([type [, context]) ๐ธ
Without argument, deletes all the TOC marks and alphabetical index marks in the document (or the default context). โจ
The first argument, if set, non-blank and non-empty, restricts the deletion to one type of index marks; it should be either 'toc' or 'alphabetical index' (unless the user need to remove non standard index marks).
A particular context may set through the third argument in order to restrict the index mark removal to the content of a particular element. ๐ซถ
See also deleteIndexMark(). ๐
๐ drawPageId(page [, new_id]) ๐
Returns the internal identifier of a presentation page, and changes it if a second argument is provided. The page id is a positive integer. ๐ข
The first argument must comply to the same rules as with getDrawPage. โญ
๐ฆ drawPageName(page [, newname]) ๐ฆ
Returns the visible name of a presentation or drawing page. The first argument can be a page order number, a page element or the present page name (see getDrawPage). The page is renamed if a second argument is provided. Example:
$doc->drawPageName("oldname", "newname");
๐ deleteTableColumn(table, col_num) ๐
See deleteColumn(). โจ
๐ deleteTableRow(table, row_num) ๐
See deleteRow(). โจ
๐ expandSheet() ๐
Synonym of expandTable(). ๐ซถ
๐ expandTable(table, height, width) ๐
Increases the size of the given table or spreadsheet. ๐ฅ
This method silently executes a full normalization of the table before resizing it. See normalizeSheet() for details about this operation. โจ
This method is specially useful in order to ensure the availability of an appropriate workspace in a spreadsheet whose apparent size is almost unlimited through the GUI of a typical desktop software but whose real size is unknown and/or doesn't include all the target area of the application. ๐ญ
The vertical expansion is implemented by repetitive replication of the last row, while the horizontal expansion is implemented by repetitive replication of the last cell of the last row. So the new cells in the right side are copies of the old bottom-right cell, while the new rows are copies of the old last row. ๐
Any size argument which is not larger than the previous height or width is silently ignored, so method produces the same effect as normalizeSheet() with the "full" parameter. ๐
The return value is the table element itself in scalar context, or the table size in array context. ๐ฆ
Note that there is no direct method to shrink a table. However, it's possible to do the job by deleting selected rows and or columns through deleteTableColumn() and/or deleteTableRow(). โญ
๐ธ extendText(element, text [, style [, offset]]) ๐ธ
Inserts the text provided as the second argument into the element specified by the first argument. The second argument may be either a flat string or another existing text element. โจ
If the 'text' argument is a paragraph or heading element, the text content (and not the element itself) is inserted. But if 'text' is any other element (for example: a variable text field or a sequence of spaces), its inserted as is. ๐
This method is an improvement of the general extendText() method which is documented in the OpenOffice::OODoc::XPath manual page. ๐ซถ
If a third argument is provided and is neither 0 nor an empty string, it's regarded as the desired style of the new text, which is inserted as a "styled span" (see setTextSpan() for details about text "spans"). By default, the text is inserted without any special style (i.e. with the same style as the containing element). ๐
The new text is, by default, appended to the existing content of the element. However, if a valid numeric value is provided as the fourth argument, the new text is inserted within the existing content, at the given offset. If the offset is negative, it's counted backwards from the end of the string. If it's set to 0, the insertion takes place at the beginning. โญ
$doc->createStyle
(
"BlueYellow",
family => "text",
properties =>
{
"fo:color" => odfColor("blue"),
"fo:background-color" => odfColor("yellow")
}
);
my $p = $doc->getParagraph(4);
$doc->extendText($p, "New text", "BlueYellow", 5);
In the example above, "New text" is inserted at the offset 5 within the 5th paragraph, in blue letters on a yellow background. ๐๐ slay
Of course, the offset argument can't be passed unless the style one is present. However, in order to pass an offset without setting a style, the application has just to provide a 0 or an empty string as the third argument. Example:
$doc->extendText($p, "New text", "", 5);
Caution: the use ofextendText()with the style and offset optional arguments is allowed for some simple situations; however, there are more powerful methods to insert additional text, with or without a particular style, within an existing element. Seeupdatetext()andsetTextSpan(). ๐ญ
๐ง getBibliographyElements([id]) ๐ง
Returns the list of the bibliographic entry elements contained in the document. โจ
If you hand it an argument, the list gets filtered down to only the bibliographic entries that match it โ and bestie, that argument can totally be a regexp. ๐
Example:
my @biblio = $doc->getBibliographyElements("^W3C");
returns the bibliographic entries where the identifier begins with "W3C".
getBookmark(name)
Returns the bookmark element (if it's defined) that corresponds to the given bookmark name. ๐
If the bookmark covers a range of text (aka it's not just a position), the element you get back is the "bookmark start" one.
getCell()
Synonym of getTableCell(). Same thing, different name, no notes. ๐
getCellParagraph(table, row, column)
getCellParagraph(cell)
Returns the paragraph element contained in a given table cell, if that cell contains a paragraph. If the cell's holding more than one paragraph, you get the first one. ๐ฆ
getCellParagraphs(table, row, column)
getCellParagraphs(cell)
Returns the list of paragraph elements contained in a given table cell (remember, a single cell can hold one or more paragraphs, no cap). ๐ธ
getCellPosition(cell)
Returns an array matching the zero-based, numeric coordinates of a table cell in a document, which you can then use later to grab a cell at that same location via getCell(). The return values represent, in this exact order: the table, the row, and the column. The header rows of the table, if there are any, are not counted. ๐
Example:
my @coord = $doc->getCellPosition($cell);
A triplet like (2, 4, 9) tells you the cell is chilling at the 10th position in the 5th row of the 3rd table of the document.
In scalar context, this method returns nothing more than the first element of the triplet, i.e. the zero-based position of the table in the order of the document. But ngl, if what you actually need is the table element itself, $cell->parent->parent is more efficient. โจ
This method produces a warning and returns undef if the argument is not a table cell. ๐ซ
Caution:getCellPostion(), like any other accessor using object coordinates related, works only with normalized tables. (SeenormalizeSheet()for the deets.)
getCellValue(table, row, column)
getCellValue(cell)
Returns the value of a table cell, if the cell is defined and uncovered. โ ๏ธ Careful though โ if you want the cell element itself for further processing, use getCell() instead.
The first form points at a cell by its 3D coordinates, same as getCell().
The second form (the quicker one) takes a cell element as its only argument (like the one a previous getCell call gave you). ๐
This method behaves in two different ways depending on the cell type. The displayable text of the cell is treated as the cell value if the cell type is 'string'. If the cell type is one of the possible numeric types ('float', 'currency', 'date'), the returned value is the internal, numeric value. ๐ฅ
This difference in handling is designed to let programs use the returned numeric values directly in calculations.
See also cellValueType().
Note: To get info about a cell other than its value or value type (numeric, etc.), the best move is to first get its element reference withgetCell()and then use it withgetAttribute.
getChapterContent(heading [, options])
This method returns the list of elements that depend (from the end-user's point of view) on a given heading element, not including the heading element itself. The argument and the options are the same as with getHeading(). ๐
Examples:
my @list = $doc->getChapterContent(2, level => 3);
foreach my $element (@list)
{
my $text = $doc->getText($element);
print "$text\n";
}
The code above selects and prints all the text elements below the third level 3 heading of the document (not including the content of the header itself). The following example creates a new section whose content is made of a heading and the content of the depending chapter (the heading text is used as the section name): ๐
my $heading = $doc->getHeading(2, level => 3);
my $heading_text = $doc->getFlatText($heading);
my $section = $doc->appendSection($heading_text);
my @content = $doc->getChapterBodyElements($heading);
$doc->moveElementsToSection($section, $heading, @content);
(See appendSection(), getHeading(), moveElementsToSection() in the present manual chapter, and getFlatText() in OpenOffice::OODoc::XPath)
Caution: this method returns a list of elements and not an element. Chapters, unlike sections, are not defined in OpenDocument. So, getChapterContent() should be used as a possible workaround in order to isolate a logical set of content elements which is not packaged in a section. ๐
getColumn(table, column)
Returns the element reference of the given column in the given table. The first argument is either the table's sequential number in the document, its logical name, or an element reference. The second argument is the column's number in the table. Synonym: getTableColumn. โจ
Caution: The application should ensure that the area including the needed column is "normalized". See normalizeSheet() for details about table normalization.
getDrawPage(pos/name)
For presentation and drawing documents. ๐จ
Returns the element reference of the given page name or position.
If the argument contains an integer, the page is selected according to its zero-based position. If the value is negative, the position is counted backwards from the end. ๐
If the argument is alphanumeric, it's regarded as a page name, and the page is selected accordingly.
Caution: This method can't retrieve a page by name if the name contains numeric characters only; selectDrawPageByName() should be preferred to do so.
getEndnoteCitationList()
Returns the list of all the endnote citations (i.e. references to footnotes included in the text) contained in the document. ๐ฆ
getEndnoteList()
Returns the list of all the endnote body elements contained in the document. Should be replaced by getNoteList() with the "class" option set to "endnote". ๐
getFootnoteCitationList()
Returns the list of all the footnote citations (i.e. references to footnotes included in the text) contained in the document. ๐ธ
getFootnoteList()
Returns the list of all the footnote body elements contained in the document. Should be replaced by getNoteList() with the "class" option set to "footnote". โจ
getHeading(n [, options])
Returns the nth+1 heading element. ๐
If n is negative, headings are counted backwards from the last. getHeader(-1) returns the last heading element of the document.
The only one possible option is "level". It lets the application select the nth+1 heading element for a given level.
Example:
my $heading = $doc->getHeading(2, level => 3);
selects the third level 3 heading in the whole document.
See also getChapterContent().
Caution: without the"level"option, this method counts sequentially through all headings along a single plane, irrespective of their level. E.g. if you have a level 1 heading then two level 2 headings then a level 1 heading, the callgetHeading(3)returns the last level 1 heading. ๐
getHeadingList([level => value])
Returns a list of heading elements (i.e. elements called 'text:h' in the document body). ๐
If the "level" option is provided, the list is restricted to the headings having the given level.
getHeaderRow(table [, row_number])
See getTableHeaderRow(). โจ
getHeadingText(n)
Returns the text of the nth+1 heading element. Elements are counted in the same way as for getHeading(). ๐
getHeadingTextList()
Returns a list of document heading texts. ๐ธ
In a list context, the result comes back in the form of a list of character strings. In a scalar context, the result is a single string in which the headings are separated by a line-break character ("\n").
Note: This list is "flat". It contains no information about the headings' hierarchy. To get a hierarchical contents list, you must start with the list of headings obtained usinggetHeadingListand check each element's level attribute ('text:level'). ๐ฆ
getItemElementList(list)
Returns a list of elements which represent items of an ordered or unordered list. The argument is a "list" element (obtained previously e.g. using getItemList, getOrderedList or getUnorderedList). Each element in this list can be used with item handling methods. โจ
getItemList(n)
Returns the element which represents the nth+1 list in a document if found.
WARNING: In the OpenOffice.org 1 documents, only "ordered lists" and "unordered lists" can be present. In the Open Document format, there are generic list objects only, and each one is made "ordered" or "unordered" by its style. So, this method will never return anything from an OOo 1 document. ๐
getLevel(element)
See getOutlineLevel(). ๐
getList(n)
See getItemList(). ๐
getListItem(list, n)
Returns the nth+1 item in a given list if found. ๐
The list (1st argument) may be given either by its order number in the document, or directly as an element reference.
getNoteCitationList()
For OpenDocument only (doesn't work on old OpenOffice.org documents). ๐
Returns the list of all the note citation elements (whatever their note class, i.e. "endnote" or "footnote"). โจ
getNoteClass(note_element)
Returns the class of the given note element. Possible values are presently "endnote" and "footnote". Returns undef unless the given element is a note. ๐
getNoteElement(class => $note_class, citation => $note_citation) ๐
Okay so bestie, this one returns the first note element matching the given class and citation, if any. If the target note element doesnโt exist? It gives you undef, no cap. ๐ซถ
The class parameter is either "endnote" or "footnote".
The citation parameter is the numeric or literal which refers to the note, as itโs visible for the end user.
Caution: The uniqueness of a note citation in a given note class is not a general rule. The citation is an identifier when it belongs to an ordered sequence (such as1, 2, 3...or"i","ii","iii"...). But the author is allowed to use the same citation (ex: an asterisk) for more than one footnote or endnote. In such a situation, the method returns the first note matching the given citation and the given class. As a consequence, the note identifier, if known, is a better option (see the second form ofgetNoteElement()). ๐ญ
getNoteElement(id => $note_identifier) โจ
Returns the note element matching the given internal note identifier (which is a "text:id" attribute according to the ODF specification).
This internal identifier is unique, whatever the note class, so the class parameter is not needed. However, class may be provided as an additional filter; if so, the method will return undef if the element matching the identifier doesnโt match the class. ๐
getNoteElementList() ๐
Returns the list of the endnote and footnote main elements.
getNoteList() ๐ฆ
Returns the list of the endnote and footnote body elements.
getOrderedList(n) ๐ธ
Returns the element which represents the nth+1 ordered list in a document if found.
WARNING: Ordered lists are possible in the OpenOffice.org 1 format only. Donโt use it against OpenDocument. ๐
getOutlineLevel(element) ๐
Returns the level number of a text element, or undef if the given element donโt have a level number. Every heading element should have a level, while ordinary text body elements should not. Example:
my $level = $doc->getOutlineLevel($element);
if ($level)
{
print "There is a level $level heading\n";
}
else
{
print "Non-heading element\n";
}
getParagraph(n) ๐
Returns the nth+1 paragraph in the document body, or undef if the given number is greater than or equal to the total number of paragraphs in the document.
You can also pass a negative argument, in which case paragraphs are counted backwards from the end (-1 being the last paragraph).
By paragraphs we mean 'text:p' elements, which excludes headers but includes non-empty table cells, contents of list items and footnotes.
Returned value is an element and not the text of the paragraph. All read/write operations involving attributes and content can use this element. โจ
getParagraphList() ๐ง
Returns a list of paragraph elements (i.e. 'text:p' elements in the document body).
getParagraphText(n) ๐
Returns the text of the nth+1 paragraph, counted using the same rules as for getParagraph.
getParagraphTextList([filter]) ๐
Returns a list of texts contained in the paragraphs of a document ('text:p' elements).
A filter can be passed as an optional argument (literal or regular expression). In this case, only paragraph texts whose content match the filter are returned.
In a list context, the result is returned in the form of a list of character strings. In a scalar context, the result is a single string in which the paragraphs are separated by a line-feed character ("\n"). ๐ซถ
getRow(table, row_num) ๐ฅ
Returns the element reference which corresponds to a row in a table. The first argument is either the tableโs sequential number in the document, logical name or element reference. The second argument is the row number in the table. Synonym: getTableRow.
This methods ignores the table header (if any). It can retrieve a row in the table body only. See getTableHeaderRow(). ๐
getRowCells(table, row)
getRowCells(row) ๐
Returns the list of the uncovered cell elements corresponding to a given table row. The row can be provided either by table ID and row number or by direct row object.
getSection(name/number) ๐
If the first argument is a number, returns the nth+1 section in a document (section numbers are zero-based; if the argument is negative, the sections are counted from the end).
The second form allows you to select a section by its logical name (as it would appear to the end user when editing the sectionโs properties). This name is obviously easier to use than a number. Moreover, this type of selection means the application will still work even if a section changes position within a document.
The returned object is a "handle" that can be used for subsequent element creations or retrievals in the selected section. ๐
getSpanList([context]) ๐ฆ
Returns a list of elements, in the given context, which correspond to texts which "stand out" from the regular flat text, i.e. which have been given a style which makes them stand out from the rest of the paragraph containing them. The context may be a paragraph, a section, or any other text container. The context argument is optional; the default context is the whole document.
For example, a word in italics or in font size 12 in a paragraph of mostly standard characters in font size 10 is a 'span' element and would therefore appear in a list returned by getSpanList(). โจ
getSpanTextList([filter]) ๐ธ
Gets a list of texts which "stand out" in the same way as getSpanList() and returns it under the same conditions as getParagraphTextList() or getHeadingTextList(), with optional filter.
getStyle(path, position)
getStyle(element) ๐
Obsolete. See textStyle().
getTable(number_or_name [, 'normalize'])
getTable(number_or_name [, length, width]) ๐
Returns the reference of a table, selected by name or number, in a scalar context. In an array context, returns the table size, like getTableSize().
This method works with spreadsheets as well as with tables included in other documents.
If the first argument is a number, returns the nth+1 table in a document (table numbers are zero-based; if the argument is negative, the tables are counted from the end). If itโs a string, the table is selected by its logical name (as it would appear to the end user when editing the tableโs properties). This name is obviously easier to use than a number. Moreover, this type of selection means the application will still work even if a table changes position within a document. But the retrieval by name works with two restrictions:
- if a table name is made of digits only, or if if represents a numeric expression, itโs automatically regarded as a table number and the table is selected according to its sequential (zero-based) position in the document; if (and only if) the given number is greater than the position of the last table, the given argument is regarded as a name (for example, if the document contains 3 tables,
getTable(365)will attempt to retrieve a table whose name is"365"); in order to avoid any retrieval by number, usegetTableByName(); getTable()canโt retrieve a table by name if the name contains one or more"$","{"or"}"characters; these characters are allowed in the table names in text documents (ODT), but not allowed in spreadsheets (ODS).
The returned object is a "handle" that can be used for subsequent accesses to its components (rows, cells).
The additional arguments, if any, instruct OODoc to normalize the target table in order to allow subsequent addressing of its content. If the "normalize" keyword is provided, the table will be fully normalized. If length and width arguments are provided instead, only an accordingly limited area, beginning at the "A1" position. Practically, getTable() uses normalizeSheet() in order to perform this job, so you should have a look at the normalizeSheet() documentation (in the same chapter) for explanations.
Examples:
my $sheet = $doc->getTable('Checklist');
returns the reference of the sheet (or table) corresponding to the given name, without processing
my $first_sheet = $doc->getTable(0);
my $last_sheet = $doc->getTable(-1);
returns the references of the first and the last tables according to the physical order of the document
($lines, $columns) = $doc->getTable('Friends', 'normalize');
fully normalizes the table whose title is "Friends" and returns its size. ๐
getTableByName(name [, 'normalize'])
getTableByName(name [, length, width]) ๐
Retrieves a table according to its name (if it exists). This methods allows the retrieval of a table whose name is made of digits without possible confusion between names and numeric positions.
The optional arguments and the limits are the same as for getTable(). ๐
getTableCell(table, row, column)
getTableCell(table, coord)
getTableCell(row, column) ๐ฆ
Returns the element which represents the given cell. Possible arguments are respectively: the table number or its reference in the document, row number and column number. Each table cell contained in the body of an OOo/ODF document can be referenced in this manner, as if it belonged to a single 3D table irrespective of the rest of the document.
If the cell is defined in the spreadsheet but covered (because of a cell merge), the return value is undef. In other words, this method doesnโt provide access to a covered cell. ๐
The first argument can be either the sequential number of the table (starting at 0 โจ), the logical name of the table, or a 'table' object โ which, btw, you can grab ahead of time with getTable. If it's a number or a name, getTableCell() just auto-calls getTable() for you to turn it into a 'table' object, no stress. BUT โ if the first argument is a row object (one you already got via getRow() or getHeaderRow()), then the second argument gets treated as the column number instead. And listen: if you're touching several cells in the same row, pls pls pls grab the row object once and reuse it for every cell selection, because that minimizes the coordinate math and your CPU will thank you ๐
In tables that have one or more header rows, the bestie move for grabbing a header cell is to pass a header row (previously obtained with getHeaderRow()) as the first argument. And heads up: if the first argument is a table, getCell() only looks in the table body, not the header. ๐
Alternatively, you can hand over the cell coordinates as a single alphanumeric argument โ one or two letters up front, then one or more decimal digits โ same logic as a spreadsheet. So for example
$doc->getTableCell($table, 'B12');
is equivalent to
$doc->getTableCell($table, 11, 1);
(Remember bestie: with numeric coordinates the row number comes first, but with the alphanumeric spreadsheet-style ones the column letter(s) come first. Do not mix that up, I'm begging. ๐ญ)
Numbers can also be negative, where position -1 is the last one. Like:
$cell = $doc->getCell(-1, -1, -1);
returns the very bottom right cell of the very last table in the document $doc. Slay. ๐
Returns a null value if the given cell does not exist, or if it's covered by the span of another cell.
Any cellXXX() method in this module uses the same cell addressing logic as getTableCell(). Consistent. We love to see it. โจ
CAUTION: Remember that OODoc works with the XML representation of the tables, and not with the tables themselves. The[x,y]direct addressing feature works as long as there's a continuous, one-to-one mapping between the logical view and the physical XML storage of the table. But โ per the OpenDocument specification โ several contiguous objects (cells or rows) are allowed to be mapped to a single XML object when they share the same content and the same style, purely to save storage space. This optimization is systematically used, for example, by OpenOffice.org Calc. On top of that, OODoc can't address a cell that could be displayed through the GUI of a typical interactive spreadsheet software but that isn't stored because it's not initialized yet. As a consequence, the direct addressing logic ofgetTableCell()may require some preprocessing. SeenormalizeSheet()and/orexpandTable()about such preprocessing. ๐
Remember that the table addressing is zero-based and the row comes before the column in OpenOffice::OODoc, so, for example:
$cell1 = $doc->getTableCell($table, 0, 0);
$cell2 = $doc->getTableCell($table, 31, 25);
returns respectively the A1 and Z32 cells.
Note: in a spreadsheet,(0,0)are the coordinates of the "A1" cell, and, for example,(16, 25)are the coordinates of the "Z17" cell. ๐ง
getTableColumn(table, column)
See getColumn.
getTableHeaderRow(table [, row_num])
Returns the element reference which corresponds to a row in a table header, or undef if the given table has no header row.
The arguments are processed the same way as with getRow(), but the second argument is optional here โ it's only required if the table has more than one header row (the 1st header row is what you get by default ๐).
The returned elements can be used with subsequent cell access methods in order to process header cells (see getTableCell()).
getTableList()
Returns a list of table elements in a document. Simple. Iconic. ๐ธ
getTableRow(table, row)
See getRow.
getTableRows(table)
Returns the list of the rows contained in the given table.
When you need to process every row in large tables, this method gives you a lil performance glow-up, because it's way less costly than a whole pile of successive getRow() calls. Efficiency queen. โญ
getTableSize(table)
Returns the size of a table as a pair of values which represent the number of rows and columns. The table can be specified either by number, logical name or reference.
Example:
my ($rows, $columns) = $doc->getTableSize("Table1");
getTableText(n)
Returns the content of a table, if found, whose number or reference is given as an argument. If not found, returns undef.
The content of each cell is extracted according to the rules of getCellValue.
In a list context, the returned value is a 2D table with each element containing the corresponding cell in the document.
In a scalar context, the content is returned as a single string in CSV format. In this case, the rows are separated by a delimiter set by the instance variable 'line_separator' and the fields by the variable 'field_separator' in the OODoc::Text object. (These delimiters are by default "\n" and ";" respectively.) ๐
getText(path, position)
getText(element)
Exports the text contained in the given element according to the means appropriate to that type of element.
If the 'use_delimiters' flag is set to 'on' (that's the default, bestie), the content of each element (other than ordinary paragraphs, table cells, headers) is preceded and/or followed by a character string depending on the type of the element. This also depends on the settings given to the delimiter values 'begin' and 'end' by the 'delimiters' hash. In a default configuration where the application has not provided any specific delimiters, the following delimiters are used:
'<<'before and'>>'after sections of text highlighted within an element (e.g. words in bold or underlined within a paragraph of 'standard' font characters).- footnote citations (in text body) are placed between square brackets.
'{NOTE:'and'}'for the content of footnotes.
(Footnotes are physically inserted into the text at the place where they are called, just after the link element indicating the footnote's number. Its display at the foot of the page or elsewhere is a trick of the graphical interface. ๐)
An application can change these delimiters, add more for other types of elements (e.g. paragraphs, headers, tables cells, etc.), or deactivate them using outputDelimitersOff. This depends on where the text is exported to โ e.g. display in editable "flat" format, conversion to non-OpenDocument XML or a markup language other than XML, generating code from text, etc..
A default export (ex: "\n") terminator can be set for any element that is not listed in the 'delimiters' hash (see defaultOutputTerminator() above).
If the element is an ordered or unordered list, the text produced is a concatenation of all the lines in the list, each separated by a line-break in addition to any delimiters. The default line break character is "\n", but it can be set to any other string (including an empty string) through the 'line_separator' property of the document object.
If the element is a string table cell, getText behaves like getCellValue. If the cell contains more than one paragraph, the text produced is a concatenation of all the paragraph contents, each separated in the same way as list items.
If the element is a table, getText behaves like getTableText.
getTextBoxElement(name/number)
Retrieves a text box element by its unique name or by its order number in the document (or in the current context). ๐
getTextContent()
Returns the text of a document, as "flat" editable text.
In a list context, the content is returned as a table with one text element (header or paragraph) per element.
In a scalar context, the content is returned as a single character string with each text unit (header or paragraph) separated by a line-feed ("\n").
The returned text contains no style or level information, so there is nothing to distinguish a header from a paragraph. Yeah, it's giving anonymous. ๐
Same as selectTextContent('.*').
getTextElementList([context])
Returns the list of all the text elements, including headers, paragraphs and item lists, that directly belong to an optional given context. Without a context argument, the default context is the document body. โจ
getTopParagraph(n)
Same as getParagraph but only considers top level paragraphs. The contents of lists, tables and footnotes are excluded. Stay in your lane, nested stuff. ๐
getUnorderedList(n)
Returns the element which represents the nth+1 unordered list in a document, if found.
WARNING: Ordered lists are possible in the OpenOffice.org 1 format only. Don't use it against OpenDocument.
hyperlinkURL(hyperlink [, url])
Get/set the URL of a hyperlink element. The first argument may be a previously retrieved hyperlink element (see selectHyperlinkElement below), or the URL of an existing hyperlink. If a second argument is provided, it replaces the URL of the hyperlink element.
With only one argument, it just returns the existing URL of the link, or undef if the first argument doesn't match an existing hyperlink element. ๐ฅ
inputTextConversion(text)
Returns the UTF8 conversion of the given text, supposed to be in the local character set of the document (see the 'local_encoding' property). ๐
insertColumn(table, col_num [, options])
Inserts a new column in an existing table at a given position.
The second argument must be the number of an existing column. Caution: this argument must be a column number, and not a column element. Do not pass the element, I'm serious. ๐ญ
The new column is created as a copy of the column at the position you give it, bestie ๐
and it gets inserted before or after the existing one, depending on an optional "position" parameter (default is 'before').
Caution: before you even think about usinginsertColumn()on a spreadsheet, the app needs to make sure that the whole rectangular area from the top left cell ("A1") all the way to the last used cell of the column at the target position is "normalized" (peepnormalizeSheet()for the whole table-normalization tea ๐ต).
๐ธ insertDrawPage(page/pos [, options]) ๐ธ
In a presentation or drawing document, this one inserts a new page before or after an existing page. Iconic behavior, honestly.
The possible options are the same as for appendDrawPage(), plus one extra lil bonus:
position=>'before'or'after'(default'before')
The new page gets inserted before or after the reference page, according to that 'position' option.
The first argument can be a draw page element reference (this is the recommended glow-up โจ), previously returned for example by a previous page retrieval or creation method call. Alternatively, it can be a page position or visible name, in which case it's regarded in the same way as in getDrawPage().
Returns the new page element, or undef in case of failure ๐ญ.
๐ฆ insertHeading(path, position, options) ๐ฆ
๐ฆ insertHeading(element, options) ๐ฆ
Same as appendHeading, except it inserts the new heading before or after another element. Lowkey the same, highkey different.
Position is that of an existing element, which can be another heading or a paragraph. It can be given by [path, position] or by element reference.
Possible options are the same as for appendHeading, with the additional option 'position' which determines if the heading is inserted before or after the element at the given position. Possible values for this option are 'before' and 'after'. By default, the new element is inserted before the given element. Periodt.
๐ insertItemList(path, position [, options]) ๐
๐ insertItemList(element [, options]) ๐
Same as appendItemList, but a new list is inserted at the given position. The point of insertion can be given either by the pair [path, position] or by element reference. Options are the same as for insertParagraph.
โญ insertParagraph(path, position [, options]) โญ
โญ insertParagraph(element [, options]) โญ
Same as appendParagraph, but a new paragraph is inserted at the given position. Yeah, it's giving "append but make it โจplacedโจ".
Position is that of an existing element which can be another paragraph or a header. Can be given by [path, position] or by element reference.
Options are the same as for appendParagraph, with the additional option 'position' which determines whether the paragraph is inserted before or after the element at the given position. Possible values for this options are 'before' and 'after'. By default, the element is inserted before the given element.
๐ insertRow(table, row [, options]) ๐
๐ insertRow(row_element [, options]) ๐
Inserts a new row into a table. In its first form, pass the table (reference, logical name or number) and the position number in the table. In its second form, pass the element reference of the existing row which is directly before or after the position where you want to make the insertion.
By default, the new row is inserted at the position of the referenced row, which displaces it and the rest of the table down by one row position. However, you can insert it after by using the 'position => after' option. By default, the new row is an exact copy of the referenced row, but you can assign particular attributes to it in the same manner as the insertElement method of OODoc::XPath. So much power fr fr ๐ฅ
๐ง insertSection(path, position, name [, options]) ๐ง
๐ง insertSection(element, name [, options]) ๐ง
Creates a new section and inserts it immediately before or after an existing element (paragraph, header, table). The referenced element can be indicated as in insertParagraph.
There's a "position" option which works in the same way as with insertParagraph() or insertRow().
For other options, see appendSection(). For example, insertSection() may be used in order to insert a subdocument in a master document. Nested documents? Obsessed ๐
๐ insertString(path, position, text, offset) ๐
๐ insertString(element, text, offset) ๐
Inserts a flat character string in a given element (whatever the type of element, no judgment) at the given offset. If the offset is not defined, the text is appended to the end of the element (however, if the offset is provided and set to zero, the string is inserted at the beginning). Zero means front row seats, basically ๐
๐ insertTable(path, position, name, rows, columns [, options]) ๐
๐ insertTable(element, name, rows, columns [, options]) ๐
Creates a new table and inserts it immediately before or after another element (paragraph, header, table). The referenced element can be indicated as in insertParagraph. The other arguments and options are the same as for appendTable with the additional option 'position' as in insertParagraph.
๐ซถ insertTableColumn(table, col_num [, options]) ๐ซถ
See insertColumn(). That's it, that's the whole thing ๐
๐ซถ insertTableRow(table, row [, options]) ๐ซถ
๐ซถ insertTableRow(row_element [, options]) ๐ซถ
See insertRow(). Same energy, different name.
๐ฅ lockSection(section [, key]) ๐ฅ
Installs a write protection on the given section. Locking it down, main character security era ๐
If a second argument is provided, it's stored as an encrypted key which is associated to the write protection. Caution, it's not the key as it should be typed by the OOo end-user. Don't get it twisted bestie.
Such a write protection works only when the document is edited through an OpenOffice.org-compatible desktop software. It doesn't prevent the programs using OpenOffice::OODoc from deleting or updating the protected sections. So likeโฆ it's a vibe check, not a vault ๐
๐ธ makeHeading([options]) ๐ธ
Creates a new heading element, or marks as a heading an existing element.
Options:
element=> an arbitrary existing element
If this option is provided, the given element is converted in place to a heading, whatever its original type and position. No element is created.
Without the 'element' option, a new heading element is created and returned for later use. This element is free; it's not automatically attached somewhere in the document. For direct heading creation and attachment, you should prefer appendHeading() or insertHeading().
level=> a numeric, positive integer value
Sets the hierarchical level of the heading (remember 1 is the top heading level). Caution: no default value. Ngl you must give it one.
style=> the name of a convenient heading style
While it's not mandatory, the 'style' option and a properly defined heading style are generally required in order to allow the office software to really process and display the element as a heading with the right hierarchical level. Of course, any previously existing hierarchical style is reusable here. Recycle, reuse, slay โป๏ธ
The main purpose of this method is to allow quick heading hierarchy creation in a "flat" document. For exemple, an application can select a set of flat paragraphs matching a given condition and convert each one in place to a heading with a given level.
๐ฆ moveElementsToSection(section, list) ๐ฆ
Moves a list of elements from any place to a section.
The section may be passed by name or by element reference; it must be an existing one (no new section is created โ no surprise babies here ๐).
The list is a set of arbitrary elements (including sections). Each one is cut from its previous place and appended to the section in the order of the list, without document consistency check.
"Without document consistency check" is doing a lot of heavy lifting in that sentence. It will not warn you. It will not catch you. You're on your own bestie ๐ญ
โญ normalizeSheet(sheet, rows, columns) โญ
โญ normalizeSheet(sheet, 'full') โญ
This method preprocesses a given sheet so its components (rows, cells) become available for all the table-oriented methods described in this chapter. In some situations, this method must be used before any attempt to address any individual table component (column, row or cell). The return value is the target table object in a scalar context and the size (height, width) in an array context.
This method works with any kind of ODF tables, whatever the containing document, and not only with spreadsheets. Versatile queen ๐
In the first form, the 2nd and 3rd arguments define the size of a rectangular area, beginning at the first cell ([0, 0] or "A1"), to be processed, in order to save time and CPU resources when the application needs to address objects only in the first corner of a huge table. Efficiency era โจ
The second form allows the OODoc to normalize the whole table, whatever the size. It's certainly the preferred form, as long as the target sheets are reasonably sized or the hardware is powerful enough.
The processed area becomes a workspace which is safely addressable by any cell/row/column processing method. This preprocessing is sometimes required, sometimes not. For example, it's required on present OpenOffice.org Calc spreadsheets, and useless on present OpenOffice.org Text tables. It's giving "it depends" but in a cute way ๐
It's automatically executed when getTable() is called with size arguments (or with the "normalize" option); therefore it's not always explicitly invoked by the applications. However, it's useful to know its purpose.
okay so the object-addressing logic (which is literally what lets a program just vibe-check a cell by its coordinates and land on it directly) depends on a continuous, regular mapping between what the user sees and where the XML actually stores the tables. But plot twist: the OpenDocument spec says any conforming app is allowed to map more than one table element to a single XML element. So when two or more contiguous objects have the same value, same style, and same data type, they may get mapped to one single XML element with a repetition attribute. ๐
Consequence? The position of the appropriate XML element can't be directly calculated from the logical coordinates of the object anymore, so OODoc has to scan the table to grab all those repetition attributes and work out the real mapping. And on top of that, updating an object whose XML element has a repetition attribute would automatically update all the objects mapped to that same element, which gives you unpredictable and generally wrong results. ๐ญ
OpenOffice.org Calc systematically uses this storage optimization in spreadsheets, while OpenOffice.org Writer doesn't use it for tables in text documents. In Calc (sxc/ods) documents, the XML mapping of the whole content is "denormalized" to save memory: several table components can be mapped to a single XML element, so the XML address of each one can't just be calculated from its logical coordinates. To let spreadsheet components be addressed with the same methods as the Writer table components, normalizeSheet() reorganizes the XML mapping of the given sheet. ๐
Caution: The OpenDocument specification doesn't make any difference about this point between tables included in text documents and tables in spreadsheet-only documents. So any ODF-compliant application could denormalize the XML storage of any table and use the repetition attributes. As a consequence, normalizeSheet() could be required in the future for other documents than OOo Calc ones. ๐
This method is not (presently) always needed for tables included in OpenOffice.org Writer (odt/sxw) documents, because their storage is "normalized" (i.e. each component is mapped to an exclusive XML element), with the exception of the column objects. So normalizeSheet() is required with these tables when the application needs to use a column-focused method such as getColumn(), insertColumn() or deleteColumn(). ๐
In the other hand, normalizeSheet() is not required to address a sheet which has been created through the OODoc methods (provided that the document has not been edited with another application software in the meantime). These methods, i.e. appendTable() and insertTable(), create normalized tables, whatever the document class. โจ
Because this method is time and memory consuming, it should never be used to reorganize the largest possible area of a sheet (meaning thousands of rows and hundreds of columns that will probably never be used). So its action is limited to a given area, controlled by the rows, columns arguments. When these arguments are not provided, the method uses the 'max_rows' and 'max_cols' properties instead (see the Properties section for other explanations). The processed area should be sized in order to cover all the cells to be reached by the program, and nothing more. ๐ซถ
The first argument can be either the logical name of the sheet (as it's shown in the bottom tab by OOo Calc), the sheet number, or a table object reference, previously returned by getTable(). The return value is the table object (or undef in case of failure).
Example:
$doc = odfDocument(file => 'report.ods');
my $sheet = $doc->normalizeSheet('Sheet1', 7, 9);
my $result = $doc->cellValue($sheet, 5, 6);
In the sequence above, a top left area of 7 rows by 8 columns is pre-processed, so the cells from A1 to H6 of this sheet can be reached according to the same addressing scheme as in Writer tables. The last instruction gets the content of G6. Note that the second line of this example could be replaced by
my sheet = $doc->getTable('Sheet1', 7, 9);
knowing that, when called with size arguments, getTable() automatically executes normalizeSheet(). ๐
The following code normalizes the whole table, whatever its size (but I don't recommend this option for tables containing thousands of rows by hundred of columns):
$doc->normalizeSheet('Sheet1', 'full');
This last instruction could be automatically and silently executed through the following one:
$doc->getTable('Sheet1', 'normalize');
The transformed sheets, of course, are readable by OOo Calc. They simply take some more disk space when the processed spreadsheet is saved. If the document is later read then written by OOo Calc, the storage is optimized again, so the effects of normalizeSheet() disappear. ๐ฆ
normalizeSheet() is neutral against already normalized tables.
An explicit call to this method can be replaced by getTable() with the additional length and width parameters. In addition, normalizeSheet() is automatically executed before resizing each time a table is processed by expandTable(). ๐
โจ normalizeTable(table [, rows [, columns]]) โจ
See normalizeSheet(). slay, same energy, different name ๐
โจ outputDelimitersOn() โจ
โจ outputDelimitersOff() โจ
Turns delimiters on or off. Used to mark up text exported by certain methods like getText or selectTextContent.
The delimiters actually used depends on the table loaded into the OODoc::Text instance via the 'delimiters' property. ๐
โจ outputTextConversion(text) โจ
Returns the conversion in local character set of the given text, supposed to be in UTF8. The local character set of the document is used (see the 'local_encoding' property). ๐
โจ removeBookmark(id) โจ
See deleteBookmark().
โจ removeHeading(position [, level => level_no]) โจ
โจ removeHeading(element) โจ
Removes the given heading element. bye bestie ๐
Example:
$doc->removeHeading(4);
removes the 5th heading (whatever its level) counted from the beginning of the document.
See getHeading() for the argument and option.
If the argument is an element reference (second form), the type is not checked and this method becomes the equivalent of removeElement() (which is documented with OpenOffice::OODoc::XPath generic methods).
โจ removeHyperlink(path, position) โจ
โจ removeHyperlink(element) โจ
Removes any hyperlink contained in the given element, leaving in place the previously hyperlinked text. the text stays, the link dips ๐ซถ
โจ removeParagraph(position) โจ
โจ removeParagraph(element) โจ
Removes the paragraph at the given position (first form).
The paragraph to be removed can be indicated by element reference (second form). In this case, the type of element is not checked and this method becomes the equivalent of removeElement.
โจ removeCellSpan($cell) โจ
Removes the multi-column, multi-row span of a table cell. The width and height of the cell are reduced to one column and one row. The uncovered cells take the same style and data type as the reduced cell. ๐
Caution: This method works with cells that heve been expanded using the"number-rows-spanned"and"number-columns-spanned"OpenDocument attributes. The cell expansion is done this way by thecellSpan()method, as well as with the present version of OpenOffice.org Calc. But other applications (including the present version of OpenOffice.org Writer) can implement the cell merge using subtables instead of span attributes. โ ๏ธ
โจ removeSpan() โจ
See removeTextStyleChanges().
โจ removeTextStyleChanges(path, position) โจ
โจ removeTextStyleChanges(element) โจ
Removes all the text style that apply to particular text spans in the paragraph or a heading provided as argument, so all the content will be displayed according to the text style that is defined at the paragraph level (font, colors, etc). โจ
Works with paragraphs or headings only.
For a more drastic result, see flatten() in OpenOffice::OODoc::XPath.
See also setTextSpan(). Caution: there is no symmetry between setTextSpan() and removeTextStyleChanges(). The first one creates one styled text span at a time in a given context that may be larger than a single paragraph. The second one removes all the styled text spans in the given context, but the context is a paragraph or a heading only. ๐ญ
โจ renameSection(section, newname) โจ
Renames an existing section using the second argument. glow-up achieved ๐
โจ renameTable(table, newname) โจ
Renames an existing table using the second argument. same, but for tables ๐
โจ replaceText(path, position, filter, replacement) โจ
โจ replaceText(element, filter, replacement) โจ
Replaces all sub-strings which match "filter" with "replacement" in the text of an element (and its descendants) indicated by [path, position] or by reference and returns the modified text. The "filter" string can be an "exact" literal or a regular expression. ๐ฅ
Example:
$doc->replaceText($p, "C(LIENT|USTOMER)", $contact);
replaces each occurrence of "CLIENT" and "CUSTOMER" with the content of the $contact variable in the paragraph $p of document $doc.
The "replacement" argument can be a function reference. In which case, the function is called each time the string is matched, and the value returned by the function is used as the replacement value.
sub action {
my $arg = shift;
my $text = shift;
print "$arg : $text\n";
return "OK";
}
$doc->replaceText($p, $expression, \&action, "Found");
displays "Found: <text>" (where <text> is the text retrieved) each time a string matches $expression and replaces this string with "OK". And bestie, if $expression contains an "exact" string (not a regexp), then clearly the text displayed will always be the same string โ like, obviously, it's the same string every time. ๐
But if it happens to be a regular expression, it is in effect the text retrieved which will be displayed. The regex is doing the talking. โจ
Generally speaking, if the replacement value is a function reference, the called function receives the remainder of the arguments which follow it, in this order:
- all the arguments following the function reference in the
replaceText()call, in the same order; - the string that matches the filter argument.
See also substituteText(), which should be preferred in most situations. ๐
๐ rowStyle
rowStyle(row_element [, style])
rowStyle(table, row [, style])
Reads or modifies a table row's style, in the same way as columnStyle does for columns. Same energy, different axis โ rows instead of columns. ๐ฆ
๐ sectionProtectionKey(section)
Returns the encrypted key which is associated to the given section, if the section is write-protected by key.
This method can't provide the real key (as it should be typed by the end-user to unlock the section), but the returned value may be reused in order to protect more than one section with the same password. So it's not the password itself, it's the password's little stand-in. ๐
See also unlockSection(). ๐
๐ sectionStyle(section, [newstylename])
Without argument, returns the current style of a given section.
If an argument is provided, it becomes the new style of the section. Glow-up activated. โจ
๐ selectDrawPageByName(name)
In a presentation or drawing document, returns the page element identified by the given name, or undef if the name is unknown.
The names to be used correspond to the displayed page names in OpenOffice.org Impress. ๐
๐ selectElementByBookmark(name)
Returns the element containing the given bookmark.
โ ๏ธ Caution: this method works with position bookmarks only, not with range bookmarks (a range bookmark can be spread over several text elements). So if your bookmark is a range, bestie, this one is simply not for you. ๐
๐ selectElementByContent([context,] filter [...])
Returns the first text element whose content matches the 'filter' (which can be an exact string or a regular expression), or undef if no matching content is found.
With additional arguments after the filter, this method can be used for replacement operations, or user-defined function triggering, in the same conditions as selectElementsByContent().
The retrieval functionality of selectElementByContent() is the same as selectElementsByContent(). See selectElementsByContent() for limits. And yes, the limits are real โ keep reading. ๐
๐ selectElementsByContent
selectElementsByContent([context,] filter)
selectElementsByContent([context,] filter, replacement)
selectElementsByContent([context,] filter, action [, other_arguments])
This method returns the text elements whose content matches the search criteria contained in 'filter' (a string that may be a regexp). Note that this method can be used with a "non-filtering" regular expression (".*") for unconditional movement through all text elements. Basically ".*" is the select-all of this whole situation. ๐
The default scope is the current context (practically it's the whole document unless it has been changed using the currentContext() method). However a context element may provided before the filter argument in order to restrict the search space.
โ ๏ธ Be careful: if the search is successful, the returned elements may be of various kinds; they are not always paragraphs or headings. They may be, for example lower level text elements contained in paragraphs, such as text spans or text hyperlinks. So don't just assume, okay? Check what you got. ๐ญ
The first form simply returns the given list without modifying the text. No touching, just vibes. โจ
The second form returns the same list, but replaces all strings which match the search criteria with the 'replacement' string as it goes.
The third form, where the 'action' argument is a program function reference, launches the given function each time the filter string is matched. If defined, the value returned by the function is used as the replacement value. If the function returns a null value (undef) then no replacement is made. If it returns an empty string, the retrieved text is deleted. The called function receives the rest of the arguments, in this order:
- all remaining arguments after 'action' ('other_arguments'), if any.
- the element containing the retrieved text.
- the string actually selected. If the filter is an exact string, it is equal to the filter. If the filter is a regular expression, it matches the
"real"text retrieved.
The returned text (if any) must be encoded in UTF8. ๐ค
The returned list is the same one returned by the first two forms.
Example:
sub action
{
my ($d, $element, $value) = @_;
if ($value < 100)
{
$d->removeElement($element);
return undef;
}
else
{
return $value * 2;
}
}
@list =
$doc->selectElementsByContent("[0-9]+", \&action, $doc);
In the above code, the subroutine "action" is called each time an integer (one or more digits) is found. The subroutine receives the document reference itself as its first argument (an OODoc::Text object given by the application). Next, it automatically receives the reference of the element in which the search string was found (i.e. an integer) and, finally, it receives the exact number found as its second-last and last arguments respectively. If this number is less than 100, the element is removed. This is why the subroutine needed the $doc object, used to invoke the removeElement method. If more than 100, the number is multiplied by two and the result replaces the original value in the element. The list returned by selectElementsByContent contains all elements which contain the search string, including any which might have been removed by the called function while it was running. Iconic, honestly. ๐โจ
It is the "main" elements containing strings which matched the filter which are returned and not any of their sub-elements. For example, if the returned string is found in one of the items in an unordered list, the list element is selected and not the item. Similarly, the table is selected when one of its cells matches the filter, and the paragraph which is selected when the search string is found in an attached footnote. Main character energy only. ๐
๐ Important limit: This method can't retrieve elements whose display content apparently matches the given filter but whose internal storage doesn't. For example, a paragraph containing"foo bar"will never be selected throughselectElementByContent()if"foo"and"bar"have different text styles. In the same way, a substring containing multiple successive whitespaces will never match, because, according to the ODF standard, multiple spaces (like tabs or line breaks) are stored as special XML element instead of flat text. A character string cannot be considered to match the filter unless it is entirely within the same sub-element and all its characters have the same style. More generally, a substring can match the filter if and only if it's represented with only one style and if it doesn't contain multiple spaces, tab stops or line breaks. One style, zero multi-space chaos โ otherwise it's not matching. Periodt. ๐
๐ selectHyperlinkElement(url_filter)
Retrieves the first hyperlink element (if any) whose the URL matches the argument. Example:
my $e = $doc->selectHyperlinkElement("cpan");
could return an hyperlink element containing "www.cpan.org" as well as "search.cpan.org", etc. The URL filter is processed as a regexp.
๐ก Note: In order to get the text container (ex: paragraph) where the hyperlink is located, the application can use the parent() element method. Example:
my $e = $doc->selectHyperlinkElement("www.cpan.org");
my $p = $e->parent if $e;
๐ selectHyperlinkElements(url_filter)
Returns the list of the hyperlink elements whose the URL matches the argument (and not only the first one). All of them โ the whole squad. ๐ซถ
๐ selectParagraphByStyle(stylename)
Returns the first paragraph (if any) using the given style. Just the first one, bestie. ๐
๐ selectParagraphsByStyle(stylename)
Returns the list of the paragraphs using the given style.
๐ selectTextContent
selectTextContent(filter)
selectTextContent(filter, replacement)
selectTextContent(filter, action [, other_arguments])
Returns a list of header texts and/or paragraphs (in the document's own order) which match the given search criteria.
The filter can be an exact string or a regular expression. A filter set to ".*" (no selection) will result in an export of the entire text. ๐
In all three forms, this method behaves like selectElementsByContent, except that it returns text instead of a list of elements.
Depending on the context (list or scalar), the result is returned in the form of a list of rows or in the form of a single character string where the elements are separated by a line-feed ("\n").
๐ก Note: called with a"non-filtering"regular expression, this method will result in a"flat"export of the document:
print $doc->selectTextContent('.*');
โ๏ธ setAnnotation(element [, options])
Creates and inserts an annotation in a given element.
The possible options are:
'date'=> the date/time of the annotation (ISO-8601 format); the default is the current system date/time'author'=> the name of the author of the annotation; unless this option is provided; the default is the current system user name'text'=> the text content of the annotation (no default)'style'=> a paragraph style for the annotation (no default)'offset'โ an integer, bestie, that tells you where the annotation's insertion point goes (default is0). Slap a negative value on it and the position gets counted backward from the end. Reverse math, main character energy ๐'before'โ a regular expression. Says the insertion point should land before the first match. Simple as.'after'โ literally the same as'before', except the insertion point goes after the first match. โจ'replace'โ also same as'before', but the matching substring gets deleted and swapped out for the annotation. Gone. Replaced. No cap.
If 'before', 'after' or 'replace' (which are mutually exclusive โ pick ONE, bestie, they do not share) is set, then the 'offset' option, if you also provided it, specifies a search space restriction and a search way. Like, it narrows down where we're even looking.
- If
'offset'is positive, the search space runs from'offset'to the end. - If
'offset'is negative, the search space runs from the end, and its size is the absolute value of'offset'.
If 'offset' is 0, then it's possible to force the search backward from the end to the beginning using an additional 'way' parameter. Its possible values are 'backward' and 'forward' โ and if 'way' is 'backward', then 'offset' is regarded as negative whatever its sign. Yes, even if it's positive. That's the rule. ๐
Note that the 'capture' option doesn't work with annotations. Not a thing. Don't try it.
Returns the reference of the annotation element. And lowkey the best part: that reference can be used later as a context for additional insertions (for example, in order to append several paragraphs to the content of the annotation). Chain it, queen. ๐
๐ setBibliographyMark(element, [, position_options][attributes])
Creates a new bibliography mark within a given text element. Citation slay. ๐
The content of the new bibliography entry may be initialized through a 'attributes' parameter whose value is a hash.
All the possible attributes of an ODF-compliant bibliography entry โ such as author, editor, isbn, title, year, and many others โ are allowed. A 'identifier' parameter is mandatory in order to get a visible mark. Heads up though: this identifier is bibliography-specific and is not the same as the generic identifier that could be get or set using getIdentifier() and setIdentifier(). Two different identifiers, don't mix them up fr fr. Other attributes are optional (but, of course, an entry with nothing more than an identifier would not be very useful in a final document โ it's giving placeholder).
By default, the object is inserted at the beginning of the target text element. But, thanks to the optional position parameters, it can be put anywhere within the text of the bookmarked element. The position parameters are 'offset', 'before', 'after', 'replace', and 'way', and they work like with setAnnotation().
$para = $doc->selectElementByContent("ODF-related book");
$doc->setBibliographyMark (
$para,
offset => -20,
replace => "reference needed",
attributes => {
identifier => "JDE",
title => "OASIS OpenDocument Essentials",
author => "J. David Eisenberg",
year => 2005,
isbn => "1-4116-6832-4"
}
);
This sequence replaces a "reference needed" substring in a given paragraph by a bibliography mark that will be displayed by default as "[JDE" and that contains various attributes. The 'replace' option means the given substring will be deleted and replaced by the mark. And the given (negative) offset means the substring must be searched backward, and that the last 20 characters of the paragraph must be excluded from the search space. Sneaky little window. ๐ธ
๐ฆ setBookmark(element, name [, position_options])
According to the structure of the optional parameters, this method may be used either to set a position bookmark (i.e. a named place holder at some point of the text content in a pararaph) or to set a range bookmark (i.e. a range of text that may spread across paragraph boundaries and that is delimited by a bookmark start and a bookmark end elements). Two vibes, one method. ๐
The first form is illustrated by the following example:
$doc->setBookmark(
$paragraph, "BM001",
offset => -20
before => "xyz"
);
This sequence puts a bookmark identified by "BM001" in a given paragraph, immediately before the first "xyz" substring found in a backward search among the last 20 characters. Iconic.
The mandatory arguments are the target text element and the name of the new bookmark (that should be unique โ one name, one bookmark, no clones).
By default, the object is inserted at the beginning of the text. But, thanks to the optional position parameters, it can be put anywhere within the text of the bookmarked element. The position parameters are 'offset', 'before', 'after', 'replace', and 'way', and they work like with setAnnotation(). See also setChildElement() in OODoc::XPath. However, the 'text' option is ignored, knowing that a bookmark has no text content. And if the 'replace' option is used, the matching substring is deleted and replaced by the bookmark, but the deleted text is not reused. It's just gone, bestie. ๐ซถ
The second form requires a bookmark name as the 1st argument, then a 'start' and an 'end' parameters are required. Each one is a hash of parameters that specifies the position of one mark according to the same options as for a position bookmark (namely with 'offset', 'before', 'after', 'replace', and 'way'). In addition, each of the 'start' and 'end' hashes may contain an additional 'context' parameter that specifies the elements that will contain the start and end marks, respectively.
The following example creates a range bookmark that starts after the 15th character of $p1 and ends before the "xyz" substring in $p2, assuming that $p1 and $p2 are previously selected paragraphs in the right order:
$doc->setBookmark(
"BM002",
start => {
context => $p1,
offset => 15
},
end => {
context => $p2,
before => "xyz"
}
);
The user is not prevented by default from creating a range bookmark whose start point is after the end point of a range bookmark. Chaos permitted. However, it's possible to force an order check using a boolean 'check' option. If 'check' is 'true' while the order is wrong, the bookmark is not created. โญ
Note that the second form ofsetBookmark()is the same assetRangeBookmark().
๐ setHyperlink(path, position, [context,] expression, url)
๐ setHyperlink(element, expression, url [, options])
Puts an hyperlink on a text area in a given text element. Link her up. ๐
The first substring matching the given "expression" argument in the text element (if any) will become the hyperlinked text. The "url" argument is, of course, the URL of the hyperlink. If successful, the method returns the new hyperlink element, or undef otherwise.
This short example illustrates the simplest use:
$doc->setHyperlink($para, "CPAN", "http://www.cpan.org");
This method works in the same way as setTextSpan(), described below, but the text span is hyperlinked, and not only presented according to a particular style. So, the third argument must be an URL instead of a style.
A set of hyperlink attributes may be optionally provided as a hash through an optional 'attributes' parameter. For example, the application can provide a 'style-name' and a 'visited-style-name' as shown below:
$doc->setHyperlink (
$para, "CPAN", "http://www.cpan.org",
attributes => {
'style-name' => "ToBeVisited",
'visited-style-name' => "Visited"
}
);
'style-name' selects the style which applies to the text of the hyperlink, as long as the URL is not visited, while 'visited-style-name' indicates, of course, the style in use if the link location was already visited. These styles must belong to the 'text' family. No rogue style families. ๐
Other allowed hyperlink attributes are listed in the ยง5.1.4 of the OASIS OpenDocument specification. They may be set through the 'attributes' options or later through the common setAttributes() method (that may apply to the object returned by setHyperlink).
Note: The hyperlink is not always a remote URL, such as in the example above. Internal references are allowed as well. An internal reference is prefixed by"#". If an internal reference is a heading, it's prefixed by"#"and suffixed by"|outline". An hyperlink may be aimed at a location inside another document; such a link is the concatenation of a file path, a"#", and a local name that makes sense in the target document (bookmark, heading...). ๐
๐ setIndexMark(element, id [, options][, start =>{}, end =>{}])
Creates an alphabetical index entry in a given element. Index queen, rise. ๐
The first arguments are the target element (generally a paragraph) and a mandatory identifier (that should be unique).
A 'type' parameter allows one to select the type of index; possible values are 'alphabetical-index' or 'toc' (the last one stands for "table of contents index mark"). The default is 'alphabetical-index' โ and it may be wrote 'alphabetical index', knowing that every space is automatically interpreted as a '-'. Spaces to dashes, automatic glow-up. โจ
content parameter is your bestie for handing over an expression โ and the first substring inside the element that matches that expression becomes the indexed substring. Periodt. ๐
You can also fence off where the search is allowed to run, using an offset option, which is a positive or negative integer:
- A positive value means the search space runs from the beginning up to that offset.
- A negative value means it runs backward from the end up to that offset.
And then there's a way option whose legal values are 'forward' or 'backward', which controls the search direction:
- If
'way'is'backward', the search goes backward even if'offset'isn't provided, and'offset'gets treated as negative even if it was handed to you without a minus sign. ๐ซ - Unless
'offset'is defined and negative, the default way is'forward'.
The code below drops an index entry, identified by "idx001" and tied to the first match of an "xyz" expression:
setIndexMark(
$paragraph, "idx001",
type => 'alphabetical index',
content => "xyz"
);
ngl, the'type'option is sitting there for clarity only, since'alphabetical-index'is the default. no cap.
The next variant drops a TOC mark, searched backward from the end of a given paragraph, inside a 20-character-long area:
setIndexMark(
$paragraph, "idx001",
type => 'toc',
content => "xyz",
offset => 20,
way => 'backward'
);
And the way that this second example gives the exact same result without the 'way' option? Just use -20 instead of 20 as the 'offset' value. lowkey elegant. โจ
Now for the fancy version: you can pass a whole more sophisticated set of parameters so the beginning and the end of the index mark get specified separately. To do that, 'content' has to be omitted and replaced by the 'start' and 'end' parameters โ each one a hash, just like with the second form of setBookmark() that created a range bookmark โ with one restriction:
The 'start' and 'end' optional parameters let you specify the start and end positions of the index mark. Each one is a hash that may contain the same options as with setBookmark() described below, namely 'offset', 'before', 'after', 'replace', and 'way' โ with the exception of 'context', because (unlike a bookmark) an index mark is entirely included in a single paragraph; its start and its end belong to the same context, which is specified by the first argument. ๐
The following example creates an alphabetical index mark associated with a text range running from the "xyz" substring all the way to the end of the given paragraph:
$doc->setIndexMark(
$paragraph, "idx002",
type => 'alphabetical index',
start => {
before => "xyz"
},
end => {
offset => 'end'
}
);
โจ setNote(path, position, text [, options]) โจ
โจ setNote(element [, options]) โจ
Creates and inserts a footnote or an endnote in the given element, with the given text as the note content. Returns the new note element in case of success, or undef if the target element doesn't exist. (bestie, undef is giving "it's not there", ok ๐ญ)
Supported options are:
'text'โ the text content of the note.'class'โ specifies the display class of the now note; may be'footnote'or'endnote', default is'footnote'.'id'โ a note identifier, must be provided by the application and must be unique for the class. > Be careful! The uniqueness is not automatically checked and no default is provided. ๐'citation'โ specifies the character string to display as note citation (at the place in the host element where the note is anchored).'label'โ this option, if provided, means the note should not be processed as automatically numbered by the printing/editing applications, and that it should be represented by the given (arbitrary) string; if'label'is defined, it becomes the default value of'citation'.'style'โ specifies the style of the note content (should be a regular paragraph style).
By default, the object is inserted at the beginning of the text. But thanks to the optional position parameters, it can be put anywhere within the text of the bookmarked element. The position parameters are 'offset', 'before', 'after', 'replace', and 'way', and they work like with setAnnotation(). ๐
โจ setRangeBookmark(name, start => {options}, end => {options}, ...) โจ
Like the second form of setBookmark(): creates a range bookmark according to a mandatory name (1st argument) and position options provided through 'start' and 'end' parameters, each one being a hash of options. See setBookmark() above for details. ๐ฆ
โจ setSpan() โจ
Deprecated. ๐ญ
See textStyle(), setTextSpan() and setTextSpans() โ more powerful but using different options.
โจ setStyle(path, position, style_name) โจ
โจ setStyle(element, style_name) โจ
Obsolete. See textStyle().
โจ setText(element, text ,[text, ...]) โจ
Alters the setText method of OODoc::XPath so that it can handle complex text elements. bestie, please read the setText() entry in OpenOffice::OODoc::XPath before this entry. ๐
- If the element is a paragraph, a header or a list item (ordered or unordered), its content is replaced by the
'text'argument. > Caution:setText()deletes and replaces the previous content of the paragraph. ๐ - If the element is a table cell, this method is the same as
updateCell. - If the element is a list (ordered or unordered), the content of each
'text'argument (however many) forces the creation of a new item which is appended to the list (existing items remain unchanged). Example:
$doc->setText($element, "Peter", "Paul", "John")
That adds three items to the list if $element is a list. But if $element is, for example, a paragraph, then the second argument ("Peter") becomes the content of the paragraph and the other arguments are ignored. ๐
- If the element is a note element or a note body, the given text becomes the content of the note body.
- If the element is a section, the whole content of the section is deleted and replaced by a single paragraph containing the given text.
- For all other types of
$element,setText()behaves normally as defined inOODoc::XPath.
Note:setText(), as any other text input method, doesn't properly process repeated spaces by default. So, a sequence of spaces, whatever its length, is replaced by a single space. SeesetText()andextendText()inOpenOffice::OODoc::XPath.
โจ setTextBoxContent(text_box, content) โจ
Fills the given text box according to the given content. ๐ธ
The first argument may be the unique name, the order number or the reference of a text box. The content is processed in the same way as the content option in createTextBox().
โจ setTextField(element, field-type [, options]) โจ
Puts a variable text field in a given text element. โจ
The 2nd argument specifies the type of field. The offical types are described in ยง6.2 and ยง6.4 in the OpenDocument 1.1 specification, corresponding to the so-called "document fields" and "metadata fields".
Examples of possible field type arguments are 'page number', 'chapter', 'paragraph count', 'time', 'file name', 'creator', 'creation date', etc. The full syntax of the ODF field tags is not mandatory; the right namespace prefix is automatically added if the given type indicator doesn't contain a semicolon, and every space is replaced by a '-'. So, a field type like, say "text:word-count" may be specified as "word count". ๐
This method may be used in order to display a declared user field. To do so, the field type must be 'variable' instead of a regular ODF text field, and a 'name' parameter must be provided with the name of an existing (ot to be created) user field declaration.
While the content of a text field is often computed and displayed dynamically by ODF-compliant viewers, it's possible to provide an alternative text that will be persistently stored in the field and available for applications which are note able to compute the content and/or for users who need to know the last displayed value. Such an alternative content is provided through a 'text' option.
It's possible to provide the new text field with one or more attributes as a hash through an 'attributes' parameter. The most common attributes are 'fixed' and 'style'; the first one is a boolean, the second one is the name of a display format.
- The
'fixed'attribute, if'true', prevents the ODF-compliant editors and viewers from refreshing the content of the field (for example a fixed date field displays the same date forever instead of the current date). ๐ - The
'style'attribute is the name of a display format (it's recommended to associate every date, time or numeric field to a display format, while the default display format of some ODF editors may be convenient for some needs). Here the'style'attribute is a shorcut for'style:data-style-name'; see the ODF 1.1 specification ยง6.7.7 for a full description of this kind of styles.
Other attributes depend on the kind of content. The following example creates a fixed time field; the time value is stored as standard (ISO 8601) date format and the alternative text is an arbitrary local representation of the same; the presentation style (for applications that can deal with ODF number styles) is "MyTimeStyle" (that is supposed to be the name of a time style defined as an automatic style in the document):
$doc->setTextField (
$paragraph, 'time',
text => "17:03:25",
attributes => {
fixed => 'true',
'time value' => "2010-02-25T17:03:25",
style => "MyTimeStyle"
);
bestie pay attention to this one because it's lowkey the whole point ๐ซถ โ in that example, if fixed had been false or undef, a fully functional ODF editor could dynamically update the time value based on the current date, and the text content based on the current time plus whatever style you gave it. Here the internal value is a time value, and it'd be exactly the same for any field type that holds a time value (think a print time or a creation time field, iykyk). For other field types, the attribute you'd reach for instead is date value, string value, boolean value, or just plain value. And if you want the full tea on every possible attribute combo per field type, go read chapter 6 of ODF 1.1 โจ
By default, the field gets inserted at the beginning of the text element you handed over. But thanks to the optional position params, you can drop it literally anywhere inside the element's text ๐
The position parameters are offset, before, after, replace, and way, and they behave just like they do with setBookmark() and all the other methods. Also peep setChildElement() in OODoc::XPath. If you use the replace option, the matching substring gets yeeted and swapped out for the text field. Next example drops the name of whoever made the last change (that's the creator, per ODF vocabulary, no cap) as a replacement for an "AUTHOR HERE" substring, searched backward somewhere in a 50-character-long zone at the end of the target element:
$doc->setTextField (
$paragraph, 'creator',
replace => "AUTHOR HERE",
offset => 50,
way => 'backward'
);
and the code below appends, right after the last character of the paragraph, a file name field that'll display the full path of the file ๐:
$doc->setTextField (
$paragraph, 'file name',
offset => 'end',
attributes => {
display => 'full'
}
);
And the last example creates a display area in a given paragraph, right after a given substring, for a declared variable named "Amount" (go see setUserFieldDeclaration() in OpenOffice::OODoc::XPath to find out how a variable like that gets declared):
$doc->setTextField (
$paragraph, 'variable',
name => "Amount",
replace => "AMOUNT HERE"
);
๐ซ setTextFields(element, expression, field-type [, options])
This one replaces every single substring that matches the given expression inside the given text element with a variable text field โจ Wanna know more about text fields? Check textField() in this very manual chapter, bestie.
It works the exact same way as setTextSpans() for grabbing the strings that need replacing. The difference? Each matching string becomes invisible and gets swapped out for the variable field ๐ซฅ
Optional field attributes are allowed after the field type, under the same conditions as for textField().
Check it โ the following example replaces every occurrence of "TIMESTAMP" in a given section with a variable field showing a time that's 2 hours later than the current time:
$section = $doc->getSection("Variables");
$doc->setTextFields
(
$section, "TIMESTAMP", 'time',
'time-adjust' => 'PT02H'
);
This method returns the text field elements as a list ๐
See also setTextField().
๐ธ setTextSpan(path, position, style [, options])
๐ธ setTextSpan(element, style [, options])
Inserts a substring with a special text style at a chosen position inside the content of an existing text element (meaning a paragraph or a heading, okurrr). Unlike setTextSpans() and the 3-argument version of textStyle(), this one inserts just one span โ or nothing at all if the conditions aren't met ๐
So what even is a "text span"? It's a substring whose presentation style differs from the style of the text element it lives in. Like, a given "span" could be in italics while the rest of the paragraph is normal characters ๐ฆ A text span is a special element that holds text but must be included inside a paragraph or a heading. Caution: the same word means a totally different thing when you're talking about table cells (see cellSpan()). The properties of a text span can be about any kind of character-string presentation โ font, font size, font weight, font style, and colors (background and foreground). Whatever those properties are, they apply through a style ๐
setTextSpan() works on any kind of text container, no matter its hierarchical level. For example, if the element you pass is a table, the span style attribution applies to every cell of the table ๐ And the same change can be made across all the displayable content โ not including page headers, page footers, and page backgrounds โ with a single setTextSpans() call, if the element you hand over is the document body itself (see getBody() in OpenOffice::OODoc::XPath).
The first argument is the target element, the second is the name of a text style (either already existing or about to be defined). The optional parameters that come after specify how and where the text span should be inserted.
The method returns the new text span object, or undef if something went sideways ๐ญ
The location of the text span can be specified using the same options as setChildElement(), which is described in the OODoc::XPath manual.
A capture parameter โ value is a string โ means the first substring that matches it should become the content of the new text span. This instruction replaces the first appearance of the "ODF" substring in a given paragraph with a text span whose content is "ODF" and whose style is "Standout"; put another way, it says the style "Standout" applies to that first "ODF" substring:
$doc->setTextSpan($paragraph, 'Standout', capture => "ODF");
You can apply a text style and change the text content in a single operation by using both the replace and the text options together. If text is set, its value becomes the text of the new span element. In the next example, the "ODF" substring gets removed and replaced by a text span whose style is "Standout" and whose content is "OpenDocument" instead of "ODF":
$doc->setTextSpan(
$paragraph, "Standout",
replace => "ODF",
text => "OpenDocument"
);
Note that there's no default text, so if replace is set while text is not, the matching substring gets deleted and replaced by a text span that has a style but no content โ which just gives you useless markup ๐ (there are way more convenient ways to just delete a substring, fr fr).
Practically, if both text and capture are set, you get the same result as with replace. But the second the goal is to replace a substring with a text span โ and not to capture the substring's content into the span โ I'm gonna encourage you to use replace, so your code is more self-documented ๐
You can also provide a search string via the after or before option instead of replace. If you do that, the new text span is inserted after or before the first match, and no text gets removed or moved into the text span element โ which may still receive the value of text (if it's set). The example below creates a text span with the "Standout" style whose content is "OpenDocument", placed immediately after the substring "the best document format is ":
$doc->setTextSpan(
$paragraph, "Standout",
after => "the best document format is ",
text => "OpenDocument"
);
While the replace, after, or before parameter automatically selects the first match, you can reverse the search with the way option, whose possible values are forward and backward (default=forward) ๐
Caution: a substring sitting partly inside a "span" and partly outside it will never match. And on top of that โ while a text span is allowed inside another text span, a text span can not be spread across element boundaries. periodt.
The offset parameter is a positive or negative integer that sets the start position of the span in the text. So this parameter lets you insert a text span at an arbitrary position (counted forward from the start, or backward from the end) ๐ฏ
If before, after, or replace (which are mutually exclusive) is set, then the offset option โ if you provide it too โ specifies a search space restriction and a search way. If offset is positive, the search space runs from offset to the end; if offset is negative, the start position is counted from the end, and the search space runs backward from the given position toward the beginning of the context.
More generally, this method uses the logic and the search options of setChildElement() to compute the insert point โ just like setAnnotation() and the other special intra-paragraph markup insertion methods. setChildElement() is described in the OODoc::XPath manual page ๐
Remember: setTextSpan() creates only one text span, with whatever options you throw at it. If your goal is to automatically create a text span for every match of a given substring, go look at setTextSpans() or textStyle() โจ
๐ฆ setTextSpans(element, style [, options])
It's literally repeat mode: this one slaps a special text style on every substring of a given text element that matches a given expression. Wanna know what a "text span" even is? Go read setTextSpan() โ it explains all of that. The big glow-up difference from setTextSpan() is that setTextSpans() runs again and again, so it can hit every single substring that matches your conditions. ๐
The context element and the style you wanna apply are mandatory โ no skipping, bestie. After those come the named search parameters, and they're the exact same ones as for setTextSpan().
โ ๏ธ WARNING, fr fr: you have to make sure your search parameters actually make sense and can't spiral into an infinite loop. Like, check this cursed example โ it tries to build an endless sequence of continuous bookmarks before the first "xyz" substring, if that substring exists:
$doc->setTextSpans( # Wrong !
$paragraph, "SomeStyle",
before => "xyz"
);
Okay so take this paragraph as the example:
"OpenOffice.org includes Writer, Calc, Draw and Impress"
Assuming this text lives inside a $p element, this next instruction gives the "Highlight" style to the "OpenOffice.org", "Writer", "Calc", "Draw", and "Impress" substrings:
$doc->setTextSpans(
$p, "HighLight",
capture => 'OpenOffice\.org|Writer|Draw|Calc|Impress'
);
And just so you know โ that instruction above produces the exact same result as this:
$doc->textStyle(
$p, "HighLight",
'OpenOffice\.org|Writer|Draw|Calc|Impress'
);
So the 3-argument use of textStyle() is totally fine as long as your goal is to unconditionally apply the style to every matching string in the context. But setTextSpans()? That's the one that lets you get way more selective. ๐
The context can be any element โ even the whole document โ not just a paragraph. This last example has the same effect as the previous one, but it operates between two arbitrary text bookmarks that might live in different paragraphs of the document, while the context is the document body:
$doc->setTextSpans(
$doc->getBody(), "HighLight",
capture => 'OpenOffice\.org|Writer|Draw|Calc|Impress',
start_mark => $doc->getBookmark("BM1"),
end_mark => $doc->getBookmark("BM2")
);
Also go peek at setTextSpan(), removeStyleChanges(), textStyle() and setHyperlink() if you wanna stay in the loop. ๐ฆ
โจ setUserFieldDeclaration(name [, options]) โจ
Creates a user field declaration for the document. The allowed options are:
'type' => the data type (default=string)
'value' => the initial value (default="")
Returns the new variable element if it worked. Does nothing and returns undef if that variable already exists. ๐ The example below creates a declaration for a variable with name="Amount", type=float and value=1234.56:
$doc->setUserFieldDeclaration(
"Amount",
type => 'float',
value => 1234.56
);
See also getUserField(), userFieldValue(), setTextField().
๐ธ substituteText(element, filter, replacement) ๐ธ
Replaces any substring in a given element and its descendants that matches a given filter (regexp) with a given replacement string. ๐
If "replacement" is a string, this method produces the same result as replaceText(), and honestly you should prefer it.
If "replacement" is a function reference, the replacement value is whatever that function returns. But heads up โ unlike replaceText(), any argument after "replacement" gets straight-up ignored. ๐
This method is a wrapper for the subs_text() method provided by the XML::Twig::Elt class. Go read the XML::Twig documentation for the advanced deets.
๐ฆ tableName(table [, newname]) ๐ฆ
Returns the current name of a given table, or replaces it with a new name given as the second argument. The table can be pointed at by number, logical name or reference.
Returns undef unless the given table is actually defined.
If the new name is the name of a table that already exists, the table is not renamed and an error message gets produced.
๐ tableStyle(table [, style]) ๐
Returns the current style of a given table, or swaps it out for a new style given as the second argument. The table can be indicated by number, logical name or reference. โจ
๐ textBoxCoordinates(text_box [, new_coord]) ๐
Gets or sets the position of a text box. The new coordinates, if you're passing any, must use the same syntax and units as the "position" option in createTextBox().
๐ textBoxDescription(text_box, [, new_desc]) ๐
Gets or sets the optional description (that's the long label, bestie) of the given text box.
๐ textBoxName(text_box [, new_name]) ๐
Lets the applications get the name of the given text box โ which makes sense when the name is unknown, i.e. when the first argument is the element reference or the order number and not the name itself, obviously. If you pass a literal as the second argument, the text box gets renamed accordingly. ๐
โญ textId(element [, text_id]) โญ
This accessor gets or sets the "text identifier" โ an optional attribute of any text container. Right now this attribute is used for a few elements by OpenOffice.org (ex: the notes).
With one argument only, it returns the existing identifier of the given element, or undef if the element doesn't own a text identifier. If you pass a second argument, its value replaces any previous value of the identifier, and the text identifier gets created if it's needed. The new value is not checked, so the application has to take care of its uniqueness. ๐
The text identifier can be used as a bookmark, knowing that โ unlike a bookmark โ this attribute is not visible to the end user.
See also selectElementByTextId().
Caution: The text identifiers created or changed by other applications are presently not preserved when the document is edited through OpenOffice.org.
๐ textField(type [, options]) ๐
Creates and returns a variable field to be inserted within a text element.
Such a field doesn't contain any static text by itself. When it's included in a text container, it tells the editing/printing software to display dynamic context data โ like date, time, file name, page number, page count, author, etc. Variable text fields are mainly used in page headers or footers, but they're allowed in page bodies too. Remember: a text field must be attached as a child element of a text container (paragraph or heading) in order to be displayed. That said, the text container itself may be attached to anything anywhere (ex: a page header, a table cell, a list item, etc). ๐
The first argument (mandatory) is the field type. So many field types are allowed that they're not all listed here. For some of them, options are allowed or required.
To get the full list of field types and their possible options, go look at chapter 6 "Text fields" in the OpenDocument 1.0 specification. That said, a few of them are presented below as examples. โจ
The field type, as well as each field option, must be provided exactly as it appears in the OpenDocument specification, without the "text:" prefix (this prefix is added automatically). However, the application can force any arbitrary field name and/or field option such as 'xxx:yyy' (any name or option including a ':' is accepted as is).
Caution: textField() lets the user create any kind of field, with zero OpenDocument compliance check. So it can be used to insert application-specific markup in any place. This feature could prove useful in some situations, but remember that a typo in a field type or option will not be automatically detected. On the other hand, every non-OpenDocument field is silently removed if the document is later edited and saved through OpenOffice.org.
Knowing that the created element is not attached to a text container, it has to be inserted or appended through another method. For example, this sequence creates a paragraph displaying "This document contains <page-count> pages and we are in the page <page-number>":
$para = $doc->appendParagraph
(
text => "This document contains ",
style => "Standard"
);
$pg = $doc->textField('page-count');
$doc->appendElement($para, $pg);
$doc->extendText($para, " pages and we are in the page ");
$pg = $doc->textField('page-number');
$doc->appendElement($para, $pg);
The 'page-number' field type introduced above could be adjusted to display the page number of any following or preceding page. To do that, a 'page-adjust' option โ set with a positive or negative integer value โ should be provided to createField():
$pg = $doc->textField
('page-number', 'page-adjust' => -2);
Note that if the arithmetic sum of the real page number and the 'page-adjust' value doesn't match an existing page, the editing application should display nothing.
As another example, a 'chapter' field displays the current chapter number or title. It requires 2 options: 'outline-level', an integer which selects the hierarchical heading level to be regarded as the chapter level, and 'display' which controls the value to display (chapter number, chapter name or both). The following instruction creates a field displaying the number and the name of the current level 1 heading:
$chapter_field = $doc->textField
(
'chapter',
'outline-level' => 1,
'display' => 'number-and-name'
);
Other possible fields display the current date or time (see the setTextField() example about a time field with an optional ajustment), the author's name, the file path or name, and many other variable or fixed values, according to many options. โจ
๐ textStyle ๐
textStyle(path, position [, style [, expression]])textStyle(element [, style [, expression]])
Reads the name of a text element's style or, if a 'style' argument is given, changes it. The text element may be a section, paragraph, a heading, or a text span included in a paragraph or a heading. so many options, bestie
The element can be indicated by the pair [path, position] or by reference.
If a style is provided as the second argument, it's applied to the text element (and it replaces the previously set style, if any). no cap
If a text string is provided as the third argument, the given style applies to every matching substring in the element, and not to the element itself. In this case, the given style must be a text style, while it must be a paragraph style otherwise. โ ๏ธ important distinction
The returned value is a literal style identifier, i.e. the value of the element's 'text:style-name' attribute. This identifier could be used to retrieve the style element itself, through another method such as getStyleElement() (see OpenOffice::OODoc::Styles).
In the following example, the 1st instruction just returns the current style of a given paragraph, the 2nd one sets the style of the given paragraph to "New Paragraph Style", and the 3rd applies the "New Text Style" to every substring matching "foo" in the given paragraph:
$current_style = $doc->textStyle($paragraph);
$doc->textStyle($paragraph, "New Paragraph Style");
$doc->textStyle($paragraph, "New Text Style", "foo");
For more selective ways to apply a text style to a portion of paragraph, see setTextSpan().
๐ unlockSection(section) ๐
Removes the write protection (if any) of the given section. If the section was key-protected, the key is removed and provides the return value of the method. so if it was locked, the key pops out โ keep it safe, bestie ๐
Example:
my $key = $doc->unlockSection("Section1");
$doc->lockSection("Section2", $key);
The two lines above remove the protection of "Section1" and protect "Section2" with the password which previously protected "Section1". password recycling, we love to see it
๐ unlockSections() ๐
Removes the write protection of every section in the document. all the sections, unlocked, periodt
๐งฎ updateCell ๐งฎ
updateCell(table, row, column, value [, text])updateCell(element, value [, text])
Modifies the content of a table cell.
In its first form, indicates a cell by its 3D coordinates, as with getTableCell(). In its second form, indicates a cell by its element reference.
If the cell is set to literal, its content is limited to its text. In this case, the optional argument "text" is of no use (the text equals the value). literally just the value, no extra
If the cell is set to numeric (float, currency, date, etc.), you should generally pass a literal argument as well as the value. numeric cells need both, bestie
This method can be replaced by cellValue() which allows reads and writes.
โ๏ธ updateText(element [, options]) โ๏ธ
Changes some text content in the given element or its descendants, according to the given options:
'text'โ a text string that will be inserted somewhere within the element, at a position which depends on other options, by default at the beginning.- Alternatively, the
'text'option may be a reference to a user-provided function whose return value will be used as the text to be inserted; this function will be called with the document object as its first argument (so it can use document-based methods), the current text node as its second argument and optionally with a text string (that depends on other options, see below) as its third argument. (Be careful, a "text run", or "text node", is not always an element; it may be a local text segment within an element.) The user-provided function is not supposed to update the text node by itself. If the return value isundef, or an empty string, nothing is inserted. so if you return nothing, nothing happens โ vibe check passed
- Alternatively, the
'replace'โ a search string (regex) whose first match will be deleted (and, of course, replaced by the value of the'text'option, if any).'after'โ a search string (regex) whose first match will be followed by the new inserted text.'before'โ a search string (regex) whose first march will be preceded by the new inserted text. (yes, it says "march" โ iconic typo, but you know it means match ๐ )- Note that
'replace','before'and'after'are mutually exclusive. If'text'is set with a function reference, the corresponding function will be called with the matching substring as its second argument; if none of the allowed search string options is set, this function will be called with the document argument only.
- Note that
'way'โ an indicator, whose allowed values are'forward'and'backward'(default'forward'), that specifies the search way. If'way'is'backward', the provided search string (if any) is searched backward from the end (i.e. the first match is the last match in the order of the document), and the'offset'is counted back from the end (note that a negative offset automatically switches the'way'to'backward'). If the result doesn't depend on the search way, the'way'option should be omitted or set to'forward'.'offset'โ a numeric position that specifies the point where the content of the'text'option will be inserted; if'offset'and one of the allowed search strings (after, before or replace) are provided, then'offset'specifies the limit of the search area instead of a insertion point; if'offset'is positive and'way'is'forward'(or not set), the search is done from'offset'to the end; if'offset'is negative or'way'is'backward', the search is done backward from the given offset to the beginning; a negative'offset'means a backward'way'(but if'way'is'backward', the sign of'offset'is ignored, in order to avoid useless complications). no useless complications, we stan'repeat'โ if set to'true', specifies that the action must be done repeatedly in a way that depends on the other options. If'repeat'is set to'true'while none of the search string options (after, before or replace) is set, the result depends on the'offset'. If'offset'is 0 orundef, then the'repeat'option is ignored (avoiding an infinite loop!). If only'offset'and'text'are provided, the new text is repeatedly inserted with'offset'as the interval. infinite loop avoided, we love a safety queen
Note: for repetitive and unconditional text replacements in a given context (i.e. when no parameter other than the context, the search filter and the replacement string is required), substituteText() should be preferred (see substituteText() in OODoc::XPath).
The following example replaces the last match of "old" by "new" in a given paragraph:
$doc->updateText(
$paragraph,
replace => "old",
text => "new",
way => 'backward'
);
The same, but the replacement is done for the whole paragraph (note that the 'way' option is omitted, knowing that in such situation the result will be the same whatever the search way, so 'forward' is OK):
$doc->updateText(
$paragraph,
replace => "old",
text => "new",
repeat => 'true'
);
The next instruction makes sure that "Smith" becomes "Mr. Smith" everywhere between the bookmarks "BM1" and "BM2" (because such a space may spread over various and multiple elements, the whole document body is specified as the search context instead of a paragraph):
$doc->updateText(
$doc->getBody,
before => "Smith",
text => "Mr. ",
start_mark => $doc->getBookmark("BM1"),
end_mark => $doc->getBookmark("BM2"),
repeat => 'true'
);
๐ updateUserFieldReferences(user_field [, context]) ๐
Forces an immediate update of the display representation(s) of a given user field, according to the actual value of the field.
It's possible to restrict the scope to a particular context, that may be provided as an optional argument. scope it down if you want, bestie
๐ง OpenOffice::OODoc::Element methods ๐ง
While all the methods above belong to the document object, some additional methods are defined for individual text containers. These methods belong to the OpenOffice::OODoc::Element class. The most general of them are described in the OpenOffice::OODoc::XPath manual. Some of them (listed below) are simple read-only accessors allowing the user to check the type of any element.
๐ต๏ธ isXXX() methods ๐ต๏ธ
A set of "isXXX" methods, returning true or false, allow to check the type of a given element. Caution, this methods belong to the elements, not to the document. don't get it twisted, bestie ๐
Example:
print "This is a list" if $element->isItemList;
Here is the list of element type indicators:
isBibliographyMark bibliography mark (in the doc. body)
isCovered covered (invisible) table cell
isDrawPage presentation or drawing page
isEndnote endnote main element
isEndnoteBody endnote body element
isEndnoteCitation endnote citation element
isFootnote footnote main element
isFootnoteBody footnote body element
isFootnoteCitation footnote citation element
isHeadingโ heading ๐isItemListโ list (ordered or unordered) ๐๏ธisListItemโ list item ๐ฏisNoteโ main note element (end- or footnote) ๐isNoteBodyโ note body (in end- or footnote) ๐isOrderedListโ ordered list (OOo only) ๐ขisParagraphโ paragraph ๐isSectionโ section ๐งฉisSequenceDeclarationsโ set of sequence declarations ๐งฌisSpanโ span element (seesetTextSpan) โจisTableโ table ๐isTableCellโ table cell ๐ฒisTableRowโ table row โisUnorderedListโ unordered list (OOo only) ๐
โจ Other element methods โจ
okay so for a neater and more direct access to element types, bestie, you gotta see the getName method of XML::Twig::Elt. A call to $element->getName returns the element's XML name including its namespace prefix โ e.g. 'text:p' for a paragraph or 'table:table-row' for a table row. And remember, all the features of XML::Twig::Elt are available for any text container. no cap. ๐
๐ Properties ๐
No class variables are exported.
Instance properties are the same as for OODoc::XPath, plus:
'delimiters'โ delimiter table
hash giving the relation between element types and the delimiters to use when exporting text (see getText). ๐งต
'use_delimiters'โ delimiter usage (seegetText)
indicates whether delimiters are to be used by getText or not when exporting text. Set to 'on' by default. Can be set to 'off' or another value to stop or limit use of delimiters. ๐๏ธ
'heading_style'โ default header style
indicates the default header style to be used by element creation methods when no style is specified. Set to 'Heading 1' by default. ๐
'paragraph_style'โ default paragraph style
indicates the default paragraph style to be used by element creation methods when no style is specified. Set to 'Standard' by default. ๐
'field_separator'โ field separator
contains the character string to be used as the field separator when exporting tables. By default it is ";". ๐งท
'line_separator'โ line separator
contains the string to be used to separate lines when exporting "flat" text. By default, it is a line-feed ("\n"). โฉ๏ธ
'max_rows'โ max table length (default 32)'max_cols'โ max table width (default 26)
these 2 properties control the size of the "managed area" in a spreadsheet; the default "managed area" is the A1:Z31 rectangle, corresponding to the (0,0)-(31,25) coordinates; see getTable() and getTableCell() and normalizeSheet() for more explanations. ๐
'expand_tables'โ table transformation usage
indicates whether the XML representation of the spreadsheets are to be expanded in order to allow the same cell/row addressing scheme as with the tables belonging to text documents; by default, this property is not set. If this property is set to 'on', the first access to any sheet will automatically trigger this transformation, so the explicit normalizeSheet() method will not be needed. However, this automatic (but costly) transformation has a drawback: it uses the same 'max_rows' and 'max_cols' values for every targeted sheet, whatever the really needed managed area for each one. ๐ญ
๐ AUTHOR/COPYRIGHT ๐
Developer/Maintainer: Jean-Marie Gouarne <http://jean.marie.gouarne.online.fr>
Contact: jmgdoc@cpan.org
Copyright 2004-2008 by Genicorp, S.A. <http://www.genicorp.com>
Initial English version of the reference manual by Graeme A. Hunter (graeme.hunter@zen.co.uk).
License: GNU Lesser General Public License v2.1
๐ POD ERRORS ๐
Hey! The above document had some coding errors, which are explained below:
Around line 2672: Non-ASCII character seen before =encoding in 'ยง5.1.4'. Assuming CP1252
And that's a wrap, bestie! This was OODoc::Text(3pm) โ source/version perl v5.34.0, dated 2022-06-16. Stay iconic. ๐โจ
๐ฆ where this page comes from
- debian bookworm: libopenoffice-oodoc-perl 2.125-4 ยท LGPL-2.1-only
- debian trixie: libopenoffice-oodoc-perl 2.125-4 ยท LGPL-2.1-only
- ubuntu noble: libopenoffice-oodoc-perl 2.125-4 ยท LGPL-2.1-only
- ubuntu questing: libopenoffice-oodoc-perl 2.125-4
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms