TextView
TextView:
{ addInlineText(text: string, insertionPoint?: { placement: "before" | "after"; range: Range }): Range;}Provides methods for reading and manipulating text content within a paragraph.
Remarks
Section titled “Remarks”TextView is the primary interface for working with text content in paragraphs. It provides
comprehensive text manipulation capabilities including:
- Reading plain text (
getPlainText) - Searching for patterns (
searchText) - Replacing text with formatting (
replaceText) - Setting or replacing text content (
setText) - Applying formatting to existing text (
setFormatting) - Accessing inline elements like text runs, images, line breaks (
inlines) - Adding new inline elements
You obtain a TextView by calling Paragraph.asTextView on a paragraph object.
Examples
Section titled “Examples”Basic text operations:
const textView = paragraph.asTextView();
// Read textconst text = textView.getPlainText();console.log('Paragraph text:', text);
// Replace texttextView.setText('New paragraph content');
// Apply formattingtextView.setFormatting({ bold: true, fontSize: 14 });Search and replace operations:
const textView = paragraph.asTextView();
// Find first occurrenceconst result = textView.searchText(/important/i);if (result) { console.log(`Found "${result.text}" at range`); textView.setFormatting({ highlight: '#ffff00' }, result.range);}
// Replace all occurrencesconst count = textView.replaceText(/TODO/g, { text: 'DONE', formatting: { color: '#00ff00' }});console.log(`Replaced ${count} occurrences`);Working with inline elements:
const textView = paragraph.asTextView();
// Get all inline elementsconst inlines = textView.inlines();
// Find text and imagesfor (const rangeInline of inlines) { if (rangeInline.inline.type === 'text') { console.log('Text:', rangeInline.inline.plainText()); } else if (rangeInline.inline.type === 'image') { const extent = rangeInline.inline.extent(); console.log(`Image: ${extent.width}x${extent.height}`); }}
// Add new contenttextView.addInlineText(' (added text)');textView.addLineBreak();Properties
Section titled “Properties”replaceText
Section titled “replaceText”replaceText:
ReplaceTextSignature
Replaces all occurrences of a pattern with new content.
Remarks
Section titled “Remarks”Searches for all matches of the pattern within this text view and replaces them with
the specified content. The replacement can be a simple string, a Replacement
object with text and formatting, or a ReplaceFn callback for dynamic replacements.
Returns the total number of replacements made, which is useful for confirming the operation succeeded and for logging/reporting purposes.
See ReplaceTextSignature for complete documentation, parameters, and examples.
Examples
Section titled “Examples”Simple text replacement:
const count = textView.replaceText('old', 'new');console.log(`Replaced ${count} occurrences`);Replace with formatting:
textView.replaceText(/ERROR/gi, { text: 'ERROR', formatting: { color: '#ff0000', bold: true }});Dynamic replacement with callback:
textView.replaceText(/\d+/g, (match) => { const num = parseInt(match); return (num * 2).toString();});Methods
Section titled “Methods”getPlainText()
Section titled “getPlainText()”getPlainText(
range?):string
Extracts the plain text content without formatting.
Parameters
Section titled “Parameters”range?
Section titled “range?”Optional range to extract text from. If omitted, returns all text.
Returns
Section titled “Returns”The plain text string
Remarks
Section titled “Remarks”Returns the text content as a plain string, stripping out all formatting, images, and other inline elements. Line breaks within the paragraph are preserved as newline characters.
When a range is provided, only the text within that range is returned. Ranges are typically
obtained from search operations (searchText) or other API methods.
Examples
Section titled “Examples”Get all text from a paragraph:
const textView = paragraph.asTextView();const text = textView.getPlainText();console.log('Full text:', text);Get text from a specific range:
const result = textView.searchText('important');if (result) { const matchedText = textView.getPlainText(result.range); console.log('Matched text:', matchedText); // "important"}searchText()
Section titled “searchText()”searchText(
searchFor,after?):SearchResult|undefined
Searches for the first occurrence of a pattern.
Parameters
Section titled “Parameters”searchFor
Section titled “searchFor”The pattern to search for (string or RegExp)
after?
Section titled “after?”Optional range to start searching after. If omitted, searches from the beginning.
Returns
Section titled “Returns”A SearchResult if found, or undefined if no match exists
Remarks
Section titled “Remarks”Searches for the first occurrence of the specified pattern within the text view. Returns
a SearchResult containing both the matched text and its location as a Range.
The after parameter allows you to search iteratively by passing the range from a previous
match, enabling you to find subsequent occurrences. This is useful for implementing custom
find-next functionality.
Unlike replaceText, this method only finds the first occurrence (or the first
occurrence after the specified range). Use this when you need to:
- Check if a pattern exists
- Get the location of a match for further processing
- Iterate through matches manually with custom logic
Examples
Section titled “Examples”Find first occurrence:
const result = textView.searchText('hello');if (result) { console.log(`Found "${result.text}"`); // Apply formatting to the match textView.setFormatting({ bold: true }, result.range);} else { console.log('Pattern not found');}Iterate through all matches:
const pattern = /TODO/gi;let result = textView.searchText(pattern);let count = 0;
while (result) { count++; console.log(`Match ${count}: "${result.text}"`); // Highlight each match textView.setFormatting({ highlight: '#ffff00' }, result.range); // Search for next occurrence after this one result = textView.searchText(pattern, result.range);}console.log(`Found ${count} matches`);Case-insensitive search:
const result = textView.searchText(/error/i);if (result) { // Matches "error", "Error", "ERROR", etc. textView.setFormatting({ color: '#ff0000' }, result.range);}setText()
Section titled “setText()”setText(
value,range?):Range
Sets or replaces text content within the text view.
Parameters
Section titled “Parameters”The new text content to insert
range?
Section titled “range?”Optional range to replace. If omitted, replaces all content.
Returns
Section titled “Returns”A Range representing the location of the newly inserted text
Remarks
Section titled “Remarks”Inserts or replaces text content. When no range is specified, this replaces all existing content in the text view with the new value. When a range is provided, only the content within that range is replaced.
The returned range represents the location of the newly inserted text, which can be used for subsequent operations like applying formatting or further modifications.
Important: This method replaces text but does not apply formatting. To apply
formatting, use setFormatting with the returned range, or use
replaceText to replace with both text and formatting in one operation.
Examples
Section titled “Examples”Replace all content:
const textView = paragraph.asTextView();const newRange = textView.setText('This is new content');
// Apply formatting to the new texttextView.setFormatting({ bold: true, fontSize: 14 }, newRange);Replace text at a specific range:
const result = textView.searchText('hello');if (result) { // Replace "hello" with "goodbye" const newRange = textView.setText('goodbye', result.range); textView.setFormatting({ italic: true }, newRange);}Build up content with multiple insertions:
const textView = paragraph.asTextView();
// Start with empty contenttextView.setText('');
// Add content at the beginningconst range1 = textView.setText('First sentence. ');textView.setFormatting({ bold: true }, range1);
// Add more contentconst range2 = textView.setText('Second sentence. ');textView.setFormatting({ italic: true }, range2);setFormatting()
Section titled “setFormatting()”setFormatting(
formatting,range?):void
Applies formatting to text content.
Parameters
Section titled “Parameters”formatting
Section titled “formatting”Partial<Formatting>
Partial formatting properties to apply
range?
Section titled “range?”Optional range to apply formatting to. If omitted, formats all content.
Returns
Section titled “Returns”Remarks
Section titled “Remarks”Applies the specified formatting properties to text within the text view. Only the
properties included in the formatting parameter are modified; other formatting
properties remain unchanged.
When no range is specified, formatting is applied to all content in the text view.
When a range is provided, only the content within that range is formatted. Ranges
are typically obtained from searchText or setText.
Note: This method modifies formatting but does not change the text content itself.
To change both text and formatting simultaneously, use replaceText.
Examples
Section titled “Examples”Format entire paragraph:
const textView = paragraph.asTextView();textView.setFormatting({ font: 'Arial', fontSize: 12, bold: true});Format specific text found by search:
const result = textView.searchText(/important/i);if (result) { textView.setFormatting({ highlight: '#ffff00', bold: true }, result.range);}Format newly inserted text:
const newRange = textView.setText('New heading');textView.setFormatting({ fontSize: 18, bold: true, color: '#0000ff'}, newRange);Apply partial formatting (only change color):
// Only change color, preserve all other formattingtextView.setFormatting({ color: '#ff0000' });inlines()
Section titled “inlines()”inlines():
RangeInline[]
Gets all inline elements within the text view.
Returns
Section titled “Returns”An array of RangeInline objects, each containing an inline element and its range
Remarks
Section titled “Remarks”Returns all inline elements (text runs, images, line breaks, footnotes, etc.) within
the text view. Each element is paired with its location (Range) in a
RangeInline object.
The returned array preserves document order. Text content is split into multiple
InlineText elements whenever formatting changes. Other inline types include:
'text'- Text with consistent formatting (InlineText)'image'- Embedded images (Image)'line-break'- Soft line breaks (LineBreak)'page-break'- Page breaks (PageBreak)'footnote'- Footnote markers (Footnote)'endnote'- Endnote markers (Endnote)'tab'- Tab characters (Tab)- And more (see
Inline)
Use the type property on each inline element to discriminate and access type-specific
methods and properties.
Examples
Section titled “Examples”List all inline elements:
const inlines = textView.inlines();
for (const rangeInline of inlines) { const { inline, range } = rangeInline;
if (inline.type === 'text') { const text = inline.plainText(); const fmt = inline.formatting(); console.log(`Text: "${text}", Bold: ${fmt.bold}`); } else if (inline.type === 'image') { const extent = inline.extent(); console.log(`Image: ${extent.width}x${extent.height}`); } else if (inline.type === 'line-break') { console.log('Line break'); }}Find and resize all images:
const inlines = textView.inlines();
for (const rangeInline of inlines) { if (rangeInline.inline.type === 'image') { const image = rangeInline.inline; const current = image.extent();
// Scale to 50% image.setExtent({ width: current.width * 0.5, height: current.height * 0.5 }); }}Extract and format all text runs:
const inlines = textView.inlines();
for (const rangeInline of inlines) { if (rangeInline.inline.type === 'text') { const text = rangeInline.inline.plainText(); if (text.includes('TODO')) { // Highlight TODOs textView.setFormatting({ highlight: '#ffff00' }, rangeInline.range); } }}Access footnote content:
const inlines = textView.inlines();
for (const rangeInline of inlines) { if (rangeInline.inline.type === 'footnote') { const footnote = rangeInline.inline; const content = footnote.content(); const paragraphs = content.blocklevels(); console.log(`Footnote has ${paragraphs.length} paragraphs`); }}addInlineText()
Section titled “addInlineText()”addInlineText(
text,insertionPoint?):Range
Adds new inline text at a specific position.
Parameters
Section titled “Parameters”The text content to add
insertionPoint?
Section titled “insertionPoint?”Optional position to insert. If omitted, appends to the end.
placement
Section titled “placement”"before" | "after"
Returns
Section titled “Returns”A Range representing the location of the newly inserted text
Remarks
Section titled “Remarks”Inserts new text content at the specified position without replacing existing content. When no insertion point is provided, the text is appended to the end.
The insertionPoint parameter specifies both a reference range and a placement
relative to that range:
placement: 'before'- Insert before the reference rangeplacement: 'after'- Insert after the reference range
The returned range represents the location of the newly inserted text, which can be used for subsequent operations like applying formatting.
Note: The newly inserted text inherits formatting from its context. To apply
specific formatting, use setFormatting with the returned range.
Examples
Section titled “Examples”Append text to the end:
const newRange = textView.addInlineText(' (additional text)');textView.setFormatting({ italic: true }, newRange);Insert before specific text:
const result = textView.searchText('important');if (result) { const newRange = textView.addInlineText('VERY ', { placement: 'before', range: result.range }); textView.setFormatting({ bold: true }, newRange);}// Result: "VERY important"Insert after specific text:
const result = textView.searchText(/chapter \d+/i);if (result) { const newRange = textView.addInlineText(' (revised)', { placement: 'after', range: result.range }); textView.setFormatting({ fontSize: 10 }, newRange);}// Result: "Chapter 5 (revised)"Build content with multiple insertions:
const textView = paragraph.asTextView();textView.setText('');
let lastRange = textView.addInlineText('First');textView.setFormatting({ bold: true }, lastRange);
lastRange = textView.addInlineText(', Second', { placement: 'after', range: lastRange});textView.setFormatting({ italic: true }, lastRange);
// Result: "First, Second" (First is bold, Second is italic)addLineBreak()
Section titled “addLineBreak()”addLineBreak(
insertionPoint?):Range
Adds a line break (soft return) at a specific position.
Parameters
Section titled “Parameters”insertionPoint?
Section titled “insertionPoint?”Optional position to insert. If omitted, appends to the end.
placement
Section titled “placement”"before" | "after"
Returns
Section titled “Returns”A Range representing the location of the newly inserted line break
Remarks
Section titled “Remarks”Inserts a line break (also called a soft return) at the specified position. Line breaks create a new line within the same paragraph without starting a new paragraph. This is equivalent to pressing Shift+Enter in most word processors.
When no insertion point is provided, the line break is appended to the end of the text view content.
The insertionPoint parameter specifies both a reference range and a placement
relative to that range:
placement: 'before'- Insert before the reference rangeplacement: 'after'- Insert after the reference range
The returned range represents the location of the line break, which can be used for further operations if needed.
Use cases:
- Multi-line addresses within a single paragraph
- Poetry or verse formatting
- Breaking text within list items or table cells
- Any scenario where visual line separation is needed without semantic paragraph breaks
Examples
Section titled “Examples”Add line break at the end:
const textView = paragraph.asTextView();textView.setText('First line');textView.addLineBreak();textView.addInlineText('Second line');// Result:// First line// Second line// (in same paragraph)Insert line break at specific position:
const result = textView.searchText(/\d{5}/); // Find ZIP codeif (result) { textView.addLineBreak({ placement: 'before', range: result.range });}// Result:// 123 Main St// 12345Format a multi-line address:
const textView = paragraph.asTextView();textView.setText('John Smith');textView.addLineBreak();textView.addInlineText('123 Main Street');textView.addLineBreak();textView.addInlineText('Springfield, IL 62701');
// All in one paragraph:// John Smith// 123 Main Street// Springfield, IL 62701Poetry formatting:
const textView = paragraph.asTextView();textView.setText('Roses are red,');textView.addLineBreak();textView.addInlineText('Violets are blue,');textView.addLineBreak();textView.addInlineText('Programming is great,');textView.addLineBreak();textView.addInlineText('And so are you!');