TextEdit -- How to Center justify text in output

set MM to month of (current date)
set DD to day of (current date)

set wday to weekday of (current date)

set TT to time string of (current date)
tell application “TextEdit”
activate
make new document at the front
set dataString to “JO TODAY IS:” & return & return & wday & " " & MM & " " & DD & return & return & “The Time is now:” & return & return & TT
set the text of the front document to dataString
set the font of the front document to "adobe garammond Pro "
set the size of the front document to 48
set the color of the front document to {32768, 0, 32768}
delay 8
tell application “TextEdit” to close (windows where name of its document is “Untitled”) saving no
–tell application (path to frontmost application as text) to close window 1 saving no
end tell


Model: MacBookPro
AppleScript: 2.7 script Edit
Browser: Safari 601.7.7
Operating System: Mac OS X (10.10)

You may try :

set MM to month of (current date)
set DD to day of (current date)

set wday to weekday of (current date)

set TT to time string of (current date)
tell application "TextEdit"
	activate
	make new document at the front
	set dataString to "JO   TODAY  IS:" & return & return & wday & "   " & MM & "   " & DD & return & return & "The Time is now:" & return & return & TT
	set the text of the front document to dataString
	set the font of the front document to "Apple Garamond BT" --"adobe garammond Pro "
	set the size of the front document to 48
	set the color of the front document to {32768, 0, 32768}
	--delay 8
	--tell application "TextEdit" to close (windows where name of its document is "Untitled") saving no
	--tell application (path to frontmost application as text) to close window 1 saving no
	--tell application "TextEdit" to close window 1 saving no
end tell

tell application "System Events" to tell process "TextEdit"
	set frontmost to true
	tell window 1
		keystroke "a" using {command down}
		size of groups --> {{565, 26}}
		tell group 1
			-- class of UI elements --> {menu button, pop up button, pop up button, combo box, color well, color well, group, radio group, pop up button, menu button}
			tell radio group 1
				-- class of UI elements --> {radio button, radio button, radio button, radio button}
				-- accessibility description of UI elements --> {"aligner à gauche", "centrer", "aligner à droite", "justifier complètement"}
				click radio button 2
			end tell
		end tell
	end tell
end tell

Oops, there is more efficient, I forgot the menu Format > Center.

set MM to month of (current date)
set DD to day of (current date)

set wday to weekday of (current date)

set TT to time string of (current date)
tell application "TextEdit"
	activate
	make new document at the front
	set dataString to "JO   TODAY  IS:" & return & return & wday & "   " & MM & "   " & DD & return & return & "The Time is now:" & return & return & TT
	set the text of the front document to dataString
	set the font of the front document to "Apple Garamond BT" --"adobe garammond Pro "
	set the size of the front document to 48
	set the color of the front document to {32768, 0, 32768}
	--delay 8
	--tell application "TextEdit" to close (windows where name of its document is "Untitled") saving no
	--tell application (path to frontmost application as text) to close window 1 saving no
	--tell application "TextEdit" to close window 1 saving no
end tell

tell application "System Events" to tell process "TextEdit"
	set frontmost to true
	tell window 1
		keystroke "a" using {command down}
		keystroke "=" using {command down}
	end tell
end tell

Yvan KOENIG running El Capitan 10.11.6 in French (VALLAURIS, France) dimanche 14 aout 2016 10:08:36

Hi Yvan.

On my GB system, TextEdit’s keystroke for centring is Command-“|” (vertical bar):

tell application "System Events"
	set frontmost of application process "TextEdit" to true
	keystroke "a" using {command down}
	keystroke "|" using {command down} -- Centre.
	key code 124 -- Move the cursor to deselect the text.  :)
end tell

Thanks, I learn’t two things.
– the use of key code 124 to deselect the text
– the different shortcuts
I assume that the difference is due to the fact that there is a key with the vertical bar on your physical keyboard but no such key on French ones.

Here is a version adjusting its behavior.

tell application "System Events"
	set frontmost of application process "TextEdit" to true
	keystroke "a" using {command down}
	if (do shell script "defaults read 'Apple Global Domain' AppleLocale") does not start with "fr_" then
		keystroke "|" using {command down} -- Center.
	else
		keystroke "=" using {command down} -- Centre.
	end if
	key code 124 -- Move the cursor to deselect the text.  :)
end tell

I tested also a “dirty one”:

tell application "System Events"
	set frontmost of application process "TextEdit" to true
	keystroke "a" using {command down}
	keystroke "|" using {command down} -- Center on some settings.
	keystroke "=" using {command down} -- Centre sur système français.
	key code 124 -- Move the cursor to deselect the text.  :)
end tell

It behaves well on my french system. Don’t know for English ones.

Yvan KOENIG running El Capitan 10.11.6 in French (VALLAURIS, France) lundi 15 aout 2016 14:02:40

Hi Yvan.

Your “clean” version’s better. Command-“=” has the same effect as Command-“+” on English systems: it increases the text size. (“=” and “+” are on the same key.)

Thanks Nigel.

But = and + are on the same key here too.
The difference is that here, to get + we must press the shift key when you do that to get = :frowning:

The problem with the ‘clean’ version is that I’m not sure that only application working in french use the vertical bar.

Yvan KOENIG running El Capitan 10.11.6 in French (VALLAURIS, France) lundi 15 aout 2016 16:40:57

Actually, “+” is the shift value here too. It’s just a local pecularity that Command-“=” produces the same effect as Shift-Command-“=”. :confused:

Here’s another approach, using ASObjC:

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

main()

on main()
	set {month:MM, day:DD, weekday:wday, time string:TT} to (current date)
	
	-- Set the text and font attributes in a new TextEdit document.
	tell application "TextEdit"
		activate
		set newDoc to (make new document at the front with properties {text:"JO   TODAY  IS:" & return & return & wday & "   " & MM & "   " & DD & return & return & "The Time is now:" & return & return & TT})
		tell newDoc's text
			set its font to "Apple Garamond BT" --"adobe garammond Pro "
			set its size to 48
			set its color to {32768, 0, 32768}
		end tell
		--delay 8
		--tell application "TextEdit" to close (windows where name of its document is "Untitled") saving no
		--tell application (path to frontmost application as text) to close window 1 saving no
		--tell application "TextEdit" to close window 1 saving no
	end tell
	
	-- Select and copy the results to the clipboard.
	tell application "System Events"
		set frontmost of application process "TextEdit" to true
		keystroke "ac" using {command down}
	end tell
	
	-- Get the clipboard contents, change the justification to centred, and put back onto the clipboard.
	delay 0.5
	set |⌘| to current application
	set theClipboard to |⌘|'s class "NSPasteboard"'s generalPasteboard()
	set clipboardContents to (theClipboard's readObjectsForClasses:({|⌘|'s class "NSAttributedString", |⌘|'s class "NSString", |⌘|'s class "NSImage", |⌘|'s class "NSURL", |⌘|'s class "NSColor"}) options:({}))'s mutableCopy()
	set theAttributedString to clipboardContents's firstObject()'s mutableCopy()
	tell theAttributedString to setAlignment:(|⌘|'s NSTextAlignmentCenter) range:({location:0, |length|:its |length|()})
	tell clipboardContents to replaceObjectAtIndex:(0) withObject:(theAttributedString)
	tell theClipboard
		its clearContents()
		its writeObjects:(clipboardContents)
	end tell
	
	-- Paste back into TextEdit over the existing selection.
	delay 0.5
	tell application "System Events"
		set frontmost of application process "TextEdit" to true
		keystroke "v" using {command down}
	end tell
end main

Hello Nigel.

No need to paste.
You may use :

	(*
	tell application "System Events"
		set frontmost of application process "TextEdit" to true
		keystroke "v" using {command down}
	end tell
	*)
	tell application "TextEdit" to tell document 1
		set its text to (get the clipboard as «class RTF »)
	end tell

Yvan KOENIG running El Capitan 10.11.6 in French (VALLAURIS, France) lundi 15 aout 2016 20:01:47

Thanks, Yvan. That’s great! :slight_smile:

You’re working a bit harder than you need to.

There’s no need to deal with all those types; the clipboard will sort things out:

set theClipboard to |⌘|'s class "NSPasteboard"'s generalPasteboard()
set clipboardContents to (theClipboard's readObjectsForClasses:{|⌘|'s class "NSAttributedString"} options:({}))'s mutableCopy()
set theAttributedString to clipboardContents's firstObject()'s mutableCopy()
tell theAttributedString to setAlignment:(|⌘|'s NSTextAlignmentCenter) range:({location:0, |length|:its |length|()})
tell theClipboard
	its clearContents()
	its writeObjects:{theAttributedString}
end tell

And here’s another approach, no clipboard:

use AppleScript version "2.4" -- Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

set MM to month of (current date)
set DD to day of (current date)
set wday to weekday of (current date)
set TT to time string of (current date)
set dataString to "JO   TODAY  IS:" & return & return & wday & "   " & MM & "   " & DD & return & return & "The Time is now:" & return & return & TT
set theFont to current application's NSFont's fontWithName:"AGaramondPro-Regular" |size|:48
set theColor to current application's NSColor's colorWithRed:0.5 green:0 blue:0.5 alpha:1.0
set parStyle to current application's NSParagraphStyle's defaultParagraphStyle()'s mutableCopy()
parStyle's setAlignment:(current application's NSTextAlignmentCenter)
set styleDict to current application's NSDictionary's dictionaryWithObjects:{theColor, theFont, parStyle} forKeys:{current application's NSForegroundColorAttributeName, current application's NSFontAttributeName, current application's NSParagraphStyleAttributeName}
set styledText to current application's NSAttributedString's alloc()'s initWithString:dataString attributes:styleDict
set theRTFData to styledText's RTFFromRange:{0, styledText's |length|()} documentAttributes:(missing value)
theRTFData's writeToFile:"/users/shane/Desktop/Testing.rtf" atomically:true
tell application "TextEdit" to open ("/users/shane/Desktop/Testing.rtf" as POSIX file)

Thanks, Shane!

The code I used was cannibalised from a library with which I’ve been doodling, which restores the clipboard contents after the pasting’s done. I forgot in the current case that it’s only necessary to bother with the NSAttributedString, since the original contents aren’t being restored.

Apart from the saving to file, your code for building the styled text from scratch in ASObjC is similar to that in my library. (It’s giving me an “unrecognized selector” error in the ‘set theRTFData’ line, which may be connected with the fact that I don’t have the specified font on my machine.) I didn’t go that route in my script above because it involved more work and I didn’t want to lose the OP completely. :wink:

I’ve noticed with pasting that it can alter colours slightly. For instance, if I set up puzzled’s document with the colour {32768, 0, 32768}, copy the text, and immediately paste it back in, the colour in the document becomes {32896, 0, 32896}. Sometimes the difference is noticeable, sometimes not. :confused:

Edit: Further testing confirms that the error I was getting with Shane’s ASObjC script was due to my not having the specified font. Also ” as with my own library, and despite pasting not being involved ” the colour in the document is not the colour specified in the script. :confused:

It might be better using +colorWithCalibratedRed:green:blue:alpha:, or perhaps +colorWithDeviceRed:green:blue:alpha:.

The colour anomaly turns out to be due to the intervening RTF, in which colour component values are graded from 0 to 255 ” as opposed to 0 to 65535 in AppleScript and 0.0 to 1.0 in ASObjC. When a component value’s converted to RTF, it’s quantised to the nearest 255th of the scale. When TextEdit gets the RTF text from the clipboard or from an RTF file, it multiplies each component by 257 ” at least, for the AppleScript representation. (255 * 257 = 65535.) All of TextEdit’s “received” colour components are exact multiples of 257. puzzled’s document, when created with AppleScript, will have the colour {32768, 0, 32768} as long as it’s open. But if it’s saved, closed, and reopened, the colour will have changed to {32896, 0, 32896}.

The calibrated versions of colours are what end up on the clipboard when text is copied from TextEdit (according to ASObjC Explorer :slight_smile: ) and +colorWithCalibratedRed:green:blue:alpha: is the method which produces the same results as saving and reopening TextEdit documents.

Interesting. I believe Sierra is introducing extended color ranges for .rtf, for the newer displays to take advantage of.