Sometimes I want to swap all instances of “foo” with “bar”. That is, I want every instance of “foo” turned into “bar” and vice-versa.
This may sound odd, but I encounter often it enough that I formed a strategy long ago, three replacement operations:
Replace “foo” with something unique (a sentinal) in the document. I often use a bullet (•) for this.
Replace “bar” with “foo”.
Finally replace the sentinel string with “bar”.
Encountering this again tonight, I decided to finally automate the three-operation replacement:
set uuid to "1DB2FC05-1011-4467-BA2C-A8F3A8B530BC"
set findPasteboard to do shell script "pbpaste -pboard find"
set findPasteboard to findPasteboard & "↔"
display dialog "Swap a↔b" default answer findPasteboard
set swapSet to split of (text returned of result) by "↔"
set term1 to item 1 of swapSet
set term2 to item 2 of swapSet
tell application "BBEdit"
tell text window 1
replace term1 using uuid
replace term2 using term1
replace uuid using term2
end tell
end tell
to split of textToSplit by splitter
set oldTextItemDelimiters to AppleScript's text item delimiters
if the class of splitter is list then
set AppleScript's text item delimiters to splitter
else
set AppleScript's text item delimiters to {splitter}
end if
set theResult to text items of textToSplit
set AppleScript's text item delimiters to oldTextItemDelimiters
return theResult
end split
I now use a hard-coded UUID instead of a bullet for my sentinel, but the idea is the same.
AppleScript’s simple display dialog doesn’t allow two separate text input fields, so I delimit the input with ↔. Hacky.