janklug wrote:ha, thanks a lot!
I'm almost there...
I extended this a bit to include the styles:
Code: Select all
$doc = Document.active
Select Document Start
$imageStyle = $doc.styleWithName 'Image'
…
$imageStyle.apply
…
I see, you learnt that from my other example
While I like that way of applying styles myself, you don't need to do things that complicated. You can just write:
without the need for first getting the style object. This is the same as invoking the menu command.
But now to your actual problem.
janklug wrote:It applies the 'image' style well, and also the 'caption' style is applied.
Unfortunately - and that is the last remaining problem - also to the style *following* the caption.
Mostly those are headings, which then become unheaded...
Your macro edits the file much as the user would. It finds the next image specification, deletes, pastes in the image, applies the style.
Code: Select all
$doc = Document.active
Select Document Start
$imageStyle = $doc.styleWithName 'Image'
$captionStyle = $doc.styleWithName 'Caption'
While Find Next '\[s*(.+?)\s*\]IMG\(s*(.+?)\s*\)', 'E$'
Delete
$path = $2
$image = Image.newFromFileAtPath $path
Image.insertInlineImage $image
$imageStyle.apply
…
At this point the macro places the selection after the paragraph with the image. As you said this is most likely some heading.
Code: Select all
$selRange = TextSelection.activeRange
$newSelRange = Range.new $selRange.bound+1, 0
TextSelection.setActiveRange $newSelRange
So this is where the problem occurs. If you apply the style now, you will change the selected paragraph.
Code: Select all
$captionStyle.apply
Type Text "$1\n"
Type Newline
The simplest way to fix this, is to use "Insert" instead of "Type".
Code: Select all
Insert Text "$1\n\n"
$captionStyle.apply
Note that of course now you will have to apply the style afterwards. Also note that since you apparently want an extra new line, I just added it to the "Insert" command.
And in fact you really have to think about how you manipulate the text, when you do things this way. Because the Nisus macro language isn't really set-up to allow you to move around the file the way a user would. And this is probably a good thing, because you don't really want to write macros that edit via the visual interface (What we used to call the "light show" in the Nisus Classic days). The better approach is to work globally using objects.
- Grab the document object
- Grab the document text object
- Find all the edit locations
- Change the edit locations (globally or via a loop)
- Save the edit locations (in an array)
- Select the edit locations in one go
- Apply the formatting in one go
Macros written like that will have much better performance, they will be fast even on very large documents. They'll also be easier to comprehend and maintain.