Showing posts with label applescript. Show all posts
Showing posts with label applescript. Show all posts

Tuesday, April 14, 2009

How do I find paragraph marks and tabs in Pages?

If you want to search for paragraph marks, tabs or other special characters in Pages, you can do that in the search dialogue (Edit > Find > Find...) using the Insert... drop down.


If you prefer to use Applescript to find this kind of items, you can use the special keywords space, tab, return, linefeed and quote, for example like this:

tell application "Pages"
repeat with achar in characters of body text of front document
if contents of achar = return then
display dialog (character offset of achar as integer)
end if
end repeat
end tell

Sunday, February 10, 2008

How do I select all instances of font X?

Paste and run the following script in Applications > AppleScript > Script Editor:
tell application "Pages"
select (every character of body text of front document whose font name is "Times-Roman")
end tell
Note that the font name may not be what you expect. The script above searches for the font "Times", even though the name in the script is "Times-Roman". If you type just "Times", it will not work.

If you need help to see what font name AppleScript expects, mark the first word of Pages front document in the desired font, and run this script:
tell application "Pages"
display dialog (font name of word 1 of body text of front document as string)
end tell


(Sorry for the bad formatting above. Blogspot is not made to display source code. However, even if you cannot see the last characters on all rows, they should paste fine when you copy them.)

Saturday, February 09, 2008

Resizing pictures with AppleScript

If you resize a picture inside a Pages document, it will just look like it is smaller. In reality, it takes up as much diskspace as before. You have not lost any information. However, sometimes you really need to free up some diskspace, and you need to resize the picture for real. The most obvious tool to do this is Preview (Tools > Adjust size).

However, there are a few other options to use. The following is a script to resize pictures using AppleScript only. There is no real UI at all. It resizes the image to the value of "targetSize" - in this case 240. If you want to resize it to some other value, just change the script.

1. Open Applications > Utilities > Applescript Editor. (Path in older versions of Mac OS X: Applications > Applescript > Script Editor.)

2. Create a new script and paste the following code:
on open theImages
repeat with anImage in theImages
tell application "Image Events"
--Set the maximum dimension of the picture.
-- If it is in landscape mode, it is the width.
-- If it is in portrait mode, it is the height.
set the targetSize to 240
set currentImage to open anImage
set imageType to currentImage's file type
scale currentImage to size targetSize
tell application "Finder" to set newImage to (container of anImage as string) & "scaled " & (name of anImage)
save currentImage in newImage as imageType
end tell
end repeat
end open
3. Save the script as an "Application".

4. Drag your image to the new script Application.

You will get a new file with the new dimension.

If you prefer to scale to a certain percentage, use this script instead:
on open theImages
repeat with anImage in theImages
tell application "Image Events"
-- Set the variable targetSize to the scale factor. 0.5 means 50%.
set the targetSize to 0.5
set currentImage to open anImage
set imageType to currentImage's file type
scale currentImage by factor targetSize
tell application "Finder" to set newImage to (container of anImage as string) & "scaled " & (name of anImage)
save currentImage in newImage as imageType
end tell
end repeat
end open


The accepted image formats are BMP, JPEG, JPEG2, PICT, PNG, PSD, QuickTime Image and TIFF.

If you feel more comfortable with Automator, you can use that as well.

Wednesday, January 30, 2008

Export folder to Word, RTF, PDF, TXT or RTFD

This AppleScript to export the content of a folder with Pages documents was kindly created by Yvan Koenig. You can find more of his scripts at his Public iDisk. If you prefer to export a selection of files, you may want to have a look at the scripts in this post, which use a Scriptlet.

To use the script below, copy it all into a new script in ScriptEditor and run. Due to blogspot's layout, you may not see all characters here, but they should be copied properly, if you highlight all the non-proportional text below.
(*
Export pages documents as Word ones in the folder where the original docs where.

Assuming that we start with:
AppleScript & Office.pages
it will be exported as:
AppleScript & Office.doc
If a file already exist with the short name
it may be saved as:
AppleScript & Office#20080128T221639.doc (if withSeconds is defined as true)
AppleScript & Office#20080128T2219.doc (if withSeconds is defined as false)

the serial number is a packed version of the date/time of the save process:

2008/01/28T22:16:39 or 2008/01/28T22:16

Thanks to Dale GILLARD who teach me the way to export without using GUI scripting.

Yvan KOENIG
28 janvier 2008
29 janvier 2008
*)

property withSeconds : false (* you may set it to true if you wish *)
property typeNum : 1 (* 1 = WORD, 2 = PDF, 3 = Txt, 4 = rtf, 5 = rtfd *)

property newExt : ""
property newType : ""
property types : {{"doc", "SLDocumentTypeMSWord"}, {"pdf", "SLDocumentTypePDF"}, {"txt", "SLDocumentTypePlainText"}, {"rtf", "SLDocumentTypeRichText"}, {"rtfd", "SLDocumentTypeRichTextBundle"}}

tell application "Finder" to set listeFichiers to every item in (choose folder) (*
dans un bloc Finder pour avoir un titre de dialogue "localisé"
• in a Finder block to get a localized dialog title. *)
if (count of listeFichiers) = 0 then return
open listeFichiers

-- ===========

on open (sel)
repeat with elem in sel
my exploreTraite(elem as alias, "")
end repeat
end open

-- ===========

on exploreTraite(elem, ptree) (*
elem est un alias
elem is an alias *)
local elem_, cl_, typeId_
set elem_ to elem as text
tell application "System Events"
set cl_ to class of item elem_
set typeId_ to type identifier of elem
end tell
set cl_ to cl_ as Unicode text

if cl_ is "file package" then
if typeId_ is "com.apple.iwork.pages.pages" then my TraiteUnPackage(elem_, ptree)
else if cl_ is "folder" then
my ExploreUnDossier(elem_, ptree)
else
-- not for us
end if -- cl_ is …
end exploreTraite

-- ===========

on ExploreUnDossier(dossier, ptree)
local nomElement, cheminElement, c
repeat with nomElement in list folder dossier without invisibles
set cheminElement to dossier & nomElement
tell application "Finder" to set c to name of (dossier as alias)
my exploreTraite(cheminElement as alias, ptree & c & ":")
end repeat
end ExploreUnDossier

-- ===========

on TraiteUnPackage(aPackage, ptree)
local docPathAndName, oldName, docName, newExt, newType
(* aPackage always ends with a colon, we must remove it *)
set aPackage to (text 1 thru -2 of (aPackage as Unicode text)) as alias

set {newExt, newType} to types's item typeNum
tell application "Finder"
set sourceFolder to (container of aPackage) as Unicode text
set oldName to name of aPackage as Unicode text
end tell -- Finder
set docName to (text 1 thru -6 of oldName) & newExt
set docPathAndName to sourceFolder & docName

tell application "System Events"
if exists file docPathAndName then
set docName to (text 1 thru -7 of oldName) & my serialize() & "." & newExt
set docPathAndName to sourceFolder & docName
end if
end tell -- system events

tell application "Pages"
open aPackage
save front document as newType in docPathAndName
close front document
end tell -- Pages
end TraiteUnPackage

-- =============

on serialize()
local cd, serial
set cd to current date
set serial to (year of cd as text) & text -2 thru -1 of ("0" & (month of cd as number)) & text -2 thru -1 of ("0" & day of cd) & "T" & text -2 thru -1 of ("0" & hours of cd) & text -2 thru -1 of ("0" & minutes of cd)
if withSeconds then
return "#" & serial & text -2 thru -1 of ("0" & seconds of cd)
else
return "#" & serial
end if
end serialize

Tuesday, January 22, 2008

How do I add keyboard shortcuts?

To see Pages' keyboard shortcuts, you can go to the Help menu > Keyboard Shortcuts.

Just like in any other Mac OS application, you can also see at the end of each menu command, if there is shortcut for it.



To add your own shortcuts to menu items follow these steps
  1. Go to System Preferences > Keyboard & Mouse > Keyboard Shortcuts.
  2. Click on the + symbol.
  3. Select Pages from the Application list. The first time you will have to select the last value, "Other...", to add Pages to the list, as the list by default only contains applications directly in the Applications folder. Applications in sub-folders have to be added manually.
  4. Type the exact name of a menu command, for example "Export..."
  5. Press a keyboard combination including shift (⇧), control (⌃), alt (⌥) and/or command (⌘) and one other key, for example ⌃⌥⇧⌘E.
  6. Click "Add".



From now on Pages accepts ⌃⌥⇧⌘E as a shortcut to bring up the Export window, which you can see by pulling down the menu again.



There are some things to think about here. You can basically only assign shortcuts to menus. You can for example not add shortcuts to items in the inspector. Even though you can write "macros" for Pages using AppleScript, there is no way to assign shortcuts to the macros, as they reside in the Finder. However, you can assign "hotkeys" to Styles by clicking on the triangle next to the name in the Styles Drawer.

If there are several menu items with the same name, only one of them will get the shortcut.

If you change language in System Preferences, the shortcut will no longer work.

Sunday, January 20, 2008

How do I change the default zoom?

New documents always come up with the same zoom value (the percentage in the lower left corner of the document window). Sometimes that is far too big or far too small, so you may want to change it.

The simplest and safest way is to go to the menu Pages > Preferences, and change the Default Zoom value.

However, you may want to change it to a value that is not in the preferences dialogue, let's say 99%, for the sake of argument.

If you want to change the zoom for the current document only, you can use an AppleScript:

tell window 1 of application "Pages"
set view scale to 99
end tell

If you want to change the default value for all new documents, and you are willing to take a certain risk, you can manually edit the file ~/Library/Preferences/com.apple.iWork.Pages.plist and set the parameter SLDefaultsPageScale to 0.9900000 (for 99%).

In Mac OS X before 10.7, you can also run the following command in the terminal. (Copy the entire line until 0.99 - not only what is visible. Blogspots HTML hides the end of the line.)
defaults write com.apple.iWork.Pages SLDefaultsPageScale 0.99

Tuesday, January 08, 2008

How do I create macros in Pages?

The way to create macros in Pages 3.0 is to use AppleScript.

Unfortunately, Pages is not recordable, unlike some programs where you can record a series of actions you perform into an editable script. For Pages you will have to create your scripts manually.

To see what kind of things can be done with Pages, open Applications > AppleScript > Script Editor, and go to the menu File > Open Dictionary > Pages.

To see some examples of scripts people already have made for Pages, make a Google search for "tell application pages".

To get a list of resources about AppleScript in general, use for example Wikipedia.

There is currently no way to add menus or buttons with your own scripts to Pages' menus or toolbars.


Pages' AppleScript dictionary as displayed in Script Editor.

Tuesday, November 27, 2007

How do I see what my fonts look like?

From Pages '09, you can see WYSIWYG font previews in the Format Bar font menu. Just make sure that you have the preferences right: Pages > Preferences > Show font preview in Format Bar font menu. To switch between WYSIWYG and standard font names, hold down the alt-key, as you click on the menu.

In previous versions this was not possible, but there were some other options that worked fairly well - some would say better.

Use the Font palette header

Follow these steps:
  1. Display the Font palette using ⌘-T or the menu Format > Fonts > Show Fonts.
  2. Click on the wheel in the lower left corner and choose "Show Preview".
You will get a preview of the currently highlighted font.

To easily scroll between the fonts, first put your cursor in the search field. This will take the focus away from your main document. Then highlight a font and scroll up and down with the arrow keys.

Use the Font palette Favorites


Select the collection "Favorites". It lists the latest font families you used, and it shows them in the last used Typeface and Size.

Use an Apple Script

Follow these steps:
  1. In the Finder, go to Applications and open Font Book.
  2. In Font Book, highlight all fonts (or the ones you are curious about).
  3. In the Finder, go to Applications > AppleScript > Example Scripts > Font Book and double click on Create Font Sample.scpt. It will open in Script Editor.
  4. In Script Editor click on "Run".
  5. Wait.
After some time, you will have a document in TextEdit that contains samples of all your Typefaces in all your fonts. Save it for future reference.

Use Font Book

Font Book is an important tool for at least two purposes. One - display what your fonts look like. Two - organise your fonts.

The main reason Apple has not included WYSIWYG font displays in Pages or the Font Palette is that it would be next to impossible with all the fonts we have today. You would have to scroll for ever - up and down, looking for a font that fits your needs. You would forget the name of one you saw and you would have to start over again.

WYSIWYG font menus worked on the first Macs, when the average user had no more than six fonts, but today the average user has several hundreds.

If you are serious about finding the most perfect font in this hay stack, use Font Book collections. It does not cost anything, and they are easy to remove, when no longer needed.

Create a collection for for example sans serif fonts, another for good body text fonts, another for Chinese fonts, and so on. It will be much easier to compare Monaco and Andale Mono, if they are in the same small collection, than if you have to scroll 150 fonts to get from one to the other. For more hints how to create collections, check this post.

Tuesday, November 06, 2007

Which are the document types used by Pages in Applescript?

The document types used by Pages under Mac OS X 10.5 (Leopard) are defined in the Pages package Content/Info.plist under the tags CFBundleDocumentTypes > [a number] > CFBundleTypeName. They are the following ones:
  • SLDocumentTypeRichText
  • SLDocumentTypeRichTextBundle (rtfd)
  • SLDocumentTypePlainText
  • SLDocumentTypeSimpleText
  • SLDocumentTypeMSWord
  • SLDocumentTypePDF
  • SLDocumentTypeAppleWorks
Not all of them can be used in Applescript to export documents. There are the same limitations as for Export using the Share > Export dialogue. To see how they can be used, see this example.

Saturday, October 13, 2007

How do I change all red text to blue?

If you have applied the same colour in a lot of places in a document and want to change them all at once, you can run the following AppleScripts.

First you want to know the code of the colour you have. Put the cursor in a coloured word and run this script in Applications > AppleScript > Script Editor.

tell application "Pages"
tell front document
set S to selection
tell body text
set C to color of character before S
display dialog (((item 1 of C) as text) & ", " & ((item 2 of C) as text) & ", " & ((item 3 of C) as text))
end tell
end tell
end tell

Then run the following AppleScript, after you have changed the example colours to the ones you found running the previous script:

tell application "Pages"
repeat with achar in characters of body text of front document
if color of achar = {53355, 23, 54} then
set color of achar to {23, 54, 53355}
end if
end repeat
end tell

Friday, October 05, 2007

How do I make Pages autosave my documents?

With the new Mac OS X, Lion, released in July 2011, Pages '09 automatically saves all open documents using Auto Save and Versions. The basic functionality is very easy: open the document, edit, close. That's it. To use Versions and the more advanced functionality, it is a good idea to have a look at Apple's description of the functionality.

However, the autosave functionality is not problem free. There have been reports of people who have lost some data. The data is not autosaved continuously, but at regular intervals, and if you crash your machine between those intervals, text will obviously be lost.

For older versions, there was a problem, which is described below:

Pages '09 before Mac OS X Lion could not automatically save documents, so if you had typed for 5 hours without saving and there is a power failure, you would have lost all your work.

The safest way to handle this is to press ⌘-S to save the document manually as often as possible.

For those who do not trust themselves to remember this, there are a few Applescripts to do this at Apple's discussion forums, for example here and here.

Sunday, December 10, 2006

How do I reference a cell in one table from another one in a formula?

In Pages 5 (2013) you enter a formula (Insert > Function > Formula Editor) and click on the other table, and a table reference (usually something like "Table 1::A1:A2" will be added automatically.

However an imported Word document with referenced tables does not get converted properly. If you import that document to Pages, you will see that the cross reference is removed. How to do it in MS Word is described in MS Office help. It is not that easy, but you enter formulas from the Table menu and you have to add bookmarks to tables to be able to reference them.

In Pages 4.3 or earlier, this does not seem possible - not even using Applescript. If you open the Applescript dictionary for tables in 4.3, you can see that a table has no properties that are not also properties of graphics. This unfortunately means that a table works like a black box, whose content cannot be reached by the outside world.

Saturday, November 04, 2006

I have one thousand Pages documents to give to someone with Windows. How do I convert them all?

Open Applications > Applescript > Script Editor.

If you have Pages 3.0 and Mac OS X 10.5 (Leopard) create a new script and paste the following code:

on open theFiles
tell application "Pages"
repeat with aFile in theFiles
open aFile
set docName to name of front document
-- Remove .pages extension.
set prevTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to ".pages"
-- Add .doc extension.
set docName to first text item of docName & ".doc"
set AppleScript's text item delimiters to prevTIDs
-- Save file to Desktop.
set docPathAndName to (path to desktop as string) & docName
save front document as "SLDocumentTypeMSWord" in docPathAndName
close front document
end repeat
end tell
end open

If you instead have Pages 2.0 and Mac OS X 10.4 (Tiger) create a new script and paste the following code:

on open theFiles
tell application "Pages"
repeat with aFile in theFiles
open aFile
set docName to name of front document
-- Remove .pages extension.
set prevTIDs to AppleScript's text item delimiters
set AppleScript's text item delimiters to ".pages"
-- Add .doc extension.
set docName to first text item of docName & ".doc"
set AppleScript's text item delimiters to prevTIDs
-- Save file to Desktop.
set docPathAndName to (path to desktop as string) & docName
save front document as ".doc" in docPathAndName
close front document
end repeat
end tell
end open

In both cases, save the script as an "Application".

Drag your 1000 Pages documents to the new file.

Sit back and wait for all the files to be processed.

Part of this code written by Dale Gillard of dmg software. Thanks Dale!

In case you wonder where the document type "SLDocumentTypeMSWord" is defined, it can be found in the Pages package Contents/Info.plist. Look for the node CFBundleDocumentTypes and number 6. The other numbers refer to other document types you also can use in this kind of script.

In case you want to convert AppleWorks documents to Pages, Yvan Koenig published an AppleScript to do just that at Apple's discussion forums.

In case you want to convert to PDF instead of MS Word, you can easily change the scripts above to do just that. If you are on Mac OS X 10.4, replace ".doc" with ".pdf". If you are on Mac OS X 10.5, replace "SLDocumentTypeMSWord" with "SLDocumentTypePDF". You can also use this script by Yvan Koenig.

If you want to export all files in a folder back to the same folder can also use the script by Yvan Koenig.