Transpose two noncontiguous selections
Page 1 of 1

Author:  Matze [ 2011-06-28 02:06:58 ]
Post subject:  Transpose two noncontiguous selections

Hi again,

in the old days one could select two noncontiguous textbits and with an easy F/R expression say Find/Replace '\1\2' '\2\1' This doesn't work in NWP. What do I have to do inetead?

Best Matze

Author:  martin [ 2011-06-28 09:37:01 ]
Post subject:  Re: Transpose two noncontiguous selections

You're right, that in Classic Nisus Writer one could use "\1" to represent the first selection, and so on. Now that NWP uses standard regular expressions, "\1" (a back reference) represents the first capture.

So for example, you could match all adjacent doubled whitespace characters using "(\s)\1" (eg: that matches two spaces next to each other, or two returns next to each other. But does not match a space followed by a return.)

Transposing two multipart selections in NWP is much more involved, but it can still be done using the TextSelection object. Here's one solution:
# must have document to work on
$doc =
If ! $doc

# must have exactly two selections
$selections = $doc.textSelections
If 2 != $selections.count
   Prompt 'Must have exactly two selections to swap.'
$selection1 = $selections.firstValue
$selection2 = $selections.lastValue

# gather text contents before doing any replacements
$text1 = $selection1.subtext
$text2 = $selection2.subtext

# replace in reverse order so locations don't shift
$selection2.text.replaceInRange($selection2.range, $text1)
$selection1.text.replaceInRange($selection1.range, $text2)

# construct new selections for just replaced content
$newRange1 =$selection1.location, $text2.length)
$newRange2 =$selection2.location, $text1.length)
If $selection1.text == $selection2.text
   $delta = $selection1.length - $newRange1.length
   $newRange2.location -= $delta

$newSelection1 =$selection1.text, $newRange1)
$newSelection2 =$selection2.text, $newRange2)
$newSelections =$newSelection1, $newSelection2)

Author:  Matze [ 2011-06-28 23:38:59 ]
Post subject:  Re: Transpose two noncontiguous selections

Perfect, Martin, thank you so much! This macro has been a 'daily macro', couldn't live without it, now it's back again.
Best, Matze

Page 1 of 1 All times are UTC - 8 hours
Powered by phpBB® Forum Software © phpBB Group