GEDitCOM II Scripting Module for Python Scripts

GEDitCOM II is installed with a GEDitCOMII.py Python module to help in writing Python scripts. This module provides numerous classes and utility functions to enhance the Python scripting experience and to turn scripting of GEDitCOM II a genealogy programming platform. This web page documents the current version of this module.

Four important remarks on the GEDitCOMII.py module are:

  1. The module is evolving and new ideas for classes an utility functions arise. If your version is out of date, you can download the lastest version here (note: if you open the module in the GEDitCOM Editor, you can read your version number in the comments at the beginning of the code).
  2. The module is a collection of convenience methods. The absence of a method for some function you need does not mean that function is not possible. You can always use native GEDitCOM II script methods as documented in the scripting topics in GEDitCOM II help window.
  3. The default module is installed in the /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 the corresponding folder GEDitCOM II user domain (or to the /Users/(your name)/Library/Application Support/GEDitCOM II/Modules folder).
  4. Because the GEDitCOMII.py module is continually evolving, it is possible it has more features then documented here. If you open the source code in the GEDitCOM Editor, you can browse all functions. Those labeled "NOT DOCUMENTED" are not yet documented. They are planned to be documented here soon.

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.


Initialization Tools

These methods are used when a script starts of for fetching basic information needed for the script.

CheckVersionAndDocument(sName,vNeed[,bNeed])
  • sName - the name of the script
  • vNeed - the GEDitCOM II version required to run this script
  • bNeed - the build number (option, the default is 1)

Returns a reference to the application object, or None if the checks fail.

CheckVersionAndDocument() Function

Python scripts cannot perform many useful tasks unless a document is open. This subroutine will verify that a document is open. It should normally be called at the beginning of every script.

This subroutine also checks that the current version is adequate for the needs of the script. If you use scripting methods that only became available in a certain version, you should specify that version number to this subroutine. The build number argument checks for build number too. Scripts that use this Python module, for example, require version 1.6, build 2. Note that when running scripts in an extension (GEDitCOM II, version 2.0 or newer), you can specify a minimum version number in the extension settings and can skip the check in this method (by either omitting vNeed and bNeed or providing low numbers).

If all checks are passed, this function returns a reference to the current application object. If no document is open or if the version number is not adequate, a message is printed to the GEDitCOM II scripting panel and the function returns None.


FrontDocument()

Returns a reference to the current front document.

FrontDocument() Function

Returns a reference to the current front document in GEDitCOM II or returns None if no document is open. To find a document other than the front document, you can look at gedit.documents()[1] (or higher than 1 and where gedit is reference to the application).



Work with Records

The methods in this section and several following sections are convenience methods for looking up records or other common tasks with records.

GetSelectedType(rtype[,gdoc])
  • rType - GEDCOM code for record type (e.g., INDI)
  • gdoc - find records in this document (or front document if omitted).

Returns list of all records of the specified type current selected in the specified document.

GetSelectedType() Function

This function finds all the currently selected records and then creates a new list having only records of one type (as specified in the rtype) parameter. Usually this function is for the current front document and the selected records refer to the front window for that document.



Work with Individual Records

These methods help access information about individual records.

GetIndividual([gdoc,prompt])
  • gdoc - find individual in this document (or front document if omitted).
  • prompt - user prompt when selecting from a list.

Returns reference to the selected individual record or None.

GetIndividual() Function

Returns a reference to the first selected individual record in the current front document, or in 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 if shown a list of all individuals and can select one. The selected one is returned (or None if that selection is canceled).


EveryIndividual([gdoc])
  • gdoc - individuals in this document, or front document if omitted.

Use in for loop to iterate over all individual records.

EveryIndividual() Function

This function returns an iterator for looping over all individuals in the front document (or in 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.


GetFather(person)
  • person - reference to an individual

Reference to the person's father or None.

GetFather() Function

Returns a reference to a person's father's record. If the person does not have a father, it returns None. If the person has more than one father, the reference is to the first father.


GetMother(person)
  • person - reference to an individual

Reference to the person's mother or None.

GetMother() Function

Returns a reference to a person's mother's record. If the person does not have a mother, it returns None. If the person has more than one mother, the reference is to the first mother.


GetAncestors(indi[,gdoc,maxgen])
  • indi - reference to an individual
  • gdoc - document for the individual (or front document if omitted)
  • maxgen - maximum number of generations to find (or all if omitted)

Returns a list of ancestors of an individual.

GetAncestors() Function

This function generates an ancestor tree and then returns a list of all ancestors in that tree. The format for the list is described in the GEDitCOM II scripting help (see listedRecords() for "Ancestor Family Tree window" under "Working with Genealogy Documents" in the "Writing Python or Ruby Scripts" help topic). The document is needed (in gdoc) for this method, but can be omitted if it is the front document. 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).


GetDescendants(indi[,gdoc,maxgen])
  • indi - reference to an individual
  • gdoc - document for the individual (or front document if omitted)
  • maxgen - maximum number of generations to find (or all if omitted)

Returns a list of descendants of an individual.

GetDescendants() Function

This function generates a descendant tree and then returns a list of all descendants in that tree. The format for the list is described in the GEDitCOM II scripting help (see listedRecords() for "Descendant Family Tree window" under "Working with Genealogy Documents" in the "Writing Python or Ruby Scripts" help topic). The document is needed (in gdoc) for this method, but can be omitted if it is the front document. 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).



Work with Family Records

These methods help access information about family records.

GetFamily([gdoc,prompt])
  • gdoc - find family in this document (or front document if omitted).
  • prompt - user prompt when selecting from a list.

Returns reference to the selected family record or None.

GetFamily() Function

Returns a reference to the first selected family record in the current front document, or in 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 if shown a list of all families and can select one. The selected one is returned (or None if that selection is canceled).


EveryFamily([gdoc])
  • gdoc - families in this document, or front document if omitted.

Use in for loop to iterate over all family records.

EveryFamily() Function

This function returns an iterator for looping over all families in the front document (or in 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.



Work with Note Records

These methods help create and access information about note records.

AddNoteRecord([gdoc,noteText])
  • gdoc - the document (or front document if omitted)
  • noteText - text for the notes

Create notes record and returns reference to the record.

AddNoteRecord() Function

Create a new notes record in the provided document (or front document if none provided) and then returns a reference to that new record. You can can provide text content for the notes in noteText or set its text later using properties of the returned record.


GetHTMLComment(ntext,comments)
  • ntext - notes text as a string
  • comments - list of labels to be searched

Returns first comment found from the list as [comment,comment text].

GetHTMLComment() Function

This will search html content (any string beginning in <div> element, usually from notes records) 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 the 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 "Generations LaTeX Book" script 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 book). It prefers the "TeX" version, but will accept an "alt" version. The one to use is found with:

    GetHTMLComment(ntext,["TeX","alt"])


Work with Structures

The methods in this section are convenience methods for working with structures.

AddStructure(grec,p)
  • grec - record or structure
  • p - properties for the new structure

AddStructure() Subroutine

Adds a structure subordinate to the record or structure in grec. 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"})


User Interaction Functions

These methods make it easier to get input from the user.

Alert(mainText[,message)
  • mainText - main text for the alert
  • message - extra line of text to display in smaller font

Alert() Subroutine

Displays an alert window to the user with the main text in bold and the optional message in a smaller font. The window has a single "OK" button to close the window.


GetInteger(prompt,title[,istart,imin,imax])
  • prompt - prompt to user
  • title - window title
  • istart - initial number in the editing field
  • imin to imax - acceptable range for the entered number

Returns entered integer or None if canceled.

GetInteger() Function

Displays a window with a single editing field for the user to enter an integer. The first two parameters provide a prompt to the user above the editing field and a title for the window. The istart 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 of None if the user cancels the process.


GetOption(prompt,msg,options)
  • prompt - prompt to the user
  • msg - addition information for the user (displayed under prompt in smaller font)
  • options - list of 1, 2, or 3 strings for text of buttons.

Returns text of the button clicked

GetOption() Function

Displays a window with the prompt and one to three buttons. The text of the buttons are provided in 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.


GetString(prompt[,initial,title])
  • prompt - prompt to the user
  • initial - initial text in the editing field
  • title - title for the window

Returns the entered text or None if canceled.

GetString() Function

Display a window with a single editing field and the prompt to the user above the field. The user can enter a single line of text and click "OK" or "Cancel". The initial 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.


GetOneItem(items[,prompt,title])
  • items - a list of items as strings
  • prompt - prompt for the user
  • title - title for the window

Returns (item text,item number) in tuple for selected item.

GetOneItem() Function

Displays a window with a list of any numbers of items and a prompt to the user above that list. The window can have an optional title. The user can select one item and click "OK" or "Cancel" (or double click the one item). The function returns the text of the clicked item and the number for the clicked item in a two-element tuple - (item text, item number). The item numbers start at 1. It returns (None, None) if the selection is cancelled by the user.



ScriptOutput Class

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 instance 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:

ScriptOutput(name,style[,file])
  • name - the name of the script
  • style - output style ("html" or "monospace")
  • file - full path name when the output will be written to a file

Returns in instance of the ScriptOutput class.

# create a ScriptOutput object
rpt = ScriptOutput(GetScriptName(),"html",None)
	
# the script adds content to the rpt object using its methods
	
# generate script out
rpt.write()
	

When the ScriptOutput object is created, you provide the script name (here the name comes from the GetScriptName() function), the style of the report ("html" in above example), and a file name if you want file output (otherwise use None as above or omit the last parameter). The bulk of the script uses ScriptOutput helper methods to add to the output data. Finally, when the script is done, call write(), which will output the script depending on the report style. The following sections list the currently supported styles.

"html" Style

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 would be needed.

ScriptOutput class: out(text)
  • text - string of text to add to the output

You add html content for output using the out() method:

  rpt.out("<h1>Section Title</h1>\n")

Build a complete report by adding any html content. The above line feed character ("\n") is not needed for html display, but can be useful if you will later look at the html content for editing. The out() method does not insert line feeds. There are several utility functions to help create html output for tables, lists, record links, etc..

ScriptOutput class: css(text)
  • text - string of text to add style sheet for this content

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. The line feeds are optional, but can help with readability if you look open the raw html text.

ScriptOutput class: write()

Call this method at the end of the script to output the data to a report or a file.

When all the content is done, you output the results using the write() method:

  rpt.write()

The output will be displayed in a report window or written to an .html file depending on whether or not you specified a file when the ScriptOutput object was created. Recall that you should only add the core html content. The ScriptOutput class will surround the content in a <div> for reports and will construct file preamble and surrounding <body> element when writing to a file. In other words, the exact same html content can be sent to a report or sent to a file simply by changing the file name parameter.

"monospace" Style

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.

You add text to this report with the out() method in the ScriptOutput class:

  rpt.out("A line of text for a report\n"")

Each new text string is concatenated to the output text. To start new lines in the report, the added text has to include line feed characters ("\n").

ScriptOutput class: cols(text1,col1,text2,col2,...)
  • texti - add this text to the output
  • coli - pad previous text up to but just before this column

There can be any number of arguments. If the number is odd, the last text is added without padding. If a column is negative, the previous text is right justified up to the column (which is then absolute value of the entered number).

To help align output in columns, you can add text with the cols() method:

  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 string (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 starting 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 subsequent out() command) to move to the next line.

ScriptOutput class: SetFont(name)
  • name - any font-family name allowed in style sheets
ScriptOutput class: SetFontSize(size)
  • size - font size in points

The default font for monospace output is 9 point 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 any other font:

  rpt.SetFont("Times")
  rpt.SetFontSize(12)

These settings can be used anytime before final output, but you cannot mix fonts and sizes. The entire output report will use the last setting provided.

When all the content is done, you output the results using the write() method:

  rpt.write()

The output will be displayed in a report window or written to an .txt file depending on whether or not you specified a file when the ScriptOutput object was created. The report window will use the specified single font. Output to file will be a plain text file (.txt). The font settings will be ignored for file output, but you can choose any font after opening that file in a text editor.


Utility Functions

These methods provide various utility functions for scripts.

GetScriptName()

Returns name of the current script

GetScriptName() Function

Returns the name of the current script. The name is the name provided to CheckVersionAndDocument() method when the script start. 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.


ProgressMessage(fraction[,msg])
  • fraction - fraction completed (0 to 1)
  • msg - String to print on next line of the scripting panel

ProgressMessage() Subroutine

Scripting of GEDitCOM II is a great tool, but it can get slow for large calculations in large files. For this reason, all good GEDitCOM II scripts should inform the user of the progress of the calculations. Here is sample code

  # 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.

Periodically during the script, you should then calculate the fraction of the script that has finished. This sample code shows a script with a repeat loop that will execute 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.

For other scripts, it may be harder to determine the fraction completed (such as a script searching for ancestors when you do not know how many ancestors will be found). For these scripts, you have three options. First, you can periodically guess the fraction. Second, you can post a message to the user with the optional 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.


MakeTable(args)
  • args - list of commands are arguments as explained in documentation

Returns html code for part of a table

MakeTable() Function

This function builds part of an html 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",["Column 1","Column 2"])
  
  # body of the table
  rpt.out(MakeTable("body"))
  for i in range(numRows) :
      rpt.out(MakeTable("row c r",col1[i],col2[i]))
    
  # end the bode and the table
  rpt.out(MakeTable("endbody","end"))

The arguments to MakeTable() have keywords and some keywords are followed by a parameter. Each call can have any number of keywords and parameters. A series of calls fill out the table. The table keywords are:

"begin" ... "end"
Each sequence must always start with a begin keyword and end with an end keyword. These trigger the <table> and </table> elements in the html data.
"caption","Text for the caption"
Provides an optional table caption. The text of the caption follows the caption keyword in a string variable.
"head l c r mystyle",["header 1","header 1","header 1","header 1"]
Provides an optional row of header cells. The head key word can optionally be followed by 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 cascasding style sheet options. If no alignment columns are used, the header row cells are centered.
"body" ... "endbody"
The remainder of the table data should be surrounded by these keywords. These make tables work better with the default cascading style sheet for reports.
"row l c r mystyle",["col 1","col 2","col 3","col 4"]
Provides an row of data for the table. The row key word can optionally be followed by 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 column uses that class from the report's cascasding style sheet options. If no alignment columns are used, the columns are left justified.

MakeList(alist[,ordered])
  • alist - a list of text strings
  • ordered - True for numbered list or False (the default) for unordered list

Returns html code for a complete list

MakeList() Function

Converts any list of strings into an html list for inclusion in a report. The list can be numbered or unorderd.


RecordLink(ref[,alternate])
  • ref - reference to a gedcom record
  • alternate - True to use alternate name or False (the default) for standard name

Returns html hyperlink to the record

RecordLink() Function

Reports created in html 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).


Centered(ctext)
  • ctext - text to be centered

Returns html block within <center> elements

Centered() Function

Returns html code to center the block of text in the passed string variable.


Cardinal(anum)
  • anum - an integer

Returns string for the number and uses words for 0 to 10

Cardinal() Function

For numbers 0 to 10, it returns the number as a word, such as "zero", "one", "two", etc.; for all other numbers it converts the number to a string and returns the result.


RomanNumeral(number)
  • number - a number

Returns Roman Numeral (upper case) for the number

RomanNumeral() Function

For integers 1 to 4999, it returns Roman number (using upper case letters) for the number; for all other numbers it converts the number to a string and returns the result.


GetAgeSpan(beginDate, endDate)
  • beginDate - serial day number for starting date
  • endDate - serial day number for ending date

Returns time span between the two dates in years.

GetAgeSpan() Function

This function converts the time between two serial day numbers into the number of years. The time span is from the beginDate to the endDate.


GCConstant(constantName)
  • constantName - name of the constant

Returns code that can be used where those constants are expected.

GCConstant() Function

Some commands take arguments that select among two or more defined constants in the Apple Scripting dictionary for GEDitCOM II. Similarly, the restriction 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.

The current named constants are: "chart", "outline", "the children", "the events", "the spouses", "charMacOS", "charANSEL", "charUTF8", "charUTF16", "charWindows", "linesLF", "linesCR", "linesCRLF", "mmGEDitCOM", "mmEmbed", "mmPhpGedView", "logsInclude", "logsOmit", "locked", "privacy", and "unlocked".

DoCommand(command_line)
  • command_line - a shell command line

Returns the output of the command (if any)

DoCommand() Function

The function executes a shell command, waits for the output, and then returns the result as a string. For example, the following commands will list the files in the working directory:

  sc = DoCommand("ls -la")
  print sc

The shell command is generic command (i.e., not under you user name) and this this example returns the directory of the computer's root folder.


WriteUTF8File(saveFile,text[,silent])
  • saveFile - full path to the file
  • text - unicode sting to write to the file
  • silent - True to exit without alerting the user (default is False)

Returns None if the save is successful or an description of the error if not.

WriteUTF8File() Subroutine

Write the text (in a possibly unicode string) to a file using 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).