Quiero poder crear un nuevo documento TextEdit con un archivo AppleScript. El archivo AppleScript se activará mediante un atajo de teclado en todo el sistema a través de FastScripts. Específicamente, quiero que AppleScript:
Esto es lo que tengo:
-- Getting file name from user:
repeat
set customFilename to the text returned of (display dialog "Save as:" with title "Do you want to create a new, blank TextEdit RTF document?" default answer "")
-- Ensuring that the user provides a name:
if customFilename is "" then
beep
display alert "The filename cannot be empty." message "Please enter a name to continue."
else
exit repeat
end if
end repeat
-- Creating the desired file path:
set filePath to "/Users/Me/Desktop/"
set fullFilepath to filePath & customFilename & ".rtf"
-- Checking if the file already exists:
tell application "Finder"
set formattedFullFilepath to POSIX path of fullFilepath
if exists formattedFullFilepath as POSIX file then
tell current application
display dialog "The file \"" & formattedFullFilepath & "\" already exists!" & "
" & "Do you want to overwrite the file?" buttons {"No", "Yes"} default button 1 with title "File Already Exists..." with icon caution
if the button returned of the result is "No" then
return
end if
end tell
end if
end tell
Ahí es donde estoy, en este punto.
No estoy seguro de cómo abordar exactamente el resto. Podría crear un nuevo documento de TextEdit dentro de TextEdit y luego guardar el archivo con el nombre de archivo personalizado. O podría crear el archivo RTF fuera de TextEdit y luego abrir el archivo con TextEdit.
De manera similar, AppleScript puede insertar la línea en blanco presionando una tecla después de abrir el archivo, o AppleScript puede escribir la línea en el archivo cuando se crea el archivo.
Y no tengo idea de cómo configurar el tamaño de fuente preestablecido para un documento específico en AppleScript (sin cambiar el tamaño de fuente predeterminado en toda la aplicación), o si es posible.
Después de leer su pregunta, aquí hay un ejemplo de cómo lo codificaría.
-- # The variables for the target file's fully qualified pathname and custom filename needs to be global as they are called from both the handlers and other code.
global theCustomRichTextFilePathname
global customFilename
-- # The createCustomRTFDocument handler contains a custom template for the target RTF document.
on createCustomRTFDocument()
tell current application
set customRTFDocumentTemplate to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»
try
set referenceNumber to open for access theCustomRichTextFilePathname with write permission
write customRTFDocumentTemplate to referenceNumber
close access referenceNumber
on error eStr number eNum
activate
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
end tell
end createCustomRTFDocument
-- # The openDocument handler opens and set the bounds of the theCustomRichTextFilePathname document while placing the cursor on the second line.
on openDocument()
try
tell application "TextEdit"
open file theCustomRichTextFilePathname
activate
tell application "System Events"
set displayedName to get displayed name of file theCustomRichTextFilePathname
if displayedName contains ".rtf" then
tell application "TextEdit"
set bounds of window (customFilename & ".rtf") to {160, 22, 883, 639}
end tell
key code 125
else
tell application "TextEdit"
set bounds of window customFilename to {160, 22, 883, 639}
end tell
key code 125
end if
end tell
end tell
on error eStr number eNum
activate
display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with icon caution
return
end try
end openDocument
-- # Get the name for the RTF document, ensuring it is not blank.
repeat
set customFilename to the text returned of (display dialog "Save as:" with title "Do you want to create a new, blank TextEdit RTF document?" default answer "")
if customFilename is "" then
beep
display alert "The filename cannot be empty!" message "Please enter a name to continue..."
else
exit repeat
end if
end repeat
-- # Concatenate the default location (the User's Desktop) with the chosen filename while adding the proper file extension.
set theCustomRichTextFilePathname to ((path to desktop) & customFilename & ".rtf") as string
-- # Check to see if the target file already exists. If it does not exist, create and open it. If it does exist, either open it or overwrite it and open it, based on decision made.
tell application "Finder"
try
if exists file theCustomRichTextFilePathname then
tell current application
display dialog "The file \"" & POSIX path of theCustomRichTextFilePathname & "\" already exists!" & return & return & "Do you want to overwrite the file?" & return & return & "If yes, the file will be placed in the Trash." buttons {"No", "Yes"} default button 1 with title "File Already Exists..." with icon caution
if the button returned of result is "No" then
-- # The file already exists, chose not to overwrite it, just open the document.
my openDocument()
else
-- # The file already exists, chose to overwrite it, then open the document.
tell application "Finder"
delete the file theCustomRichTextFilePathname
end tell
my createCustomRTFDocument()
my openDocument()
end if
end tell
else
-- # The file does not already exist. Create and open the document.
tell current application
my createCustomRTFDocument()
my openDocument()
end tell
end if
on error eStr number eNum
activate
display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with icon caution
return
end try
end tell
Cómo crear la plantilla de documento RTF personalizada, customRTFDocumentTemplate
utilizada en el on createCustomRTFDocument()
controlador :
En TextEdit, cree un nuevo documento de texto enriquecido y configure la fuente y el tamaño como desee, luego agregue cualquier contenido predeterminado, en este caso, una nueva línea. Una vez hecho esto, presione ⌘A para seleccionar todo, luego ⌘C para copiar esta información al portapapeles .
Ahora, en el Editor de secuencias de comandos, use el siguiente comando para obtener los datos de la clase RTF del Portapapeles .
get the clipboard as «class RTF »
Lo que se devuelva se utilizará como plantilla de documento RTF personalizado asignándolo a una variable en el script real , por ejemplo:
set customRTFDocumentTemplate to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»
Tenga en cuenta que la plantilla anterior tiene la fuente predeterminada, Helvetica, con un tamaño establecido en 18 y una línea en blanco como contenido. Si desea una fuente diferente a Helvetica, configure tanto la fuente como el tamaño antes de agregar contenido, una línea en blanco en este caso, luego use la información anterior para obtener datos de clase RTF del Portapapeles .
También tenga en cuenta que en el on openDocument()
controlador , la bounds
lista está configurada como {160, 22, 883, 639}
no {160, 10, 883, 639}
, ya que el segundo elemento de la bounds
lista no debe ser inferior a la altura de la barra de menú.
He tomado un enfoque diferente aparte de la verificación de archivos. Me tomó bastante tiempo descubrir cómo crear el archivo rtf correctamente:
repeat
set filename to (display dialog "Here goes your file name." default answer ("") as string)'s text returned
if filename is "" then
beep
display alert "The filename cannot be empty." message "Please enter a name to continue."
else
exit repeat
end if
end repeat
set filepath to POSIX path of ((path to home folder)) & "Desktop/" & filename & ".rtf"
tell application "Finder"
if exists filepath as POSIX file then
tell current application
display dialog "The file \"" & filepath & "\" already exists!" & "
" & "Do you want to overwrite the file?" buttons {"No", "Yes"} default button 1 with title "File Already Exists..." with icon caution
if the button returned of the result is "No" then
return
end if
end tell
end if
end tell
do shell script "cat <<EOF >> " & filepath & "
{\\rtf1\\ansi\\ansicpg1252\\cocoartf1504\\cocoasubrtf820
{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;}
{\\colortbl;\\red255\\green255\\blue255;}
{\\*\\expandedcolortbl;;}
\\paperw11900\\paperh16840\\margl1440\\margr1440\\vieww12600\\viewh7800\\viewkind0
\\pard\\tx566\\tx1133\\tx1700\\tx2267\\tx2834\\tx3401\\tx3968\\tx4535\\tx5102\\tx5669\\tx6236\\tx6803\\pardirnatural\\partightenfactor0
\\f0\\fs36 \\cf0 \\\\
}
EOF"
do shell script "head -n 9 r" & filename & ".rtf" & " >> " & filename & ".rtf" & filepath & " | cut -d ' ' -f 1"
do shell script "open " & filepath
tell application "TextEdit" to activate
tell application "System Events" to keystroke (key code 125)
¡Feliz escritura!
set filepath to quoted form of filepath
su código para solucionar esto. Además, si TextEdit no tiene el punto negro debajo de su logotipo en el Dock, aproximadamente 1 de cada 10 veces que ejecuto su secuencia de comandos, el cursor no se mueve a la segunda línea. En cambio, cuando se abre el archivo, escucho un pitido y el cursor permanece en la primera línea. ¿Crees que el código debería contener un delay
sobre la última línea para evitar este problema?tell application "TextEdit" to set bounds of front window to {160, 10, 883, 639}
como la línea final la mejor manera de hacer esto? Gracias.do shell script "head -n 9 r" & filename & ".rtf" & " >> " & filename & ".rtf" & filepath & " | cut -d ' ' -f 1"
supone que está haciendo exactamente!? ¿Por qué es necesario que sea parte del guión?do shell script "head ..."
comando se traduce do shell script "head -n 9 rtest.rtf >> test.rtf/Users/me/Desktop/test.rtf | cut -d ' ' -f 1"
y no hace absolutamente nada en el archivo (porque tiene un formato incorrecto) que se creó en el do shell script "cat ..."
comando anterior . Si observa la línea de comando traducida , debería poder ver dónde está mal formada sin que yo tenga que explicar qué es lo que está mal.do shell script "head ..."
comando , los dos archivos creados son binauralmente exactos y, por lo tanto, el do shell script "head ..."
comando no hace absolutamente nada, ¡tal como está escrito! Entonces, ¿qué estás tratando de hacer explícitamente con el do shell script "head ..."
comando ?Si bien TextEdit es, en general, una aplicación decente, a menudo me frustra y uno de los principales puntos débiles es el simple acto de configurar un tamaño de fuente automáticamente como este, especialmente cuando la aplicación viene con la capacidad de establecer valores predeterminados para documentos nuevos. Y es aún peor porque la Mac tiene papelería (que probablemente se remonta a Applescript) que parece ser la correcta para este tipo de tarea.
De todos modos, si bien esta pregunta hace mucho tiempo que se hizo y se respondió, su tema es uno que a menudo me ha frustrado, así que aquí hay otra patada en la lata, siendo la brevedad su característica clave. Funciona en Sierra pero aparentemente no tanto en Catalina.
use scripting additions
set rdat to «data RTF 7B5C727466315C616E73695C616E7369637067313235325C636F636F61727466313530345C636F636F617375627274663736300A7B5C666F6E7474626C5C66305C6673776973735C6663686172736574302048656C7665746963613B7D0A7B5C636F6C6F7274626C3B5C7265643235355C677265656E3235355C626C75653235353B7D0A7B5C2A5C657870616E646564636F6C6F7274626C3B3B7D0A5C706172645C74783732305C7478313434305C7478323136305C7478323838305C7478333630305C7478343332305C7478353034305C7478353736305C7478363438305C7478373230305C7478373932305C7478383634305C7061726469726E61747572616C5C7061727469676874656E666163746F72300A0A5C66305C66733336205C636630205C0A7D»
tell application "TextEdit"
set fs to (path to desktop) as text
set fn to choose file name default location alias fs -- include .rtf extension
set ndo to make new document with properties {text:rdat}
set bounds of window 1 to {160, 22, 883, 639}
save ndo in fn without replacing
end tell
tell application "Finder" to open fn
delay 0.5
tell application "TextEdit"
set last paragraph of document 1 to linefeed
end tell
En pocas palabras, ingresa un nombre de archivo y un documento con ese nombre y se crea un párrafo de tamaño predeterminado, luego se establecen los límites y se guarda, cierra y vuelve a abrir.
Notas: El uso de guardar así le avisará cuando ya exista un archivo con ese nombre. Incluir la extensión del archivo establecerá el tipo de documento en texto enriquecido. El texto de 'Configuración' puede proporcionar un método para configurar el punto de inserción. Desafortunadamente, TextEdit tiene algunos problemas al configurar el formato de esta manera y cerrar/reabrir es la única forma que conozco de evitarlo. Tomé prestado el 'rtf de datos' aquí de la respuesta del usuario 3439894.
error "Finder got an error: Handler can’t handle objects of this class." number -10010
-- Además, aunque el formato predeterminado de un documento de TextEdit es texto enriquecido, sin embargo, muchos usos lo configuran como texto sin formato, y cuando se establece en texto sin formato, su secuencia de comandos crea un texto sin formato document , no un documento de texto enriquecido como lo solicita el OP. Mi secuencia de comandos crea un documento de texto enriquecido independientemente de la preferencia de formato de TextEdit .
esfera de rubik
usuario3439894
on openDocument()
controlador en el código AppleScript para manejar si la extensión está oculta o no. El archivo debe crearse sin ocultarlo; sin embargo, si se oculta, el mod que hice para el controlador lo explica. Tenga en cuenta que podría haberlo dicho,set bounds of front window to {...}
pero lo escribí de esta manera para que solo actúe en la ventana nombrada, por lo que si por casualidad hay algún error, no se moverá ni cambiará el tamaño de otra ventana de TextEdit que pueda estar abierta al mismo tiempo.esfera de rubik
usuario3439894
return
declaración en elon createCustomRTFDocument()
controlador , por lo que debe actualizar su código de trabajo . Además, el«data RTF ... »
asignado acustomRTFDocumentTemplate
es solo un ejemplo de trabajo y debe reemplazarlo con«data RTF ... »
creado desde su sistema y por qué di instrucciones sobre cómo obtener esa información.esfera de rubik
set customRTFDocumentTemplate to «data RTF 7B5C72»
declaración (tuve que truncar la declaración en este comentario debido al límite de caracteres)? Lo he intentado:set myVariable to "7B5C72"
seguido deset customRTFDocumentTemplate to «data RTF myVariable»
. Pero no funciona.usuario3439894
write
comando como se muestra en mi respuesta. ¿Por qué necesita variabilizar los datos paracustomRTFDocumentTemplate
? Una plantilla es solo eso, una plantilla y, si necesita más de una plantilla, cree y codifique plantillas adicionales dentro del script .esfera de rubik
esfera de rubik
usuario3439894
else
bloque incorrecto . Está arreglado ahora.