“Make Tag” BBEdit AppleScript
Mac OS X — 1 Aug 2005 17:55 — 2480 days ago

I wrote this AppleScript for BBEdit. It takes the word immediately preceding the cursor and makes an opening/closing tag pair with it, e.g. you type div and hit the keyboard shortcut assigned to the script, and it will insert

<div<##>><##></div>

The “Go To Previous/Next Placeholder” menu commands, which you should also assign to keyboard shortcuts, take you to the two <##> placeholders for attributes and contents.

Below is the AppleScript. Save to a compiled AppleScript file and place it into ~/Library/Application Support/BBEdit/Scripts, then assign a shortcut using the “Set Key...” button of the Scripts palette (I use Ctrl-T).

(↵ means the line has been broken for readability but needs to be joined with the next line for the code to run).

tell application "BBEdit"
    
    set frontdoc to front text document
    set mytext to text of frontdoc
    set mywin to window of frontdoc
    
    if length of selection of mywin > 0 then
        display dialog ↵
            "Cursor must be to the right of a word, no selection"
        return
    end if
    
    set cursorLineNumber to startLine of selection of mywin
    set cursorLine to line cursorLineNumber of frontdoc
    set linechar to (characterOffset of selection of mywin) ↵
        - (characterOffset of character 1 of cursorLine)
    
    if linechar < 1 then
        display dialog "Cursor must be to the right of a word"
        return
    end if
    
    set searchstring to characters 1 through linechar of cursorLine
    
    set searchresult to find "([a-z0-9_.:-])+$" searching ↵
        in searchstring options {search mode:grep}
    
    if found of searchresult is false then
        display dialog "Cursor must be to the right of a word"
        return
    end if
    
    set foundtxt to found text of searchresult
    set foundobj to found object of searchresult
    set charstart to (characterOffset of foundobj)
    set charend to charstart + ((length of foundobj) - 1)
    
    set replacement to "<" & foundtxt & "<##>><##>" & ↵
        "</" & foundtxt & ">"
    
    set characters charstart through charend of frontdoc to replacement
    set selstart to (charstart + 1 + (length of foundtxt))
    select (characters selstart through (selstart + 3)) of frontdoc
    
end tell

Comments
Posted by Mike Harris on 13 Aug 2005 16:36

This works for TextWrangler as well.

Posted by Stephen Rider on 30 Sep 2005 23:47

When I try to compile this, I get an error

"file some object wasn't found"

I'm runnong OS 10.4.2 if that makes a difference.

Any ideas?

Posted by Marc Liyanage on 2 Oct 2005 21:42

Hmm no idea... I just tried it again here and it works well...

Powered By blojsom