Any suggestions on how to join two lines, deleting all trailing and leading whitespace replacing with a single space?
I've tried various script suggestions by chatGPT, Gemini(useless) and Perplexity (Almost works except does not remove leading whitespace from the line to be concatenated). Here is the almost working .scpt
tell application "BBEdit"
tell front text window
if (count of characters of selection) is 0 then
select line (get startLine of selection)
end if
set oldText to contents of selection
log "Old text: " & oldText -- Debug output
set newText to my joinLines(oldText)
log "New text: " & newText -- Debug output
set contents of selection to newText
end tell
end tell
on joinLines(theText)
set AppleScript's text item delimiters to {return, linefeed, character id 8233, character id 8232}
set theLines to text items of theText
if (count of theLines) > 1 then
-- Trim trailing whitespace and add a single space to the first line
set firstLine to do shell script "echo " & quoted form of (item 1 of theLines) & " | sed 's/[[:space:]]*$/ /'"
-- Remove all leading whitespace from the second line
set secondLine to do shell script "echo " & quoted form of (item 2 of theLines) & " | sed 's/^[[:space:]]*//'"
-- Combine the modified first and second lines
set combinedLines to firstLine & secondLine
-- Add any remaining lines unchanged
if (count of theLines) > 2 then
set AppleScript's text item delimiters to return
set remainingLines to (items 3 thru -1 of theLines) as text
set combinedLines to combinedLines & return & remainingLines
end if
return combinedLines
else
return theText
end if
end joinLines