Builtins

Builtins are Constants, Variables, Functions and Statements that provide additional information and allow for data manipulations.

Builtin Constants

Builtin constants are used to provide information about object parameters, such as maximum recommended name length, flags etc. Many of the object types have their own Constants section which lists the builtin constants for that particular object (see e.g. UL_PIN).

The following builtin constants are defined in addition to the ones listed for the various object types:

   
EAGLE_VERSION EAGLE program version number (int)
EAGLE_RELEASE EAGLE program release number (int)
EAGLE_SIGNATURE a string containing EAGLE program name, version and copyright information
EAGLE_PATH a string containing the complete path of the EAGLE executable
EAGLE_DIR a string containing the directory of the EAGLE installation ($EAGLEDIR)
EAGLE_HOME a string containing the user's home directory when starting EAGLE ($HOME)
eagle_epf a string containing the complete path of the currently used eagle.epf
OS_SIGNATURE a string containing a signature of the operating system (e.g. Mac..., Windows... or Linux)
REAL_EPSILON the minimum positive real number such that 1.0 + REAL_EPSILON != 1.0
REAL_MAX the largest possible real value
REAL_MIN the smallest possible (positive!) real value. The smallest representable number is -REAL_MAX
INT_MAX the largest possible int value
INT_MIN the smallest possible int value
PI the value of "pi" (3.14..., real)
usage a string containing the text from the #usage directive

These builtin constants contain the directory paths defined in the directories dialog, with any of the special variables ($HOME and $EAGLEDIR) replaced by their actual values. Since each path can consist of several directories, these constants are string arrays with an individual directory in each member. The first empty member marks the end of the path:

path_lbr[]    Libraries
path_dru[]    Design Rules
path_ulp[]    User Language Programs
path_scr[]    Scripts
path_cam[]    CAM Jobs
path_epf[]    Projects

When using these constants to build a full file name, you need to use a directory separator, as in

string s = path_lbr[0] + '/' + "mylib.lbr";

The libraries that are currently in use through the USE command:

used_libraries[]  

Builtin Variables

Builtin variables are used to provide information at runtime.

int argc    number of arguments given to the RUN command
string argv[] arguments given to the RUN command (argv[0] is the full ULP file name)

Builtin Functions

Builtin functions are used to perform specific tasks, like printing formatted strings, sorting data arrays or the like.

You can also write your own functions and use them to structure your User Language Program.

The builtin functions are grouped into the following categories:

Alphabetical reference of all builtin functions:

abs()
acos()
asin()
atan()
ceil()
cfgget()
cfgset()
clrgroup()
country()
cos()
exit()
exp()
fdlsignature()
filedir()
fileerror()
fileext()
fileglob()
filename()
fileread()
filesetext()
filesize()
filetime()
floor()
frac()
inch2u()
ingroup()
isalnum()
isalpha()
iscntrl()
isdigit()
isgraph()
islower()
isprint()
ispunct()
isspace()
isupper()
isxdigit()
language()
log()
log10()
lookup()
max()
mic2u()
mil2u()
min()
mm2u()
neterror()
netget()
netpost()
palette()
pow()
printf()
round()
setgroup()
setvariant()
sin()
sleep()
sort()
sprintf()
sqrt()
status()
strchr()
strjoin()
strlen()
strlwr()
strrchr()
strrstr()
strsplit()
strstr()
strsub()
strtod()
strtol()
strupr()
strxstr()
system()
t2day()
t2dayofweek()
t2hour()
t2minute()
t2month()
t2second()
t2string()
t2year()
tan()
time()
tolower()
toupper()
trunc()
u2inch()
u2mic()
u2mil()
u2mm()
variant()
xmlattribute()
xmlattributes()
xmlelement()
xmlelements()
xmltags()
xmltext()

Character functions

Character functions are used to manipulate single characters.

The following character functions are available:

isalnum()
isalpha()
iscntrl()
isdigit()
isgraph()
islower()
isprint()
ispunct()
isspace()
isupper()
isxdigit()
tolower()
toupper()

is...()

Function

Check whether a character falls into a given category.

Syntax

int isalnum(char c);
int isalpha(char c);
int iscntrl(char c);
int isdigit(char c);
int isgraph(char c);
int islower(char c);
int isprint(char c);
int ispunct(char c);
int isspace(char c);
int isupper(char c);
int isxdigit(char c);

Returns

The is... functions return nonzero if the given character falls into the category; zero otherwise.

Character categories

isalnum   letters (A to Z or a to z) or digits (0 to 9)
isalpha   letters (A to Z or a to z)
iscntrl   delete characters or ordinary control characters (0x7F or 0x00 to 0x1F)
isdigit   digits (0 to 9)
isgraph   printing characters (except space)
islower   lowercase letters (a to z)
isprint   printing characters (0x20 to 0x7E)
ispunct   punctuation characters (iscntrl or isspace)
isspace   space, tab, carriage return, new line, vertical tab, or formfeed  (0x09 to 0x0D, 0x20)
isupper   uppercase letters (A to Z)
isxdigit  hex digits (0 to 9, A to F, a to f)

Example

char c = 'A';
if (isxdigit(c))
   printf("%c is hex\n", c);
else
   printf("%c is not hex\n", c);

to...()

Function

Convert a character to upper- or lowercase.

Syntax

char tolower(char c);
char toupper(char c);

Returns

The tolower function returns the converted character if c is uppercase. All other characters are returned unchanged. The toupper function returns the converted character if c is lowercase. All other characters are returned unchanged.

See also strupr, strlwr

File handling functions

Filename handling functions are used to work with file names, sizes and timestamps.

See output() for information about how to write into a file.

fileerror()

Function

Returns the status of I/O operations.

Syntax

int fileerror();

Returns

The fileerror function returns 0 if everything is ok.

See also output, printf, fileread

fileerror checks the status of any I/O operations that have been performed since the last call to this function and returns 0 if everything was ok. If any of the I/O operations has caused an error, a value other than 0 will be returned.

You should call fileerror before any I/O operations to reset any previous error state, and call it again after the I/O operations to see if they were successful.

When fileerror returns a value other than 0 (thus indicating an error) a proper error message has already been given to the user.

Example

fileerror();
output("file.txt", "wt") {
  printf("Test\n");
  }
if (fileerror())
   exit(1);

fileglob()

Function

Perform a directory search.

Syntax

int fileglob(string &array[], string pattern);

Returns

The fileglob function returns the number of entries copied into array.

See also dlgFileOpen(), dlgFileSave()

fileglob performs a directory search using pattern.

pattern may contain '*' and '?' as wildcard characters. If pattern ends with a '/', the contents of the given directory will be returned.

Names in the resulting array that end with a '/' are directory names.

The array is sorted alphabetically, with the directories coming first.

The special entries '.' and '..' (for the current and parent directories) are never returned in the array.

If pattern doesn't match, or if you don't have permission to search the given directory, the resulting array will be empty.

Note for Windows users: The directory delimiter in the array is always a forward slash. This makes sure User Language Programs will work platform independently. In the pattern the backslash ('') is also treated as a directory delimiter.

Sorting filenames under Windows is done case insensitively.

Example

string a[];
int n = fileglob(a, "*.brd");

Filename functions

Function

Split a filename into its separate parts.

Syntax

string filedir(string file);
string fileext(string file);
string filename(string file);
string filesetext(string file, string newext);

Returns

filedir returns the directory of file (including the drive letter under Windows).

fileext returns the extension of file.

filename returns the file name of file (including the extension).

filesetext returns file with the extension set to newext.

See also Filedata Functions

Example

if (board) board(B) {
  output(filesetext(B.name, ".out")) {
    ...
    }
  }

Filedata Functions

Function

Gets the timestamp and size of a file.

Syntax

int filesize(string filename);
int filetime(string filename);

Returns

filesize returns the size (in byte) of the given file.

filetime returns the timestamp of the given file in seconds. The format is compatible to be used with the time functions.

See also time, Filename Functions

Example

board(B)
  printf("Board: %s\nSize: %d\nTime: %s\n",
         B.name, filesize(B.name),
         t2string(filetime(B.name)));

File Input Functions

File input functions are used to read data from files. The following file input is available:

See output() for information about how to write into a file.

fileread()

Function

Reads data from a file.

Syntax

int fileread(dest, string file);

Returns

fileread returns the number of objects read from the file.

The actual meaning of the return value depends on the type of dest.

See also lookup, strsplit, fileerror

If dest is a character array, the file will be read as raw binary data and the return value reflects the number of bytes read into the character array (which is equal to the file size).

If dest is a string array, the file will be read as a text file (one line per array member) and the return value will be the number of lines read into the string array. Newline characters will be stripped.

If dest is a string, the entire file will be read into that string and the return value will be the length of that string (which is not necessarily equal to the file size, if the operating system stores text files with "cr/lf" instead of a "newline" character).

Example

char b[];
int nBytes = fileread(b, "data.bin");
string lines[];
int nLines = fileread(lines, "data.txt");
string text;
int nChars = fileread(text, "data.txt");

Mathematical functions

Mathematical functions are used to perform mathematical operations. The following mathematical functions are available:

abs()
acos()
asin()
atan()
ceil()
cos()
exp()
floor()
frac()
log()
log10()
max()
min()
pow()
round()
sin()
sqrt()
trunc()
tan()

Error Messages

If the arguments of a mathematical function call lead to an error, the error message will show the actual values of the arguments. Thus the statements

real x = -1.0;
real r = sqrt(2 * x);

will lead to the error message

Invalid argument in call to 'sqrt(-2)'

Absolute, Maximum and Minimum Functions

Function

Absolute, maximum and minimum functions.

Syntax

type abs(type x);
type max(type x, type y);
type min(type x, type y);

Returns

abs returns the absolute value of x.

max returns the maximum of x and y.

min returns the minimum of x and y.

The return type of these functions is the same as the (larger) type of the arguments. type must be one of char, int or real.

Example

real x = 2.567, y = 3.14;
printf("The maximum is %f\n", max(x, y));

Rounding Functions

Function

Rounding functions.

Syntax

real ceil(real x);
real floor(real x);
real frac(real x);
real round(real x);
real trunc(real x);

Returns

ceil returns the smallest integer not less than x.

floor returns the largest integer not greater than x.

frac returns the fractional part of x.

round returns x rounded to the nearest integer.

trunc returns the integer part of x.

Example

real x = 2.567;
printf("The rounded value of %f is %f\n", x, round(x));

Trigonometric Functions

Function

Trigonometric functions.

Syntax

real acos(real x);
real asin(real x);
real atan(real x);
real cos(real x);
real sin(real x);
real tan(real x);

Returns

acos returns the arc cosine of x.

asin returns the arc sine of x.

atan returns the arc tangent of x.

cos returns the cosine of x.

sin returns the sine of x.

tan returns the tangent of x.

Constants

PI the value of "pi" (3.14...)

Note:

Angles are given in radians.

Example

real x = PI / 2;
printf("The sine of %f is %f\n", x, sin(x));

Exponential Functions

Function

Exponential Functions.

Syntax

real exp(real x);
real log(real x);
real log10(real x);
real pow(real x, real y);
real sqrt(real x);

Returns

exp returns the exponential e to the power of x. log returns the natural logarithm of x. log10 returns the base 10 logarithm of x. pow returns the value of x to the power of y. sqrt returns the square root of x.

Example

real x = 2.1;
printf("The square root of %f is %f\n", x, sqrt(x));
printf("The 3rd root of %f is %f\n", x, pow(x, 1.0/3));

Miscellaneous functions

Miscellaneous functions are used to perform various tasks.

The following miscellaneous functions are available:

Configuration Parameters

Function

Store and retrieve configuration parameters.

Syntax

string cfgget(string name[, string default]);
void cfgset(string name, string value);

Returns

cfgget returns the value of the parameter stored under the given name. If no such parameter has been stored, yet, the value of the optional default is returned (or an empty string, if no default is given). The cfgget function retrieves values that have previously been stored with a call to cfgset().

The cfgset function sets the parameter with the given name to the given value.

The valid characters for name are 'A'-'Z', 'a'-'z', '0'-'9', '.' and '_'.

Parameter names are case sensitive.

The parameters are stored in the user's eaglerc file. To ensure that different User Language Programs don't overwrite each other's parameters in case they use the same parameter names, it is recommended to put the name of the ULP at the beginning of the parameter name. For example, a ULP named mytool.ulp that uses a parameter named MyParam could store that parameter under the name

mytool.MyParam

Because the configuration parameters are stored in the eaglerc file, which also contains all of EAGLE's other user specific parameters, it is also possible to access the EAGLE parameters with cfgget() and cfgset(). In order to make sure no ULP parameters collide with any EAGLE parameters, the EAGLE parameters must be prefixed with "EAGLE:", as in

EAGLE:Option.XrefLabelFormat

Note that there is no documentation of all of EAGLE's internal parameters and how they are stored in the eaglerc file. Also, be very careful when changing any of these parameters! As with the eaglerc file itself, you should only manipulate these parameters if you know what you are doing! Some EAGLE parameters may require a restart of EAGLE for changes to take effect. In the eaglerc file the User Language parameters are stored with the prefix "ULP:". Therefore this prefix may be optionally put in front of User Language parameter names, as in

ULP:mytool.MyParam

Example

string MyParam = cfgget("mytool.MyParam", "SomeDefault");
MyParam = "OtherValue";
cfgset("mytool.MyParam", MyParam);

country()

Function

Returns the country code of the system in use.

Syntax

string country();

Returns

country returns a string consisting of two uppercase characters that identifies the country used on the current system. If no such country setting can be determined, the default "US" will be returned.

See also language

Example

dlgMessageBox("Your country code is: " + country());

exit()

Function

Exits from a User Language Program.

Syntax

void exit(int result);
void exit(string command);

See also RUN

The exit function terminates execution of a User Language Program.

If an integer result is given it will be used as the return value of the program. If a string command is given, that command will be executed as if it were entered into the command line immediately after the RUN command. In that case the return value of the ULP is set to EXIT_SUCCESS.

Constants

EXIT_SUCCESS    return value for successful program execution (value 0)
EXIT_FAILURE    return value for failed program execution (value -1)

fdlsignature()

Function

Calculates a digital signature for Premier Farnell's Design Link.

Syntax

string fdlsignature(string s, string key);

The fdlsignature function is used to calculate a digital signature when accessing Premier Farnell's Design Link interface.

language()

Function

Returns the language code of the system in use.

Syntax

string language();

Returns

language returns a string consisting of two lowercase characters that identifies the language used on the current system. If no such language setting can be determined, the default "en" will be returned.

See also country

The language function can be used to make a ULP use different message string, depending on which language the current system is using.

In the example below all the strings used in the ULP are listed in the string array I18N[], preceeded by a string containing the various language codes supported by this ULP. Note the vtab characters used to separate the individual parts of each string (they are important for the lookup function) and the use of the commas to separate the strings. The actual work is done in the function tr(), which returns the translated version of the given string. If the original string can't be found in the I18N array, or there is no translation for the current language, the original string will be used untranslated.

The first language defined in the I18N array must be the one in which the strings used throughout the ULP are written, and should generally be English in order to make the program accessible to the largest number of users.

Example

string I18N[] = {
  "en\v"
  "de\v"
  "it\v"
  ,
  "I18N Demo\v"
  "Beispiel f?r Internationalisierung\v"
  "Esempio per internazionalizzazione\v"
  ,
  "Hello world!\v"
  "Hallo Welt!\v"
  "Ciao mondo!\v"
  ,
  "+Ok\v"
  "+Ok\v"
  "+Approvazione\v"
  ,
  "-Cancel\v"
  "-Abbrechen\v"
  "-Annullamento\v"
  };
int Language = strstr(I18N[0], language()) / 3;
string tr(string s)
{
  string t = lookup(I18N, s, Language, '\v');
  return t ? t : s;
}
dlgDialog(tr("I18N Demo")) {
  dlgHBoxLayout dlgSpacing(350);
  dlgLabel(tr("Hello world!"));
  dlgHBoxLayout {
    dlgPushButton(tr("+Ok")) dlgAccept();
    dlgPushButton(tr("-Cancel")) dlgReject();
    }
  };

lookup()

Function

Looks up data in a string array.

Syntax

string lookup(string array[], string key, int field_index[, char separator]);
string lookup(string array[], string key, string field_name[, char separator]);

Returns

lookup returns the value of the field identified by field_index or field_name. If the field doesn't exist, or no string matching key is found, an empty string is returned.

See also fileread, strsplit

An array that can be used with lookup() consists of strings of text, each string representing one data record.

Each data record contains an arbitrary number of fields, which are separated by the character separator (default is '\t', the tabulator). The first field in a record is used as the key and is numbered 0.

All records must have unique key fields and none of the key fields may be empty; otherwise, it is undefined which record will be found.

If the first string in the array contains a "Header" record (i.e. a record where each field describes its contents), using lookup with a field_name string automatically determines the index of that field. This allows using the lookup function without exactly knowing which field index contains the desired data. It is up to the user to make sure that the first record actually contains header information.

If the key parameter in the call to lookup() is an empty string, the first string of the array will be used. This allows a program to determine whether there is a header record with the required field names.

If a field contains the separator character, that field must be enclosed in double quotes (as in "abc;def", assuming the semicolon (';') is used as separator). The same applies if the field contains double quotes ("), in which case the double quotes inside the field have to be doubled (as in "abc;""def"";ghi", which would be abc;"def";ghi).

It is best to use the default "tab" separator, which doesn't have these problems (no field can contain a tabulator).

Here's an example data file (';' has been used as separator for better readability):

Name;Manufacturer;Code;Price
7400;Intel;I-01-234-97;$0.10
68HC12;Motorola;M68HC1201234;$3.50

Example

string OrderCodes[];
if (fileread(OrderCodes, "ordercodes") > 0) {
   if (lookup(OrderCodes, "", "Code", ';')) {
      schematic(SCH) {
        SCH.parts(P) {
          string OrderCode;
          // both following statements do exactly the same:
          OrderCode = lookup(OrderCodes, P.device.name, "Code", ';');
          OrderCode = lookup(OrderCodes, P.device.name, 2, ';');
          }
        }
      }
   else
      dlgMessageBox("Missing 'Code' field in file 'ordercodes');
   }

palette()

Function

Returns color palette information.

Syntax

int palette(int index[, int type]);

Returns

The palette function returns an integer ARGB value in the form 0xaarrggbb, or the type of the currently used palette (depending on the value of index).

The palette function returns the ARGB value of the color with the given index (which may be in the range 0 to PALETTE_ENTRIES-1). If type is not given (or is -1) the palette assigned to the current editor window will be used. Otherwise, type specifies which color palette to use (PALETTE_BLACK, PALETTE_WHITE or PALETTE_COLORED). The special value -1 for index makes the function return the type of the palette that is currently in use by the editor window.

If either index or type is out of range, an error message will be given and the ULP will be terminated.

Constants

   
PALETTE_TYPES the number of palette types (3)
PALETTE_BLACK the black background palette (0)
PALETTE_WHITE the white background palette (1)
PALETTE_COLORED the colored background palette (2)
PALETTE_ENTRIES the number of colors per palette (64)

sleep()

Function

Sleeps number of seconds.

Syntax

void sleep(int seconds);

See also time()

The sleep function delays the execution of an ULP program for number of seconds.

sort()

Function

Sorts an array or a set of arrays.

Syntax

void sort(int number, array1[, array2,...]);

The sort function either directly sorts a given array1, or it sorts a set of arrays (starting with array2), in which case array1 is supposed to be an array of int, which will be used as a pointer array.

In any case, the number argument defines the number of items in the array(s).

Sorting a single array

If the sort function is called with one single array, that array will be sorted directly, as in the following example:

string A[];
int n = 0;
A[n++] = "World";
A[n++] = "Hello";
A[n++] = "The truth is out there...";
sort(n, A);
for (int i = 0; i < n; ++i)
    printf(A[i]);

Sorting a set of arrays

If the sort function is called with more than one array, the first array must be an array of int, while all of the other arrays may be of any array type and hold the data to be sorted. The following example illustrates how the first array will be used as a pointer:

numeric string Nets[], Parts[], Instances[], Pins[];
int n = 0;
int index[];
schematic(S) {
  S.nets(N) N.pinrefs(P) {
    Nets[n] = N.name;
    Parts[n] = P.part.name;
    Instances[n] = P.instance.name;
    Pins[n] = P.pin.name;
    ++n;
    }
  sort(n, index, Nets, Parts, Instances, Pins);
  for (int i = 0; i < n; ++i)
      printf("%-8s %-8s %-8s %-8s\n",
             Nets[index[i]], Parts[index[i]],
             Instances[index[i]], Pins[index[i]]);
  }

The idea behind this is that one net can have several pins connected to it, and in a netlist you might want to have the net names sorted, and within one net you also want the part names sorted and so on. Note the use of the keyword numeric in the string arrays. This causes the strings to be sorted in a way that takes into account a numeric part at the end of the strings, which leads to IC1, IC2,... IC9, IC10 instead of the alphabetical order IC1, IC10, IC2,...IC9.

When sorting a set of arrays, the first (index) array must be of type int and need not be initialized. Any contents the index array might have before calling the sort function will be overwritten by the resulting index values.

status()

Function

Displays a status message in the status bar.

Syntax

void status(string message);

See also dlgMessageBox()

The status function displays the given message in the status bar of the editor window in which the ULP is running.

system()

Function

Executes an external program.

Syntax

int system(string command);

Returns

The system function returns the exit status of the command. This is typically 0 if everything was ok, and non-zero in case of an error.

The system function executes the external program given by the command string, and waits until the program ends.

Input/Output redirection

If the external program shall read its standard input from (or write its standard output to) a particular file, input/output needs to be redirected.

On Linux and Mac OS X this is done by simply adding a '<' or '>' to the command line, followed by the desired file name, as in

system("program < infile > outfile");

which runs program and makes it read from infile and write to outfile.

On Windows you have to explicitly run a command processor to do this, as in

    system("cmd.exe /c program < infile > outfile");

(on DOS based Windows systems use command.com instead of cmd.exe).

Background execution

The system function waits until the given program has ended. This is useful for programs that only run for a few seconds, or completely take over the user's attention.

If an external program runs for a longer time, and you want the system call to return immediately, without waiting for the program to end, you can simply add an '&' to the command string under Linux and Mac OS X, as in

system("program &");

Under Windows you need to explicitly run a command processor to do this, as in

system("cmd.exe /c start program");

(on DOS based Windows systems use command.com instead of cmd.exe).

Example

int result = system("simulate -f filename");

This would call a simulation program, giving it a file which the ULP has just created. Note that simulate here is just an example, it is not part of the EAGLE package!

If you want to have control over what system commands are actually executed, you can write a wrapper function that prompts the user for confirmation before executing the command, like

int MySystem(string command)
{
  if (dlgMessageBox("!Ok to execute the following command?<p><tt>" + command + "</tt>", "&Yes", "&No") == 0)
     return system(command);
  return -1;
}
int result = MySystem("simulate -f filename");

Unit Conversions

Function

Converts internal units.

Syntax

real u2inch(int n);
real u2mic(int n);
real u2mil(int n);
real u2mm(int n);
int inch2u(real n);
int mic2u(real n);
int mil2u(real n);
int mm2u(real n);

Returns

u2inch returns the value of n in inch.

u2mic returns the value of n in microns (1/1000mm).

u2mil returns the value of n in mil (1/1000inch).

u2mm returns the value of n in millimeters.

inch2u returns the value of n (which is in inch) as internal units.

mic2u returns the value of n (which is in microns) as internal units.

mil2u returns the value of n (which is in mil) as internal units.

mm2u returns the value of n (which is in millimeters) as internal units.

See also UL_GRID

EAGLE stores all coordinate and size values as int values with a resolution of 1/320000mm (0.003125µ). The above unit conversion functions can be used to convert these internal units to the desired measurement units, and vice versa.

Example

board(B) {
  B.elements(E) {
    printf("%s at (%f, %f)\n", E.name,
           u2mm(E.x), u2mm(E.y));
    }
  }

Network functions

Network functions are used to access remote sites on the Internet.

neterror()

Function

Returns the error message of the most recent network function call.

Syntax

string neterror(void);

Returns

neterror returns a textual message describing the error that occurred in the most recent call to a network function.

If no error has occurred, the return value is an empty string.

See also netget, netpost

The neterror function should be called after any of the other network functions has returned a negative value, indicating that an error has occurred. The return value of neterror is a textual string that can be presented to the user.

For errors related to SSL connections (HTTPS) also consider the note in netget.

Example

string Result;
if (netget(Result, "http://web.cadsoft.de/cgi-bin/http-test?see=me&hear=them") >= 0) {
   // process Result
   }
else
   dlgMessageBox(neterror());

netget()

Function

Performs a GET request on the network.

Syntax

int netget(dest, string url[, int timeout]);

Returns

netget returns the number of objects read from the network. The actual meaning of the return value depends on the type of dest.

In case of an error, a negative value is returned and neterror() may be called to display an error message to the user.

See also netpost, neterror, fileread

The netget function sends the given url to the network and stores the result in the dest variable. If no network activity has occurred for timeout seconds, the connection will be terminated. The default timeout is 20 seconds.

The url must contain the protocol to use (HTTP, HTTPS or FTP) and can contain name=value pairs of parameters, as in

http://web.cadsoft.de/cgi-bin/http-test?see=me&hear=them
ftp://ftp.cadsoft.de/eagle/userfiles/README

If a user id and password is required to access a remote site, these can be given as

https://userid:password@www.site.com/...

If dest is a character array, the result will be treated as raw binary data and the return value reflects the number of bytes stored in the character array.

If dest is a string array, the result will be treated as text data (one line per array member) and the return value will be the number of lines stored in the string array. Newline characters will be stripped.

If dest is a string, the result will be stored in that string and the return value will be the length of the string. Note that in case of binary data the result is truncated at the first occurrence of a byte with the value 0x00.

If you need to use a proxy to access the Internet with HTTP or HTTPS, you can set that up in the "Configure" dialog under "Help/Check for Update" in the Control Panel.

SSL Connections

For SSL connections (request per HTTPS) certificates are necessary, which may miss or be expired on some systems. The connection fails then with according error message that you can query with neterror(). With this error message it should be possible to install missing or update expired certificates and make the connection work this way. It depends on your system how to do this (in Windows e.g. via Control Panel/Internet Options etc.).

Example

string Result;
if (netget(Result, "http://web.cadsoft.de/cgi-bin/http-test?see=me&hear=them") >= 0) {
   // process Result
   }
else
   dlgMessageBox(neterror());

netpost()

Function

Performs a POST request on the network.

Syntax

int netpost(dest, string url, string data[, int timeout[, string content_type] ]);

Returns

netpost returns the number of objects read from the network. The actual meaning of the return value depends on the type of dest. In case of an error, a negative value is returned and neterror() may be called to display an error message to the user.

See also netget, neterror, fileread

The netpost function sends the given data to the given url on the network and stores the result in the dest variable.

If no network activity has occurred for timeout seconds, the connection will be terminated. The default timeout is 20 seconds.

If content_type is given, it overwrites the default content type of "text/html; charset=utf-8". The url must contain the protocol to use (HTTP or HTTPS).

If a user id and password is required to access a remote site, these can be given as

https://userid:password@www.secret-site.com/...

If dest is a character array, the result will be treated as raw binary data and the return value reflects the number of bytes stored in the character array.

If dest is a string array, the result will be treated as text data (one line per array member) and the return value will be the number of lines stored in the string array. Newline characters will be stripped.

If dest is a string, the result will be stored in that string and the return value will be the length of the string. Note that in case of binary data the result is truncated at the first occurrence of a byte with the value 0x00.

If you need to use a proxy to access the Internet with HTTP or HTTPS, you can set that up in the "Configure" dialog under "Help/Check for Update" in the Control Panel.

If you should face problems related to SSL connections (HTTPS) consider the note in netget.

Example

string Data = "see=me\nhear=them";
string Result;
if (netpost(Result, "http://web.cadsoft.de/cgi-bin/http-test", Data) >= 0) {
   // process Result
   }
else
   dlgMessageBox(neterror());

Printing functions

Printing functions are used to print formatted strings.

printf()

Function

Writes formatted output to a file.

Syntax

int printf(string format[, argument, ...]);

Returns

The printf function returns the number of characters written to the file that has been opened by the most recent output statement. In case of an error, printf returns -1.

See also sprintf, output, fileerror

Format string

The format string controls how the arguments will be converted, formatted and printed. There must be exactly as many arguments as necessary for the format. The number and type of arguments will be checked against the format, and any mismatch will lead to an error message The format string contains two types of objects: plain characters and format specifiers.

Format specifiers

A format specifier has the following form:

% [flags] [width] [.prec] type

Each format specification begins with the percent character (%). After the % comes the following, in this order:

an optional sequence of flag characters, [flags]
an optional width specifier, [width]
an optional precision specifier, [.prec]
the conversion type character, type

Conversion type characters

   
d signed decimal int
o unsigned octal int
u unsigned decimal int
x unsigned hexadecimal int (with a, b,...)
X unsigned hexadecimal int (with A, B,...)
f signed real value of the form [-]dddd.dddd
e signed real value of the form [-]d.dddde[±]ddd
E same as e, but with E for exponent
g signed real value in either e or f form, based on given value and precision
G same as g, but with E for exponent if e format used
c single character
s character string
% the % character is printed

Flag characters

The following flag characters can appear in any order and combination:

   
"-" the formatted item is left-justified within the field; normally, items are right-justified
"+" a signed, positive item will always start with a plus character (+); normally, only negative items begin with a sign
" " a signed, positive item will always start with a space character; if both "+" and " " are specified, "+" overrides " "

Width specifiers

The width specifier sets the minimum field width for an output value.

Width is specified either directly, through a decimal digit string, or indirectly, through an asterisk (*). If you use an asterisk for the width specifier, the preceding argument (which must be an int) to the one being formatted (with this format specifier) determines the minimum output field width.

In no case does a nonexistent or small field width cause truncation of a field. If the result of a conversion is wider than the field width, the field is simply expanded to contain the conversion result.

   
n At least n characters are printed. If the output value has less than n characters, the output is padded with blanks (right-padded if "-" flag given, left-padded otherwise).
0n At least n characters are printed. If the output value has less than n characters, it is filled on the left with zeros.
* The argument list supplies the width specifier, which must precede the actual argument being formatted.

Precision specifiers

A precision specifier always begins with a period (.) to separate it from any preceding width specifier. Then, like width, precision is specified either directly through a decimal digit string, or indirectly, through an asterisk (*). If you use an asterisk for the precision specifier, the preceding argument (which must be an int) to the one being formatted (with this format specifier) determines the precision.

   
none Precision set to default.
.0 For int types, precision is set to default; for real types, no decimal point is printed.
.n n characters or n decimal places are printed. If the output value has more than n characters the output might be truncated or rounded (depending on the type character).
* The argument list supplies the precision specifier, which must precede the actual argument being formatted.

Default precision values

   
douxX 1
eEf 6
gG all significant digits
c no effect
s print entire string

How precision specification (.n) affects conversion

   
douxX .n specifies that at least n characters are printed. If the input argument has less than n digits, the output value is left-padded with zeros. If the input argument has more than n digits, the output value is not truncated.
eEf .n specifies that n characters are printed after the decimal point, and the last digit printed is rounded.
gG .n specifies that at most n significant digits are printed.
c .n has no effect on the output.
s .n specifies that no more than n characters are printed.

Binary zero characters

Unlike sprintf, the printf function can print binary zero characters (0x00).

char c = 0x00;
printf("%c", c);

Example

int i = 42;
real r = 3.14;
char c = 'A';
string s = "Hello";
printf("Integer: %8d\n", i);
printf("Hex:     %8X\n", i);
printf("Real:    %8f\n", r);
printf("Char:    %-8c\n", c);
printf("String:  %-8s\n", s);

sprintf()

Function

Writes formatted output into a string.

Syntax

int sprintf(string result, string format[, argument, ...]);

Returns

The sprintf function returns the number of characters written into the result string. In case of an error, sprintf returns -1.

See also printf

Format string

See printf.

Binary zero characters

Note that sprintf cannot return strings with embedded binary zero characters (0x00). If the resulting string contains a binary zero character, any characters following that zero character will be dropped. Use printf if you need to output binary data.

Example

string result;
int number = 42;
sprintf(result, "The number is %d", number);

String functions

String functions are used to manipulate character strings.

The following string functions are available:

strchr()
strjoin()
strlen()
strlwr()
strrchr()
strrstr()
strsplit()
strstr()
strsub()
strtod()
strtol()
strupr()
strxstr()

strchr()

Function

Scans a string for the first occurrence of a given character.

Syntax

int strchr(string s, char c[, int index]);

Returns

The strchr function returns the integer offset of the character in the string, or -1 if the character does not occur in the string.

See also strrchr, strstr

If index is given, the search starts at that position. Negative values are counted from the end of the string.

Example

string s = "This is a string";
char c = 'a';
int pos = strchr(s, c);
if (pos >= 0)
   printf("The character %c is at position %d\n", c, pos);
else
   printf("The character was not found\n");

strjoin()

Function

Joins a string array to form a single string.

Syntax

string strjoin(string array[], char separator);

Returns

The strjoin function returns the combined entries of array.

See also strsplit, lookup, fileread

strjoin joins all entries in array, delimited by the given separator and returns the resulting string.

If separator is the newline character ('\n') the resulting string will be terminated with a newline character. This is done to have a text file that consists of N lines (each of which is terminated with a newline) and is read in with the fileread() function and split into an array of N strings to be joined to the original string as read from the file.

Example

string a[] = { "Field 1", "Field 2", "Field 3" };
string s = strjoin(a, ':');

strlen()

Function

Calculates the length of a string.

Syntax

int strlen(string s);

Returns

The strlen function returns the number of characters in the string.

Example

string s = "This is a string";
int l = strlen(s);
printf("The string is %d characters long\n", l);

strlwr()

Function

Converts uppercase letters in a string to lowercase.

Syntax

string strlwr(string s);

Returns

The strlwr function returns the modified string. The original string (given as parameter) is not changed.

See also strupr, tolower

Example

string s = "This Is A String";
string r = strlwr(s);
printf("Prior to strlwr: %s - after strlwr: %s\n", s, r);

strrchr()

Function

Scans a string for the last occurrence of a given character.

Syntax

int strrchr(string s, char c[, int index]);

Returns

The strrchr function returns the integer offset of the character in the string, or -1 if the character does not occur in the string.

See also strchr, strrstr

If index is given, the search starts at that position. Negative values are counted from the end of the string.

Example

string s = "This is a string";
char c = 'a';
int pos = strrchr(s, c);
if (pos >= 0)
   printf("The character %c is at position %d\n", c, pos);
else
   printf("The character was not found\n");

strrstr()

Function

Scans a string for the last occurrence of a given substring.

Syntax

int strrstr(string s1, string s2[, int index]);

Returns

The strrstr function returns the integer offset of the first character of s2 in s1, or -1 if the substring does not occur in the string.

See also strstr, strrchr

If index is given, the search starts at that position. Negative values are counted from the end of the string.

Example

string s1 = "This is a string", s2 = "is a";
int pos = strrstr(s1, s2);
if (pos >= 0)
   printf("The substring starts at %d\n", pos);
else
   printf("The substring was not found\n");

strsplit()

Function

Splits a string into separate fields.

Syntax

int strsplit(string &array[], string s, char separator);

Returns

The strsplit function returns the number of entries copied into array.

See also strjoin, lookup, fileread

strsplit splits the string s at the given separator and stores the resulting fields in the array.

If separator is the newline character ('\n') the last field will be silently dropped if it is empty. This is done to have a text file that consists of N lines (each of which is terminated with a newline) and is read in with the fileread() function to be split into an array of N strings. With any other separator an empty field at the end of the string will count, so "a:b:c:" will result in 4 fields, the last of which is empty.

Example

string a[];
int n = strsplit(a, "Field 1:Field 2:Field 3", ':');

strstr()

Function

Scans a string for the first occurrence of a given substring.

Syntax

int strstr(string s1, string s2[, int index]);

Returns

The strstr function returns the integer offset of the first character of s2 in s1, or -1 if the substring does not occur in the string.

See also strrstr, strchr, strxstr

If index is given, the search starts at that position. Negative values are counted from the end of the string.

Example

string s1 = "This is a string", s2 = "is a";
int pos = strstr(s1, s2);
if (pos >= 0)
   printf("The substring starts at %d\n", pos);
else
   printf("The substring was not found\n");

strsub()

Function

Extracts a substring from a string.

Syntax

string strsub(string s, int start[, int length]);

Returns

The strsub function returns the substring indicated by the start and length value. The value for length must be positive, otherwise an empty string will be returned. If length is ommitted, the rest of the string (beginning at start) is returned.

If start points to a position outside the string, an empty string is returned.

Example

string s = "This is a string";
string t = strsub(s, 4, 7);
printf("The extracted substring is: %s\n", t);

strtod()

Function

Converts a string to a real value.

Syntax

real strtod(string s);

Returns

The strtod function returns the numerical representation of the given string as a real value. Conversion ends at the first character that does not fit into the format of a real constant. If an error occurs during conversion of the string 0.0 will be returned.

See also strtol

Example

string s = "3.1415";
real r = strtod(s);
printf("The value is %f\n", r);

strtol()

Function

Converts a string to an integer value.

Syntax

int strtol(string s);

Returns

The strtol function returns the numerical representation of the given string as an int value. Conversion ends at the first character that does not fit into the format of an integer constant. If an error occurs during conversion of the string 0 will be returned.

See also strtod

Example

string s = "1234";
int i = strtol(s);
printf("The value is %d\n", i);

strupr()

Function

Converts lowercase letters in a string to uppercase.

Syntax

string strupr(string s);

Returns

The strupr function returns the modified string. The original string (given as parameter) is not changed.

See also strlwr, toupper

Example

string s = "This Is A String";
string r = strupr(s);
printf("Prior to strupr: %s - after strupr: %s\n", s, r);

strxstr()

Function

Scans a string for the first occurrence of a given regular expression.

Syntax

int strxstr(string s1, string s2[, int index[, int &length]]);

Returns

The strxstr function returns the integer offset of the substring in s1 that matches the regular expression in s2, or -1 if the regular expression does not match in the string.

See also strstr, strchr, strrstr

If index is given, the search starts at that position. Negative values are counted from the end of the string.

If length is given, the actual length of the matching substring is returned in that variable.

Regular expressions allow you to find a pattern within a text string. For instance, the regular expression "i.*a" would find a sequence of characters that starts with an 'i', followed by any character ('.') any number of times ('*'), and ends with an 'a'. It would match on "is a" as well as "is this a" or "ia". Details on regular expressions can be found, for instance, in the book Mastering Regular Expressions by Jeffrey E. F. Friedl.

Example

string s1 = "This is a string", s2 = "i.*a";
int len = 0;
int pos = strxstr(s1, s2, 0, len);
if (pos >= 0)
   printf("The substring starts at %d and is %d charcaters long\n", pos, len);
else
   printf("The substring was not found\n");

URN functions

URN functions are used to process URNs.

urnbase()

Function

Extracts the base URN from a URN string.

Syntax

string urnbase(string urn);

Returns

The urnbase function returns the base URN of the provided URN, that is, the URN without trailing version or /. For example, the base URN of "urn:adsk.eagle:footprint:123/4" is "urn:adsk.eagle:footprint:123". If no version is present, the input string will be returned.

Example

string urn = "urn:adsk.eagle:footprint:123/4";
string base = urnbase(urn);
printf("The base URN is: %s\n", base);

urnversion()

Function

Extracts the version from a URN string.

Syntax

int urnversion(string urn);

Returns

The urnversion function returns the version of the provided URN, i.e. the number following the /. If no version is present, -1 is returned.

Example

string urn = "urn:adsk.eagle:footprint:123/4";
int version = urnversion(urn);
printf("The URN version is: %d\n", version);

Time functions

Time functions are used to get and process time and date information.

The following time functions are available:

sleep()
t2day()
t2dayofweek()
t2hour()
t2minute()
t2month()
t2second()
t2string()
t2year()
time()
timems()

time()

Function

Gets the current system time.

Syntax

int time(void);

Returns

The time function returns the current system time as the number of seconds elapsed since a system dependent reference date.

See also Time Conversions, filetime, timems()

Example

int CurrentTime = time();

timems()

Function

Gets the number of milliseconds since the start of the ULP.

Syntax

int timems(void);

Returns

The timems function returns the number of milliseconds since the start of the ULP. After 86400000 milliseconds (i.e. every 24 hours), the value starts at 0 again.

See also time

Example

int elapsed = timems();

Time Conversions

Function

Convert a time value to day, month, year etc.

Syntax

int t2day(int t);
int t2dayofweek(int t);
int t2hour(int t);
int t2minute(int t);
int t2month(int t);
int t2second(int t);
int t2year(int t);

string t2string(int t[, string format]);

Returns

*t2day* returns the day of the month (1..31)
*t2dayofweek* returns the day of the week (0=sunday..6)
*t2hour* returns the hour (0..23)
*t2minute* returns the minute (0..59)
*t2month* returns the month (0..11)
*t2second* returns the second (0..59)
*t2year* returns the year (including century!)
*t2string* returns a formatted string containing date and time

See also time

The t2string function without the optional format parameter converts the given time t into a country specific string in local time.

If t2string is called with a format string, that format is used to determine what the result should look like.

The following expressions can be used in a format string:

   
d the day as a number without a leading zero (1 to 31)
dd the day as a number with a leading zero (01 to 31)
ddd the abbreviated localized day name (e.g. "Mon" to "Sun")
dddd the long localized day name (e.g. "Monday" to "Sunday")
M the month as a number without a leading zero (1-12)
MM the month as a number with a leading zero (01-12)
MMM the abbreviated localized month name (e.g. "Jan" to "Dec")
MMMM the long localized month name (e.g. "January" to "December")
yy the year as a two digit number (00-99)
yyyy the year as a four digit number
h the hour without a leading zero (0 to 23 or 1 to 12 if AM/PM display)
hh the hour with a leading zero (00 to 23 or 01 to 12 if AM/PM display)
m the minute without a leading zero (0 to 59)
mm the minute with a leading zero (00 to 59)
s the second without a leading zero (0 to 59)
ss the second with a leading zero (00 to 59)
z the milliseconds without leading zeros (always 0, since the given time only has a one second resolution)
zzz the milliseconds with leading zeros (always 000, since the given time only has a one second resolution)
AP use AM/PM display (AP will be replaced by either "AM" or "PM")
ap use am/pm display (ap will be replaced by either "am" or "pm")
U display the given time as UTC (must be the first character; default is local time

All other characters will be copied "as is". Any sequence of characters that are enclosed in singlequotes will be treated as text and not be used as an expression. Two consecutive single quotes ('') are replaced by a single quote in the output.

Example

int t = time();
printf("It is now %02d:%02d:%02d\n",
       t2hour(t), t2minute(t), t2second(t));
printf("ISO time is %s\n", t2string(t, "Uyyyy-MM-dd hh:mm:ss"));

Object functions

Object functions are used to access common information about objects.

The following object functions are available:

clrgroup()
ingroup()
setgroup()
setvariant()
variant()

clrgroup()

Function

Clears the group flags of an object.

Syntax

void clrgroup(object);

See also ingroup(), setgroup(), GROUP command

The clrgroup() function clears the group flags of the given object, so that it is no longer part of the previously defined group.

When applied to an object that contains other objects (like a UL_BOARD or UL_NET) the group flags of all contained objects are cleared recursively, but with analogous limitations like for setgroup().

Example

board(B) {
  B.elements(E)
    clrgroup(E);
  }

ingroup()

Function

Checks whether an object is in the group.

Syntax

int ingroup(object);

Returns

The ingroup function returns a non-zero value if the given object is in the group.

See also clrgroup(), setgroup(), GROUP command

If a group has been defined in the editor, the ingroup() function can be used to check whether a particular object is part of the group.

Objects with a single coordinate that are individually selectable in the current drawing (like UL_TEXT, UL_VIA, UL_CIRCLE etc.) return a non-zero value in a call to ingroup() if that coordinate is within the defined group.

A UL_WIRE returns 0, 1, 2 or 3, depending on whether none, the first, the second or both of its end points are in the group.

A UL_RECTANGLE and UL_FRAME returns a non-zero value if one or more of its corners are in the group. The value has bit 0 set for the upper right corner, bit 1 for the upper left, bit 2 for the bottom left, and bit 3 for the bottom right corner.

Higher ranking objects that have no coordinates (UL_NET, UL_SEGMENT, UL_SIGNAL, UL_POLYGON) or that are actually not available as drawing objects (UL_SHEET, UL_DEVICESET, UL_SYMBOL, UL_FOOTPRINT), return a non-zero value if one or more of the objects within them are in the group. For details on the object hierarchies see Object Types.

UL_CONTACTREF and UL_PINREF, though not having coordinates of their own, return a non-zero value if the referenced UL_CONTACT or UL_PIN, respectively, is within the group. For other not selectable objects like UL_GRID, UL_VARIANT or wires of a UL_TEXT or UL_FRAME object, the behaviour of ingroup() is undefined and therefore should not be used.

Identifying the context menu object

If the ULP is started from a context menu the selected object can be accessed by the group mechansim. A one element group is made from the selected object. So it can be identified with ingroup(). (see also SET and RUN).

Example

output("group.txt") {
  board(B) {
    B.elements(E) {
      if (ingroup(E))
         printf("Element %s is in the group\n", E.name);
      }
    }
  }

setgroup()

Function

Sets the group flags of an object.

Syntax

void setgroup(object[, int flags]);

See also clrgroup(), ingroup(), GROUP command

The setgroup() function sets the group flags of the given object, so that it becomes part of the group.

If no flags are given, the object is added to the group as a whole (i.e. all of its selection points, in case it has more than one).

If flags has a non-zero value, only the group flags of the given points of the object are set. For a UL_WIRE this means that '1' sets the group flag of the first point, '2' that of the second point, and '3' sets both. Any previously set group flags remain unchanged by a call to setgroup().

When applied to an object that contains other objects (like a UL_BOARD or UL_NET) the group flags of all contained objects are set recursively with following limitations:

It's not the case for UL_LIBRARY and UL_SCHEMATIC. Subordinate objects that are not selectable or not inidividually selectable are not flagged (e.g. UL_GRID or UL_VARIANT objects or wires of UL_TEXT or UL_FRAME objects).

For details on the object hierarchies see Object Types.

Example

board(B) {
  B.elements(E)
    setgroup(E);
  }

setvariant()

Function

Sets the current assembly variant.

Syntax

int setvariant(string name);

See also variant(), UL_VARIANTDEF, VARIANT command

The setvariant() function sets the current assembly variant to the one given by name. This can be used to loop through all of the parts and "see" their data exactly as defined in the given variant.

name must reference a valid assembly variant that is contained in the current drawing.

This function returns a non-zero value if the given assembly variant exists, zero otherwise.

The assembly variant that has been set by a call to setvariant() is only active until the User Language Program returns. After that, the variant in the drawing will be the same as before the start of the ULP.

Setting the assembly variant in a board is only possible if the consistent schematic is loaded.

Example

if (setvariant("My variant")) {
   // do something ...
else
   // error: unknown variant

variant()

Function

Query the current assembly variant.

Syntax

string variant(void);

See also setvariant(), UL_VARIANTDEF, VARIANT command

The variant() function returns the name of the current assembly variant. If no variant is currently selected, the empty string ('') is returned.

Example

string CurrentVariant = variant();

XML functions

XML functions are used to process XML (Extensible Markup Language) data. The following XML functions are available:

xmlattribute()
xmlattributes()
xmlelement()
xmlelements()
xmltags()
xmltext()

xmlattribute(), xmlattributes()

Function

Extract the attributes of an XML tag.

Syntax

string xmlattribute(string xml, string tag, string attribute);
int xmlattributes(string &array[], string xml, string tag);

See also xmlelement(), xmltags(), xmltext()

The xmlattribute function returns the value of the given attribute from the given tag within the given xml code. If an attribute appears more than once in the same tag, the value of its last occurrence is taken.

The xmlattributes function stores the names of all attributes from the given tag within the given xml code in the array and returns the number of attributes found. The order is not necessarily the same like in the given xml code. If an attribute appears more than once in the same tag, its name appears only once in the array.

The tag is given in the form of a path.

If the given xml code contains an error, the result of any XML function is empty, and a warning dialog is presented to the user, giving information about where in the ULP and XML code the error occurred. Note that the line and column number within the XML code refers to the actual string given to this function as the xml parameter.

Example

// String XML contains the following data:
//<root>
//  <body abc="def" xyz="123">
//    ...
//  </body>
//</root>

string s[];
int n = xmlattributes(s, XML, "root/body");

// Result: { "abc", "xyz" }

string s = xmlattribute(XML, "root/body", "xyz");

// Result: "123"

xmlelement(), xmlelements()

Function

Extract elements from an XML code.

Syntax

string xmlelement(string xml, string tag);
int xmlelements(string &array[], string xml, string tag);

See also xmltags(), xmlattribute(), xmltext()

The xmlelement function returns the complete XML element of the given tag within the given xml code. The result still contains the element's outer XML tag, and can thus be used for further processing with the other XML functions. Any whitespace within plain text parts of the element is retained. The overall formatting of the XML tags within the element and the order of element attributes may be different than the original xml code, though. If there is more than one occurrence of tag within xml, the first one will be returned. Use xmlelements if you want to get all occurrences.

The xmlelements function works just like xmlelement, but returns all occurrences of elements with the given tag. The return value is the number of elements stored in the array.

The tag is given in the form of a path.

If the given xml code contains an error, the result of any XML function is empty, and a warning dialog is presented to the user, giving information about where in the ULP and XML code the error occurred. Note that the line and column number within the XML code refers to the actual string given to this function as the xml parameter.

Example

// String XML contains the following data:
//<root>
//  <body>
//    <contents>
//      <string>Some text 1</string>
//      <any>anything 1</any>
//    </contents>
//    <contents>
//      <string>Some text 2</string>
//      <any>anything 2</any>
//    </contents>
//    <appendix>
//      <string>Some text 3</string>
//    </appendix>
//  </body>
//</root>
//

string s = xmlelement(XML, "root/body/appendix");

// Result: " <appendix>\n  <string>Some text 3</string>\n </appendix>\n"

string s[];
int n = xmlelements(s, XML, "root/body/contents");

// Result: { " <contents>\n  <string>Some text 1</string>\n  <any>anything 1</any>\n </contents>\n",
//           " <contents>\n  <string>Some text 2</string>\n  <any>anything 2</any>\n </contents>\n"
//         }

xmltags()

Function

Extract the list of tag names within an XML code.

Syntax

int xmltags(string &array[], string xml, string tag);

See also xmlelement(), xmlattribute(), xmltext()

The xmltags function returns the names of all the tags on the top level of the given tag within the given xml code. The return value is the number of tag names stored in the array.

Each tag name is returned only once, even if it appears several times in the XML code.

The tag is given in the form of a path.

If the given xml code contains an error, the result of any XML function is empty, and a warning dialog is presented to the user, giving information about where in the ULP and XML code the error occurred. Note that the line and column number within the XML code refers to the actual string given to this function as the xml parameter.

Example

//String XML contains the following data:
//<root>
//  <body>
//    <contents>
//      <string>Some text 1</string>
//      <any>anything 1</any>
//    </contents>
//    <contents>
//      <string>Some text 2</string>
//      <any>anything 2</any>
//    </contents>
//    <appendix>
//      <string>Some text 3</string>
//    </appendix>
//  </body>
//</root>
//

string s[];
int n = xmltags(s, XML, "root/body");

// Result: { "contents", "appendix" } 

int n = xmltags(s, XML, "");        

// Result: "root"

xmltext()

Function

Extract the textual data of an XML element.

Syntax

string xmltext(string xml, string tag);

See also xmlelement(), xmlattribute(), xmltags()

The xmltext function returns the textual data from the given tag within the given xml code.

Any tags within the text are stripped, whitespace (including newline characters) is retained.

The tag is given in the form of a path.

If the given xml code contains an error, the result of any XML function is empty, and a warning dialog is presented to the user, giving information about where in the ULP and XML code the error occurred. Note that the line and column number within the XML code refers to the actual string given to this function as the xml parameter.

Example

// String XML contains the following data:
//<root>
//  <body>
//    Some <b>text</b>.
//  </body>
//</root>
//

string s = xmltext(XML, "root/body");

// Result: "\n    Some text.\n  "

Builtin Statements

Builtin statements are generally used to open a certain context in which data structures or files can be accessed. The general syntax of a builtin statement is

name(parameters) statement

where name is the name of the builtin statement, parameters stands for one or more parameters, and statement is the code that will be executed inside the context opened by the builtin statement.

Note that statement can be a compound statement, as in

board(B) {
  B.elements(E) printf("Element: %s\n", E.name);
  B.Signals(S)  printf("Signal: %s\n", S.name);
  }

The following builtin statements are available:

board()

Function

Opens a board context.

Syntax

board(identifier) statement

See also schematic, library

The board statement opens a board context if the current editor window contains a board drawing. A variable of type UL_BOARD is created and is given the name indicated by identifier.

Once the board context is successfully opened and a board variable has been created, the statement is executed. Within the scope of the statement the board variable can be accessed to retrieve further data from the board.

If the current editor window does not contain a board drawing, an error message is given and the ULP is terminated.

Check if there is a board

By using the board statement without an argument you can check if the current editor window contains a board drawing. In that case, board behaves like an integer constant, returning 1 if there is a board drawing in the current editor window, and 0 otherwise.

Accessing board from a schematic

If the current editor window contains a schematic drawing, you can still access that schematic's board by preceding the board statement with the prefix project, as in

project.board(B) { ... }

This will open a board context regardless whether the current editor window contains a board or a schematic drawing. However, there must be an editor window containing that board somewhere on the desktop!

Example

if (board)
   board(B) {
     B.elements(E)
       printf("Element: %s\n", E.name);
     }

deviceset()

Function

Opens a device set context.

Syntax

deviceset(identifier) statement

See also footprint, symbol, library

The deviceset statement opens a device set context if the current editor window contains a device drawing. A variable of type UL_DEVICESET is created and is given the name indicated by identifier.

Once the device set context is successfully opened and a device set variable has been created, the statement is executed. Within the scope of the statement the device set variable can be accessed to retrieve further data from the device set.

If the current editor window does not contain a device drawing, an error message is given and the ULP is terminated.

Check if there is a device set

By using the deviceset statement without an argument you can check if the current editor window contains a device drawing. In that case, deviceset behaves like an integer constant, returning 1 if there is a device drawing in the current editor window, and 0 otherwise.

Example

if (deviceset)
   deviceset(D) {
     D.gates(G)
       printf("Gate: %s\n", G.name);
     }

library()

Function

Opens a library context.

Syntax

library(identifier) statement

See also board, schematic, deviceset, footprint, symbol

The library statement opens a library context if the current editor window contains a library drawing. A variable of type UL_LIBRARY is created and is given the name indicated by identifier.

Once the library context is successfully opened and a library variable has been created, the statement is executed. Within the scope of the statement the library variable can be accessed to retrieve further data from the library.

If the current editor window does not contain a library drawing, an error message is given and the ULP is terminated.

Check if there is a library

By using the library statement without an argument you can check if the current editor window contains a library drawing. In that case, library behaves like an integer constant, returning 1 if there is a library drawing in the current editor window, and 0 otherwise.

Example

if (library)
   library(L) {
     L.devices(D)
       printf("Device: %s\n", D.name);
     }

module()

Function

Opens a module context.

Syntax

module(identifier) statement

See also board, library, schematic, sheet

The module statement opens a module context if the current editor# #window contains a module drawing. The module statement opens a module context if in the editor window currently a module drawing is edited. A variable of type UL_MODULE is created and is given the name indicated by identifier.

Once the module context is successfully opened and a module variable has been created, the statement is executed. Within the scope of the statement the module variable can be accessed to retrieve further data from the module.

If the current editor window does not contain a module drawing, an error message is given and the ULP is terminated.# If in the editor window currently no module drawing is edited, an error message is given and the ULP is terminated.

Check if there is a module

By using the module statement without an argument you can check if the current editor window contains a module drawing. In that case, module behaves like an integer constant, returning 1 if there is a module drawing in the current editor window, and 0 otherwise.

Example

if (module)
   module(M) {
     printf("Module: %s\n", M.name);
     }

output()

Function

Opens an output file for subsequent printf() calls.

Syntax

output(string filename[, string mode]) statement

See also printf, fileerror

The output statement opens a file with the given filename and mode for output through subsequent printf() calls. If the file has been successfully opened, the statement is executed, and after that the file is closed.

If the file cannot be opened, an error message is given and execution of the ULP is terminated.

By default the output file is written into the Project directory.

File Modes

The mode parameter defines how the output file is to be opened. If no mode parameter is given, the default is "wt".

a append to an existing file, or create a new file if it does not exist
w create a new file (overwriting an existing file)
t open file in text mode
b open file in binary mode
D delete this file when ending the EAGLE session (only works together with w)
F force using this file name (normally *.brd, *.sch and *.lbr are rejected)

Mode characters may appear in any order and combination. However, only the last one of a and w or t and b, respectively, is significant. For example a mode of "abtw" would open a file for textual write, which would be the same as "wt".

Nested output statements

output statements can be nested, as long as there are enough file handles available, and provided that no two active output statements access the same file.

Example

void PrintText(string s)
{
  printf("This also goes into the file: %s\n", s);
}
output("file.txt", "wt") {
  printf("Directly printed\n");
  PrintText("via function call");
  }

footprint(), new as of EAGLE 9.1

Function

Opens a footprint context.

Syntax

footprint(identifier) statement (new as of EAGLE 9.1)

See also library, deviceset, symbol

The footprint statement opens a package context if the current editor window contains a package drawing. A variable of type UL_FOOTPRINT is created and is given the name indicated by identifier.

Note: the footprint statement is new in EAGLE 9.1. For backwards compatibility with prior EAGLE versions, package is available as an alias.

Once the footprint context is successfully opened and a footprint variable has been created, the statement is executed. Within the scope of the statement the footprint variable can be accessed to retrieve further data from the footprint.

If the current editor window does not contain a footprint drawing, an error message is given and the ULP is terminated.

Check if there is a footprint

By using the footprint statement without an argument you can check if the current editor window contains a footprint drawing. In that case, footprint behaves like an integer constant, returning 1 if there is a footprint drawing in the current editor window, and 0 otherwise.

Example

if (footprint)
   footprint(F) {
     F.contacts(C)
       printf("Contact: %s\n", C.name);
     }

schematic()

Function

Opens a schematic context.

Syntax

schematic(identifier) statement

See also board, library, module, sheet

The schematic statement opens a schematic context if the current editor window contains a schematic drawing. A variable of type UL_SCHEMATIC is created and is given the name indicated by identifier.

Once the schematic context is successfully opened and a schematic variable has been created, the statement is executed. Within the scope of the statement the schematic variable can be accessed to retrieve further data from the schematic.

If the current editor window does not contain a schematic drawing, an error message is given and the ULP is terminated.

Check if there is a schematic

By using the schematic statement without an argument you can check if the current editor window contains a schematic drawing. In that case, schematic behaves like an integer constant, returning 1 if there is a schematic drawing in the current editor window, and 0 otherwise.

Accessing schematic from a board

If the current editor window contains a board drawing, you can still access that board's schematic by preceding the schematic statement with the prefix project, as in

project.schematic(S) { ... }

This will open a schematic context regardless whether the current editor window contains a schematic or a board drawing. However, there must be an editor window containing that schematic somewhere on the desktop!

Access the current sheet

Use the sheet statement to directly access the currently loaded sheet.

Access the current Module

Use the module statement to directly access the currently edited module.

Example

if (schematic)
   schematic(S) {
     S.parts(P)
       printf("Part: %s\n", P.name);
     }

sheet()

Function

Opens a sheet context.

Syntax

sheet(identifier) statement

See also schematic

The sheet statement opens a sheet context if the current editor window contains a sheet drawing. A variable of type UL_SHEET is created and is given the name indicated by identifier.

Once the sheet context is successfully opened and a sheet variable has been created, the statement is executed. Within the scope of the statement the sheet variable can be accessed to retrieve further data from the sheet.

If the current editor window does not contain a sheet drawing, an error message is given and the ULP is terminated.

Check if there is a sheet

By using the sheet statement without an argument you can check if the current editor window contains a sheet drawing. In that case, sheet behaves like an integer constant, returning 1 if there is a sheet drawing in the current editor window, and 0 otherwise.

Example

if (sheet)
   sheet(S) {
     S.instances(I)
       printf("Instance: %s\n", I.name);
     }

symbol()

Function

Opens a symbol context.

Syntax

symbol(identifier) statement

See also library, deviceset, footprint

The symbol statement opens a symbol context if the current editor window contains a symbol drawing. A variable of type UL_SYMBOL is created and is given the name indicated by identifier.

Once the symbol context is successfully opened and a symbol variable has been created, the statement is executed. Within the scope of the statement the symbol variable can be accessed to retrieve further data from the symbol.

If the current editor window does not contain a symbol drawing, an error message is given and the ULP is terminated.

Check if there is a symbol

By using the symbol statement without an argument you can check if the current editor window contains a symbol drawing. In that case, symbol behaves like an integer constant, returning 1 if there is a symbol drawing in the current editor window, and 0 otherwise.

Example

if (symbol)
   symbol(S) {
     S.pins(P)
       printf("Pin: %s\n", P.name);
     }