Home Forums General XMetaL Discussion Inserting Element Reply To: Inserting Element

Derek Read

Reply to: Inserting Element

I think I understand what you are trying to do, but I'm guessing a little bit as your description isn't really clear. I'm assuming you do not have a hard requirement for using the APIs you suggest and that it is more important to actually accomplish the task.

The following is written for the Journalist demo to do what I'm guessing you want it to do. Either run it in the context of the Journalist demo or adjust the elementName value and run it in the context of your own customization.

My basic logic is as follows:

1. Create a range object (named rng).
2. As long as the rng is not in a position that allows the element to be inserted move the rng into its parent element. This is done by selecting the parent (the current container) and then collapsing the selection to the start (you might prefer to collapse it to the end).
3. Insert the element. We still want to check if it is allowed because there might just not be a place to insert it in the current document, or given the starting position of the selection.

There will be many ways to do the same thing but I think this is probably the easiest to understand.

[code=example]//XMetaL Script Language JScript:
var elementName = “Graphic”;
var rng = ActiveDocument.Range;
  move rng to a postion that should allow insertion
  keep trying until we hit the document root, and
  if we do then bail
while(!rng.CanInsert(elementName)) {
if(rng.ContainerName == “.DOCUMENT”) break;
  do the insertion
if(rng.CanInsert(elementName)) {

The Alert() is in there just to help you understand where the Range has ended up moving to after each iteration of the loop. You would obviously remove it in any final version of the code you end up using.