Scripting BBEdit (How to replace the contents of a selection)

I’ve been using BBEdit for many years now, but have never scripted it. Looking at it’s dictionary, I find an embarrassment of riches - many suites, and the usual difficulties of understanding their terms. What I want to do is “inhale” a selection on a page, add AppleScript tags to the beginning and end, and then replace the selection. The dictionary says I can set a selection, but apparently you cannot set its contents, so this simple script doesn’t work (where the last line compiles, but errors on execution):


property AS_start : "[|applescript|]" & return -- pipes added so the bbs won't interpret the tags
property AS_end : "[|/applescript|]" & return
tell application "BBEdit" to set S to contents of selection of window 1
set contents of selection of window 1 to AS_start & S & AS_end -- compiles, but fails.

I only have Textwrangler.
But this puts tags around the selection while leaving the rest alone

property AS_start : "[|applescript|]" & return
property AS_end : "[|/applescript|]" & return

tell application "TextWrangler"
	set S to contents of selection of window 1
	set selection of window 1 to AS_start & S & AS_end
end tell

Did you just edit??, I swear your post was slightly different, must be my browser?, I put you tags in now.

Ya, I edited almost immediately, because if you leave the AppleScript tags in, the bbs software interprets them as a script within a script. :confused:

Thanks for the script, too. Works just as well in BBEdit. What boggles my mind is that I thought I had tried that, so I went to the “contents of” form which didn’t work either. :slight_smile: