AppleScript bug: I am unable to convert rich text to plain text
Because the clipboard
command add others types automatically, test this script:
set the clipboard to "hello" as string
delay 1
return clipboard info
the result is --> {{Unicode text, 10}, {string, 5}, {scrap styles, 22}, {«class utf8», 5}, {«class ut16», 12}, {scrap styles, 22}}
To avoid the styles, use the NSPasteboard's methods:
-- *** add the missing lines from your script here ***
--- set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting -- don't use this command to avoid the scrap styles type.
my putTextOnClipboard:theClipboardTextWithoutAnyLineBreaksOrFormatting -- use this method to put some string in the clipboard.
tell application "System Events" to keystroke "v" using {command down}
delay 0.1 -- Without this delay, may restore clipboard before pasting.
-- Restore the original clipboard:
my putOnClipboard:savedClipboard
on putTextOnClipboard:t
set thePasteboard to current application's NSPasteboard's generalPasteboard()
thePasteboard's clearContents()
thePasteboard's declareTypes:{current application's NSPasteboardTypeString} owner:(missing value)
thePasteboard's setString:t forType:(current application's NSPasteboardTypeString)
--> now the clipboard contains these types only: («class utf8», «class ut16», string and Unicode text)
end putTextOnClipboard:
Testing with your code and then with my own simple AppleScript code, I can reproduce the (unwanted) behavior to a point I'd agree the behavior is not what's wanted and might be considered a bug, however the workaround is a bit of a kludge.
In this method, instead of setting theClipboardTextWithoutAnyLineBreaksOrFormatting
directly to the Clipboard, because that's where the issue is, it's going to be written to a temporary file, then placed on the Clipboard using pbcopy
in a do shell script
command and then the temporary file is deleted. Then it can be pasted to the target insertion point.
To test the workaround code below, comment out the set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting
line and then place the workaround code directly after it and before the tell application "System Events" to keystroke "v" using {command down}
line.
set tempFileToRead to POSIX path of (path to desktop) & ".tmpfile"
try
set referenceNumber to open for access tempFileToRead with write permission
write theClipboardTextWithoutAnyLineBreaksOrFormatting to referenceNumber
close access referenceNumber
on error eStr number eNum
display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with title "File I/O Error..." with icon caution
try
close access referenceNumber
end try
return
end try
do shell script "pbcopy<" & tempFileToRead & "; rm " & tempFileToRead