Main Help → Writing Extensions → Scripting Commands
Many commands are available that let you interrogate documents or records for information or do miscellaneous calculations and other actions. Most commands are available when using Internal Scripts, AppleScript, Python scripts. Some special any new commands are defined for Internal Scripting only.
All of GEDitCOM II's scripting commands, in alphabetical order, are listed below. Click each command for details. Also see general command about all commands below the table.
Documentation for each command lists which objects support that command. Required arguments are listed with the command; optional arguments are enclosed in square brackets. Commands that work in AppleScript are defined by the AppleScript useage style. Each of these commands is followed by the format needed to use them in Internal Scripts or Python scripts. When using Internal scripts, optional arguments (in square brackets) can be omitted only if all prior arguments are provided. When using Python, all arguments must be supplied, but you can usually specify None (in Python) for optional arguments that are not needed.
Some commands only became available in certain versions of GEDitCOM II or GEDitCOM; this condition is indicated with "(since x.y/a.b)" where "x.y" is the GEDitCOM II version needed and "a.b" is the GEDitCOM version needed. Any command or feature not labeled should available in any version, although Internal Scripts always require 3.0/1.0.
Note that numerous commands are designated as "Internal Script use only." Although such commands are not available to AppleScript or Python scripts, most of those commands can be accomplished in those languages by other methods (e.g., working with lists or dictionaries).
Commands in internal scripts have one of two formats:
command (arg1),(arg2),[(arg3)],... (object).command (arg1),(arg2),[(arg3)],...
The first is a "direct" commmand that is used without reference to any object. The second is a command specific to an object. The object targeted by the command is determined by the object specifier in (object). Two common methods to target and object are to use just an object name or a variable that contains just an object name:
indi.listAncestors alist,5 #ref="indi" ^#ref.listAncestors atlist,5
Here indi is object name for an individual record. The first method uses the object's name. The second uses caret '^' in front of variable that contains the object name. These are common methods to target objects but the object specifier can use multiple (atom)'s too. Whenever the object specifier uses a variable in the (root) element, however, it must be prefaced with a caret '^' symbol.
All command arguments (e.g., (arg1), (arg2), ...) are evaluated first as an expression and the expression result is passed to the command. Some consequences of this process are:
"(object1)", "(object2)", etc.). Objects for command arguments are passed using a quoted object specifier, although quotes can be omitted if passing just an object's name (or an expression that evaluates to an object's name or an object specifier)."#var", but alternatively can be an string expression that evaluates to a variable name. This method of passing variable names to a command is analogous to pointers in other languages:
#ref = "#var" command #refAlthough the Internal Scripting language does not require variables to start with
#, variable names passed to scripting commands for a returned result are required to being in #.
objName) to be passed as a string expression that evaluates to the object's name. Because object names cannot start in #, if you follow the suggestion to always start variables with #, the object names can be passed unquoted."#var" passed to a command must start with a # sign is to guarantee such commands can distinguish between variable and object names in the first parameter.Important: Targeting a command with an invalid object (i.e., (object).(command) where (object) is a failed object specifier>) or passing an invalid object to a command that expects an object will normally cause an error that ends the script. Such errors can be trapped by testing the object first using:
@objName = "(object)"If (object) in either option is a failed specifier, these options will set objName to a None object. These commands can therefore validate any object before targeting it with other commands or using it an "@" expressions to read an object property. For example, if you are accessing albums by name, but not sure that the album exists, you can use following code to avoid aborting the script with an invalid object reference:
#name="My Album" @album = "gcapp.documents.0.albums.#name" ifDef album ! album found and can use it else ! album not found, decide what to do endif
name (it will be called "New Album" if name is not provided).(object#) is an invalid object specifier. Use addObject to add a list as a single object to another list.(object) is a document. This command then adds a new record of type (type) to the document and sets objName to the new record's object. (type) is GEDCOM record type code such as INDI, FAM, SOUR, NOTE, etc. When adding INDI records, (info) can be "male" or "female" to set sex of the individual. When adding _PLC records (custom place records), (info) can be a place name and and it should be unique in the file (if not, a number will be added to make it unique. If (type) is not a standard GEDCOM record type or one of the custom GEDitCOM II record types, the new record will be added as a custom record type.(object) is an album. This command then adds one or more GEDCOM records defined by (object#) to the album. If any (object#) is a list or GC list, the GEDCOM records in those lists are added to the album. Any objects in a list that are not GEDCOM records are skipped. No errors are caused by trying to add non-records or using a list that has no GEDCOM records. A script can check if the command added any records by checking the album count property before and after the command.(struct) to the new structure, and then add it to the target object. The structure's tag and contents are required. The level is automatically set to one higher than the target object. The new structure is added at the optional (index) in subordinate structures or after structure (after) in subordinate structures depending on if the optional argument is an number or an existing object. If the last argument is omitted, the structure is added at the end of the subordinate structures (using optional (after) since 3.2/1.0).action argument, which is the text to follow "Undo" in the undo menu item text. If you use a begin undo command, you must provide the matching end undo command. The undo grouping can be disrupted by dialog boxes, meaning you should not use the display dialog or other user input commands within an undo grouping.(object).beginUndo and (object).endUndo (action)beginUndo(), endUndoAction_("script changes")get every individual rather then getting them one at a time). This command lets you read any amount of properties from a collection of objects in a single function call. It can help to increase the efficiency of long scripts. The target argument is a list of objects and selector argument is a list of properties (from the AppleScript dictionary for GEDitCOM II objects). This command will find all requested properties for each target object. The returned result will list of lists. There will be one sublist for each property in selector. Each sublist will match the length of target and will have that property for each object in target. When the data you want is not available in a property, you can set an item of selector to "evaluate" and provide argument list where the corresponding item of argument is an expression to find the data. When argument is provided, it must have the same length as selector. For items of selector that are not "evaluate", the corresponding item of argument should be an empty string.
tell front document
set props to {"birth date", "death date", "evaluate"}
set args to {"", "", "DEAT.CAUS"}
set indis to every individual
set bd to bulk reader target indis selector props argument args
end tell
The corresponding AppleScript to read the same data without using bulk reader would be:
tell front document
set bd to {{}, {}, {}}
repeat with indi in every individual
tell indi
set end of item 1 of bd to birth date
set end of item 2 of bd to death date
set end of item 3 of bd to (evaluate expression "DEAT.CAUS")
end tell
end repeat
end tell
In both cases, bd will be something like {{"4 JUL 1776", "15 AUG 1843", ...}, {"15 SEP 1854", "29 FEB 1904", ...},{"", "Cancer", ...}}, but the bulk reader method will get the same data faster, especially in large files.bulkReaderSelector_target_argument_(selector,target,argument)
true or false if the target record for the command can link to the specified record type (by GEDCOM tag for the record type). In other words, the specified record type can "move to" the target record.(object).canLink "#var",(type) set #var to "true" or "false" if can link to record type in (type)canLinkRecordType_("SOUR")
(type) (e.g., INDI, FAM, etc.) in a document to empty.(object). The optional argument only applies when object is a document. It can be "no" (or "false") to close the document without saving, "yes" (or "true") to save before closing the document, or a path to a file with extension ".gedpkg" to save document under that new name. For safety, the file at provided path must not exist (i.e., it will not overwrite existing files). Also, "yes" only works for previously saved files. Untitled files (such as after opening a ".ged" file with an OpenFile command) will only be saved if you provide a valid save path. (closing documents since 3.1b4/1.0)(object).closeChild ["#var"] - #var, which is optional, is set to closed window's title (since 3.2/1.0).closeChild()
(PathToFolder) to a zip file. The variable #var is set to the resulting zip file name, which will be folder name plus .zip and possibly with an inserted number, if needed, to avoid overwriting an existing file. Note that .gedpkg files created by GEDitCOM II are actually folders and therefore can be compressed with this commandpathToFoldermust be a full POSIX path (a path with folders separated by /'s) to a folder (which need not exist yet). The two optional arguments correspond to settings for steps #3 and #4 in the multimedia consolidation process. See GEDitCOM II help for more details on multimedia consolidation and both default to true.
(object).consolidateMultimedia (pathToFolder),[(preserve)],[(links)] (since 3.2/1.0)consolidateMultimediaToFolder_changeLinks_preservePaths_("pathToFolder",True,False) - use capitalized True or False in Python.
destination argument. The destination file must be specified by a full POSIX path (a path with folders separated by /'s). The specified file must not exist, otherwise the command will return an error.(object).copyFile "#result",(destination) - if successful, #result will be empty. If an error, it will be "cannotCopy" if no file for copying (including multimedia as a URL link) or "copyFailed" if file found, but could not be copied (most common reasons are a file at provided path already exists or you do not have permission to write at that location) (since 3.1/1.0).copyFileDestination_("/Users/myhome/path/tofile")
gcapp.get doc,"frontDocument") to get object for the new document.objName to that list. The command can include any number of expressions and/or quoted object specifiers and they are all added to the new list (using specifiers since 3.5/1.0). Note that failed object specifiers will add text of the specifier as a string instead of causing an error. Use addObject after creating the list to validate object specifiers before adding them to the list. See here for information on working with lists.objName to that dictionary. See here for introduction working with dictionaries.(objName) is the object name assigned to the ScriptOutput object and (title) is the title for the window when the results are opened in a report window. The optional (style) is the style of the report and can be "html" (which is the default), "monospace", or "plain text". See internal scripting of reports for more details on using ScriptOutput objects to create reports.(expr) to the cascading style sheet (CSS) for the current ScriptOutput. All such text will be added to the report by the write command.dateformat(date) string function in expressions insteaddateFormatFullDate_("1 AUG 1291")DateNumbers "#var",(date) - final result in #var[1] to #var[6] with #var[0] set to number of parts founddateNumbersFullDate_("2 JUL 1776")DateParts "#var",(date) - final result in #var[1] to #var[5] with #var[0] set to 5. An invalid date will have #var[0]=1 and an error message in #var[1].datePartsFullDate_("FROM 2 JUL 1776 TO 6 JUL 1776")DateStyle "#var",(date),[(format)] - set #var to the formatted datedateStyleFullDate_withFormat_("2 JUL 1776", "%d %M %y %b")DateText "#var",(sdn),[(format)] - set #var to the formatted datedateTextSdn_withFormat_(2455032,"%d %M %y %b")#today$ insteaddateToday()dateyear(date) string function in expressions insteaddateYearFullDate_("2 JUL 1776")@recs = "gdoc.selectedRecords" recs.0.delete ! instead of @rec = "recs.0" rec.deleteThe first removes the record from the
recs list while the second does not (although you could manually remove it with "recs.remove 0" if needed).(PathToFiles)'s.Name: Joseph Smith Born: 23 Dec 1805 in Sharon, VT Died: 27 Jun 1844 in Carthage, ILor in a narrative style:
Joseph Smith was born 23 Dec 1805 in Sharon, VT. He died 27 Jun 1844 in Carthage, IL.The optional
output options are provided in a list with short, quoted codes. Some codes have meaning only for certain records. The meanings of the codes are:
Joseph Smith was married to Emma Hale.(applies to all except HEAD, SUBN, and SUBM)
Joseph Smith was married to Emma Hale.(applies to all except HEAD and SUBN)
html document such as a custom report and it therefore converts certain characters for safe html display. The use of either "LINKS" or "MAINLINK" implies html and thus "HTML" is not needed. It is only needed when neither "LINKS" nor "MAINLINK" are used, but you still want html output (applies to all records).(object).description "#theVar",(options) where options is an valid list of the above options.objectDescriptionOutputOptions_(list_variable)
spouse argument by "husband", "wife", or "both".(object).detach "(object1)" where (object1) specfies a spouse or child in the family or can be "husband", "wife", "both", or id of any child in the family (note these options fail if an existing object name is "husband", "wife", or "both"). Only one person can be detached with each commmand.detachChild_spouse_(theIndividualOrID,"husband")
(object) and the single argument (object1) must be albums. This command will then remove any records in the target album that are in the other album. The album in (object1) is left unchanged.byName, which is an album name, or byType, where type is the GEDCOM record tag such as INDI, FAM, etc.) in the main index window for the document. The optional argument sorting will additionally sort the records by the column identified with the expression given with the argument. If neither byName nor byType is specfied, the sorting option will sort the current list in the main index window.(object).display (byName),[(byType)],[(sorting)] - to display by type set (byName) to empty string.displayByName_byType_sorting_("album name","INDI","view")(object1). Both the target and the (object1) object must be any subclass of GEDCOM Records. The results will be identical to dragging the target record and dropping it the (object1) record. The most common uses are to "drop" sources, notes, or multimedia objects onto records. It can handle some other drops as well (see drag and drop documentation in GEDitCOM II for details are possible options).(object).evaluateExpression "#var",(expr) - set #var to evaluated expresison in (expr)evaluateExpression_("BIRT.DATE")char_MacOS/char_ANSEL/char_UTF8/char_UTF16/char_Windows - pick the export character setlines_LF/lines_CR/lines_CRLF - pick the line termination styleGEDCOM551/GEDCOM551_Embedded/GEDCOM55/GEDitCOM_Records/GEDitCOM_Settings/GEDitCOM_All - pick style to be exportedEDitCOM_Records/GEDitCOM_Settings/GEDitCOM_All export custom GEDitCOM II records, "Settings" adds settings for albums, and "All" adds settings and thumbnails of multimedia objects. More details on these options are in the GEDitCOM II help on exporting.(object).exportGEDCOM "/Users/john/Desktop/myfile.ged",(options) - where (options) is a list with strings matching above options (in any order and case insensitive). (since 3.2/1.0)
exportGedcomFilePath_withOptions_("/Users/john/Desktop/myfile.ged",listVariable)- note that in Python, the defined constants have to be replaced by their hexadecimal values: char_MacOS = 0x784F7031, char_ANSEL = 0x784F7032, char_UTF8 = 0x784F7033, char_UTF16 = 0x784F7034, char_Windows = 0x784F7035, lines_LF = 0x784F7036, lines_CR = 0x784F7037, lines_CRLF = 0x784F7038, GEDCOM551 = 0x784F7039, GEDCOM551_Embedded = 0x784F7041, GEDCOM55 = 0x784F7042, GEDitCOM_Records = 0x784F7043, GEDitCOM_All = 0x784F7044, and GEDitCOM_Settings = 0x784F7045. See below for more information and an alternative.
value is provided, find structures with the specified tag and value. If value is not provided, find all structures with that tag and any text.output is "list" (or if it is omitted), the returned result will be a list of lists. The number of items in the main list is the number of structures found. For each found structure, the sublist will have the contents of the first line of the structure as the first item, and a list of numbers to find that structure in the remaining items. For example:
tell individual 1
set places to find structures tag "PLAC"
-- result could be {{"Boston, MA, USA", 3, 2}, {Seattle, WA, USA, 4, 1}}
end tell
The first item in the list means a PLAC line containing "Boston, MA, USA" was found at structure 2 of structure 3 of individual 1. Similarly, "Seattle, WA, USA" was found at structure 1 of structure 4 of individual 1. See the "Change Place Name" script for an example of using this output option and making use of the returned integers to change the found tags.output is "references", the returned result will instead be a list of references to the found structures. For example:
tell individual 1
set places to find structures tag "PLAC" output "references"
-- result could be {reference to structure 2 of structure 3 of individual 1,
-- structure 1 of structure 4 of individual 1}
end tell
set placRef to item 1 of places
contents of placRef
The number of items in the returned list will be the number of found structures. Each item will be a reference to a structure. You can extract the items in the list to reference a structure, access or change its contents, move it elsewhere, delete it, etc.. Normally returning "references" is more useful. The "list" option is the default for backward compatibility of some scripts.tag value can by one of the following special strings — INDIEvents, INDIAttributes, INDIOrdinances, or FAMEvents — and it will return all events, attributes, or ordinances for the target record. When using these special strings the value argument is ignored.
(object).findStructures objvar,(tag),[(contents)] - set objvar to a list of the found structures and always returns them as structure objects (i.e., always using "references" output and the "list" option is not available).findStructuresTag_output_value_("PLAC","Germany","references")name value as a GEDCOM name and optionally change the case to "upper", "uppersurname", or "title". See the "Change Name Case" script for a sample use of this command.FormatName "#result",(value),[(case)] - set #var to the formatted name.formatNameValue_case_("John /Smith/","upper")(object) and the assignment type (to variable or object). The options are:(object) is an internal scripting object and the assignment type is to an object, set objName to one of that object's "to-many" or "to-single" attributes defined by (attr). If the optional (attr) is not provided, set objName to (object).(object) is a string or number extracted from a list or a dictionary and the assignment type is to a variable, set #var to that string or numerical value and (attr) is not used. Note 1: it easier to "get" such strings using "@" expression, but option to get strings from lists and dictionaries left in for backward compatibility (see below). Note 2: "getting" object properties requires an "@" expression and including a property as last element in (object) will cause an error.(object) is an invalid object specifier, the command will cause an error.objName, the object name will set to None. This response can be used to validate (object) before using it in subsequent scripting:
#name="Bad Name" indis.#name.get indi ifDef indi ! commands that use indi else ! commands when individual with that name was not found endif(This option to not cause an error since 3.2/1.0)
get command can be done by other methods. Since 3.5/1.0, option 1 above can be replaced by object assignments that are easier to write and to understand (more similar to other languages):
indis.4.get indi @indi = "indis.4" doc.families.3 husb,"husband" @husb = "doc.families.3.husband" ^#var.get obj @obj = #varMove the object specifier to right side of an assignment and append
".(attr)" if used in the command. If the original command used dereferencing with a variable, omit the caret symbol. Finally, if the final right side has any periods, it must be quoted. Option 2 above can be replaced by an "@" expression:
myList.3.get "#var" #var = @myList.3 myDict.key.get "#value" #value = @myDict.keyThe only difference between a "get" command and an object assignment is when the object specifier to the command is invalid. By option 3 above, an invalid specifier in a "get" command will cause an error. In contrast, moving an invalid object specifier to the right in an object assignment will assign the object to None instead of causing an error. Thus, use a "get" command for robust error checking and debugging or switch to an assignment method to avoid scripts stopping with errors.
objName = "(object)" where (object) is a quoted object specifier for the desired object (quotes can be omitted if (object) is just an object name). If (object) is not a valid object, objName will be set to None object that can be checked with ifDef or ifNDef conditionals.@objName = "(object)". The GetObject command is still available but only needed if you want a script to run in versions earlier than 3.5/1.0.index in the target object. (object1) must be a valid object specifier and list indices for insertion are zero based.index in the target object. (expr) must be a valid expression and indices for insertion are zero based. This command is not allowed for monospace reports. Inserting strings into a ScriptOutput object available since 3.3/1.0.(object)) and the single argument ((object1)) must be albums. This command will then change the target album to contain only those records that are in both albums. The album in (object1) is left unchanged.(string) (if omitted joined by empty string). To work best, all elements in the target should be strings. Non-string items will be joined as well with MacOS deciding how to represent those items as strings. The provided quoted variable, #var, is set equal to the joined strings.(expr) to the <head> element for the current ScriptOutput. All such text will be added to the report by the write command.(object).listAncestors objVar,[(gens)] where (gens) is a number and objVar is set to the listed records for internal scripts (since 3.0b3/1.0)listAncestorsGenerations_(6)
(object).listDescendants objVar,[(gens)] where (gens) is a number and objVar is set to the listed records for internal scripts (since 3.0b3/1.0)listDescendantsGenerations_(6)
local(key) or string(ley) string function in expressions insteadlocalStringForKey_("PLAC")(bounds) for a map and sets (objVar) to a list with four items. The first two are longitude and latitude for the southwest corner and the second two are width (E-W longitude span) and height (N-S latitude span) for a bounding rectangle. Typically (bounds) is set to the content of a _BNDS custom tag used by GEDitCOM II and the command accepts all entry syles supported in GEDitCOM II. Note that input coordinates, as in GEDitCOM II, have latitude before longitude, but this command returns rectangle with longitudinal for x axis and latitude for y axis (i.e., the usual format for rectangles). If the provided (bounds) can not be decoded, the return result will a list with one item as a string explaining the error.MakeFolder "#var",(fullpath) - set #var to "true" or "false" if it succeeds (since 3.1/1.0)makeFolderDestination_("fullpath")
(object).mergeWith objVar,[(force)] to merge (objectVar) record into target (object). Optional (force) can be "true" to force the merge (since 3.4/1.0)mergeWithRecord_force_("@I71@",True)(before). The move is limited to within the structures for the parent object. If (before) is not found, object is moved to be the first structure. If it is not provided, the object is moved to be the last structure.(row) and (col). The values are 1-based and using 0 for either ignores that setting (i.e., changes just row or column). The row must be to valid position between header and footer (i.e., you cannot overwrite header and footer). Rows outside available rows or columns greater then allowed columns per row are ignored.(row)>0, it inserts (row) new lines. If (col)>0, it moves that column on the current line (lines can have any number of columns). But, if the requested column is less than the length of the current line, it will start a new line and then move to that column.(item 1 of parts & item 2 or parts & item 3 of parts) or as theList as string and you will get the correct name, but without the slashes ("John Edward Smith, Jr.").NameParts "#var",name - set #var[1] to #var[3] to the three name parts (and #var[0]=3)namePartsGedcomName_("John Edward /Smith/, Jr.")num line feeds into a report. If optional num is not provided, one line is inserted. For monospace reports, if the number of lines runs into the footer, the footer is inserted, a new page is started with a header, and the next line will be first line on the new page.NotifyProgress (fraction),[(message)]notifyProgressFraction_message_(0.8,"working")(s1) in string (target) at or after character (c1) (first character is character 1). If (c1)≤0, it finds the last occurrence of string (s1) in string (target) at or before -(c1) characters from the end of the string. The variable #var is set to the location or set to zero if (s1) is not in (target). This command was provided as an alternative to offset(string) function in expressions for use when (s1) contains back slashes. The addition of offset(s1,c1,target) in 3.5/1.0 makes this command unnecessary..gedpkg or .ged file specified by its full path. File opening can be done by standard AppleScript; this command allows file opening in internal scripts. The open action returns to your script before the file is done reading. To access data in the new file, an internal script needs a block that waits until the file has been read:
#oldnum=@gcapp.documents.count Repeat if @gcapp.opening="false" then exit if @gcapp.documents.count>#oldnum then break sleep .5 EndRepeatThis block's repeat loop continues until number of documents increases or until
@gcapp.opening is false. When the number increases, the reading is done and the front document will be the newly-opened document. If @gcapp.opening turns false, the file could not be opened (e.g., invalid path or file type). Whan such as error occurs, an error message with an explanation is automatically displayed. Here the script exits, but it could provide other options.OpenURL (URLorFullpath) (since 3.1/1.0)openURLDestination_("URLorFullpath")
(expr) can be any text for the report. To start new lines in the report use return in the expression (and not "\n" within a string).out command now.
The second option, with more than one argument, provides pairs of arguments for text and column number. The output for each (text,col) pair is as follows:
col is less that end of the current line, a new line is started.col. If text is longer than available space, it is truncated to fit. If text is shorter than available space, it can be left justified, right justified, or centered in available space as follows:
col<0, the text is right justified (and absolute value of col is used for column number).col is omitted (i.e. an odd number of arguments), it is set equal to report colsPerRow setting such that the last text applies to space that spans to the end of the line.
(texti,coli) pairs can be added to a list first and then the command provides just the list object as a single argument.(object), which must be a List, and will remove that element from the list. If the element is a string, the variable #var will be set to that element. If it as object, the objName will be set to that element. If the list is empty, this command will not cause an error. Instead, if the first argument is "#var", that variable will be removed from the list of variables. If the first argument is objName, that object name will set to None.(object).populate - where (object) must be an existing album and no need to provide a name (because it will use album that is the target of the command)populateAlbum_("album name")
(name) name. It is required, but it is only used if any error message is displayed.(name) and the check on version number is skipped.(minVersion) as floating point number (x.y). The script will run only in (minVersion) or newer. If the script needs a feature added in a higher build of that version, enter that requirement in (minBuild) (if omitted, the default is 1). Note that although internal scripting first appeared in 3.0, build 1, a lot was changed in 3.0, build 2. To avoid documenting all those changes, if you request any version before 3.0, build 2, this check is changes to requiring 3.0, build 2. Features added after 3.0, build 2 will be listed as such in this documentation.(minGCVersion) and (minGCbuild). These will be used when someone is using GEDitCOM, while (minVersion) and (minbuild) will be ignored.PreChecks #scriptName,3,1,1,1 @gdoc = "gcapp.frontDocument"This first line does all prechecks and supports both GEDitCOM II and GEDitCOM. If they fail, the script displays the reason and stops. If all is OK, the internal script can continue and fetch the front document with the get command. The document is guaranteed to be available.
settings property in the scripting dictionary. For internal scripting and python, the property names are NSCopies, NSMustCollate, NSFirstPage, NSLastPage, NSPagesAcross, NSPagesDown, NSPrintTime, NSFaxNumber, and NSPrinterName. Unfortunately, MacOS may not honor these settings, especially when printing with a dialog.
One issue with printing is that control will return to your script before printing actually occurs. In some scripts, this timing may cause problems. To have the script wait for printing to finish, you can use the following procedure:
tell front document
show browser individual 1
print with print dialog
-- wait until browser has printed
repeat
if printing is false then
exit repeat
end if
end repeat
end tell
First you open a browser window (so a record can be printed) and then send print command to the document. The repeat loop causes the script to wait until the document printing property changes from true (meaning printing is still processing) to false (meaning GEDitCOM II is finished printing, although the physical print out may still be in a printer queue).repeat loop to wait for printing does not work:
repeat while printing is false end repeatbecause AppleScript apparently ignores loops containing no commands (perhaps a minor bug in AppleScript?). The work around is the method above that checks
printing status within the loop.
(object).print [(dialog)],[(setDict)] to print front window target document. Optional (dialog) can be "false" to skip print dialog. Optional (setDict) can be dictionary object of print settings (since 3.4/1.0)gedit.print_printDialog_withProperties_(gdoc,True,None) - notice that you have to send the command to the application object and provide the document that is the target of the command as the first argument in the function. Futhermore, the print dialog argument, which is with or without in AppleScript, is True or False in Python.
(string) is provided, the list is first converted to a string (as in the join command) and that string is put on the pasteboard. Note that strings on the pasteboard can be pasted into other applications while the custom style used for lists without (string) cannot.(string) is used for a dictionary, it is ignored.objName) and the pasteboard has a custom pasting of a List or Dictionary, objName will be set to the recovered object as explained below. If instead, the first argument is a valid variable name (in "#var") and the pasteboard has a string (from GEDitCOM II or from any other application), #var will be set to that string. If neither of the above two cases apply, #var will be undefined or objName will be set to None type (depending on which was in the first argument).RefreshFormats or RefreshScripts (since 3.4/1.0)refreshFormats()
(index) from a list or remove record in (object1) from an album. List items use zero-based numbering.(key) (which can be any valid expression).(s1) in string (target) with string (s2). The variable #var is set to the resulting string. This command was provided as an alternative to replace(string) function in expressions for use when (s1) or (s1) contain back slashes. The addition of replace(s1,s2,target) in 3.5/1.0 makes this command unnecessary.(path) using the Finder (that path can contain "~" to indicate home directory). If (path) is a file, it tries to "double click" on the file opening in its preferred application. If (path) is a a folder, that folder opens in a Finder window. If these two options fail, it tries to open the parent folder in a Finder window. If all options file, an error occurs.gplug) or an AppleScript or Python script.runScriptAtPath_("/Path/to/script")
html files, it is important to insure that text included from the GEDCOM file be formatted well for such files. You can pass any text to this command, such as text from a notes record. If that raw text is plain text, this command will check for certain special characters and convert them to html entities (e.g., <, >, ", and & are converted to <, >, ", and &).html output. To achieve this goal you can use the insertPs argument. If the argument is "all", it will surround the text in <p> and </p> elements and replace each line break with </p><p>. Thus each line in the raw text will be a paragraph in the html output. If insertPs is "interior", the </p><p> elements will still be inserted at line breaks, but the output will not be surrounded by <p> and </p> elements.raw text is html text surrounded by <div> and </div> elements, it will be assumed to be valid html text and returned unchanged, except for internal links. Because GEDitCOM II allows such html text to link to internal records (e.g., using <a href="//@I342@">John Smith</a>), this command will, by default, remove such links and leave the text (e.g., John Smith). By using the reformat links argument, you can optionally change the links rather than remove them. The reformat links argument should provide an AppleScript record that can include format strings by GEDCOM Record tag type. If an internal link refers to an record type included in the AppleScript record, the link will be changed to the provided string with the place holder "%@" replaced by the GEDCOM Record ID without the @ signs. The above example for individual records of "I%@.html" would convert the above example link to be <a href="II342.html">John Smith</a> (which happens to be how it is used in the Web Site Export). If the provided AppleScript record has no item for a linked GEDCOM record, that link will be removed rather than reformatted.SafeHTML "#theVar",(someText),[(insertPs)],[(relink)] - optional (relink) is a dictionary object with keys for record types and their values for replacement format (since 3.1/1.0)safeHtmlRawText_insertPs_reformatLinks_(someText,"all",{'INDI':"I%@.html"})(expr) to safe text for a LaTeX document and sets #safe (passed in first argument) to that safe text. The process escapes certain standard characters needed by LaTeX, uses a "verbatim" mode to insert certain LaTeX elements, puts some characters in math mode, and converts all double quotes to LaTeX method for double quotes.
CreateList reps,hexchar("25e6"),hexchar("a0")
CreateList repsto,hexchar(2202),"~"
CreateList special,reps,repsto
SafeTex "#safe",#expr,special
The optional (special) must be a list that contains exactly two other lists that have identical numbers of strings. The single-character strings in the first list are the unicode characters to be replaced. The corresponding strings (which can be any length) in the second list are the strings the replace each character. The above code replaces white bullet and non-breaking space with a black bullet and LaTeX "~" used for non-breaking spaces.
(CopyPath) is omitted, this command saves the target document object. If the document has not been saved before, the user is given a standard "Save File" panel to choose a save location. If (CopyPath) is provided, it must be full path to a valid save location. A copy of the file will be saved to that location and the original will left unchanged (i.e., remain in its current state, which might include unsaved changes).
gdoc.save
Repeat
sleep 0.1
if @gdoc.saving is false
break
endif
EndRepeat
if @gdoc.path=""
! This result means the user canceled the save process
exit
endif
! The save completed
Supported By: documentsfull date argument. Serial day numbers are an integer count of days where 1 is a year around 4000 BC; they are handy for date calculations. The returned result will a list of two numbers. If the provided date is invalid, the returned result will be {0,0}.SDNRange "#var",(date) - sets #var[1] and #var[2] to the range (and sets #var[0]=2)sdnRangeFullDate_("AUG 1947")(property) of the object defined by (object) to the evaluated expression in (expr). Any property listed for any of the scripting objects that is not marked "r/o" (for read only) can be set with this command. Any object's "to-single" attribute marked as "settable" can also be set where (expr) must be an object name for the expected type of object.(property)s that are strings is to use an '@' expression assignment command. The set command still works and is needed to set "to-single" attributes of objects.(object) must be a dictionary). Three commands are available to add three types of values using a (key), which can be any string or numeric expression. The first one adds any valid object to the dictionary. The other two add any valid expression (in (expr)) to the dictionary. The main use for setNumberForKey is in scripts that will later use the keysSortedByNumericValues relation of the dictionary.setStringForKey is to using an assignment command:
@myDict.key = expr @myList.3.key = exprto set
(key) to string value of any expression. The left side either references the dictionary or a dictionary extra from a list. It can note use any more-general object specifiers.(object).showAncestors [(gens)],[(style)] where (gens) is a number and (style) can be "chart" or "outline'.showAncestorsGenerations_treeStyle_(6,chart/outline) - note that in Python, the defined constants have to be replaced by their hexadecimal values: chart = 0x74724348 and outline = 0x74724F55. See below for more information and an alternative. If you need to access the new tree window in MacOS Ventura or newer, follow this command by calling WaitForWindow().
(object).showBrowser - show browser window for the target object (since 3.2/1.0)showBrowser() - if you need to access the new browser window in MacOS Ventura or newer, follow this command by calling WaitForWindow().paneID. If no such ID, the default pane opens. Note that pane IDs are set by the current browser style and may differ from the pane names.(object).showBrowser (paneID) - show selected pane in browser window for the target objectshowBrowserpaneWithId_() - if you need to access the new browser window in MacOS Ventura or newer, follow this command by calling WaitForWindow().
(object).showDescandants [(gens)],[(style)] where (gens) is a number and (style) can be "chart" or "outline'.showDescendantsGenerations_treeStyle_(6,chart/outline) - note that in Python, the defined constants have to be replaced by their hexadecimal values: chart = 0x74724348 and outline = 0x74724F55. See below for more information and an alternative. If you need to access the new tree window in MacOS Ventura or newer, follow this command by calling WaitForWindow().
delay seconds instead.time and then use time.sleep(seconds).(object), which must be a list. If the command has no arguments, the list items are sorted by case-insensitive comparisons. All items must be strings.(key1) is the primary sort criterion and if (key1) values are the same those items are sorted using (key2) values. The (type1) and (type2) arguments can be "numeric" to sort values numerically or any other text (or omitted) to use case-insensitive comparisons. The values should be strings or numbers. An error will result when sorting dictionaries if any item in the list is not a dictionary or if any dictionary lacks either key needed for sorting. Sorting of dictionaries available since 3.3/1.0 (some bugs with optional arguments and dictionaries fixed in 3.5/1.0).(object).sortData (type) - where (type) is any of the types listed above, but without the word "the".sortData_(the children/the events/the spouses) - note that in Python, the defined constants have to be replaced by their hexadecimal values: 'the children' = 0x736B4348, 'the events' = 0x736B4556, 'the spouses' = 0x736B5350, and 'the multimedia' = 0x736B4D4D. See below for more information and an alternative.
soundex(text) string function in expressions insteadsoundexForText_("string")
(object)) must be a list or GC list. This command creates a new list, which is stored in objName, containing elements from index start to index end-1 (note the first element in a list is at index 0). If optional end-1 is omitted, the sublist will be from start to the end of the list.#var (which must be quoted variable name). The second argument, args, must be a list whose first item is a command that can be run on a command line and any remaining items are arguments or options. For example, to get a list of files in a directory, you could use args = ["ls", "-la"] where first item is Unix command to list files and second is option to output one file per line with detailed information. The two optional arguments can provide a working directory and shell environment variables for the command line task. If not provided, the working direction is the disk's root directory. The path to the directory can use "~" to refer to user's home directory. The environment must be a dictionary with shell variables as keys with their values as string. Most common is to set PATH variable used to locate the command. If environment is not provided, the process will use the one assigned to the running GEDitCOM II application.#var will have error details and its first line will be "ERROR". A common error is "Command not found" when the desired command is not in the assigned PATH for the environment. If you get such an error, either use environment with PATH variable set to include the path to your command or specify the command by its full path (e.g. "/opt/local/bin/svn" for svn installed using MacPorts).(object)) and the single argument ((object1)) must be albums. This command will then change the target album to be a union of the records in the two albums. The album in (object1) is left unchanged.UniqueFile "#var",(fullpath) - set #var to full path to the unique file name (since 3.1/1.0)uniqueFileDestination_("fullpath")
list items. To have an item preselected, use a semicolon (";") as the first character (the semicolon will not be displayed). If no item is marked as selected, the first item will be selected. The required prompt is displayed above the list box to explain the requested selection (it can be any length and use multiple lines). The optional title is displayed in the title bar of the window. The optional buttons can change the text of the default "OK" and "Cancel" buttons and optionally add a third button. The optional multiple argument can be true or false to allow selection of multiple items (if it is false and more than one item is marked as selected, only the first one will be selected; default is false).UserChoice "#var",(prompt),(list),[(title)],[(multiple)],[(btn1)],[(btn2)],[(btn3)] - where (list) specifies a valid list object. Set #var[1] to text of clicked button, #var[2] to #var[1+n] to text of selected items, and #var[2+n] to #var[2n+1] to selected indices (also sets #var[0]=2n+1)userChoiceListItems_prompt_buttons_multiple_title_(["item 1","item 2","item 3"], "Prompt Text", ["OK","Cancel"], False, "Panel Title") - use capitalized True or False in Python.
prompt is displayed above the text field to explain the requested input (it can be any length and use multiple lines). The optional initial text is placed in the text field (it can only be a single line). The optional title is displayed in the title bar of the window. The optional buttons can change the text of the default "OK" and "Cancel" buttons and optionally add a third button. The returned result of this command is a list with two items. The first item is the text of the button that was clicked. The second item is the text entered by the user in the text field.UserInput "#var",(title),[(prompt)],[(initialText)],[(btn1)],[(btn2)],[(btn3)] - set #var[1] to text of clicked button and #var[2] to text entered by the user (also sets #var[0]=2)userInputPrompt_buttons_initialText_title_("Prompt Text", ["OK","Cancel"], "default text", "Panel Title")
start argument can be used to define the initially selected folder and/or file (if not provided for GEDitCOM the start location will be genealogy workspace folder). The extensions list means the user can only select files with those extensions (if omitted, any file can be selected). The title is title for the open panel window (this title is not displayed in new MacOS's, but kept as parameter for compatibility). The prompt is a string that will appear in the window to help the user.UserOpenFile "#var",[(extensions)],[(prompt)],[(start)],[(title)],[(multiple)] - sets #var to the selection (or empty if canceled). (extensions) must be a List. Any omitted or empty arguments are ignored (since 3.1/1.0). If (multiple) argument is "true", user can select multiple files (since 3.3/1.0). When done, #var[0] is set to number of files selected and the paths are in #var[1], #var[2], etc. (note that #var is set to first selected file, or empty if canceled, for backward compatibility). The option to select multiple files is currently only available for internal scripts.userOpenFileExtensions_prompt_start_title_(["ged","gedpkg"], "Pick a genealogy file", "/Users/nairnj/Desktop", "Open")
start argument can be used to define the initially selected folder (if not provided for GEDitCOM the start location will be genealogy workspace folder). The title is title for the open panel window. The prompt is a string that will appear in the window. When done, the command will return the full POSIX path to the selected folder (or empty if canceled).UserOpenFolder "#var",[(prompt)],[(start)],[(title)] - sets #var to the selection. Any omitted or empty arguments are ignored (since 3.1/1.0).userOpenFolderPrompt_start_title_("Choose any folder", "/Users/nairnj/Desktop", "Open")
UserOption "#var",(title),[(message)],[(btn1)],[(btn2)],[(btn2)] - sets #var to text of the clicked buttonuserOptionTitle_buttons_message_("Main text", ["OK","Cancel"], "Subtitle text")
start argument can be used to define the initially selected folder and/or file name (the file need not exist and you can supply just the name if the start folder is not important). The extensions list means the user should save to files with those extensions; if they choose another extension, they will be prompted to use the first extension in the list. The title argument is the title for the save panel. The prompt is a string that will appear in the window. If the selected file already exists, the user will be asked to confirm that it is OK to replace that file. When done, the command will return the full POSIX path to the selected file (or empty if canceled).UserSaveFile "#var",[(extensions)],[(prompt)],[(start)],[(title)] - sets #var to the selection. (extensions) must be a List. Any omitted or empty arguments are ignored (since 3.1/1.0).userSaveFileExtensions_prompt,start_title_(["ged","gedpkg"], "Save file to this location", "/Users/nairnj/Desktop", "Save")
user select by type "INDI"
repeat
set pr to picked record
if pr is not "" then
exit repeat
end if
end repeat
The loop waits until the picked record property is set and no longer an empty string. Once set, it will be a reference to the selected record or be "Cancel" if the user canceled the selection process.
(object).UserSelect (type),[(prompt)] or (object).UserSelect "","(list)",[(prompt)] - select by (type) or by (list) object of IDs (when (type) is an empty string). As in AppleScript, the command merely starts the window and the script must wait in a loop until the user makes a selection. The loop in an internal script is:
gdoc.UserSelect "INDI" Repeat @res = "gdoc.pickedRecord" if @res.count>0 then break EndRepeat if @res.0="Cancel" then exit @rec = "res.1"When done,
rec will be the selected record.userSelectByType_fromList_prompt_("INDI",None,"Select an individual"). As in AppleScript, the command merely starts the window and the script must wait in a loop until the user makes a selection. The loop in Python is:
gdoc.userSelectByType_fromList_prompt_("INDI",None,prompt)
while True :
rec = gdoc.pickedRecord().get()
if rec != "" : break
When done, rec will be a reference to the selected record or "Cancel" if user canceled the selection process.
(key), which is any valid expression. If the value is a string or a number, set #var (which must be a quoted variable name starting in "#") to that value. If the value is an object, set objName (which must be a valid object name) to that object. If value type and the first argument are mismatched (e.g., using objName when value is a string or number or using "#var" when value is an object) or if (key) is not in the dictionary, then "#var" will be undefined or objName will be set to None type. Such results can be checked using ifDef conditionals (note: before 3.2/1.0, a mismatch in value type and first argument caused an error).(object1) or "#var" :
(preface) (an option provided in case information for the preface is not known until done adding other text). Note that an optional (preface) will be ignored for plain text and monospace reports.(object1) for a document, the results will open in a report window for that document. Html reports will display the html content. Plain text and monospace reports will display using the report's monoFont and monoSize settings."#var", that variable will be set to text content of the report (for html report that text will be formatted suitable to export to an html file). The most common reason for the "#var" option is to export the results to a file. Here is sample code:
rpt.write "#report"
CreateList exts,"txt" ! use "html" for html report
UserSaveFile "#file",exts
if #file!=""
Export #report,#file
endif
Supported By: ScriptOutputchart, outline, etc.) have to referenced by their underlying numeric code in Python scripts rather then their defined name. The hexadecimal constants relevant to various commands above are listed with those commands. Alternatively, you can use the GCConstant() utililty subroutine (which is in the module for Python) and refer to them by name. With this subroutine, you refer to constants using GCConstant("chart"), etc., passing the case-sensitive name defined in the dictionary as a string.