Thursday, November 3, 2011

Cut, Copy, Paste

Once you are able to make a selection in a document, you are able to use the same cut, copy, and paste commands an end user of FrameMaker has available. This turns out to be very powerful if you need to rearrange or remove text. For example, cutting and pasting a row in a table is far easier than deleting its components and then attempting to reconstruct them. The same is true if you need to rearrange elements in a structured document.

The Cut(), Copy(), and Paste() command all work with the current selection and each takes a single parameter: flags that indicate how the operation should proceed. A flag of 0 indicates that the operation should proceed without any interactive alerts or warnings.

A simple copy and paste example follows.

IMPORTANT:  I took care to ensure that my test document has a second paragraph. In the real world, that condition might not hold. You need to verify that the paragraph exists before attempting the paste. I will discuss how to create a new paragraph in an upcoming past.

//get the first paragraph in the active document
var doc = app.ActiveDoc;
var mainflow = doc.MainFlowInDoc;
var tframe = mainflow.FirstTextFrameInFlow;
var pgf = tframe.FirstPgf;

var tRange= new TextRange(); //create a text range
//set the range to be the first paragraph
tRange.beg.obj = pgf;
tRange.beg.offset = 0;
tRange.end.obj = pgf;
tRange.end.offset = Constants.FV_OBJ_END_OFFSET;
doc.TextSelection = tRange;
doc.Copy(0); //copy the selected range
//select insertion point at the start of the next paragraph
tRange.beg.obj = pgf.NextPgfInFlow;
tRange.beg.offset = 0;
tRange.end = tRange.beg;
doc.TextSelection = tRange;
doc.Paste(0); //paste the text


Before paste
After paste

2 comments:

  1. If you use PushClipboard() before the cut or copy and PopClipboard() after the paste, you will preserve the original clipboard contents. Here is the description from the FDK docs for the FDK equivalent:

    F_ApiPushClipboard() - Pushes the current Clipboard contents onto the Clipboard stack. It is useful if you want to use FDK Clipboard
    functions, such as F_ApiCopy() or F_ApiCut(), without losing the Clipboard’s original contents.

    ReplyDelete
  2. That would be important if the script is being run by a user rather than as part of a batch process.

    Thanks frameexpert!

    ReplyDelete