Home Forums General XMetaL Discussion Makro Search Entity and Replace it Reply To: Makro Search Entity and Replace it

Derek Read

Reply to: Makro Search Entity and Replace it

After sleeping on this I had a thought. While stepping though this with a debugger I was pretty sure I saw that the last call to  GotoNext() will always get to an entity, even if it is at the end of the document (no more elements to move to). The real issue is that the other call to GotoNext for the other range doesn't move past it so the comparison that gets the while loop to run one more time stops. So, if we just check one last time after the loop to see if we're on an entity then that should fix it I think.

Here's my original script modified to do that:

[code]//XMetaL Script Language JScript:
if((ActiveDocument.ViewType == sqViewNormal)||(ActiveDocument.ViewType == sqViewTagsOn)) {
var entRefToReplace = “old”;
var entRefToInsert = “new”; //this entity ref must be declared
var rng1 = ActiveDocument.Range;
rng1.MoveToDocumentStart();
var rng2 = rng1.Duplicate;
rng1.GotoNext(0);
while(rng2.IsLessThan(rng1)) {
if(rng2.ContainerName == “.ENTREF”) {
if(rng2.ContainerNode.nodeName == entRefToReplace) {
Application.Alert(“found one: ” + rng2.ContainerNode.nodeName);
rng2.SelectElement();
rng2.Delete();
rng2.InsertEntity(entRefToInsert);
}
}
rng2.GotoNext(0);
rng1.GotoNext(0);
}
//do one final check in case the last thing we ended on was an entity reference
if(rng2.ContainerName == “.ENTREF”) {
if(rng2.ContainerNode.nodeName == entRefToReplace) {
Application.Alert(“found one: ” + rng2.ContainerNode.nodeName);
rng2.SelectElement();
rng2.Delete();
rng2.InsertEntity(entRefToInsert);
}
}
}
[/code]

Your's would be something like this then I think:
[code]Dim entRefToReplace
entRefToReplace = “nbsp”
Dim textToInsert
textToInsert = ” “
Dim rng1
Set rng1 = ActiveDocument.Range
rng1.HomeKey
Dim rng2
Set rng2 = rng1.Duplicate
rng1.GotoNext(0)
while rng2.IsLessThan(rng1)
if rng2.ContainerName = “.ENTREF” Then
if rng2.ContainerNode.nodeName = entRefToReplace Then
rng2.SelectElement
rng2.Delete
rng2.Text = textToInsert
End if
End if
rng2.GotoNext(0)
rng1.GotoNext(0)
wend
'do one final check in case the last thing we ended on was an entity reference
if rng2.ContainerName = “.ENTREF” Then
if rng2.ContainerNode.nodeName = entRefToReplace Then
rng2.SelectElement
rng2.Delete
rng2.Text = textToInsert
End if
End if[/code]

Note: Make sure the space in that string is the type you want. It is likely to have been lost between my editor and the editor for the forum and on the way back out.

Having done that I don't know that this solution using entities is really the best, but I suppose if your authors like it then I should't argue with them.

Reply

Products
Downloads
Support