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:
/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).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.
These methods are used when a script starts of for fetching basic information needed for the script.
Returns a reference to the application object, or None
if the checks fail.
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
.
Returns a reference to the current front document.
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).
The methods in this section and several following sections are convenience methods for looking up records or other common tasks with records.
Returns list of all records of the specified type current selected in the specified document.
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.
These methods help access information about individual records.
Returns reference to the selected individual record or None
.
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).
Use in for
loop to iterate over all individual records.
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.
Reference to the person's father or None
.
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.
Reference to the person's mother or None
.
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.
Returns a list of ancestors of an individual.
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).
Returns a list of descendants of an individual.
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).
These methods help access information about family records.
Returns reference to the selected family record or None
.
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).
Use in for
loop to iterate over all family records.
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.
These methods help create and access information about note records.
Create notes record and returns reference to the record.
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.
Returns first comment found from the list as [comment,comment text]
.
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"])
The methods in this section are convenience methods for working with structures.
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"})
These methods make it easier to get input from the user.
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.
Returns entered integer or None
if canceled.
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.
Returns text of the button clicked
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.
Returns the entered text or None
if canceled.
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.
Returns (item text,item number) in tuple for selected item.
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.
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:
"html"
or "monospace"
)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"
StyleThe 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.
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..
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.
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"
StyleThis 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").
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.
font-family
name allowed in style sheetsThe 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.
These methods provide various utility functions for scripts.
Returns name of the current script
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.
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.
Returns html
code for part of a table
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
keyword and end with an end
keyword. These trigger the <table>
and </table>
elements in the html data.caption
keyword in a string variable.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.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.Returns html
code for a complete list
Converts any list of strings into an html
list for inclusion in a report. The list can be numbered or unorderd.
Returns html
hyperlink to the record
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).
Returns html
block within <center>
elements
Returns html
code to center the block of text in the passed string variable.
Returns string for the number and uses words for 0 to 10
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.
Returns Roman Numeral (upper case) for the number
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.
Returns time span between the two dates in years.
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
.
Returns code that can be used where those constants are expected.
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".
Returns the output of the command (if any)
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.
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.
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
).