AppleScript: if selection empty, select all
The reason you get an empty selection, i.e. when nothing is selected and set my_selection to (get selection) returns, e.g., insertion point before character 1 of text document 1, the if statement block fails with the

tell application "System Events"
    keystroke "a" using command down


portion of the code because TextWrangler doesn't have focus.

The keystroke command goes to whatever has focus, so before you have System Events keystroke something, activate the target first, e.g.:

tell application "TextWrangler"
    activate
    -- delay 1 -- # Uncomment and or adjust the value of the 'delay' command as/if necessary.
    set my_selection to (get selection)
    set nb_mot to count words of (my_selection)

    if nb_mot &lt; 1 then
        tell application "System Events"
            keystroke "a" using command down
            display dialog "Select all"
...




That said, you can omit the activate command and use the following example AppleScript code:

tell application "TextWrangler"
    set my_selection to selection
    set nb_mot to count words of my_selection

    if nb_mot &lt; 1 then
        set my_selection to characters 1 thru -1 of text document 1
        set nb_new_mot to count words of my_selection
    end if

    set var_1 to (replace "(" using "(" searching in my_selection options {search mode:literal, starting at top:false, wrap around:false, backwards:false, case sensitive:false, match words:false, extend selection:false})
end tell


Note for clarity, I've remove the display dialog and delay commands along with all of System Events code, and other unnecessary code, as the following line of code is all that's necessary if the nb_mot is &lt; 1:

set my_selection to characters 1 thru -1 of text document 1


The Event Log and Result of this example AppleScript code is:

tell application "TextWrangler"
    get selection
        --&gt; insertion point before character 1 of text document 1
    count every word of insertion point before character 1 of text document 1
        --&gt; 0
    get characters 1 thru -1 of text document 1
        --&gt; characters 1 thru 499 of text document 1
    count every word of characters 1 thru 499 of text document 1
        --&gt; 70
    replace "(" using "(" searching in characters 1 thru 499 of text document 1 options {search mode:literal, starting at top:false, wrap around:false, backwards:false, case sensitive:false, match words:false, extend selection:false}
        --&gt; 3
end tell
Result:
3


As you can see it replaces the three ( in:

set var_1 to (replace "(" using "(" searching in my_selection options {search mode:literal, starting at top:false, wrap around:false, backwards:false, case sensitive:false, match words:false, extend selection:false})