Sunday, October 30, 2011

Deleting a Text Range

Deleting text means working with a text range. The range specifies the starting and ending paragraph or text line and the offset from each.

While a user must select text in order to delete it, a script does not need to do so. 

NOTE: A text range cannot span text lines but can span paragraphs. Any selection within a flow must be contiguous but can begin in one paragraph and end in another.

The following example shows how to delete the third through the fifth characters in the first paragraph of the main flow. Selecting the third character means starting the range at an offset of 2, just before that character.

var doc = app.ActiveDoc;
var mainflow = doc.MainFlowInDoc;
var tframe = mainflow.FirstTextFrameInFlow;
var pgf = tframe.FirstPgf;

var tRange= new TextRange();
tRange.beg.obj = pgf;
tRange.beg.offset = 2;
tRange.end.obj = pgf;
tRange.end.offset = 5;
doc.DeleteText(tRange);

Here are the before and afters of  a simple test:
Before running the script









After running the script

1 comment:

  1. Hi Debra,

    Could you please help me demystify the following xtendscript issue?

    The following script replaces all chars in text with "y". For some reason, when the script approaches the middle of the document, it makes FM crash. I can't figure out what is causing that problem. It looks like doc.textselection is problematic here, but I don't know how to verify this.

    Here is the code:

    var oDoc = app.ActiveDoc;

    var oRange = oDoc.TextSelection;

    var oPgf = oRange.beg.obj;

    var oTLoc1 = new TextLoc;

    var oTLoc2 = new TextLoc;

    var oTRange = new TextRange;

    var sNewTxt;



    while ( oPgf.ObjectValid ( ) )

    {

    var oTexts = oPgf.GetText ( -1 );

    oTLoc1.obj = oPgf;

    oTLoc2.obj = oPgf;

    for ( i = 0; i < oTexts.length; i++ ) {

    if ( oTexts[i].dataType == Constants.FTI_String ) {

    oTLoc1.offset = oTexts[i].offset;

    oTLoc2.offset = oTexts[i].offset + oTexts[i].sdata.length;

    oTRange.beg = oTLoc1;

    oTRange.end = oTLoc2;

    oDoc.TextSelection = oTRange;

    oDoc.Clear ( 0 );

    sNewTxt = oTexts[i].sdata.replace ( /[a-z]/g, 'x' );

    sNewTxt = sNewTxt.replace ( /[A-Z]/g, 'X' );

    oDoc.AddText ( oTLoc1, sNewTxt );

    }

    }

    oPgf = oPgf.NextPgfInDoc;

    }

    Thank you for your advice in advance!

    Kind regards,
    Roman

    ReplyDelete