Main Help → Writing Extensions → Python Modules
GEDitCOM II is installed with a GEDitCOMII.py Python module to help in writing Python scripts. Two remarks on the GEDitCOMII.py module are:
/Users/(your name)/Library/Application Support/GEDitCOM II/System/Modules folder. If you download a new version, it can replace the module at this location or can be saved in to the user section in a /Users/(your name)/Library/Application Support/GEDitCOM II//Modules folder. Either folder can hold Python modules (the user section is checked first)The following topics explain the GEDitCOMII module classes and functions. They are grouped by subject.
Some of the methods take optional parameters and they are surrounded by square brackets ([...]). If a method as more then one optional parameter, you can provide any number, but must start from the beginning and include all up to the last one needed.
These methods are used when a script starts for fetching basic information needed for the script.
sName - the name of the scriptvNeed - the GEDitCOM II version required to run this scriptbNeed - the build number (option, the default is 1)vNeed and bNeed or providing low numbers).None.
None if no document is open. To find a document other than the front document, you can look at gedit.documents()[i], where i is document number (the front document is number 0) and gedit is reference to the application.This class and its methods help formatting script output for reports or to save to files. In brief, you create one instance of the class for your script and then use the ScriptOutput methods to help preparing the script output. It it very helpful to any scripts that create reports and/or save results to a file. A template for its use in a script is:
# create a ScriptOutput object
rpt = ScriptOutput(GetScriptName(),"html",None)
# the script adds content to the rpt object using its methods
rpt.out("Text for the script output")
# generate script out
rpt.write()
When you create the ScriptOutput instance, the second parameter defines the style of the output. The most common output style for scripts is to use html content. This output can either be displayed in a GEDitCOM II window or saved to a standard .html file that can be opened in any browser. If a file name is provided in the third parameter when creating the ScriptOutput object is created, the output will be saved to an .html file. If the third parameter is None (or omitted), the output will be displayed in a GEDitCOM II window. In either case, your script only provides the internal html content. The ScriptOutput class will take care of all other elements needed for an .html file or a report. In fact, the exact same script can provide output to a window or to a file simply by changing the file name parameter; no other changes are needed.
The other style is monospace. This style is used for a plain text report (or file) with no options for formatting (except to select the font). It is used for quick or simple output. It is called "monospace" because the default font is a fixed-width font (Courier) which provides the option of aligning output in columns by counting the number of characters in each row. The font can, however, be changed. When done, the plain text can be sent to a GEDitCOM II window or written to a text file (if a file name is provided).
name - the name of the scriptstyle - output style ("html" or "monospace")file - full path name when the output will be written to a fileScriptOutput object is created, you provide the script name, the style of the report, and a file name if you want file output (otherwise use None or omit the last parameter). Scripts then prepare output using this object and various methods (most commonly the out() method). When done, finish the output with the write() method.text - string of text to add to the outputhtml output, embed html elements in the text such as
rpt.out("<h1>Section Title</h1>\n")
Build a complete report by adding any html content. There are several html helper functions to help create output for tables, lists, record links, etc..monospace output, simply build the report by adding text. You can add "\n" to include line feeds because out() does not insert them.
out("\n")
text - string of text to add style sheet definitions for this contenthtml output, you can define styles for elements by adding a style element to the head element of type 'text/css'. The ScriptOutput class does all the work. All you need do is add style definitions for element types using the css() method. For example, one definition could be:
rpt.css("table { border-bottom: 1px solid #ccc;}\n")
You can add as many css definitions you want for the html output. Each one uses standard methods for cascading style sheets.monospace output.
text - string with complete html elements to include in the head element
html output, this method can add content to the document's head element. A common use is to add javascript for the report document.monospace output.
text# - add this text to the output (# is 1, 2, etc.)col# - pad previous text up to but just before this column (# is 1, 2, etc.)monospace output and a fixed-width font.
It is used as follows:
rpt.cols("John Smith",30,"14 Oct 1754",-45,"NY")
This method adds a series of text blocks aligned in columns. The first text starts in column 1. The subsequent text strings (in odd-numbered arguments of which there can be any number) starts in the column number preceding that text. If the number is negative, the previous text is right justified up to that column otherwise the previous text is padded with blank characters up to that column (note: to start with leading blanks, make the first text argument an empty string). This command can be used in the middle of the line, but then the column numbers are relative to the current position and not to the start of the current line. This command does not end the line; you still need line feed characters (in last argument or a subsequent out() command) to move to the next line.html output.
name - any font-family name allowed in style sheetsmonospace output only. The default font for monospace output is Courier. This font is a fixed-width font, which is essential if you intend to use cols() or character spacings to align output in columns. If you don't need aligned columns, you can select a proportional font instead. You cannot mix fonts. If more than on SetFont() command is used, only the last will will be used.html output.
size - font size in pointsSetFontSize() command is used, only the last will will be used.html output.
rpt.write()If no file name was provided, the report will be displayed in a GEDitCOM II report window. If the style was
html, it will display as html content. If the style was monospace, it will display as plain text. If a file name is given, the output will be written to a file. For html style, it will be written to an html file that can be opened with a browser. For monospace output, it will be written to a plain text file that can be opened with a text editor.The methods in this section and several following sections are convenience methods for looking up records or other common tasks with records.
rType - GEDCOM code for record type (e.g., INDI)gdoc - find records in this document (or front document if omitted).rtype) parameter. If no such records are select, it will return an empty list. This method is faster then looping your self and picking out the records.
These methods help access information about individual records.
gdoc - find individual in this document (or front document if omitted).prompt - user prompt when selecting from a list.gdoc if provided. If no records are selected or if none of the selected records are individual records, this function looks at the prompt argument. If it is omitted (or None) the function returns None. If prompt is provided, the user is shown a list of all individuals and can select one. The selected one is returned (or None if that selection is canceled).
gdoc - individuals in this document, or front document if omitted.gdoc if provided). A template for its use is:
for (n,indi) in EveryIndividual() :
(loop statements)
In the loop, n is the individual number (with the first one being number zero) and indi is a reference to each individual record.
person - reference to an individualNone. If the person has more than one father, the reference is to the first father.person - reference to an individualNone. If the person has more than one mother, the reference is to the first mother.indi - reference to an individualgdoc - document for the individual (or front document if omitted)maxgen - maximum number of generations to find (or all if omitted)listedRecords() for "Ancestor Family Tree window". By default the list will have all ancestors in the file. The optional maxgen can limit the list to any number of generations (parents are generation number 1).indi - reference to an individualgdoc - document for the individual (or front document if omitted)maxgen - maximum number of generations to find (or all if omitted)listedRecords() for "Descendant Family Tree window". By default the list will have all descendants in the file. The optional maxgen can limit the list to any number of generations (children are generation number 1). These methods help access information about family records.
gdoc - find family in this document (or front document if omitted).prompt - user prompt when selecting from a list.gdoc if provided). If no records are selected or if none of the selected records are family records, this function looks at the prompt argument. If it is omitted (or None) the function returns None. If prompt is provided, the user is shown a list of all families and can select one. The selected one is returned (or None if that selection is canceled).
gdoc - families in this document, or front document if omitted.gdoc if provided). A template for its use is:
for (n,fam) in EveryFamily() :
(loop statements)
In the loop, n is the family number (with the first one being number zero) and fam is a reference to each family record.
famrec - reference to a family record.These methods help create and access information about note records.
gdoc - the document (or front document if omitted)noteText - text for the notesnoteText or set its text later using properties of the returned record.
ntext - notes text as a stringcomments - list of comment labels to be searchedhtml content (any string beginning in <div> element, usually from a notes record with web content) for comments. A comment is defined as <!--name Text of the comment--> where name is the comment label and "Text of the comment" is the comment text. You provide the notes text (as a string) and a list of labels to be searched. The returned result will be the text of the first comment that matches a label in the comments list. The returned result will be a list:
[label,Text of the comment]If no comment is found, the returned result is
[None,None]. For example, GEDitCOM II uses a "name" comment to allow users to specify the name for notes with html content. You can fetch this name with:
GetHTMLComment(ntext,["name"])Your scripts can define custom comments. The comments will not show up in GEDitCOM II when viewing the
html content (because they are comments), but can be read by your script. For example the "Create Generations Book" etension defines "TeX" and "alt" comments to allow alternate versions of notes to be included in the book (because notes only with html content are not compatible with that book). It prefers the "TeX" version, but will accept an "alt" version. The one to use is found with:
GetHTMLComment(ntext,["TeX","alt"])
These methods help create and access information about place records.
gdoc - find place record in this document (or front document if omitted).prompt - user prompt when selecting from a list.gdoc if provided). If no records are selected or if none of the selected records are place records, this function looks at the prompt argument. If it is omitted (or None) the function returns None. If prompt is provided, the user is shown a list of all places and can select one. The selected one is returned (or None if that selection is canceled).
plc - reference to a place record.[lat, lon] in a two element list. If the place has no map or its bounding box is not valid, the returned result will a list with one element having a string that describes the error.
The methods in this section are convenience methods for working with structures.
grec - record or structurep - properties for the new structuregrec. It is added to the end of other subordinate structures. The structure properties are specified in the p argument as a dictionary. For example, to add an occupation to an individual, you could use:
AddStructure(indi,{"name":"OCCU","contents":"Electrician"})
The dictionary can use properties defined in GEDitCOM II's Apple Scripting dictionary. You do not need to set the structure level number because that is set automatically depending on where you add the structure.
This class is a wrapper class for GEDCOM event data (individual or family events). It provides options for describing the event in a sentence for use in reports. It also caches the event data, which can speed up scripts if you need to access the event data more than once. For example, the methods calculate and return event data the first time they are called and store that result. If you call the method again, it returns a previously calculated result rather the having the re-read the data from GEDitCOM II. Similarly, the variables are read once when the instance is created and stored for later use.
evnt = Event(e)The initialization reads the date and place. Other methods get output for the event only when needed and do it efficiently.
verb - verb appropriate for this eventatAge - true or false to include age (if available) in the phrase (default is false)verb [at age (age)] (date) in (place)
e.g., died at age 84 on 12 OCT 1856 in Boston, MA, USA
The phrase starts with the verb (e.g., "died"), optionally includes the age (if atAge is true), and ends with date and place.
noun - noun appropriate to this event (e.g., person's name or a pronoun)verb - verb appropriate for this eventatAge - true or false to include age (if available) in the phrase (default is false)freq - list of two numbers to determine probability of each phrasenoun verb [at age (age)] (date) in (place)
e.g. Sam Adams died at age 84 on 12 OCT 1856 in Boston, MA, USA
(date) [at age (age)], noun verb in (place)
e.g. On 12 Oct 1856 at age 84, Sam Adams died in Boston, MA, USA
noun verb in (place) (date) [at age (age)]
e.g. Sam Adams died in Boston, MA USA on 12 Oct 1856 at age 84
The noun is usually a person's name or a pronoun ("he" or "she", which will be capitalized if needed). The verb should be appropriate for the above phrases and the event type. The phrase optionally includes the age if atAge is true. The optional freq parameter determines the probability of each phrase. It should be a list with two numbers less than one, freq = [n1, n2]. Phrase 1 is picked with probability n1; phrase 2 with probability n2-n1; phrase 3 with probability 1-n2. The default setting is freq = [1./3., 2./3.], which makes each phrase equally likely with probability of 1/3.
SetGedWords().[0, 0].This class is a wrapper class for GEDCOM attribute data. It is a subclass of the Event class with the only change being that the phrases that are produced include the attribute value in their output.
According to the GEDCOM standard, residence structures are attributes, but unlike all other attributes, they have no value on the first line of the structure. In formatting residences for output, they work better be treating them as an event and wrapping them in an Event class instead of an Attribute class.
a - a reference to a GEDCOM structure for an attributeattr = Attribute(a)The initialization reads the date and place. Other methods get output for the attribute only when needed and do it efficiently.
These variables are same as for the super Event class except that attr.event is a reference to the attribute.
The methods are the same as for the super Event class except that the description outputs are slightly altered:
verb (attribute value) [at age (age)] (date) in (place)
e.g. occupation was brewer at age 84 on 12 OCT 1856 in Boston, MA, USA
where "occupation was" is the verb passed to this method and "brewer" is the value of the attribute inserted into the phrase. See this method in the Event class for more details.noun verb (attribute value) [at age (age)] (date) in (place)
e.g. Sam's occupation was brewer at age 84 on 12 OCT 1856 in Boston, MA, USA
(date) [at age (age)], noun verb (attribute value) in (place)
e.g. On 12 Oct 1856 at age 84, Sam's occupation was brewer in Boston, MA, USA
noun verb (attribute value) in (place) (date) [at age (age)]
e.g. Sam's occupation was brewer in Boston, MA USA on 12 Oct 1856 at age 84
Here noun should be a possessive noun. See this method in the Event class for more details.These methods make it easier to get input from the user.
mainText - main text for the alertmessage - extra line of text to display in smaller fontprompt - prompt to usertitle - window titleistart - initial number in the editing fieldimin to imax - acceptable range for the entered numberistart parameter is the initial integer in the editing field (defaults to 0 if omitted). The optional imin and imax specify the range of valid integers. If the user enters a number outside this range, and error message is provided and they are asked to try again. One or both limits can be specified. Finally, the function returns the entered integer or None if the user cancels the process.
prompt - prompt to the usermsg - additional information for the user (displayed under prompt in smaller font)options - list of 1, 2, or 3 strings for text of buttons.options, which much be a list with one to three strings. The buttons are arranged right to left. The first button in the list is the default button (highlighted in blue and can be selected by typing return or enter). The msg parameter is an extra prompt for the user, which is displayed under the prompt in a smaller font. It can be None if not needed. The returned value is the text of the button the user clicks.
prompt - prompt to the userinitial - initial text in the editing fieldtitle - title for the windowinitial parameter can provide initial text to be in the editing field. The optional title will be title of the window. When done, the function will return the text entered by the user or None if the process was canceled.
items - a list of items as stringsprompt - prompt for the usertitle - title for the window(item text, item number). The item numbers start at 1. It returns (None, None) if the selection is cancelled by the user. To select multiple items, you have to use the lower-level command list choice command rather than this convenience method in the module.
These method help formatting results to output into a report that is formatted using html elements. Their use is optional; you can always directly insert html elements into strings.
args - list of commands and parameters as explained belowhtml table and returns the html code. You can uses a series of MakeTable() calls to build any size table. A template for its use (when using ScriptOutput class, but that is optional) is:
# start table then add optional add caption and header
rpt.out(MakeTable("begin","caption","Sample Table"))
rpt.out(MakeTable("head",headCols))
# body of the table
rpt.out(MakeTable("body"))
for i in range(numRows) :
rpt.out(MakeTable("row c r",colData[i]))
# end the body and the table
rpt.out(MakeTable("endbody","end"))
The arguments to MakeTable() are keywords followed by zero or one parameter. Each call can have any number of keywords with parameters. A series of calls fill out the table. The table keywords, which are usually in this order, are:
"begin" —
Each table sequence must start with a begin keyword and it takes no parameters. It is like a <table> element in html content."caption","Text for the caption" —
Provides an optional table caption. It must be followed by one parameter that has the text of the caption."head l c r mystyle",headCols —
Provides an optional row of header cells. The text for the columns are in the list variable headCols. The head key word can optionally include alignment codes l, c, or r (separated by whitespace) to have the columns left justified, centered, or right justified. If any other alignment code is used (e.g., mystyle above), that header cell uses that class from the report's CSS options. If no alignment settings are used, the header row cells are centered."body" —
The body of the table data should begin with a body keyword. This keywords makes tables work better with the default cascading style sheet for reports."row l c r mystyle",colData —
Provides a row of data for the table. The text for the columns are in the list variable colData. The row key word can optionally be followed by alignment codes as explain for the head keyword, except that for columns, if no alignment settings are used, the columns are left justified."endbody" —
The body of the table data should end with an endbody keyword. This keyword makes tables work better with the default cascading style sheet for reports."end" —
Each table sequence must finish with an end keyword and it takes no parameters. It is like a </table> element in html content.alist - a list of text stringsordered - True for numbered list or False (the default) for unordered listhtml list for inclusion in a report. The list can be numbered or unordered.
ref - reference to a gedcom recordalternate - True to use alternate name or False (the default) for standard namehtml can include internal links to records by using an <a> with its href set to the record's ID. This function helps insert those links. The text of the link can be the name() property of the record or its alternameName() property (depending on the optional alternate parameter).
ctext - text to be centeredhtml code to center the block of text in the passed string variable.
This methods help processing of date information.
beginDate - serial day number for starting dateendDate - serial day number for ending datebeginDate to the endDate.
newWords - a complete dictionary of words to replace GEDCOM date words
{"ABT":"about","EST":"about","BEF":"before","AFT":"after",\
"FROM":"from","TO":"to","BET":"between","AND":"and",\
"CAL":"calculated","INT":"interpreted",\
"ON":"on","IN":"in"}
The new dictionary must specify new strings for all these key words. One use could be to format dates in a different language. A script can fetch these string using GetGedWord().
key - a key GEDCOM word
SetGedWords() method (although a script could add additional keys, if needed, by using SetGedWords()).
These functions are for help working with latitude and longitude coordinates in various editing fields.
gpsStr - string with latitude and longitude information for a bounding box[south, west, north, east] in a four element list. If the input data are not valid, the returned result will be a list with one element having a string that describes the error.
gpsStr - string with latitude and longitude information for a bounding box[lat, lon] in a two element list. If the input data are not valid, the returned result will be a list with one element having a string that describes the error.
pt1 - latitude and longitude pair of signed numbers: [lat, lon]pt2 - latitude and longitude pair of signed numbers [lat, lon]atLat - a latitude between -90 and 90These methods provide various utility functions for scripts.
CheckVersionAndDocument() method when the script starts. Thus, this method assumes that method was used, but all Python scripts should start with that method to check the current version and to verify a document is open.
fraction - fraction completed (0 to 1)msg - String to print on next line of the scripting panel# set progress variables
fractionStepSize = nextFraction = 0.01
# main script loop
for i in range(1, numTasks)
# the script code
# time for progress
fractionDone = float(i) / float(numTasks)
if fractionDone > nextFraction:
ProgressFraction(fractionDone)
nextFraction = nextFraction + fractionStepSize
At the beginning of the script you define two variables. The fractionStepSize defines how often to inform the user of progress. There is no point in sending too many notifications since the progress is rounded to the nearest percent. A good choice is usually to notify the user after each percent is completed and thus fractionStepSize is set to 0.01. The nextFraction variable defines the next time the notification should be sent to GEDitCOM II. It is initialized to the same value as fractionStepSize to define the point for the first notification.numTasks times. At the end the each pass through the loop, the fractionDone is easily calculated to be i/numTasks (converted to floating point). If this fraction has passed a predetermined notification point (stored in nextFraction), the fraction is sent to GEDitCOM II using ProgressMessage() and nextFraction is advanced by the fractionStepSize defined at the start of the script.msg argument; it can be any string. Third, you can do nothing; GEDitCOM II will provide a spinning indicator to tell the user the script is running.
# save the previous window's id prevId=gedit.windows()[0].id() ... # a command that creates a new window (such as report output) rpt.write() # after that command, wait for new window to be noticed WaitForWindow(prevId) ... # now can access the front-most window in other commandsThis call fixes scripts running in MacOS Ventura and works in prior MacOS's as well. The required parameter is id of the window that was opened prior to opening the new window. By default, this method will wait a maximum of 1 second. You can change the maximum wait time if needed with the optional
maxTime parameter in seconds. The required wait is typically less than 10 ms (or 0.01 seconds)
anum - an integerSetCardinal().
newCards - list of words for cardinal numbersnumber - a numbertarget - a stringwebsite - full URL for a web site[x, y, width, height] where x and y are coordinates of lower-left corner and width and height are the size of the visible area. The visible area will leave room for the dock (if visible) and the menu bar.
utext - string of textconstantName - name of the constantrestriction property of individual records returns a defined constant. These constants are used in AppleScript by their name, but in Python scripts, you have to use the underlying numeric codes instead. The GCConstant() function converts a named constant into its numeric value. The constant's name is passed as the subroutine's single argument as a string variable.command_line - a shell command linesc = DoCommand("ls -la")
print sc
The shell command is a generic command (i.e., not under your user name) and thus this example returns the directory of the computer's root folder.
saveFile - full path to the filetext - unicode string to write to the filesilent - True to exit without alerting the user (default is False)UTF8 encoding. The file name must be the full POSIX path (folders delimited by slashes) to the file. If the save is successful, this method returns None after saving. If an error occurs, this method returns a description of the error. If silent is False, the user is also alerted of the error using a standard alert window. If silent is True, the description is returned without showing an alert (the default for silent is False).