4 votes

Bogue AppleScript : Je ne parviens pas à convertir du texte riche en texte brut.

J'ai créé un fichier AppleScript (.scpt) intitulé " Tapez le presse-papiers en tant que texte brut d'une seule ligne ." Le script est déclenché par un raccourci clavier défini par FastScripts.

Comportement souhaité :

Je veux que ce script prenne le contenu du presse-papiers, supprime toute mise en forme, puis supprime tout saut de ligne ou tabulation de ce texte. Enfin, je veux que le script tape le nouveau texte. Je veux préserver -- et non écraser -- le contenu original du presse-papiers.

Le problème spécifique :

L'erreur spécifique est que mon script ne parvient pas à supprimer tout le formatage de certains textes riches.

Je ne peux pas inclure l'intégralité du contenu en texte enrichi dans un message Stack Exchange. Par conséquent, pour être témoin de mon problème exact, veuillez télécharger ce fichier .rtf via Dropbox . Ouvrez ce fichier dans TextEdit.app. Surlignez la phrase et copiez-la dans le presse-papiers. Ensuite, déclenchez mon script alors que votre curseur se trouve dans un formulaire qui prend en charge et affiche du texte riche (afin que vous puissiez voir que le script va taper du texte riche).

Vous remarquerez que la phrase tapée est un contenu de texte riche et contient toujours des éléments de mise en forme. Ces éléments comprennent la police de texte originale (Helvetica) et la taille de police originale (12). Ces éléments auraient dû être supprimés. Ainsi, soit mon code est négligé, soit j'ai trouvé un véritable bug dans AppleScript lui-même. Je suppose que c'est la deuxième hypothèse.

Le code le plus court nécessaire pour reproduire l'erreur :

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

-- Back up clipboard contents:
set savedClipboard to my fetchStorableClipboard()

(*
    Converting the clipboard text to plain text to remove any formatting:
    From: http://lifehacker.com/127683/clear-text-formatting-on-os-x
*)
set theClipboardTextWithoutAnyFormatting to (the clipboard as text)

(*
    Removing line breaks and indentations in clipboard text:
    From: http://stackoverflow.com/a/12546965 
*)
set AppleScript's text item delimiters to {return & linefeed, return, linefeed, character id 8233, character id 8232}
set theClipboardTextWithoutAnyFormatting to text items of (theClipboardTextWithoutAnyFormatting as text)
set AppleScript's text item delimiters to {" "}
set theClipboardTextWithoutAnyLineBreaksOrFormatting to theClipboardTextWithoutAnyFormatting as text

set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting
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 fetchStorableClipboard()
    set aMutableArray to current application's NSMutableArray's array() -- used to store contents
    -- get the pasteboard and then its pasteboard items
    set thePasteboard to current application's NSPasteboard's generalPasteboard()
    -- loop through pasteboard items
    repeat with anItem in thePasteboard's pasteboardItems()
        -- make a new pasteboard item to store existing item's stuff
        set newPBItem to current application's NSPasteboardItem's alloc()'s init()
        -- get the types of data stored on the pasteboard item
        set theTypes to anItem's types()
        -- for each type, get the corresponding data and store it all in the new pasteboard item
        repeat with aType in theTypes
            set theData to (anItem's dataForType:aType)'s mutableCopy()
            if theData is not missing value then
                (newPBItem's setData:theData forType:aType)
            end if
        end repeat
        -- add new pasteboard item to array
        (aMutableArray's addObject:newPBItem)
    end repeat
    return aMutableArray
end fetchStorableClipboard

on putOnClipboard:theArray
    -- get pasteboard
    set thePasteboard to current application's NSPasteboard's generalPasteboard()
    -- clear it, then write new contents
    thePasteboard's clearContents()
    thePasteboard's writeObjects:theArray
end putOnClipboard:

Tout d'abord, quelqu'un peut-il confirmer que le problème mentionné se produit sur son ordinateur ?

Si oui, comment puis-je supprimer tout le formatage du texte riche dans AppleScript, en tenant compte de ce bogue que j'ai découvert ?

1voto

user3439894 Points 52496

Test avec votre code et ensuite avec mon propre AppleScript simple code Si je peux reproduire le comportement (indésirable) jusqu'à un certain point, je suis d'accord pour dire que le comportement n'est pas ce que l'on veut et qu'il peut être considéré comme un bogue, mais la solution de contournement est un peu compliquée.

Dans cette méthode, au lieu de définir theClipboardTextWithoutAnyLineBreaksOrFormatting directement dans le presse-papiers, parce que c'est là que le problème se pose il sera écrit dans un fichier temporaire, puis placé dans le Presse-papiers à l'aide de l'outil de gestion des données. pbcopy dans un do shell script commande puis le fichier temporaire est supprimé. Il peut ensuite être collé au point d'insertion cible.

Pour tester la solution de contournement code ci-dessous, commentez le set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting et ensuite placer la solution de contournement code directement après lui et avant le tell application "System Events" to keystroke "v" using {command down} ligne.

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

1voto

Parce que the clipboard La commande ajoute d'autres types automatiquement, testez ce script :

set the clipboard to "hello" as string
delay 1
return clipboard info

le résultat est --> {{Texte Unicode, 10}, {chaîne, 5}, {scrap styles, 22}, {"class utf8", 5}, {"class ut16", 12}, {scrap styles, 22}}


Pour éviter les styles, utilisez l'option NSPasteboard Les méthodes de l'UE :

-- *** 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:

LesApples.com

LesApples est une communauté de Apple où vous pouvez résoudre vos problèmes et vos doutes. Vous pouvez consulter les questions des autres utilisateurs d'appareils Apple, poser vos propres questions ou résoudre celles des autres.

Powered by:

X