EasyCatalog Lua Scripting
In the release of InDesign CC2015, EasyCatalog implemented a more sophisticated command parser based on the Lua scripting language. This gives EasyCatalog users the power to extend its functionality beyond its current capabilities making anything possible.
Feel free to talk to us at CUNKA about using the power of LUA in EasyCatalog to solve your issues.
Overview
Lua is a powerful, efficient, lightweight scripting language.
It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.
Lua scripts are executed in a number of contexts:
Field Options - Appearance Panel
Scripts can be used to control the appearance and content of each cell. In this context, predefined variables are available, indicating the position and size of the cell:- x
- y
- width
- height
See our Using Appearance to change the panel style example.
Text Frame Content
Lua code enclosed with text markers [[ and ]] is treated as an executable script. The SELECTION object can be used to inspect the populating content. The markers can be modified and behaviour disabled via an Advanced preference.See our Document decisions while paginating examples.
Script Label
Scripts are processed during content population. A "frame" variable is passed into the script representing a FRAME object.See our Controlling a Frame from a Script Label and Using a frame script label examples.
Custom Reports
A "selection" variable is passed into the script representing a SELECTION object.See our Custom Report example.
Tabular Fields
Provides processing and creation of tabular field content. When used in "Additional Processing..." of tabular fields, a variable "table" of class "TABLE" is passed, which represents the fields tabular content.See our Tableof example.
Custom Fields
'Advanced' type fields execute scripts. The return value becomes the field content. Example:-return string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)"));
Events
Script files are executed in response to certain events. Consult the scripting documentation for more detailed information. Variables are passed in based on the context of the call. For example, during pagination a "document" object is provided.
Augmenting Datasources
A createcontent.lua script, located in the data sources scripts folder, is called immediately before data is loaded. The script is passed a ‘records’ variable which is a RECORDSET object. Further details.
Batch Creation of Formatted Field Content
If a script called createformattedcontent.lua is present in a data sources Scripts folder, it is called as the last stage of formatted field content creation. This makes it possible to create formatted content for any field, both tabular and regular. Any existing formatted content is replaced. Unformatted content cannot be changed.Example:
-- Populate a single field with a value based on its content recordset = DATASOURCE.get():getrecordset(); for record = 1,recordset:size() do myRecord = recordset:getrecord(record); myField = myRecord:field("field to test"); str = myField:content(); if str == "1" then myField:setformattedcontent("value is one"); else myField:setformattedcontent("something other than one"); end; end
Post Processing of Formatting Rules
A formattingrule variable is passed during execution of Formatting Rules "Post Processing" code. Post Processing occurrs after the Formatting Rule has been populated, but before it is paginated. This provides a mechanism to manipulate the content of the Formatting Rule.Accessing the InDesign Scripting DOM
Where a FRAME or FORMATTINGRULE object is available, the InDesign Scripting DOM can be accessed.Example: Insert text into a text frame
framedom = frame:getdom(); framedom:parentStory():texts():item(0):contents("This is the InDesign Scripting DOM")
Debugging Lua
Read our detailed instructions Debugging EasyCatalog LUA with ZeroBrane.
Remote debugging is supported using the ZeroBrane Studio IDE. Debugging is only available when "Enable Sockets" is set to true in Advanced preferences. To Debug:
- Copy mobdebug.lua and socket.lua into any location checked by the 'require' command (A list is shown if the module cannot be found). These are available from the ZeroBrane download.
- Launch the IDE. Go to Project | Start Debugger Server and start the debugger server (if this menu item is disabled, the server is already started)
- Add require('mobdebug').start() call to your script.
- Test your script. You should see a green arrow pointing to the next statement after the start() call in the IDE and should be able to step through the code
Summary of classes and methods exposed to the Lua language
Appearance Functions
drawcircle (x, y, radius) | Draws a circle. |
drawline (x1, y1, x2, y2) | Draw a line. |
drawstring (x, y, string[, width]) | Draws a string, optionally constrained to a given width. |
fillrect (x, y, width, height) | Fill a rectangle with the current color. |
lineto (x, y) | Draw a line to the given position, then make that position the current. |
moveto (x, y) | Move to a set position. |
setcolor (red, green, blue) | Apply color to the next operation. |
setlinewidth (width) | Sets the current line width. |
setopacity (opacity) | Apply opacity to subsequent drawing operations. |
General Functions
base64encode (string) | Encode a string using Base64. |
encryptdecryptfile (key, key) | Toggle encrypt or decryption of the given file |
field (name) | Get the contents of a named field. |
fieldsetcontent (name, new) | Set the content of a named field. |
formatedatetime (date, input_format, output_format) | Formats the given date-time string. |
processjson (method, json, params) | Process JSON using one of the built in methods. |
setplaceholder ([flag=true]) | Used in Advanced custom fields to flag the field as a placholder. |
sha1encode (string[, wanthex=true]) | Encode a string using SHA1. |
sha256encode (string) | Encode a string using SHA256. |
split (string, delimiter[, unique=false]) | Splits the given string into a table. |
tolower (string) | Convert a string to lowercase. |
topoints (uom) | Convert a string containing a unit of measure to points. |
toupper (string) | Convert a string to uppercase. |
Class FIELD
content () | Get the fields formatted content. |
get ([name]) | Return a FIELD object for the named field. |
getdatasource () | Get the parent DATASOURCE. |
getrawcontent () | Get the fields raw content as a string. |
getupdatestate () | Return the status of the field. |
name () | Get the name of the field. |
setcontent (value) | Set the field content. |
setformattedcontent (value) | Set the formatted content of the field. |
setupdatestate (flags) | Set the update state flags for the field. |
xml () | Contents of the field as an XML object. |
Class RECORD
exists (key[, datasource]) | Check if the specified record exists. |
field (value) | Return a FIELD object for the given field. |
fieldexists (name) | Returns true if a named field exists. |
get (key[, datasource]) | Get the specified record . |
key () | Get the key field value of a record. |
select () | Select the record for content population. |
size () | Number of fields in the record. |
Class TEXT
insert (text[, charstyle]) | Insert the specified text into the text flow. |
insertfield (name) | Insert a field into the text flow. |
inserthyperlink (text, destination, type) | Insert a Hyperlink. |
insertrule (rulename) | Insert a Formatting Rule into the text flow. |
pageindex () | Returns the page index of where the command is executed. |
pagename () | Returns the name of the page the command is executed on. |
pagetype () | Returns the type of page at insertion point(left/right/unisex). |
repeatrule (rulename[, separator]) | Repeats a formatting rule for each record paginated. |
x () | X position of command on layout (in points). |
y () | Y position of command on layout (in points). |
Class SELECTION
cut (from, to) | Cuts a range of elements from the selection and return a new SELECTION. |
get (index) | Returns a new SELECTION object for the Nth child element. |
getcontent (fieldname) | Returns the formatted content of a the given field. |
getrecordset () | Returns all records in the selection. |
group (group) | Returns a new SELECTION object with the contents of the named group. |
name () | Returns the name of the selection. |
new (RECORDSET) | Creates a new SELECTION object containing records in the given set. |
root () | Returns a new SELECTION object which represents the current selection. |
setroot () | Sets a new root selection. |
size () | Returns the number of child elements. |
type () | Selection type. |
Class FRAME
aligncontent (align) | Align the content of a frame within the frame bounds. |
applyframecolor (colorname) | Apply a stroke color to the frame |
applyframestroke (strokeweight) | Apply a frame stroke. |
applyobjectstyle (stylename) | Apply an object style to the frame. |
bottom ([position]) | Get or set the bottom position of the frame relative to the page. |
contentheight ([width]) | Get/Set the height of the frame. |
contentwidth ([width]) | Get/Set the width of the frame. |
delete () | Delete the frame. |
duplicate ([cell]) | Duplicate the frame. |
fillcontent () | Fill content proportionally within the frame. |
fitcontent () | Fit content proportionally within the frame. |
fitframetocontent () | Fit the frame to the content |
generateqrcodetext (text[, swatchname]) | Generate text based QR code content. |
generateqrcodevcard (FirstName, LastName, JobTitle) | Generate a QR code V Card. |
getbounds () | Get the bounds of the frame. |
getdom ([object=PageItem]) | Retrieve the InDesign scripting DOM for a PageItem, Document or Application |
getframe (name) | Gets a named FRAME. |
hascontent () | Return true if the frame has content. |
height ([height]) | Get or set the frames height. |
inserthttpimage (url) | Insert an image from the given URL into the frame |
left ([position]) | Get or set the left position of the frame relative to the page top left. |
movecontent (x, y) | Position content relative to the frame. |
moverel (x, y) | Move the frame relative to its current position. |
moveto (x, y) | Move the frame to a specified position. |
moveto (layer) | Move the frame to the named layer. |
qrcodehyperlink (URL[, swatchname]) | Generate Hyperlink based QR code content. |
releaseanchored () | Release the anchored items. |
resize (width, height) | Resize the frame. |
right ([position]) | Get or Set the right position of the frame in points relative to the page top left. |
scalecontent (scale) | Scale the frame content. |
setcomputedfieldcommand (command) | Set the computed field command for the frame. |
setimageindex (index) | Populate the frame with the nth image of a multi image field. |
top ([position]) | Get or set the top position of the frame relative to the page top left. |
updatecontent ([selection]) | Populate the frames fields. |
width ([width]) | Get or Set frame width in points. |
Class DATASOURCE
decryptlua (key) | Decrypt all Lua script files associated with data source. |
encryptlua (key) | Encrypt all Lua scripts associated with data source. |
env (name) | Get a data source environment variable. |
get ([name=current]) | Get a DATASOURCE object. |
getdom () | Returns the scripting DataSource DOM object. |
getfieldindex () | Get the index of a named field. |
getlocation () | Get location of the data source. |
getoption (name) | Returns the named option for the data source, or nil if the option does not exist. |
getrecordset () | Get a RECORDSET object, representing the records of the data source. |
newtable () | Return a table representing the contents of the data source. |
setoption (name, value) | Set the named data source option to the given value. |
size () | Number of records in the data source. |
synchronizewithsource () | Synchonize the datasource with the source data. |
updatecustomfield (field, saveflag, redrawflag) | Force a custom field to update its formatted content. |
xreffield (search, lookfor, return) | Looks up a field based on another fields content. |
Class TABLE
append (table, position) | Append another table onto this one. |
cell (row, column) | Returns a CELL object for the given row and column. |
colcount () | Get the total number of columns in the table. |
collapserows (one[, two[, three[, four]]]) | Removes rows from the table where the specified column indexes are empty. |
combinecols (first, second, separator[, always=true]) | Combines the content of the first column with the second, then deletes the second. |
combinerows (first, second, separator) | Combines the content of the first row with the second, then deletes the second. |
condensetocols (one[, two[, three[, four]]]) | Condense table, leaving only the specified columns, in the specified order |
copycol (from, to) | Copies the specified column index into the given position. |
distinctbodyrows (one[, two[, three[, four]]]) | Removes body rows where the specified columns contain the same value. |
distinctcols (list) | Removes columns from a table where the specified rows contain the same values. |
distinctcontent (top, left, bottom, right) | Removes duplicate content from a range of cells in a table. |
distinctrows (one[, two[, three[, four]]]) | Removes rows where the specified columns contain the same value. |
entitydecode () | HTML Entity decode table contents. |
entityencode () | HTML Entity encode table contents. |
exportexcel (path) | Export table as an Excel file (xlsx) |
exportxml (path) | Export table to an XML file |
getcolindex (searchrow, searchfor) | Returns the index of the column containing the given string. |
getrowindex (searchcol, searchfor) | Returns the index of the row containing the given string. |
getstyle () | Get the table style. |
hlookup (inspect, value, return[, exact=true]) | Searches for a value in a row, and then returns a value in the same column from a row you specify. |
insertcol (after[, count=1]) | Insert column(s) into the table. |
insertrow (after[, count=1]) | Insert row(s) into the table. |
jointable (table, sourcecolumn, matchcolumn) | Join the contents of another table by matching a column in both tables. |
movecol (from, to) | Moves a column into the specified position. |
moverow (from, to) | Moves a row into the specified position. |
new ([various]) | Create a new TABLE object. |
newexcel (path) | Creates a new TABLE object from the Excel spreadsheet at the specified path |
newsql (query) | Create a new TABLE object from the given SQLite query. |
openinbrowser () | Present the contents of the table in the default browser |
present () | Presents the table back to the caller. |
processembeddedcommands () | Process commands embedded in cell content. |
removecol (column) | Removes a column. |
removeemptycols () | Removes all columns where the cell content is empty. |
removeemptyrows ([col1[, col2[, coln]]]) | Removes all rows where cell content is empty. |
removerow (row) | Remove a row. |
rotate () | Return a rotated version of the the table. |
rowcount () | Count of rows. |
select (row) | Make a specified row the active for content population/update. |
setcellstylerange (style, colstart, colend, rowstart, rowend) | Set the style of a range of cells in a table. |
setcolcleansing (index, search, replace) | Perform a search and replace on a column using regular expressions. |
setcoltype (where, type) | Set the type of a column. |
setcolwidthoption (column, option[, min=0[, max=0]]) | Set the width option for a column |
setfooterrowcount (count) | Set the number of footer rows. |
setheaderrowcount (count) | Set the number of header rows. |
setrowcleansing (index, search, replace) | Perform a search and replace on a row using regular expressions. |
setrowkeepwithnext (rowindex, keep) | Set the rows keep with next property. |
setrowstroke (row, edge, weight) | Set the cell stroke for each cell in the row. |
setrowstyle (rowindex, stylename) | Set the cell style for each cell in the row. |
setscriptlabel (label) | Set the script label of the table. |
setsortfunction (function) | Define a customized sorting function which returns true if the first argument is less than (i.e. |
setsortlanguage (language) | Sets the language used for linguistic sort comparisons. |
setsorttype (type) | Sets the sort type for default sort operations. |
setstyle (style) | Set the table style of the table. |
setupdatetype (type) | Sets the update type for the table. |
sortcols (row[, start=1[, end=maximum columns]]) | Sort the columns in a table using the contents of a given row. |
sortrows (column, opt, opt) | Sort the rows in a table using the given column. |
sortrowsbyvalue (row, values[, start=1[, end=max rows]]) | Sorts rows in the given column using a set of predefined values. |
stackcolumns (maxcols, headercols) | Creates a table of with a maximum of maxcols columns. |
totable () | Return the table as an array of rows, each with an array of columns. |
vlookup (searchcol, searchstring, returncol[, exact=true]) | Searches for a value in a column, and then returns a value in the same row from a column you specify. |
Class CELL
copyformatting (cell) | Copy the formatting of the given cell. |
getcontent ([cleansing=false]) | Return cell content. |
getscriptlabel () | Get the script label. |
getstyle () | Get the cell style associated with the cell. |
getwidth () | Get the width of the cell with a point UOM, or nil if it's not been defined. |
setcleansing (search, replace) | Perform a search and replace on cell content. |
setcolspan () | Get the cells column span. |
setcontent (content) | Set the cell content. |
setfill (color) | Set the cells background Swatch or RGB/CMYK value |
setheader (header) | Set the cell as an header. |
setheight (height) | Set the fixed height of the cell. |
setmergeoption (name, value) | Set the cell horizontal or vertical merge options. |
setminimumheight (height) | Set the minimum height of the cell. |
setrowspan () | Get the cells row span. |
setscriptlabel (label) | Set the cells script label. |
setstrokeswatch (edge, swatch) | Set the swatch for a given stroke. |
setstroketint (edge, percentage) | Set the tint value for a given stroke. |
setstrokeweight (edge, weight) | Set a stroke weight associated with the cell. |
setstyle (style) | Set the cell style associated with the cell. |
setuirgb (red, green, blue) | Set the color of a cell. |
setwidth (width) | Set the width of the cell. |
xml () | Get the cells associated XML Node. |
Class XML
getnodes (xpath) | Execute an XPath expression and returns an array of XMLNODE's that match. |
gettable (xpath[, node]) | Returns a TABLE object created from nodes returned by the XPath command. |
new (xml) | Create a new XML parser |
pivottable (record, X, Y, value) | Returns a pivot TABLE object created from the x,y,z parameters. |
Class PROGRESSBAR
new () | Create a new PROGRESSBAR. |
show (title, stepcount[, showcancel=false]) | Display the progress bar. |
update (message) | Update to the next step. |
Class FORMATTINGRULE
align (frames, align[, area=rule]) | Align frames or groups of frames in an area. |
alignedges (frames, align) | Align the edges of a set of FRAMES. |
arrange (frames[, align=left[, final=align[, valign=top[, area[, gutter=0]]]]]) | Arrange frames or groups of frames as a set of rows. |
canarrange (frames[, area[, gutter=0]]) | Determines if frames can be arranged in an area. |
getbounds ([param1[, param2[, param3[, param4[, param5]]]]]) | Returns the geometric bounds of the Formatting Rule, or given arguments. |
getdom () | Retrieve the scripting DOM for the Formatting Rule |
getframe (name) | Gets a named FRAME. |
getframes ([regex]) | Returns a FRAME array. |
placerule (name, x, y[, SELECTION]) | Place a Formatting Rule at the given position. |
Class MENU
MENU.menuitemproperties | Properties of a menu item. |
additem (menuitemproperties) | Add a custom menu item. |
Class DIALOG
dialogproperties | Properties of a dialog. |
widgetproperties | Properties of a widget. |
addwidget (widgets) | Add a single widget or table of widgets to the dialog box. |
alert (message[, type=alert[, buttontext]]) | Display an alert message. |
choosefile (prompt) | Choose a file. |
choosefolder () | Choose a folder. |
close () | Close the dialog box. |
getwidget (id) | Gets the widgetproperties of a named widget |
new (dialogproperties) | Create a new dialog box. |
open () | Display the dialog box. |
saveas () | saveas. |
setwidget (properties) | Sets the widgetproperties of a named widget |
Class HTTP
get (url[, headers[, settings[, filepath]]]) | Perform a HTTP GET operation. |
getparam (body, param) | Perform a HTTP getparam operation. |
gettofile (url, path[, params[, params]]) | Retreive data to file from a URL based resource. |
getwithheaders (url[, headers[, settings[, filepath]]]) | Perform a HTTP GET operation with headers. |
oathgetauthrorizationcode (url, port, url) | Perform a HTTP oathgetauthrorizationcode operation (CS7 or above). |
post (url, data[, headers[, params]]) | Post data to a URL |
urlencode (unencoded) | URL Encode the given string. |
Class LINK
applycharacterstyle (stylesheet) | Apply a character style to a link. |
createhyperlink (hyperlink) | Create Hyperlink associated with the link. |
delete () | Delete an array of links from document. |
getcomputed () | Get the Computed Field command associated with the link |
getcontent () | Get the content of the link. |
getdatasourcename () | Get the data source name. |
getfield () | Get the field name of the link. |
getframe () | Get the FRAME the links is contained within. |
getkey () | Get the links key value. |
getnotes () | Get notes associated with the link. |
getpagenumber () | Get the page number the link is on. |
getspread () | Get the spread the link is on. |
gettextendpos () | Returns the text index of the end of the link. |
gettextlength () | Returns the text length of the link. |
gettextstartpos () | Returns the text index of the start of the link. |
isonpasteboard () | Returns true if the link is on the pasteboard. |
isoutofdate () | Returns true if the link needs updating. |
isoverset () | Returns true if any part of the link is in overset text. |
istext () | Returns true for text based links, false for frame links. |
setdatasourcename (datasource) | Update the project name component of a physical link |
setfieldname (fieldname) | Update the field name component of a physical link. |
setkey (key) | Update the key component of a physical link. |
Class XMLNODE
content () | Returns the content of this node. |
valueof (xpath) | Returns the value from an XPath command relative to this node. |
Class RECORDSET
addfied (name[, value]) | Add a field to the recordset. |
addrecord ([record]) | Add a record to the recordset. |
append (recordset) | Append the contents of the given record set. |
callback (function, sortfield, group1[, group2[, group3]]) | Calls a function for each group of records within this recordset. |
duplicaterecord (record) | Duplicate the 'nth' record. |
filter (field1, value1, field2, value2, field3, value3) | Create a new record set, based on the supplied filter. |
getactivedocname () | Get the active document name |
getdocname () | Get the document name |
getpagepositions (ds[, field=all[, type=any[, rel=page[, uom=mm]]]]) | Creates a table of records placed in the document along with positional information. |
getrecord (record) | Return a record, either by index or by key |
new (fields, records) | Create a new RECORDSET object. |
relatedrecords (field1[, field2[, field3]]) | Create a set of related records based on matching field content. |
removefield (name) | Remove a field from the recordset. |
removerecord (record) | Remove the 'nth' record. |
renamefield (oldname, newname) | Rename a field. |
setfieldcontent (name, value) | Set the content of a field for all records in the recordset. |
settabular (fieldname, TABLE) | Sets the tabular data of all named fields in this record set. |
size () | The number of records in the record set. |
sort (field1[, field2[, field3[, field4[, field5]]]]) | Sort the records in the record set. |
tableof ([field1[, field2[, field3[, field4[, field5]]]]]) | Create a new table. |
Class DOCUMENT
applymaster (index, master) | Apply a named master page to a page in the document. |
deletepage (index) | Delete a page in the document. |
getactive () | Get the active DOCUMENT |
getdom () | Get the Application Scripting DOM. |
getlinks () | Get an array of LINKs in the document |
getselectedlinks () | Get an array of LINKs in the document |
insertpage () | Insert a page at the end of the document. |
pagecount () | Returns the number of pages in the document. |
pagehastags (pageindex) | Determine if a page has any tags. |
pageheight (pageindex) | Get the height of the a page in points. |
pagemargins (pageindex) | Get the page margins. |
pagetype (pageindex) | Get the page type (left/right/unisex). |
pagewidth (pageindex) | Get the width of the a page in points. |
placerule (pageindex, rulename, x, y, data[, location]) | Place a Formatting Rule into the given position. |
synchronize () | Scan the document, updating the placed and error state of each field |
Appearance Functions
- drawcircle (x, y, radius)
-
Draws a circle.
Parameters:
- x number
- y number
- radius number
- drawline (x1, y1, x2, y2)
-
Draw a line.
Parameters:
- x1 number start x position
- y1 number start y position
- x2 number end x position
- y2 number end y position
- drawstring (x, y, string[, width])
-
Draws a string, optionally constrained to a given width.
Parameters:
- x number
- y number
- string string
- width number constrain to given width (optional)
- fillrect (x, y, width, height)
-
Fill a rectangle with the current color.
Parameters:
- x number
- y number
- width number
- height number
- lineto (x, y)
-
Draw a line to the given position, then make that position the current.
Parameters:
- x number
- y number
- moveto (x, y)
-
Move to a set position.
Parameters:
- x number
- y number
- setcolor (red, green, blue)
-
Apply color to the next operation.
Parameters:
- red number (0-255)
- green number (0-255)
- blue number (0-255)
- setlinewidth (width)
-
Sets the current line width.
Parameters:
- width number
- setopacity (opacity)
-
Apply opacity to subsequent drawing operations. Opacity should be between 0.0 (transparent) and
(1.0) opaque.
Parameters:
- opacity number (0-1)
General Functions
- base64encode (string)
-
Encode a string using Base64.
Parameters:
- string string String to encode
Returns:
-
string
encoded string
Usage:
str = base64encode("some value");
- encryptdecryptfile (key, key)
-
Toggle encrypt or decryption of the given file
Parameters:
Usage:
done, path = DIALOG.choosefile("Choose a file"); if done == true then encryptdecryptfile(path, "secretkey") end;
- field (name)
-
Get the contents of a named field. If the field is a tabular field, a TABLE object will be
returned
Parameters:
- name string
Returns:
-
string
Field content
Usage:
content = field('price');
- fieldsetcontent (name, new)
-
Set the content of a named field.
Parameters:
Usage:
fieldsetcontent('price', '$99');
- formatedatetime (date, input_format, output_format)
-
Formats the given date-time string.
Parameters:
Returns:
-
string
Formatted String
- processjson (method, json, params)
-
Process JSON using one of the built in methods.
Parameters:
- method string Method name. Currently supports jmespath and mustache.
- json string The source JSON.
- params string Parameters for the method.
Returns:
-
result
The result string
Usage:
j = '{\n "locations": [\n {"name": "Seattle", "state": "WA"},\n {"name": "New York", "state": "NY"},\n {"name": "Bellevue", "state": "WA"},\n {"name": "Olympia", "state": "WA"}\n ]\n}' e = "locations[?state == 'WA'].name | sort(@) | {WashingtonCities: join(', ', @)}" return processjson("jmespath", j,e)
- setplaceholder ([flag=true])
-
Used in Advanced custom fields to flag the field as a placholder.
Parameters:
- flag bool (default true)
Usage:
setplaceholder(true);
- sha1encode (string[, wanthex=true])
-
Encode a string using SHA1.
Parameters:
- string string String to encode
- wanthex bool Return the value in Hexadecimal. (default true)
Returns:
-
string
Encoded string
Usage:
str = sha1encode("some value");
- sha256encode (string)
-
Encode a string using SHA256.
Parameters:
- string string String to encode
Returns:
-
string
Encoded string
Usage:
str = sha256encode("some value");
- split (string, delimiter[, unique=false])
-
Splits the given string into a table. Handles Unicode strings.
Parameters:
Returns:
-
table
table of split strings
Usage:
-- All values v = split("a-b-c", "-"); return v[1] -- returns "a" -- Unique values v = split("a-a-a-b-b-b-c-c-c", "-", true); return v[2] -- returns "b"
- tolower (string)
-
Convert a string to lowercase. Handles Unicode strings.
Parameters:
- string string String to convert
Returns:
-
string
Lower case string
Usage:
lower = tolower("ÉCHELLE");
- topoints (uom)
-
Convert a string containing a unit of measure to points.
Parameters:
- uom string Value including unit of measure
Returns:
-
number
Value in points
Usage:
pointval = topoints("5cm");
- toupper (string)
-
Convert a string to uppercase.
Parameters:
- string string String to convert
Returns:
-
string
Upper case string
Usage:
upper = toupper("échelle");
Class FIELD
- content ()
-
Get the fields formatted content. Returns a TABLE if the field is a tabular field, otherwise the
fields formatted content.
Returns:
-
string
Fields formatted content (non tabular fields).
Or
-
TABLE
(tabular fields)
Usage:
mytable = mysel:getfield('data'):content(); rowcount = mytable:rowcount(); for i = 1, rowcount do --- Process Row end
- get ([name])
-
Return a FIELD object for the named field. This is not a member function as the field is
determined from the calling context.
Parameters:
- name string Field name. If no name is suppled then the 'current' field is given. Useful for the Appearance context. (optional)
Returns:
-
FIELD
object
Usage:
--- Notice the use of 'FIELD.' rather than 'FIELD:' --- As this is a function of the FIELD class and not a member type function, --- the single dot notation should be used. myField = FIELD.get('variants'); --- get an XML object associated with a field myXML = myField:xml() --- return field content return FIELD.get('item_id'):content();
- getdatasource ()
-
Get the parent DATASOURCE.
Returns:
Usage:
mydatasource = myField:getdatasource();
- getrawcontent ()
-
Get the fields raw content as a string.
Returns:
-
string
Fields raw content.
Usage:
rawdata = mysel:getfield('data'):getrawcontent();
- getupdatestate ()
-
Return the status of the field.
Returns:
-
int
update status, bits in return value (1 = updated during synchronize, 2 = updated by user)
Usage:
for i=1,records:size() do record = records:getrecord(i); for x=1, record:size() do field = record:field(x); if field:getupdatestate() & 2 == 2 then error("field ".. field:name() .. " needs updating"); end end end
- name ()
-
Get the name of the field.
Returns:
-
string
Field name
Usage:
myName = myField:name();
- setcontent (value)
-
Set the field content. Recreates the formatted content. Can only be used in certain contexts
where legal to do so.
Parameters:
- value string New content
Usage:
- setformattedcontent (value)
-
Set the formatted content of the field. The unformatted content remains unchanged.
Parameters:
- value string New content (string or TABLE for tabular fields)
Usage:
recordset = DATASOURCE.get():getrecordset(); for record = 1,recordset:size() do myRecord = recordset:getrecord(record); tab = TABLE.new(); tab:cell(1,1):setformattedcontent("Table for a Single Field #" .. record); myRecord:field("Example Tabular Field"):setformattedcontent(tab); str = myRecord:field("ID_catalogue"):content(); if str == "1" then myRecord:field("ID_catalogue"):setformattedcontent("content is one"); else myRecord:field("ID_catalogue"):setformattedcontent("content is other than one"); end; end
- setupdatestate (flags)
-
Set the update state flags for the field.
Parameters:
- flags integer
Usage:
for i=1,records:size() do record = records:getrecord(i); for x=1, record:size() do field = record:field(x); if field:getgetupdatestate() & 2 == 2 then field:setupdatestate(0) end end end
- xml ()
-
Contents of the field as an XML object.
Returns:
-
XML object
See also:
Usage:
myField = FIELD.get('variants'); myXML = myField:xml();
Class RECORD
- exists (key[, datasource])
-
Check if the specified record exists.
Parameters:
Returns:
-
bool
true if the record exists
Usage:
myRecord = RECORD.exists('SKU123', 'Some Data Source');
- field (value)
-
Return a FIELD object for the given field. Takes name or index. Throws an error if the field
does not exist.
Parameters:
- value string Name or index of a field
Returns:
-
FIELD
New object instance
Usage:
content = myRecord:field('variants');
- fieldexists (name)
-
Returns true if a named field exists.
Parameters:
- name string Name of a field
Returns:
-
true
if a field exists
Usage:
exists = myRecord:fieldexists('variants');
- get (key[, datasource])
-
Get the specified record .
Parameters:
Returns:
-
RECORD
or nil if the record could not be found
Usage:
myRecord = RECORD.get('SKU123', 'Some Data Source');
- key ()
-
Get the key field value of a record.
Returns:
-
string
Key field value
Usage:
rec = RECORD.get(); keys = ""; for i=1,rec:size() do key = rec:key(i); keys = keys .. key .. ',' end return fieldnames;
- select ()
-
Select the record for content population. Used primarily for embedded commands where field
specifiers are enclosed as part of a command sequence.
Returns:
-
none
Usage:
myfield:select();
- size ()
-
Number of fields in the record.
Returns:
-
int
Number of fields
Usage:
rec = RECORD.get(); fieldnames = ""; for i=1,rec:size() do field = rec:field(i); fieldnames = fieldnames .. field:name() .. ',' end return fieldnames;
Class TEXT
- insert (text[, charstyle])
-
Insert the specified text into the text flow. Meta character sequences, such as ^p, ^n, etc are
interpreted.
Parameters:
Returns:
-
none
Usage:
--- Function to echo the insertion point location function traceposition(sel) for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(TEXT.pageindex()); TEXT.insert(' - '); TEXT.insert(TEXT.x()); TEXT.insert(' x '); TEXT.insert(TEXT.y()); TEXT.insert('^p'); end; end; traceposition(SELECTION.root());
- insertfield (name)
-
Insert a field into the text flow.
Parameters:
- name string Name of the field to insert
Returns:
-
none
Usage:
TEXT.insertfield('Company Name');
- inserthyperlink (text, destination, type)
-
Insert a Hyperlink.
Parameters:
- text string text to insert
- destination string desitination hyperlink
- type string type of hyperlink "page", "url"
Returns:
-
none
Usage:
value = field(“Current Page No”) page_table = split(value) for index, value in ipairs(page_table) do TEXT.inserthyperlink(‘to page ’ .. value, value, ‘page’) end
- insertrule (rulename)
-
Insert a Formatting Rule into the text flow.
Parameters:
- rulename string name of a Formatting Rule associated with the document
Returns:
-
none
Usage:
TEXT.insertrule('my rule');
- pageindex ()
-
Returns the page index of where the command is executed. -1 if it's on overset or on the
pasteboard.
Returns:
-
int
page index number
Usage:
function traceposition(sel) for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(TEXT.pageindex()); TEXT.insert(' - '); TEXT.insert(TEXT.x()); TEXT.insert(' x '); TEXT.insert(TEXT.y()); TEXT.insert('^p'); end; end; traceposition(SELECTION.root());
- pagename ()
-
Returns the name of the page the command is executed on.
Returns:
-
string
page name
Usage:
function traceposition(sel) for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(TEXT.pagename()); TEXT.insert(' - '); TEXT.insert(TEXT.pageindex()); TEXT.insert(' - '); TEXT.insert(TEXT.x()); TEXT.insert(' x '); TEXT.insert(TEXT.y()); TEXT.insert('^p'); end; end; traceposition(SELECTION.root());
- pagetype ()
-
Returns the type of page at insertion point(left/right/unisex).
Returns:
-
string
type ("left","right","unisex")
Usage:
if TEXT.pagetype() == "left" then TEXT.insertbreak("frame"); end
- repeatrule (rulename[, separator])
-
Repeats a formatting rule for each record paginated.
Parameters:
Returns:
-
none
Usage:
[[TEXT.repeatrule('my rule','^p')]];
- x ()
-
X position of command on layout (in points). -1 if it's on overset or on the pasteboard.
Returns:
-
number
X position in points, spread based
Usage:
function traceposition(sel) for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(TEXT.pageindex()); TEXT.insert(' - '); TEXT.insert(TEXT.x()); TEXT.insert(' x '); TEXT.insert(TEXT.y()); TEXT.insert('^p'); end; end; traceposition(SELECTION.root());
- y ()
-
Y position of command on layout (in points). -1 if it's on overset or on the pasteboard.
Returns:
-
number
Y position in points, spread based
Usage:
function traceposition(sel) for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(TEXT.pageindex()); TEXT.insert(' - '); TEXT.insert(TEXT.x()); TEXT.insert(' x '); TEXT.insert(TEXT.y()); TEXT.insert('^p'); end; end; traceposition(SELECTION.root());
Class SELECTION
Example: Formatting Rule Post Processing code thats creates a column for each group, with a Heading at the top followed by repeating records underneath.
-- starting x position x = 0;-- Function used to proces each group of data into a single column -- "elements" is single group containing child records function process_group(elements) -- Place the group header at the top local y = 0; local result = formattingrule:placerule("Heading",x, 0, elements); y = y + result:height(); -- Repeat for each record for i=1,elements:size() do record_element = elements:get(i); local result = formattingrule:placerule("Product",x, y, record_element); y = y + result:height(); end x = x + result:width(); end -- In this sample the root element contains multiple child -- elements, which are groups of records group_data = SELECTION.root(); for i=1,group_data:size() do -- get the 'Nth' child element - a single group of records group_elements = group_data:get(i); -- build the column process_group(group_elements); end
- cut (from, to)
-
Cuts a range of elements from the selection and return a new SELECTION.
Parameters:
- from int Start index
- to int End index
Returns:
-
SELECTION
New selection object
Usage:
-- create a new selection based on a set of records sel = SELECTION.new(version_records); -- cut elements 2 and 3 into a new selection sel2 = sel:cut(2,3)
- get (index)
-
Returns a new SELECTION object for the Nth child element. When executed in a document content
context, the new selection is the 'current' selection.
Parameters:
- index int Child to get
Returns:
-
SELECTION
New selection object
Usage:
group_data = SELECTION.root(); for i=1,group_data:size() do group_elements = group_data:get(i); process_group(group_elements); end
- getcontent (fieldname)
-
Returns the formatted content of a the given field.
Parameters:
- fieldname string Name of a field
Returns:
-
string
contents of the field
Usage:
-- get a named field from the root selection -- as a member group_data = SELECTION.root(); product_ID = group_data:getcontent("ProductId"); -- get a named field from the root selection -- finds the contents of the first field product_ID = SELECTION.getcontent("Price Label");
- getrecordset ()
-
Returns all records in the selection.
Returns:
-
RECORDSET
object
Usage:
--- Record set can be accessed through the root object recordset = SELECTION.root():getrecordset(); --- Or direct from the SELECTION recordset = SELECTION.getrecordset(); for record = 1,recordset:size() do myRecord = recordset:getrecord(record); dostuff(myRecord); end
- group (group)
-
Returns a new SELECTION object with the contents of the named group.
Parameters:
- group string name of a group
Returns:
-
SELECTION
Usage:
groupName = mySELECTION:group('group name');
- name ()
-
Returns the name of the selection. For a group this is the group name. For a record it's the
value of the records key.
Returns:
-
string
group name or record key based on the type of the object
Usage:
newSEL = mySELECTION:name();
- new (RECORDSET)
-
Creates a new SELECTION object containing records in the given set.
Parameters:
- RECORDSET RECORDSET object
Returns:
-
SELECTION
New selection object
Usage:
-- Post Processing Formatting Rule example that repeats -- a formatting rule for every record in an external data source version_records = DATASOURCE.get('external data source'):getrecordset(); sel = SELECTION.new(version_records); ypos = 100; for i=1,sel:size() do local result = formattingrule:placerule("version",0, ypos, sel:get(i)); ypos = ypos + 100; end;i
- root ()
-
Returns a new SELECTION object which represents the current selection. This is not a member
function so should be referenced using the "dot" notation (not colon).
Returns:
-
SELECTION Root selection object
Usage:
function level(sel, index) if sel:size() > 0 then for i=1,index do TEXT.insert(' '); end; end; for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(sel2:type()); TEXT.insert(' - '); TEXT.insert(sel2:name()); TEXT.insert('^p'); level(sel2, index+1); end; end; level(SELECTION.root(), 0);
- setroot ()
- Sets a new root selection.
- size ()
-
Returns the number of child elements.
Returns:
-
int
count Number of child elements
Usage:
function level(sel, index) if sel:size() > 0 then for i=1,index do TEXT.insert(' '); end; end; for i=1,sel:size() do sel2 = sel:get(i); TEXT.insert(sel2:type()); TEXT.insert(' - '); TEXT.insert(sel2:name()); TEXT.insert('^p'); level(sel2, index+1); end; end; level(SELECTION.root(), 0);
- type ()
-
Selection type.
Returns:
-
string
One of record, group, relationalgroup, relationalrecord
Usage:
selType = mySELECTION:type();
Class FRAME
- aligncontent (align)
-
Align the content of a frame within the frame bounds.
Parameters:
- align string centre, topleft, topright, bottomleft, bottomright, topcentre, centreleft, centreright
Usage:
frame:qrcodehyperlink(url); frame:aligncontent("centreleft");
- applyframecolor (colorname)
-
Apply a stroke color to the frame
Parameters:
- colorname Swatch name, RGB or CMYK value
Usage:
frame:applyframecolor(field('frame_color')); frame:applyframecolor('#FF0000'); frame:applyframecolor('c100m0y0k0');
- applyframestroke (strokeweight)
-
Apply a frame stroke.
Parameters:
- strokeweight number Weight of the stroke in points
Returns:
-
nothng
Usage:
count = frame:applyframestroke(10);
- applyobjectstyle (stylename)
-
Apply an object style to the frame.
Parameters:
- stylename string Object style name
Returns:
-
nothing
Usage:
frame:applyobjectstyle("error");
- bottom ([position])
-
Get or set the bottom position of the frame relative to the page.
Parameters:
- position number (optional)
Returns:
-
number
bottom position relative to page in points
Usage:
bottom = frame:bottom(); frame:bottom(110); frame:bottom('10 cm');
- contentheight ([width])
-
Get/Set the height of the frame. Parameter can be either a string with a UOM or a number in
points.
Parameters:
- width number (optional)
Returns:
-
number
height in points
Usage:
frame:contentheight('3cm'); height = frame:contentheight();
- contentwidth ([width])
-
Get/Set the width of the frame. Parameter can be either a string with a UOM or a number in
points.
Parameters:
- width number (optional)
Returns:
-
number
width in points
Usage:
frame:contentwidth('3cm'); width = frame:contentwidth();
- delete ()
-
Delete the frame.
Usage:
frame:delete();
- duplicate ([cell])
-
Duplicate the frame. If used in formatting rule post processing, the frame is duplicated at the
same level. If the frame is anchored in text flow it will be anchored to the right.
Parameters:
- cell A CELL object to populate the frame content (optional)
Returns:
-
FRAME
duplicated frame
Usage:
width = frame:width(); -- create a frame below newframe = frame:duplicate(); newframe:moveto(frame:x(),frame:y()+frame:height()); -- create a frame to the right newframe = frame:duplicate(); newframe:moveto(frame:x()+frame:width(),frame:y());
- fillcontent ()
-
Fill content proportionally within the frame.
Usage:
frame:qrcodehyperlink(url); frame:fillcontent();
- fitcontent ()
-
Fit content proportionally within the frame.
Usage:
frame:qrcodehyperlink(url); frame:fitcontent(); frame:scalecontent(1.2);
- fitframetocontent ()
-
Fit the frame to the content
Usage:
frame:qrcodehyperlink(url); frame:fitframetocontent(); frame:scalecontent(1.2);
- generateqrcodetext (text[, swatchname])
-
Generate text based QR code content.
Parameters:
Usage:
mytext = 'some text'; frame:qrcodetext(mytext); frame:fitcontent(); frame:scalecontent(1.2);
- generateqrcodevcard (FirstName, LastName, JobTitle)
-
Generate a QR code V Card. CC 2015 and above only.
Parameters:
Usage:
frame:qrcodevcard("FirstName", "LastName", "JobTitle", "TelNo", "CellNo", "Email", "Website", "Org", "Street", "City", "State", "Zip", "Country"); frame:fitcontent(); frame:scalecontent(1.2);
- getbounds ()
-
Get the bounds of the frame. Returns a point based structure.
Returns:
-
structure { "left" = x1, "right" = x2, "top" = y1, "bottom" = y2 }
Usage:
container = formattingrule:getframe("container"); area = container:getbounds();
- getdom ([object=PageItem])
-
Retrieve the InDesign scripting DOM for a PageItem, Document or Application
Parameters:
- object string to get, PageItem, Document, Application (default PageItem)
Usage:
d = frame:getdom(); d:transparencySettings():dropShadowSettings():size(0.6)
- getframe (name)
-
Gets a named FRAME. The name is determined from the contents of its Script Label.
Parameters:
- name string Name of the frame to get.
Returns:
-
The found FRAME
Or
-
nil if no frame is found
Usage:
frame = formattingrule:getframe("container of logos"); named_frame = frame:getframe("logo 1");
- hascontent ()
-
Return true if the frame has content.
Returns:
-
bool
true if the frame has content
Usage:
hascontent = frame:hascontent();
- height ([height])
-
Get or set the frames height. Returns point units, takes points or a measurement with a unit of
measure.
Parameters:
- height number (optional)
Usage:
myheight = frame:height();
- inserthttpimage (url)
-
Insert an image from the given URL into the frame
Parameters:
- url string image URL
Usage:
frame:inserthttpimage("http://placeimg.com/640/480/any");
- left ([position])
-
Get or set the left position of the frame relative to the page top left.
Parameters:
- position number (optional)
Returns:
-
number
left position relative to page in points
Usage:
left = frame:left(); frame:left(110); frame:left('10 cm');
- movecontent (x, y)
-
Position content relative to the frame.
Parameters:
- x number position of content relative to frame left
- y number position of content relative to frame top
Usage:
frame:movecontent('5mm','5mm');
- moverel (x, y)
-
Move the frame relative to its current position.
Parameters:
- x number delta x
- y number delta y
Usage:
y = FIELD.get('Y'):content(); frame:moveto(frame:x(),y);
- moveto (x, y)
-
Move the frame to a specified position.
Parameters:
- x number position
- y number position
Usage:
y = FIELD.get('Y'):content(); frame:moveto(frame:x(),y);
- moveto (layer)
-
Move the frame to the named layer.
Parameters:
- layer string name of layer
Usage:
frame:movetolayer("text");
- qrcodehyperlink (URL[, swatchname])
-
Generate Hyperlink based QR code content.
Parameters:
Usage:
frame:qrcodehyperlink(url); frame:fitcontent(); frame:scalecontent(1.2);
- releaseanchored ()
-
Release the anchored items.
Usage:
frame:releaseanchored();
- resize (width, height)
-
Resize the frame.
Parameters:
- width number
- height number
Usage:
height = FIELD.get('Height'):content(); frame:resize(frame:x(),height);
- right ([position])
-
Get or Set the right position of the frame in points relative to the page top left.
Parameters:
- position number (optional)
Returns:
-
right position relative to page left (points)
Usage:
right = frame:right(); frame:right(110); frame:right('10 cm');
- scalecontent (scale)
-
Scale the frame content.
Parameters:
- scale number content scale (1=100%)
Usage:
url = 'www.65bit.com'; frame:qrcodehyperlink(url); frame:fitcontent(); frame:scalecontent(1.2);
- setcomputedfieldcommand (command)
-
Set the computed field command for the frame. The frames content is updated.
Parameters:
- command string The command to set
Usage:
frame:setcomputedfieldcommand("GETIMAGE(1)");
- setimageindex (index)
-
Populate the frame with the nth image of a multi image field. Returns true if the frame was
successfully populated
Parameters:
- index int Index of the image to use (1..n)
Returns:
-
bool
true if the image was successully populated
Usage:
-- example used in post processing of a formatting rule -- repeats an icon for every image in a tagged field -- and then positions the frames inside the rule container_bounds = formattingrule:getbounds(); icon = formattingrule:getframe("icon"); index = 1; while icon:setimageindex(index) do index = index + 1 icon = icon:duplicate(); end icon:delete() if index == 1 then return end named_frames = formattingrule:getframes("icon"); formattingrule:positionframes(named_frames, container_bounds, 0, "left-right");
- top ([position])
-
Get or set the top position of the frame relative to the page top left.
Parameters:
- position number (optional)
Returns:
-
number
top position relative to page in points
Usage:
top = frame:top(); frame:top(0); frame:top('1 cm');
- updatecontent ([selection])
-
Populate the frames fields. Updates the fields if no selection is given, or populate with the
given item.
Parameters:
- selection A SELECTION object (optional)
Usage:
-- example duplicates an anchored frame for -- every item in the selection con = formattingrule:getframe("icon"); el = SELECTION.root(); or i=2,sel:size() do newframe = icon:duplicate(); newframe:updatecontent(sel:get(i)); nd
- width ([width])
-
Get or Set frame width in points.
Parameters:
- width number (number in points or string with unit of measure) (optional)
Returns:
-
number
width in points
Usage:
width = frame:width();
Class DATASOURCE
- decryptlua (key)
-
Decrypt all Lua script files associated with data source.
Parameters:
- key string Encryption key
Returns:
-
true
if succeeded
Usage:
myDATASOURCE:decryptlua(key);
- encryptlua (key)
-
Encrypt all Lua scripts associated with data source. All 'require' usages must be replaced with
'ecrequire' for scripts located in the data sources 'Scripts' folder.
Parameters:
- key string Encryption key
Returns:
-
true
if succeeded
Usage:
ds:encryptlua(key);
- env (name)
-
Get a data source environment variable.
date - current date
username - the name of the user logged on to the machine.
platform - "Macintosh" or "Windows".
osversion - version number of the operating system.
decimalpt - the system default for the decimal separator.
thousandssep - the system default for the thousands separator.
applicationname - "InDesign", "InCopy" or "InDesign Server".
workspacefolder - path to the workspace folder.
applicationversion - version number of the application.
datasourcespecifier - data source specifier string.
datasourcelastsynctime - the last sync time of the data source.
datasourcename - name of the data source.
Parameters:
- name string Environment variable name
Usage:
return DATASOURCE.get():env('username');
- get ([name=current])
-
Get a DATASOURCE object.
Parameters:
- name string Name of an existing data source (default current)
Returns:
-
DATASOURCE
New DATASOURCE object for the named data source
Usage:
-- Get the current data source thisdatasource = DATASOURCE.get(); -- Get a named data source thatdatasource = DATASOURCE.get('Some Other Data Source');
- getdom ()
-
Returns the scripting DataSource DOM object. Not available in Advanced custom fields.
Usage:
d = DATASOURCE.get():getdom(); return d:getFieldOption("Category 1", "prefix");
- getfieldindex ()
-
Get the index of a named field.
Returns:
-
int
index of field, or -1 if it does not exist
Usage:
index = DATASOURCE.getfieldindex('field name');
- getlocation ()
-
Get location of the data source.
Returns:
-
string
path full path to the data source
Usage:
path = myDATASOURCE:getlocation();
- getoption (name)
-
Returns the named option for the data source, or nil if the option does not exist. Options are
stored in options.xml inside the datasource data folder.
Parameters:
- name string Option name
Returns:
-
value option value
Usage:
thisdatasource = DATASOURCE.get(); options_value = thisdatasource:getoption("locale");
- getrecordset ()
-
Get a RECORDSET object, representing the records of the data source.
Returns:
-
RECORDSET
object
Usage:
myrecordset = myDATASOURCE:getrecordset();
- newtable ()
-
Return a table representing the contents of the data source.
Returns:
-
TABLE
New table object
Usage:
mytable = DATASOURCE.get('xxxx'):newtable();
- setoption (name, value)
-
Set the named data source option to the given value. The option can be a user parameter, data
source setting or another arbritary option.
Parameters:
Usage:
thisdatasource = DATASOURCE.get(); options_value = thisdatasource:setoption("locale", "US");
- size ()
-
Number of records in the data source.
Returns:
-
int
Number of records
Usage:
recordcount = mydatasource:size();
- synchronizewithsource ()
-
Synchonize the datasource with the source data.
Usage:
thisdatasource = DATASOURCE.get(); thisdatasource:synchronizewithsource();
- updatecustomfield (field, saveflag, redrawflag)
-
Force a custom field to update its formatted content. During exectution of
createformattedcontent.lua, custom fields have already been processed. This allows specific
fields to be recalulated at this time. Can also be used on custom menus to force field to
format.
Parameters:
- field string Field name
- saveflag bool Save changes to the workspace folder
- redrawflag bool Redraw all open panels.
Usage:
DATASOURCE.get():updatecustomfield("field", false, false);
- xreffield (search, lookfor, return)
-
Looks up a field based on another fields content.
Parameters:
- search string Field to search contents
- lookfor string String to search for
- return string Field to return
Returns:
-
FIELD
field object
Usage:
-- Example that looks up values in one data source based on a semi-colon -- delimited list of codes ds = DATASOURCE.get('MX_Part'); local function split(str, sep) local result = {} local regex = ("([^%s]+)"):format(sep) for each in str:gmatch(regex) do table.insert(result, each) end return result end ret = ""; local lines = split(field("CONCAT_CHAD_RA"), ";") for _,line in ipairs(lines) do ret = ret .. ds:xreffield("Code", line,"Libellé"):content() .. ";" end return ret
Class TABLE
- append (table, position)
-
Append another table onto this one.
Parameters:
Returns:
-
none
Usage:
table:append(otherTable, 'bottom');
- cell (row, column)
-
Returns a CELL object for the given row and column.
Parameters:
- row int row index
- column int column index
Returns:
-
CELL
object
Usage:
mytable2 = TABLE:new(); for i,myNode in ipairs(myNodes) do newsize = myNode:valueof('framesize/text()'); mytable2:cell(1,i+1):setcontent(newsize); end mytable2:sortrows(1, false); mytable2:distinctcols(1);
- colcount ()
-
Get the total number of columns in the table.
Returns:
-
int
count of columns
See also:
Usage:
columns = table:colcount();
- collapserows (one[, two[, three[, four]]])
-
Removes rows from the table where the specified column indexes are empty.
Parameters:
- one Column Index
- two (optional)
- three (optional)
- four (optional)
Returns:
-
none
Usage:
table:collapserows(1,3,5);
- combinecols (first, second, separator[, always=true])
-
Combines the content of the first column with the second, then deletes the second.
Parameters:
- first int column to combine
- second int column to combine
- separator string text to separate the contents
- always bool add a separater (default true)
Returns:
Usage:
first = tablex:getcolindex(1, 'peso_neto'); second = tablex:getcolindex(1, 'peso_bruto'); table:combinecols(first,second,' / ');
- combinerows (first, second, separator)
-
Combines the content of the first row with the second, then deletes the second.
Parameters:
- first int row to combine
- second int row to combine
- separator string text to separate the contents
Returns:
Usage:
first = tablex:getrowindex(1, 'peso_neto'); second = tablex:getrowindex(1, 'peso_bruto'); table:combinerows(first,second,' / ');
- condensetocols (one[, two[, three[, four]]])
-
Condense table, leaving only the specified columns, in the specified order
Parameters:
- one Column Index
- two (optional)
- three (optional)
- four (optional)
Returns:
-
none
Usage:
table:condensetocols(2,4,7,9,12);
- copycol (from, to)
-
Copies the specified column index into the given position. Inserts a new column at the
destination index.
Parameters:
- from int Column index to copy
- to int Destination column index
Returns:
-
none
Usage:
table:copycol(2,1);
- distinctbodyrows (one[, two[, three[, four]]])
-
Removes body rows where the specified columns contain the same value.
Parameters:
- one Column Index
- two (optional)
- three (optional)
- four (optional)
Returns:
-
none
Usage:
table = TABLE.new(); table:cell(1,1):setcontent("a"); table:cell(2,1):setcontent("a"); table:cell(3,1):setcontent("b"); table:cell(4,1):setcontent("b"); table:setheaderrowcount(1); table:distinctbodyrows(1); return table:__tostring();
- distinctcols (list)
-
Removes columns from a table where the specified rows contain the same values.
Parameters:
- list int variable number of column indexes, specifying the columns to check
Returns:
-
none
Usage:
table = TABLE.new(); table:cell(1,1):setcontent("a"); table:cell(1,2):setcontent("a"); table:cell(1,3):setcontent("b"); table:cell(1,4):setcontent("b"); table:distinctcols(1); return table:__tostring();
- distinctcontent (top, left, bottom, right)
-
Removes duplicate content from a range of cells in a table.
Parameters:
- top int top row index
- left int left column index
- bottom int bottom row index (constrained to maximum)
- right int right column index (constrained to maximum)
Returns:
-
none
Usage:
table:distinctcontent(2,1,10,15);
- distinctrows (one[, two[, three[, four]]])
-
Removes rows where the specified columns contain the same value.
Parameters:
- one Column Index
- two (optional)
- three (optional)
- four (optional)
Returns:
-
none
Usage:
table = TABLE.new(); table:cell(1,1):setcontent("a"); table:cell(2,1):setcontent("a"); table:cell(3,1):setcontent("b"); table:cell(4,1):setcontent("b"); table:distinctrows(1); return table:__tostring();
- entitydecode ()
-
HTML Entity decode table contents.
Returns:
-
none
Usage:
table:entitydecode();
- entityencode ()
-
HTML Entity encode table contents.
Returns:
-
none
Usage:
table:entityencode();
- exportexcel (path)
-
Export table as an Excel file (xlsx)
Parameters:
- path string Path to the file
Returns:
-
none
Usage:
-- create a new xlsx file with the table contents. table:exportexcel("/Users/USER/desktop/output.xlsx");
- exportxml (path)
-
Export table to an XML file
Parameters:
- path string Path to the file
Returns:
-
none
Usage:
table:exportxml("file.xml");
- getcolindex (searchrow, searchfor)
-
Returns the index of the column containing the given string. -1 if not found.
Parameters:
- searchrow int Row index to inspect
- searchfor string Content to search for
Returns:
-
int
Index of column, -1 if not found
Usage:
index = table:getcolindex(1,'xxxx');
- getrowindex (searchcol, searchfor)
-
Returns the index of the row containing the given string.
Parameters:
- searchcol int Column to search
- searchfor string Content to search for
Returns:
-
int
Index of column, -1 if not found
Usage:
index = table:getrowindex(1,'xxxx');
- getstyle ()
-
Get the table style.
Returns:
-
style name
Usage:
mystyle = table:getstyle();
- hlookup (inspect, value, return[, exact=true])
-
Searches for a value in a row, and then returns a value in the same column from a row you
specify.
Parameters:
- inspect int row index to inspect
- value string the value to be found
- return int the row index containing the value to return
- exact bool true for an exact match, false to match using value as a regular expression (default true)
Returns:
-
string
the value found, otherwise nil
Usage:
value = FIELD.get('Format'):content():hlookup(3,'850',1); if value == nil then return "" end; return value
- insertcol (after[, count=1])
-
Insert column(s) into the table.
Parameters:
- after int Index to insert after
- count int Number of columns to insert (default 1)
Usage:
-- insert after the second table:insertcol(2); -- to insert at the start, specify an index of 0 table:insertcol(0); -- insert 3 columns at the start table:insertcol(0,3); -- insert columns at the end table:insertcol(table:colcount());
- insertrow (after[, count=1])
-
Insert row(s) into the table.
Parameters:
- after int Index of the row to insert after
- count int Number of rows to insert (default 1)
Returns:
-
none
Usage:
-- insert after the second table:insertrow(2); -- to insert at the start, specify an index of 0 table:insertrow(0); -- insert 3 rows at the start table:insertrow(0,3); -- insert a row at the end table:insertrow(table:rowcount());
- jointable (table, sourcecolumn, matchcolumn)
-
Join the contents of another table by matching a column in both tables.
Parameters:
- table TABLE Table to join
- sourcecolumn int Source column to match
- matchcolumn int Column in other table to match to
Returns:
-
none
Usage:
othertable = DATASOURCE.get('Product Tips'):newtable(); table:distinctrows(1); table:setsorttype('numeric'); table:sortrows(1); table:jointable(othertable,1,1); table:removecol(4); table:removecol(4); table:removecol(2); table:present();
- movecol (from, to)
-
Moves a column into the specified position.
Parameters:
- from int Source column index
- to int Destination column index
Returns:
-
none
Usage:
table:movecol(2,1);
- moverow (from, to)
-
Moves a row into the specified position.
Parameters:
- from int Source row index
- to int Destination row index
Returns:
-
none
Usage:
table:moverow(1,2);
- new ([various])
-
Create a new TABLE object.
Parameters:
- various TABLE object, table of values, string of HTML (optional)
Returns:
-
TABLE
The newly created table object
Usage:
-- creating an empty table and filling it empty_then_filled = TABLE.new(); for row=1,10 do for col=1,10 do empty_then_filled:cell(row,col):setcontent(tostring(col) .. ' x ' .. tostring(row)); end end -- creating a single row table single_row = TABLE.new( { "col1", "col2", "col3" } ); -- creating a table with multiple rows & columns t = { { "row1, col1", "row1, col2", "row1, col3"}, { "row2, col1", "row2, col2", "row2, col3"}, { "row3, col1", "row3, col2", "row3, col3"}, }; multi_row = TABLE.new(t); -- creating a copy of an existing TABLE t = TABLE.new(); t:cell(1,1):setcontent("row1,col1") table_copy = TABLE.new(t); table_copy:cell(2,1):setcontent("row2,col1") - create a table from HTML = TABLE.new("<table><tr><td>1</td><td>2</td></tr></table>");
- newexcel (path)
-
Creates a new TABLE object from the Excel spreadsheet at the specified path
Parameters:
- path string Path to the Excel file
Returns:
-
none
Usage:
path = "/Tables XLS/XLS/" .. field('Model') .. ".xlsx" ; table = TABLE.newexcel(path); table:present();
- newsql (query)
-
Create a new TABLE object from the given SQLite query. Each datasource is a virtual table.
Requires the Relational Module.
Parameters:
- query string query to execute
Returns:
-
TABLE
A newly created table object
Usage:
mytable = TABLE.newsql('select Univers,Famille from CatalogueBibleRouge'); mytable:present();
- openinbrowser ()
-
Present the contents of the table in the default browser
Returns:
-
none
Usage:
table:openinbrowser("");
- present ()
-
Presents the table back to the caller.
Usage:
--- return a new table with one cell mytable = TABLE.new(); mytable:cell(1,1):setcontent('content'); mytable:present();
- processembeddedcommands ()
-
Process commands embedded in cell content.
Usage:
t = TABLE.new({"FIELDSTR('Product Name')","FIELDSTR('Product Description')"}); t:processembeddedcommands(); t:present()
- removecol (column)
-
Removes a column.
Parameters:
- column int column index to remove
Returns:
-
none
Usage:
table:removecol(1);
- removeemptycols ()
-
Removes all columns where the cell content is empty. Header rows are not checked.
Returns:
-
none
Usage:
table:removeemptycols();
- removeemptyrows ([col1[, col2[, coln]]])
-
Removes all rows where cell content is empty. Header rows are not checked. Optional column
indexes to check can be provided (Columns are treated as empty if they don't exist).
Parameters:
- col1 (optional)
- col2 (optional)
- coln (optional)
Returns:
-
none
Usage:
-- remove rows where all columns are emty table:removeemptyrows(); -- remove rows where column 2,3 & are empty table:removeemptyrows(2,3,4);
- removerow (row)
-
Remove a row.
Parameters:
- row int row index to remove
Returns:
-
none
Usage:
table:removerow(1);
- rotate ()
-
Return a rotated version of the the table.
Returns:
-
TABLE
A new rotated TABLE object, does not affect the table itself
Usage:
table:movecol(5,1); table:setheaderrowcount(1); newtable = table:rotate();
- rowcount ()
-
Count of rows.
Returns:
-
int
count of table rows
See also:
Usage:
rows = table:rowcount();
- select (row)
-
Make a specified row the active for content population/update.
Parameters:
- row int row to use
Returns:
-
none
Usage:
--- Content between [[ and ]] is processed by the command parser --- This example repeats 'Tagged Content' fo each row in a tabular field --- Tagged Content would typically contain field specifiers [[ mysel = SELECTION.root(); mytable = mysel:getfield('data'):content(); for i = 1, mytable:rowcount() do mytable:select(i); ]]Tagged Content[[ end; ]]
- setcellstylerange (style, colstart, colend, rowstart, rowend)
-
Set the style of a range of cells in a table. Doesn't report an error if the range is invalid.
Parameters:
- style string style name;
- colstart int column start index
- colend int column end index
- rowstart int row start index
- rowend int row end index
Returns:
-
none
Usage:
table:setcellstylerange("order nr right", 2, table:colcount(), 1, 1);
- setcolcleansing (index, search, replace)
-
Perform a search and replace on a column using regular expressions. Note that backslashes need
to be escaped twice, once for LUA and once again for the Regular Expression parser.
Parameters:
- index int column index
- search string search for regular expression
- replace string replace with regular expression
Returns:
-
none
Usage:
table:setcolcleansing(2, "11:Bilderpool\\Arbeitsschutz\\Koerperschutz\\ID IDENTITY\\Bilder\\", "");
- setcoltype (where, type)
-
Set the type of a column.
Parameters:
- where int where to insert a new column
- type string type of the column(image,text);
Returns:
-
none
Usage:
mycell = table:setcoltype(1, "image");
- setcolwidthoption (column, option[, min=0[, max=0]])
-
Set the width option for a column
Parameters:
- column int column index to remove
- option string width option to set (fixed,variable,fittotext)
- min string Minimum width for fittotext (default 0)
- max string Maximum width for fittotext (default 0)
Returns:
-
none
Usage:
table:setcolwidthoption(1,"fittotext", "1cm", "10cm"); table:setcolwidthoption(2,"variable");
- setfooterrowcount (count)
-
Set the number of footer rows.
Parameters:
- count int number of footer rows
Returns:
-
none
Usage:
table:setfooterrowcount(1);
- setheaderrowcount (count)
-
Set the number of header rows.
Parameters:
- count int number of header rows
Returns:
-
none
Usage:
table:setheaderrowcount(2);
- setrowcleansing (index, search, replace)
-
Perform a search and replace on a row using regular expressions. Note that backslashes need to
be escaped twice, one for LUA and once for the Regular Expression parser.
Parameters:
- index int row index
- search string search for regular expression
- replace string replace with regular expression
Returns:
-
none
Usage:
table:setrowcleansing(2, "11:Bilderpool\\Arbeitsschutz\\Bilder\\", "");
- setrowkeepwithnext (rowindex, keep)
-
Set the rows keep with next property.
Parameters:
- rowindex int Row index
- keep bool
Returns:
-
none
Usage:
table:setrowkeepwithnext(2, true);
- setrowstroke (row, edge, weight)
-
Set the cell stroke for each cell in the row.
Parameters:
- row int row to set
- edge string left, right, top, bottom, all
- weight number weight of the stroke (in points)
Returns:
-
none
Usage:
table:setrowstroke(2, "top", 0);
- setrowstyle (rowindex, stylename)
-
Set the cell style for each cell in the row.
Parameters:
- rowindex int Row index
- stylename string Name of a cell style
Returns:
-
none
Usage:
table:setrowstyle(2, "header");
- setscriptlabel (label)
-
Set the script label of the table.
Parameters:
- label string
Returns:
-
none
Usage:
table:setscriptlabel("price table");
- setsortfunction (function)
-
Define a customized sorting function which returns true if the first argument is less than
(i.e. is ordered before) the second.
Sorting is via a qsort algorithm, which can cause stack faults if the callback function is not
correctly implemented.
Parameters:
- function string the name of a function to be used for sorting. The function is passed two string arguments and retuns true if the first is less than the second.
Returns:
-
none
See also:
Usage:
-- custom sort callback function -- strings passed, sort ascending function customsort(a,b) return a < b; end -- Associate the sort function with the table table:setsortfunction("customsort"); -- Sort the table by column 1 from row 2 onwards table:sortrows(1,2); -- Remove the existing soft function table:setsortfunction("");
- setsortlanguage (language)
-
Sets the language used for linguistic sort comparisons. List of languages is available in
InDesign's text properties.
Parameters:
- language string language to use
Returns:
-
none
See also:
Usage:
table:setsortlanguage("English: USA");
- setsorttype (type)
-
Sets the sort type for default sort operations.
Parameters:
- type string alphanumeric, numeric, custom
Returns:
-
none
Usage:
table:setsorttype("numeric");
- setstyle (style)
-
Set the table style of the table.
Parameters:
- style string style name;
Returns:
-
none
Usage:
table:setstyle("tablestyle");
- setupdatetype (type)
-
Sets the update type for the table. Controls the same setting as Table->Table Options.
Parameters:
- type string update type to apply, "update" or "recreate"
Usage:
- sortcols (row[, start=1[, end=maximum columns]])
-
Sort the columns in a table using the contents of a given row. Table sorting uses the function
defined by setsortfunction.
Parameters:
- row int row index
- start int start column index (default 1)
- end int end column index (default maximum columns)
Usage:
table:sortcols(1,2,32); table:sortcols(1,2); table:sortcols(1);
- sortrows (column, opt, opt)
-
Sort the rows in a table using the given column. custom sorting can be defined by calling
setsortfunction prior to sorting,
or by calling setsortype. For alphanumeric sorting the lingustic sorting properties can be
controlled by setsortlanguage.
Parameters:
- column int Column to use for the sort/ table of columns and types/list of column indexes
- opt int =maximum rows] end End row index
- opt int =maximum rows] end End row index
See also:
Usage:
-- custom sort callback function -- strings are passed in , this example will sorting ascending function customsort(a,b) return a < b; end -- Associate the sort function with the table table:setsortfunction("customsort"); -- Sort the table using column 1 from row 2 onwards table:sortrows(1,2); -- Sort the table using column 1,3,5 from row 2 onwards table:sortrows("1,3,5",2); -- sort first by column 2, alpha, ascending -- then sub-sort by column 1, numeric descending t = TABLE.new( { { 1,"a"}, { 2,"b"}, { 3,"b"}, { 5,"a"}, { 0.8,"b"} } ); t:sortrows( { [1] = {column = 2, type = "alpha", direction = "ascending" }, [2] = {column = 1, type = "numeric", direction = "descending" }, });
- sortrowsbyvalue (row, values[, start=1[, end=max rows]])
-
Sorts rows in the given column using a set of predefined values.
Parameters:
- row int row index
- values TABLE table of possible values in order
- start int start row index (default 1)
- end int end row index (default max rows)
Usage:
t = TABLE.new(); t:cell(1,1):setcontent("XL"); t:cell(2,1):setcontent("M"); t:cell(3,1):setcontent("S"); t:cell(4,1):setcontent("XXL"); t:sortrowsbyvalue(1, { "S", "M", "L", "XL", "XXL"});
- stackcolumns (maxcols, headercols)
-
Creates a table of with a maximum of maxcols columns. Columns beyond this limit are stacked
vertically.
Parameters:
- maxcols int Maximum number of columns in the resulting table
- headercols int =0] Number of columns on the left to repeat for each stacked set of columns
Returns:
-
none
Usage:
table:stackcolumns(5, 1);
- totable ()
-
Return the table as an array of rows, each with an array of columns.
Returns:
-
table
table of rows, each with a table of columns
Usage:
luatable = table:totable();
- vlookup (searchcol, searchstring, returncol[, exact=true])
-
Searches for a value in a column, and then returns a value in the same row from a column you
specify.
Parameters:
- searchcol int column index to inspect
- searchstring string the value to search for
- returncol int column index to return
- exact bool true for an exact match, false to match using value as a regular expression (default true)
Returns:
-
The value found as a string
Or
-
nil if no value is found
Usage:
value = FIELD.get('Format'):content():vlookup(3,'850',1); if value == nil then return "" end; return value
Class CELL
- copyformatting (cell)
-
Copy the formatting of the given cell. Does not affect the cells content
Parameters:
- cell CELL to copy
Returns:
-
number
Usage:
table:cell(2,1):copyformatting(table:cell(1,1));
- getcontent ([cleansing=false])
-
Return cell content.
Parameters:
- cleansing bool true to return the content including cleansing (default false)
Returns:
-
string
cell content
Usage:
content = mycell:getcontent();
- getscriptlabel ()
-
Get the script label.
Returns:
-
label
Usage:
v = table:cell(3,1):getscriptlabel();
- getstyle ()
-
Get the cell style associated with the cell.
Returns:
-
style name
Usage:
style = table:cell(3,1):getstyle();
- getwidth ()
-
Get the width of the cell with a point UOM, or nil if it's not been defined.
Returns:
Usage:
width = table:cell(1,1):getwidth();
- setcleansing (search, replace)
-
Perform a search and replace on cell content.
Parameters:
Returns:
-
none
Usage:
--- Simple replacement of a with b table:cell(1,1):setcleansing('a','b'); --- Use a back reference to extract partial content table:cell(1,1):setcleansing('(...)_.*','\1');
- setcolspan ()
-
Get the cells column span.
Usage:
table:cell(1,1):setcolpan(2)
- setcontent (content)
-
Set the cell content.
Parameters:
- content string new content
Returns:
-
none
Usage:
mycell:setcontent('new content');
- setfill (color)
-
Set the cells background Swatch or RGB/CMYK value
Parameters:
- color string Swatch name, RGB or CMYK value
Returns:
-
none
Usage:
table:cell(1,1):setfill(field('cell_color')); table:cell(2,1):setfill('#FF0000'); table:cell(3,1):setfill('c100m0y0k0');
- setheader (header)
-
Set the cell as an header.
Parameters:
- header bool Header flag
Returns:
-
none
Usage:
mycell:setheader(true); mytable:cell(r,c):setheader(true);
- setheight (height)
-
Set the fixed height of the cell. Parameter can be a number in points or a string with a unit of
measure.
Parameters:
- height string value
Returns:
-
none
Usage:
table:cell(1,1):setheight('5cm'); table:cell(1,1):setheight('30 pt'); table:cell(1,1):setheight(50);
- setmergeoption (name, value)
-
Set the cell horizontal or vertical merge options.
Parameters:
- name string option to set (horizontalmerge, verticalmerge)
- value string option value (none, ifcontentmatches, ifpopulatedcontentmatches);
Returns:
-
none
Usage:
outputTable:cell(1,2):setmergeoption('verticalmerge','ifcontentmatches'); -- perform a left to right fill of empty cells on each row and merge them for row=1,table:rowcount() do for col=2,table:colcount() do if table:cell(row,col):getcontent() == '' then prevContent = table:cell(row,col-1):getcontent(); table:cell(row,col):setcontent(prevContent); table:cell(row,col):setmergeoption('horizontalmerge','ifcontentmatches') table:cell(row,col-1):setmergeoption('horizontalmerge','ifcontentmatches') end end end
- setminimumheight (height)
-
Set the minimum height of the cell. Parameter can be a number in points or a string with a unit
of measure.
Parameters:
- height string value
Returns:
-
none
Usage:
table:cell(1,1):setminimumheight('5cm'); table:cell(1,1):setminimumheight('30 pt'); table:cell(1,1):setminimumheight(50);
- setrowspan ()
-
Get the cells row span.
Usage:
table:cell(1,1):setrowspan(2)
- setscriptlabel (label)
-
Set the cells script label.
Parameters:
- label string script label
Returns:
-
none
Usage:
table:cell(3,1):setscriptlabel('pricecell');
- setstrokeswatch (edge, swatch)
-
Set the swatch for a given stroke.
Parameters:
Returns:
-
none
Usage:
table:cell(1,1):setstrokeswatch('left','red'); table:cell(1,1):setstrokeswatch('right','red'); table:cell(1,1):setstrokeswatch('top','red'); table:cell(1,1):setstrokeswatch('bottom','red');
- setstroketint (edge, percentage)
-
Set the tint value for a given stroke.
Parameters:
- edge string left, right, top, bottom, all
- percentage number tint(0-100)
Returns:
-
none
Usage:
table:cell(1,1):setstroketint('left',50); table:cell(1,1):setstroketint('right',0.5); table:cell(1,1):setstroketint('top',0.5); table:cell(1,1):setstroketint('bottom',0.5);
- setstrokeweight (edge, weight)
-
Set a stroke weight associated with the cell.
Parameters:
- edge string left, right, top, bottom, all
- weight number weight of the stroke (in points)
Returns:
-
none
Usage:
table:cell(1,1):setstrokeweight('left',0.5); table:cell(1,1):setstrokeweight('right',1.5); table:cell(1,1):setstrokeweight('top',0.5); table:cell(1,1):setstrokeweight('bottom',0);
- setstyle (style)
-
Set the cell style associated with the cell.
Parameters:
- style string cell style name
Returns:
-
none
Usage:
table:cell(3,1):setstyle('red');
- setuirgb (red, green, blue)
-
Set the color of a cell. Used in the panel for display purposes only.
Parameters:
- red number (0-255)
- green number (0-255)
- blue number (0-255)
Returns:
-
none
Usage:
table:cell(3,1):setuirgb(127,60,50);
- setwidth (width)
-
Set the width of the cell.
Parameters:
- width string Measurement with UOM, default is points
Returns:
-
none
Usage:
table:cell(1,1):setwidth('5cm'); table:cell(1,1):setwidth('30 pt'); table:cell(1,1):setwidth(50);
- xml ()
-
Get the cells associated XML Node.
Returns:
-
XMLNode object
Usage:
content = mycell:xml();
Class XML
- getnodes (xpath)
-
Execute an XPath expression and returns an array of XMLNODE's that match.
Parameters:
- xpath string XPath command
Returns:
-
array of XMLNODE objects
Usage:
myNodes = myXML:getnodes('//variant'); myTable = TABLE:new(); for i,myNode in ipairs(myNodes) do newsize = myNode:valueof('gender/text()'); myTable:cell(i,1):setcontent(newsize); end myTable:sortrows(1); myTable:distinctrows(1);
- gettable (xpath[, node])
-
Returns a TABLE object created from nodes returned by the XPath command.
Parameters:
- xpath string XPath command
- node XMLNode to parse from (optional)
Returns:
-
TABLE
node content as a TABLE object
See also:
Usage:
mytable = myxml:gettable("//Products");
- new (xml)
-
Create a new XML parser
Parameters:
- xml string
Returns:
-
XML
New XML parser
Usage:
myxml = XML.new(xml_data);
- pivottable (record, X, Y, value)
-
Returns a pivot TABLE object created from the x,y,z parameters.
Parameters:
- record string XPath command for record
- X string XPath command for the X axis values
- Y string XPath command for the Y axis values
- value string XPath command for table value
Returns:
-
TABLE
Pivot table as a TABLE object
See also:
Usage:
myXML = FIELD.get('variants'):xml() table = myXML:pivottable('//variant', 'gender/text()', 'framesize/text()','framesize/text()'); table:sortrows(1,2); table:sortcols(1,2);
Class PROGRESSBAR
Example:
local newbar = PROGRESSBAR.new(); newbar:show("Million Step Bar", 1000000, true); for step = 1, 1000000 do cancel = newbar:update("Step " .. step); if cancel == true then error("operation cancelled"); end end
- new ()
-
Create a new PROGRESSBAR.
Returns:
-
PROGRESSBAR
new progress bar
Usage:
local newbar = PROGRESSBAR.new();
- show (title, stepcount[, showcancel=false])
-
Display the progress bar. Sets update title of the bar and the number of steps.
Parameters:
- title string Progress bar title text
- stepcount int Number of Steps
- showcancel bool true if the option to cancel should be given (default false)
Usage:
newbar:show("Million Step Bar", 1000000, true)
- update (message)
-
Update to the next step.
Parameters:
- message string Description of the step
Returns:
-
bool
true if the user cancelled
Usage:
cancel = newbar:update("Step " .. c);
Class FORMATTINGRULE
- align (frames, align[, area=rule])
-
Align frames or groups of frames in an area. The passed table may contain FRAMES or tables of
FRAMES.
When a table is passed the items within are treated as a single object.
Parameters:
- frames Table of objects to position (FRAMES or tables of FRAMES)
- align Alignment (left,right,centre,justified,top,bottom)
- area to arrange within { "left" = x1, "right" = x2, "top" = y1, "bottom" = y2 } (default rule)
Usage:
-- Example for a formatting rule consisting of a single icon and a text box -- the icon is repeated above the text box for every record in the group. -- "icon" is the Script Label of the icon graphic frame icon = formattingrule:getframe("icon"); -- selection contains all records for the formatting rule sel = SELECTION.root(); -- first item is already paginated, so start at the 2nd for i=2,sel:size() do -- duplicate the frame. If the item is anchored it will be duplicated after. newf = icon:duplicate(); newf:moveto(icon:x(),icon:y()); -- update the content of the frame with the selection item newf:updatecontent(sel:get(i)); end -- get all the frames with the script label "icon" named_frames = formattingrule:getframes("icon"); -- arrange them into the area of the formating rule, left alignment is the dafault formattingrule:arrange(named_frames); -- now arrange the tableframe above the icon group formattingrule:arrange( { formattingrule:getframe("tableframe"), named_frames} ); formattingrule:align( named_frames, "right" );
- alignedges (frames, align)
-
Align the edges of a set of FRAMES.
Parameters:
- frames Table of FRAMES or tables of FRAMES
- align options are align-horizontal-centres, align-vertical-centres, align-top-edges, align-bottom-edges, align-left-edges, align-right-edges
Usage:
named_frames = formattingrule:getframes("Main_Title2_image_Cover.*"); formattingrule:alignedges(named_frames, "align-top-edges");
- arrange (frames[, align=left[, final=align[, valign=top[, area[, gutter=0]]]]])
-
Arrange frames or groups of frames as a set of rows. The passed table may contain FRAMES or
tables of FRAMES.
An optional area can be specified, the default area is the area of the formatting rule.
When frames contains a table of frames, these are treated as a single object
Parameters:
- frames Table of objects to position (FRAMES or tables of FRAMES)
- align Alignment for each row (left,right, ,justified) (default left)
- final Alignment for last row (left,right,center,justified) (default align)
- valign Vertical alignment of each row (top,bottom,center) (default top)
- area Area to arrange in { "left" = x1, "right" = x2, "top" = y1, "bottom" = y2 } (optional)
- gutter Space between frames in points, vertically and horizontally (default 0)
Returns:
-
bool
true if the frames were successfully arranged into the area. Frames are untouched if false.
Usage:
-- Example for a formatting rule consisting of a single icon and a text box -- the icon is repeated above the text box for every record in the group. -- "icon" is the Script Label of the icon graphic frame icon = formattingrule:getframe("icon"); -- selection contains all records for the formatting rule sel = SELECTION.root(); -- first item is already paginated, so start at the 2nd for i=2,sel:size() do -- duplicate the frame. If the item is anchored it will be duplicated after. newf = icon:duplicate(); newf:moveto(icon:x(),icon:y()); -- update the content of the frame with the selection item newf:updatecontent(sel:get(i)); end -- get all the frames with the script label "icon" named_frames = formattingrule:getframes("icon"); -- arrange them into the area of the formating rule, left alignment is the dafault formattingrule:arrange(named_frames); -- arrange the tableframe above the icon group formattingrule:arrange( { formattingrule:getframe("tableframe"), named_frames} );
- canarrange (frames[, area[, gutter=0]])
-
Determines if frames can be arranged in an area.
An optional area can be specified, the default area is the area of the formatting rule.
When frames contains a table of frames, these are treated as a single object
Parameters:
- frames Table of objects to position (FRAMES or tables of FRAMES)
- area Area to arrange in { "left" = x1, "right" = x2, "top" = y1, "bottom" = y2 } (optional)
- gutter Space between frames in points, vertically and horizontally (default 0)
Returns:
-
bool
true if the frames can be arranged into the area.
Usage:
-- formatting rule contains a single frame with a script label of "icon" -- which is repeated until it fills the area of the rule frames = { formattingrule:getframe("icon") } index = 1; while formattingrule:canarrange(frames) do new_frame = formattingrule:getframe("icon"):duplicate(); table.insert(frames, new_frame); index = index + 1; end frames[index]:delete(); table.remove(frames, index); -- arrange then horizontally centered formattingrule:arrange(frames, "center") -- vertically align formattingrule:align(frames, "vcenter")
- getbounds ([param1[, param2[, param3[, param4[, param5]]]]])
-
Returns the geometric bounds of the Formatting Rule, or given arguments. Bounds are given in
points relative to the top-left (0,0)
Parameters:
- param1 Array of FRAME objects, single FRAME object, name of a frame (optional)
- param2 (optional)
- param3 (optional)
- param4 (optional)
- param5 (optional)
Returns:
-
structure { "left" = x1, "right" = x2, "top" = y1, "bottom" = y2 }
Usage:
-- get the bounds of the formatting rule area = formattingrule:getbounds(); -- bounds of all 'cover_image' frames, passing in an array image_area = formattingrule:getbounds(formattingrule:getframes("cover_image.*")); -- bounds of single FRAME area = formattingrule:getbounds(formattingrule:getframe("image_area")); -- bounds of a named frame area = formattingrule:getbounds("image_area"); -- bounds of multiple named frames area = formattingrule:getbounds("Image_Cover1", "Image_Cover2"); -- Accessing the return value error ("l=" .. area.left .. ", r=" .. area.right .. ", t=" .. area.top .. ", b=" .. area.bottom);
- getdom ()
-
Retrieve the scripting DOM for the Formatting Rule
Usage:
d = formattingrule:getdom();
- getframe (name)
-
Gets a named FRAME. The name is determined from the contents of its Script Label.
Parameters:
- name string Name of the frame to get.
Returns:
-
The found FRAME
Or
-
nil if no value is found
Usage:
container_bounds = formattingrule:getframe("container"):getbounds(); named_frames = formattingrule:getframes("Main_Title2_image_Cover.*"); formattingrule:positionframes(named_frames, container_bounds, 0, "left-right", "bottom-middle");
- getframes ([regex])
-
Returns a FRAME array. Ordered alphabetically by name if present. Names should be unique as they
form the key to the resulting array. When not unique, the index is used.
Parameters:
- regex string Regular expression to match against Script Labels. (optional)
Returns:
-
Array of FRAME objects. The index is the Frame Label or index number if none exists
Or
-
nil if no matching frames found
Usage:
-- Get a all the frames starting with image: image_frames = formattingrule:getframes("image.*"); -- Get all frames, then reference a specific frame from the result by name all_frames = formattingrule:getframes(); container_bounds = all_frames["container"]:getbounds();
- placerule (name, x, y[, SELECTION])
-
Place a Formatting Rule at the given position. Incorporates it hierarchicaly as the last child
in the parent frame. There is no independant updating of the placed rule.
Parameters:
- name string Formatting Rule name
- x number X Position relative to parents top-left
- y number Y Position relative to parents top-left
- SELECTION Data to populate with (optional)
Returns:
-
FRAME
The formatting rules FRAME
Usage:
-- Starting at x(0) and y(0), create a 4 x 4 grid of the 'redbox' Formatting Rule ypos = 0; xpos = 0; nextypos = 0 for x=1,4 do for y=1,4 do local result = formattingrule:placerule("redbox",xpos, ypos); xpos = result:right(); nextypos = result:bottom(); end xpos = 0; ypos = nextypos; end -- Selectively place a rule based on the contents of a field sel = SELECTION.root(); field_content = sel:getcontent('seite'); if field_content == "10" then formattingrule:placerule("small_green",0,0); else formattingrule:placerule("small_red",0,0); end -- Insert a populated rule for each item in the selection sel = SELECTION.root(); ypos = 0; xpos = 0; for i=1,sel:size() do local result = formattingrule:placerule("art",xpos, ypos, sel:get(i)); ypos = result:bottom(); end; -- for each selected item, place a rule and then arrange it left-right in the formatting rule bounds sel = SELECTION.root(); frame_array = {} for i=1,sel:size() do frame_array[i] = formattingrule:placerule("art",0, 0, sel:get(i)); end; formattingrule:positionframes(frame_array, formattingrule:getbounds(), 0, "left-right", "top-left");
Class MENU
- MENU.menuitemproperties
-
Properties of a menu item.
Fields:
- gettitle Function which returns the menus name. Called each time it appears.
- onselect Function called when actioned.
- position Position on the menu.
- onupdate Function which determines enabled state. true for enabled. (optional)
- type Type of menu item 'normal' or 'separator' (optional)
- additem (menuitemproperties)
-
Add a custom menu item.
Parameters:
- menuitemproperties Table of properties.
Usage:
m1 = { position = 1, gettitle = getmenuname, onupdate = updatemenustate, onselect = domenu}; m2 = { type = "separator", position = 2 }; MENU.additem( m1 ); MENU.additem( m2 );
Class DIALOG
- dialogproperties
-
Properties of a dialog.
Fields:
- title Text displayed in the title bar
- validate Function to validate settings prior to closing. Takes the dialog as an argument and returns the id of the control with the invalid setting or nothing for OK (optional)
- width Width of the dialog in pixels. If none supplied, determined by the control bounds (optional)
- height Height on the dialog in pixels (optional)
- widgetproperties
-
Properties of a widget.
Fields:
- type [all] Type of widget (group, editbox, editboxpassword, cancelbutton, okbutton, button, statictext, menu, checkbox, hyperlinktext, separator, custom, customchild)
- top [all] Position of the control, relative to the dialog top left or the parent group widget
- left [all]
- id [all] unique id of the widget for referencing (optional)
- right [all] (optional)
- bottom [all] (optional)
- height [all] (optional)
- width [all] (optional)
- enable [all] Enabled state (default true)
- visible [all] Visible state (default true)
- parentid [all] parent widgetid (optional)
- alignment [statictext,hyperlintext] Alignment of the content (default left)
- title [statictext,hyperlintext,button] Text to display (optional)
- content [editbox] Content (optional)
- hyperlink [hyperlink] URL to link to (optional)
- selectedindex [menu] Ondex of the selected item (optional)
- selectedtext [menu] The text of the selected item (optional)
- menuitems [menu] Table of strings (optional)
- state [checkbox] true for set and false for unset. (optional)
- onchange [checkbox,editbox] Callback function to handle widget content change (optional)
- vscroll [custom] true to support a vertical scroll bar (default false)
- stepamount [custom] the amount of each scroll step in pixels (default 1)
- multiselect [custom] true to support multiple selection (default false)
- singleselect [custom] true to support single row selection. (default true)
- selectedrows [custom] Field used to set and get list of row numbers selected. (optional)
- onclick [button, customchild] Callback function to handle click (optional)
- ondblclick [customchild] Callback to handle double click (optional)
- drawmethod [customchild] Callback to render the widget (optional)
- addwidget (widgets)
-
Add a single widget or table of widgets to the dialog box.
Parameters:
- widgets Single widget or table of widgets to add.
See also:
Usage:
configdialog:addwidget( { { type = "statictext", title = "Name", align = "left", left = 20, top = 20, right = 100, bottom = 40, }, { type = "editbox", id = "Name", left = 100, top = 20, right = 450, bottom = 40, content = configdialog.name, enable = false }, { type = "statictext", title = "API Key2:", align = "left", left = 20, top = 20+25, right = 100, bottom = 40+25 }, { type = "editbox", id = "ID", left = 100, top = 20+25, right = 450, bottom = 40+25, content = config.apiKey, enabled = true }, { type = "button", id = "testbutton", title = "Show JSON Result", left = 100, top = 20+25+25, right = 250, bottom = 40+25+25, onchange = testbuttonpress}, { type = "custom", id = "preview", multiselect = true, left = 100, top = 20+25+25+25, right = 450, bottom = 40+25+25+560, vscroll = true }, }
- alert (message[, type=alert[, buttontext]])
-
Display an alert message.
Parameters:
- message string Message Text.
- type string Alert Type ("alert" , "warning", "error", "yesno" or "yesnocancel") (default alert)
- buttontext Table of button labels:
Returns:
-
Text of the button pressed
Usage:
-- simple alert DIALOG.alert("Please enter a valid string"); -- yes no cancel alert with custom button text choice = DIALOG.alert( "Yes No Cancel Example", "yesnocancel", { yes = "Go", no = "Stop", cancel = "Exit" });
- choosefile (prompt)
-
Choose a file.
Parameters:
- prompt message to display
Returns:
- bool true if file was chosen
- string path to chosen file
Usage:
done, path = DIALOG.choosefile("Choose a file");
- choosefolder ()
-
Choose a folder.
Returns:
- bool true if folder was chosen
- string path to chosen folder
Usage:
done, path = DIALOG.choosefolder("Choose a folder");
- close ()
-
Close the dialog box.
Usage:
configdialog:close();
- getwidget (id)
-
Gets the widgetproperties of a named widget
Parameters:
- id string ID of the widget to get
Returns:
-
table of widgetproperties
Usage:
-- get the content of a named edit box config.id = configdialog:getwidget("ID").content;
- new (dialogproperties)
-
Create a new dialog box.
Parameters:
- dialogproperties Table of properties.
Returns:
-
DIALOG
new dialog object
See also:
Usage:
function validatemethod(dialog) x = dialog:getwidget("Name").content; if x == "" then DIALOG.alert("Please enter a valid name"); return "Name"; end end configdialog = DIALOG.new( { title = "New Custom Data Source", validate = validatemethod} );
- open ()
-
Display the dialog box.
Returns:
-
bool
true for OK, false if Cancelled
Usage:
configdialog = DIALOG.new( { title = "New Simple Dialog " } ); configdialog:addwidget( { { type = "statictext", title = "Name", align = "left", left = 20, top = 20, right = 100, bottom = 40, }, { type = "editbox", id = "Name", left = 100, top = 20, right = 450, bottom = 40, content = config.name, enable = enable_name }, }); if configdialog:open() then end
- saveas ()
-
saveas.
Returns:
- bool true if ok
- string path to file location
Usage:
done, path = DIALOG.saveas("fred.xml", { "xml", "json", "txt", "indd" } );
- setwidget (properties)
-
Sets the widgetproperties of a named widget
Parameters:
- properties new widgetproperties
Returns:
-
table of widgetproperties
Usage:
widgetproperties = configdialog:getwidget("ID"); widgetproperties.content = "new value"; configdialog:setwidget(widgetproperties);
Class HTTP
- get (url[, headers[, settings[, filepath]]])
-
Perform a HTTP GET operation.
Parameters:
- url string URL to retreive from
- headers Table of headers (optional)
- settings Table of connection parameters - "useauthentication", "usernamepassword", "useproxy", "proxyusernamepassword", "proxyaddress" (optional)
- filepath Path to a file to write. When used, response body is returned empty and the contents are written to the file (optional)
Returns:
- int Response code
- string Response body
Usage:
url = "https://newsapi.org/v2/everything?q=".. config.keyword .. "&apiKey=" .. config.id; response_code, response_body = HTTP.get(url) if response_code ~= 200 and response_code ~= 401 then error(response_code .. response_body); end json_return = cjson.decode(response_body)
- getparam (body, param)
-
Perform a HTTP getparam operation.
Parameters:
Returns:
-
string
content
Usage:
local contentOfCode = getparam(body, "code");
- gettofile (url, path[, params[, params]])
-
Retreive data to file from a URL based resource.
Parameters:
- url string URL to retreive from
- path string to file
- params Optional table of connection parameters - "useauthentication", "usernamepassword", "useproxy", "proxyusernamepassword", "proxyaddress" (optional)
- params Optional table of connection parameters - "useauthentication", "usernamepassword", "useproxy", "proxyusernamepassword", "proxyaddress" (optional)
Returns:
- int Response code
- string Response content
Usage:
url = "https://newsapi.org/v2/everything?q=".. config.keyword .. "&apiKey=" .. config.id; path = "Macintosh HD:Users:NAME:Desktop:content.json"; response, error_str = HTTP.gettofile(url, path) if response ~= 200 and response ~= 401 then error(error_str .. body); end json_return = cjson.decode(content)
- getwithheaders (url[, headers[, settings[, filepath]]])
-
Perform a HTTP GET operation with headers.
Parameters:
- url string URL to retreive from
- headers Table of headers (optional)
- settings Table of connection parameters - "useauthentication", "usernamepassword", "useproxy", "proxyusernamepassword", "proxyaddress" (optional)
- filepath Path to a file to write. When used, response body is returned empty and the contents are written to the file (optional)
Returns:
Usage:
url = "https://newsapi.org/v2/everything?q=".. config.keyword .. "&apiKey=" .. config.id; response_code, response_body, response_headers = HTTP.getwithheaders(url) if response_code ~= 200 and response_code ~= 401 then error(response_code .. response_body); end json_return = cjson.decode(response_body) for nn, vv in pairs(response_headers) do entry = "NAME:" .. nn .. "; VALUE" .. vv .. ";"; end
- oathgetauthrorizationcode (url, port, url)
-
Perform a HTTP oathgetauthrorizationcode operation (CS7 or above).
Parameters:
- url string Moved permanently redirect
- port int Port to listen on
- url string Moved permanently redirect
Returns:
-
integer
code and string response body
Usage:
local code, body = HTTP.oathgetauthrorizationcode(url, 8087, "https://dam3.getdam.com");
- post (url, data[, headers[, params]])
-
Post data to a URL
Parameters:
- url string URL to post to
- data string Content to post
- headers Table of connection headers (optional)
- params Optional table of connection parameters - "useauthentication", "usernamepassword", "useproxy", "proxyusernamepassword", "proxyaddress" (optional)
Returns:
- int Code
- string Content
Usage:
url = "http://ptsv2.com/t/78cm9-1541599588/post"; code, body = HTTP.post(url, "Example data being posted") error (code .. "/" .. body);
- urlencode (unencoded)
-
URL Encode the given string.
Parameters:
- unencoded string
Returns:
Usage:
url = "https://newsapi.org/v2/everything?q=".. HTTP.urlencode(config.keyword) .. "&apiKey=" .. config.id;
Class LINK
- applycharacterstyle (stylesheet)
-
Apply a character style to a link.
Parameters:
- stylesheet string Name of the stylesheet to apply
Returns:
-
nothng
Usage:
link:applycharacterstyle("error");
- createhyperlink (hyperlink)
-
Create Hyperlink associated with the link.
Parameters:
- hyperlink string Hyperlink
Returns:
-
true
or false
Usage:
link:createhyperlink(url);
- delete ()
-
Delete an array of links from document.
Returns:
-
int
number of links deleted
Usage:
allLinks = document:getlinks(); count = LINK.delete(allLinks);
- getcomputed ()
-
Get the Computed Field command associated with the link
Returns:
-
string
Computed field command
Usage:
command = link:getcomputed();
- getcontent ()
-
Get the content of the link.
Returns:
-
string
content
Usage:
str = link:getcontent();
- getdatasourcename ()
-
Get the data source name.
Returns:
-
string
Data source name
Usage:
str = link:getdatasourcename();
- getfield ()
-
Get the field name of the link.
Returns:
-
string
Field name
Usage:
str = link:getfieldname();
- getframe ()
-
Get the FRAME the links is contained within.
Returns:
Usage:
frame = link:getframe();
- getkey ()
-
Get the links key value.
Returns:
-
string
Key field value
Usage:
str = link:getkey();
- getnotes ()
-
Get notes associated with the link.
Returns:
-
string
notes
Usage:
data = link:getnotes();
- getpagenumber ()
-
Get the page number the link is on.
Returns:
-
int
page number
Usage:
str = link:getpagenumber();
- getspread ()
-
Get the spread the link is on.
Returns:
-
string
Spread name
Usage:
str = link:getspread();
- gettextendpos ()
-
Returns the text index of the end of the link.
Returns:
-
int
Text end index
Usage:
count = link:gettextendpos();
- gettextlength ()
-
Returns the text length of the link.
Returns:
-
int
Length of the link content
Usage:
count = link:gettextlength();
- gettextstartpos ()
-
Returns the text index of the start of the link.
Returns:
-
int
Text start index
Usage:
count = link:gettextstartpos();
- isonpasteboard ()
-
Returns true if the link is on the pasteboard.
Returns:
-
bool
true if link on pasteboard
Usage:
bool = link:isonpasteboard();
- isoutofdate ()
-
Returns true if the link needs updating.
Returns:
-
bool
true if link out of date.
Usage:
bool = link:isoutofdate();
- isoverset ()
-
Returns true if any part of the link is in overset text.
Returns:
-
bool
true if in overset text
Usage:
bool = link:isoverset();
- istext ()
-
Returns true for text based links, false for frame links.
Returns:
-
bool
true if is text frame
Usage:
bool = link:istext();
- setdatasourcename (datasource)
-
Update the project name component of a physical link
Parameters:
- datasource string
Returns:
-
nothing
Usage:
link:setdatasourcename(str);
- setfieldname (fieldname)
-
Update the field name component of a physical link.
Parameters:
- fieldname string
Returns:
-
nothing
Usage:
link:setfieldname(str);
- setkey (key)
-
Update the key component of a physical link.
Parameters:
- key string
Usage:
link:setkey(str);
Class XMLNODE
- content ()
-
Returns the content of this node.
Returns:
-
string
Nodes content
Usage:
value = myNODE:content();
- valueof (xpath)
-
Returns the value from an XPath command relative to this node.
Parameters:
- xpath string XPath command
Returns:
-
string
Value of expression
Usage:
value = myNODE:valueof('@name');
Class RECORDSET
- addfied (name[, value])
-
Add a field to the recordset. Only to be used in createcontent.lua
Parameters:
Usage:
-- using name only records:addfield("newfield"); -- using field options f = { name = "anotherfield", type="tabular"} records:addfield(f);
- addrecord ([record])
-
Add a record to the recordset. Only to be used in createcontent.lua or menu based scripts.
Parameters:
- record RECORD (optional)
- append (recordset)
-
Append the contents of the given record set.
Parameters:
- recordset RECORDSET object
- callback (function, sortfield, group1[, group2[, group3]])
-
Calls a function for each group of records within this recordset. Function is passed a RECORDSET
parameter.
Parameters:
- function string Function name to call
- sortfield string Name of the field to sort the each group by
- group1 string Name of the field to group by
- group2 string Optional sub grouping (optional)
- group3 string Optional sub grouping (optional)
Usage:
function handle_subset(recordset) tab = TABLE.new(); tab:cell(1,1):setcontent("content for group #" .. group_index); recordset:settabular("CF_TEST", tab); group_index = group_index + 1; end recordset = DATASOURCE.get():getrecordset(); recordset:callback("handle_subset", "", "marca");
- duplicaterecord (record)
-
Duplicate the 'nth' record.
Parameters:
- record int index to duplicate (1..n)
Returns:
Usage:
newrecord = records:duplicaterecord(1);
- filter (field1, value1, field2, value2, field3, value3)
-
Create a new record set, based on the supplied filter.
Parameters:
- field1 string name of a field
- value1 string value to filter
- field2 string name of a field
- value2 string value to filter
- field3 string name of a field
- value3 string value to filter
Returns:
-
RECORDSET
Usage:
newRecordSet = myRECORDSET:filter('Cat','General','Subcat', 'Motors');
- getactivedocname ()
-
Get the active document name
Returns:
-
string
The name of the document
Usage:
docname = document:getactivedocname();
- getdocname ()
-
Get the document name
Returns:
-
string
The name of the document
Usage:
docname = document:getdocname();
- getpagepositions (ds[, field=all[, type=any[, rel=page[, uom=mm]]]])
-
Creates a table of records placed in the document along with positional information.
Parameters:
- ds DATASOURCE Object
- field string Field name to search for eg: 'Price' (default all)
- type string Content type to search for eg: 'text', 'picture' or 'any' (default any)
- rel string Output coordinates relative to either 'Page' or 'origin (default page)
- uom string Output coordinates unit of measure eg: 'cm', 'mm or 'pt' etc (default mm)
Returns:
-
TABLE of records along with position information fields (x,y,width,height)
Usage:
thisdatasource = DATASOURCE.get(); table = document:getpagepositions(thisdatasource, 'all', 'any', 'page', "cm"; if table then done, path = DIALOG.saveas("output.xlsx", { "xlsx" } ); if done then table:exportexcel(path); end end
- getrecord (record)
-
Return a record, either by index or by key
Parameters:
- record int index to get, starting from 1. Or key value string
Returns:
-
RECORD
The found record
Usage:
-- get by index myRECORD = myRECORDSET:getrecord(2); -- get by key value myRECORD = myRECORDSET:getrecord("abc");
- new (fields, records)
-
Create a new RECORDSET object.
Parameters:
- fields table of field names and field option settings
- records table of record content
Returns:
-
RECORDSET
Usage:
url = "https://newsapi.org/v2/everything?q=".. HTTP.urlencode(config.keyword) .. "&apiKey=" .. config.id; err, body = HTTP.get(url) if err ~= 200 and err ~= 401 then error(err .. body); end json_return = cjson.decode(body) status = json_return["status"]; if status ~= "ok" then error (json_return["message"]); end arts = json_return["articles"]; records = {} for i=1, #arts do article = arts[i]; newrecord = { article.title , article.description, article.url} table.insert(records, newrecord); end; fields = { { name = "title", key = "true"}, { name = "description"}, { name = "url"} } return RECORDSET.new(fields, records);
- relatedrecords (field1[, field2[, field3]])
-
Create a set of related records based on matching field content.
Parameters:
- field1 string name of a field
- field2 string name of a field (optional)
- field3 string name of a field (optional)
Returns:
-
RECORDSET
Usage:
newRecordSet = RECORDSET.relatedrecords('Cat','Subcat');
- removefield (name)
-
Remove a field from the recordset. Only to be used in createcontent.lua
Parameters:
- name string field name
Usage:
records:removefield("newfield");
- removerecord (record)
-
Remove the 'nth' record. Only to be used in createcontent.lua
Parameters:
- record int index to remove (1..n)
Usage:
records:remove(1);
- renamefield (oldname, newname)
-
Rename a field. Only to be used in createcontent.lua
Parameters:
Usage:
records:renamefield("old", "new");
- setfieldcontent (name, value)
-
Set the content of a field for all records in the recordset.
Parameters:
Usage:
- settabular (fieldname, TABLE)
-
Sets the tabular data of all named fields in this record set. For advanced custom field
commands, The field should be a tabular field with 'command script' content type defined.
Parameters:
- fieldname string Name of the field to assing the table to.
- TABLE table data to set
Usage:
function handle_subset(recordset) tab = TABLE.new(); tab:cell(1,1):setcontent("content for group #" .. group_index); recordset:settabular("CF_TEST", tab); group_index = group_index + 1; end recordset = DATASOURCE.get():getrecordset(); recordset:callback("handle_subset", "", "marca");
- size ()
-
The number of records in the record set.
Returns:
-
int
number of records
Usage:
count = records:size();
- sort (field1[, field2[, field3[, field4[, field5]]]])
-
Sort the records in the record set. Uses field specific type and language sorting properties.
Parameters:
- field1 string
- field2 string (optional)
- field3 string (optional)
- field4 string (optional)
- field5 string (optional)
Returns:
-
None
Usage:
myrecordset:sort('this','then this','finally this');
- tableof ([field1[, field2[, field3[, field4[, field5]]]]])
-
Create a new table. Field names can optionally be specified
Parameters:
- field1 string field name to get (optional)
- field2 string field name to get (optional)
- field3 string field name to get (optional)
- field4 string field name to get (optional)
- field5 string field name to get (optional)
Returns:
-
None
Usage:
myTable = myRECORDSET:tableof('this','then this','finally this');
Class DOCUMENT
- applymaster (index, master)
-
Apply a named master page to a page in the document.
Parameters:
- index int Index of page to apply master to
- master string Name of master page to apply
Returns:
-
None
Usage:
document:applymaster(2,'mymaster1'); document:applymaster(3,'mymaster1'); document:applymaster(4,'C-Master'); document:applymaster(5,'C-Master');
- deletepage (index)
-
Delete a page in the document.
Parameters:
- index int Index of page to delete
Returns:
-
None
Usage:
pagecount = document:pagecount(); document:deletepage(pagecount);
- getactive ()
-
Get the active DOCUMENT
Returns:
-
DOCUMENT
New DOCUMENT object
Usage:
mydocument = DOCUMENT.getactive(); pagecount = mydocument:pagecount();
- getdom ()
-
Get the Application Scripting DOM.
Returns:
-
DOM
the Application Scripting DOM
Usage:
app = getdom();
- getlinks ()
-
Get an array of LINKs in the document
Returns:
-
array
An array of LINK objects
Usage:
mytable = TABLE:new(); myLinks = document:getlinks(); r=1; c=1; mytable:cell(r,c):setcontent("Key"); mytable:cell(r,c):setheader(true); r=r+1; for i,myLink in ipairs(myLinks) do theKey = myLink:getkey(); mytable:cell(r,c):setcontent(theKey); r=r+1; end mytable:present();
- getselectedlinks ()
-
Get an array of LINKs in the document
Returns:
-
array
An array of LINK objects
Usage:
mytable = TABLE:new(); myLinks = document:getselectedlinks(); r=1; c=1; mytable:cell(r,c):setcontent("Key"); mytable:cell(r,c):setheader(true); r=r+1; for i,myLink in ipairs(myLinks) do theKey = myLink:getkey(); mytable:cell(r,c):setcontent(theKey); r=r+1; end mytable:present();
- insertpage ()
-
Insert a page at the end of the document.
Returns:
-
None
Usage:
document:insertpage();
- pagecount ()
-
Returns the number of pages in the document.
Returns:
-
int
Usage:
pagecount = document:pagecount();
- pagehastags (pageindex)
-
Determine if a page has any tags.
Parameters:
- pageindex int Index of page to check
Returns:
-
bool
true if page has tags
Usage:
-- delete all pages without tags for page=document:pagecount(),2,-1 do if document:pagehastags(page) == false then document:deletepage(page); end; end;
- pageheight (pageindex)
-
Get the height of the a page in points.
Parameters:
- pageindex int Index of page
Returns:
-
number
height in points
Usage:
height = document:pageheight(1);
- pagemargins (pageindex)
-
Get the page margins.
Parameters:
- pageindex int Index of page
Returns:
- number left margin in points
- number top margin in points
- number right margin in points
- number bottom margin in points
Usage:
left,top,right,bottom = doc:pagemargins(pageindex);
- pagetype (pageindex)
-
Get the page type (left/right/unisex).
Parameters:
- pageindex int Index of page
Returns:
-
string
type of p_sortage ("left","right","unisex")
Usage:
type = document:pagetype(1);
- pagewidth (pageindex)
-
Get the width of the a page in points.
Parameters:
- pageindex int Index of page
Returns:
-
number
width in points
Usage:
width = document:pagewidth(1);
- placerule (pageindex, rulename, x, y, data[, location])
-
Place a Formatting Rule into the given position.
Parameters:
- pageindex int Index of page
- rulename string Formatting rule name
- x int X Position
- y int Y Position
- data SELECTION to populate with
- location string lefttop(Default),middletop,middlebottom,rightmiddle,righttop,rightbottom,leftbottom (optional)
Usage:
--- Get the active document doc = DOCUMENT.getactive(); --- Get the margins for the first page left,top,right,bottom = doc:pagemargins(1); --- Place inside margins at the bottom right myframe = doc:placerule(1,'New Rule',doc:pagewidth(1)-right,doc:pageheight(2)-bottom, SELECTION.root(), 'rightbottom'); --- Place inside margins at the top left myframe = doc:placerule(1,'New Rule',left,top, SELECTION.root(), 'lefttop');
- synchronize ()
- Scan the document, updating the placed and error state of each field