GSAK (Geocaching Swiss Army Knife)
 

Contents - Index


Automating GSAK (Macros)

Jump to: command/function summary   database variables   system variables

GSAK has automation or macro (or scripting) support in the form of a macro language. Macros comprise of lines of code written to a plain text file. The default extension for a GSAK macro is .gsk. You can create a macro file using a text editor such as GSAK's macro editor. The lines of the  macro can include commands, variables, expressions and internal functions.  

The difference between a command and a function can sometimes be confusing. Basically a command (other languages often refer to this as a "procedure") does not return a value where as a function does. Other properties that help to differ between the two:
1. Functions can be used in expressions (expressions are used in IF, While, Set commands). Commands cannot. 
2. Functions can be nested within each other, commands cannot. Example: alltrim(left(upper('abcd'),2))
3. Functions have fixed parameters and all parameters must be included
4. Function parameters are always enclosed in brackets and separated by commas.
5. Commands have named parameters (some with default values), and can include/exclude optional parameters.

Nested conditional statements in the form of IF and WHILE (for looping) are also supported, as is the ability to interrogate system variables and database variables as well as being able to update many of them. Variable substitution is also supported. For communication between macros  GSAK also supports persistent variables.

You can find real world working macros here

Once the lines of text of a macro have been created, these are saved in a plain-text file. It is recommended that you save all your macros in the "Macro" folder of your install folder of GSAK. Saving them there ensures that they are backed up and restored when using the GSAK backup and restore features.

A macro file can be run from within GSAK (Macro=>Run, or Ctrl-M) or from the command line when starting GSAK. You can also allocate macros to tool buttons for easy execution. You can even have GSAK automatically execute a macro on start up - see Tools=>Options=>Advanced

To run a macro when starting GSAK from the command line:

GSAK /run "c:\some folder\commands.txt"

/run = the first parameter on the line to indicate GSAK is to automatically run all the commands in the file designated by parameter 2

The file name only needs to be surrounded by quotation marks if the path to the file contains any spaces. The file is just a plain ASCII text file and may contain the commands in any order:

Command Syntax - Parameters are surrounded by <> (do not include these when creating a macro) and items in square brackets([ ])  are optional. Valid options for parameters are separated by | (piping symbol). All commands and parameters are not case sensitive. Blank lines are ignored.  Comments can be inserted by using the # symbol. Having a comment on the same line as a command is also supported but the # symbol must be at the very end of the command. With command parameters, the data following the = (equal sign) is accepted verbatim as the parameter value. Only when using an expression can you have optional spaces before and after the = sign. For example:
 

# This macro will do bla, bla
$x = 0
Goto Position=Top
While not($_EOL)  # Loop through the entire file
  $x = $x + 1 # count the number of waypoints
  Goto Position=Next
EndWhile
# Show total number recs
Pause Msg=$x


Command names and mandatory parameters are validated. When GSAK encounters an invalid command or missing parameter the macro will abort with an error message. For example if you used the command DEBUG Statux=on (Notice the parameter has been incorrectly spelt as Statux instead of Status) you would get the following error message. 



You can use GSAK variables in all commands but expressions can only by used in the SET, IF, MFILTER and WHILE commands. For example:
 

SET $FileName = $_Install + "\test.GPX"
LOAD File="$FileName"


Is valid, but the following is not, because the contents after File= is an expression. 
 

LOAD File=$_Install + "\test.GPX"


If you want to use an expressions in a command this manner, then just allocate the expression to a variable first, then use that variable in the command.

Command/Function Summary (Green=Command, blue=function)
  

Abs
Returns an absolute value of a number

AddNew         
Add a new record to a table

Appendfile   
Append data to an existing file

Alltrim
Remove spaces before and after a string

Asc            
Return the ascii value of a character

At             
Get the position of string found in another string

ArcCos         
Calculates the inverse cosine of a given number

ArcCosh        
Calculates the inverse hyperbolic cosine of a given number

ArcSin         
Calculates the inverse sine of a given number

ArcSinh        
Calculates the inverse hyperbolic sine of a given number

ArcTan         
Calculates the arctangent of a given number

ArcTanh        
Calculates the inverse hyperbolic tangent of a given number

BoolToStr       
Convert Boolean value to a string

Backup         
Backup GSAK databases(s) and settings

BeginSub       
Begin a subroutine

Break          
Exit out of the current WHILE loop

CacheMate      
Load CacheMate logs and finds from a CM2GPX generated file

Cancel         
Cancel the macro and return to the GSAK GUI

CancelFilter   
Cancel the current filter

Centre         
Set the current centre point

Choose         
Select from a list of choices

Chr            
Convert a decimal value to its ASCII equivalent

Clip           
Copy information to the windows clipboard

Cos            
Calculates the cosine of an angle

Cosh           
Calculates the hyperbolic cosine of an angle

Database       
Select, create, delete a database

DatabaseExists 
Test to see if a GSAK database exists

DataRestore    
Restore saved database fields

DataSave       
Save database fields

DateDiff       
Find the number of days between two dates

DateFormat     
Convert a date to string using current system date settings

DateToString   
Reverse of the StringToDate function

Debug          
Debug a macro script

Declare         
Declare a variable

Delay          
Delay the running of a macro by milli seconds

Delete         
Delete waypoint(s) from the current database

Editform       
Edit a GSAK form

Else           
Execute statements for the false condition of an IF command

EndRead        
See the FileRead command

EndSub         
End a subroutine

Exit           
Exit GSAK (not just the macro but the whole program)

ExitSub        
Exit a subroutine

Exp            
Exp returns the value of e raised to the power of X

Export         
Export any of the GSAK supported file types

Extract        
Extract part of a string from another given a delimiter

FileCopy       
Copy a file

FileErase      
Erase file(s)

FileExists
Test if file exists in fully qualified path

FileOpen 
Open a file

FileRead       
Read a text file line by line

Filter         
Select a saved filter

FolderExists   
Test if a folder/directory exists

Frac           
Get the fractional part of a number

GCalc          
Calculations using longitude and latitude

GeoCalc        
Calculations using longitude and latitude (Deprecated)

GetClipText          
Get the current clipboard text

GetEnvV        
Get value of a system environment variable

GetFile        
Read the contents of a disk file

GetMail        
Allows you to download attachments from a POP3 mail account

GetSpecial     
Get the value of any special tag(s)

GoSub          
Call a subroutine

GoTo           
Position the current waypoint in the grid

Grab           
Grab coordinates adding waypoints to current database

HttpEncode            
HttpEncode a string

HTML            
HTML generation helper

If             
Run macro commands only if a certain condition exists

Include        
Insert a code file into a macro

Input          
Prompt user for data and assign to a variable

Int            
Get the integer portion of a number

IsEmpty        
Test if a string is empty

IsOwner          
Ownership of the current cache or log

Left           
Get the left most characters of a string

Len            
Get the length of a string

List           
Manipulate lists (Array like support)

Ln             
Get the natural logarithm of a number (Ln(e) = 1)

Load           
Load a GPX/loc/zip file into the database (or folder of these files)

Log            
Get log base n of a number

Macro          
Run another macro (subroutine)

MacroFlag      
Set/Clear macro flags

MacroSet       
Update dialog settings from within a macro

MFilter        
"On the fly" macro filter

MimeDecode     
Mime decode a string

MimeEncode     
Mime encode a string

MoveCopy       
Move or Copy waypoints from one database to another

MsgOK        
Simple message box with single OK button

NumToStr       
Convert a number value to a string value

Option         
Request explicit declaration of variables or not

Pause          
Pause the macro (with message)

PlayWav        
Play a WAV sound file

PurgeLogs      
Purge out required log records from a database

PurgeNote      
Purge/delete out details from user notes

PutFile        
Write a file to disk

Quote          
Enclose a string in double quotes

RegEx          
Use a regular expression to find a string in another string

RegExCount     
Count the number of times a regular expression is found in a string

RegExData      
Return the matching data of a regular expression

RegExEscape    
Escape data so can search as plain text

RegExReplace   
Replace matching regular expression with a string

RegExSub       
Retrieve the matching sub expression

RemoveVar       
Remove a macro variable from memory

Replace        
Global replace of data fields

Replace        
Replace one string with another

RestoreFilter  
Restore filters settings saved by SaveFilter

Return         
Exit the current macro file only

RGBColor      
Convert RGB color values to a number to use in SetColor command

Right         
Get the right most characters of a string

ROT13       
ROT13 encode/decode a string

RunPgm         
Run any external program

SaveFilter     
Save filter settings to restore later with RestoreFilter function

Seek           
Quickly postion or find a code

Set            
Create or assign the value of an expression to a variable

SetColor       
Set colors for rows or columns

Showform       
Show a GSAK form

ShowStatus     
Show the status of a macro command

ShowStop       
Show a stop dialog when running a macro so you can cancel the macro at any time

Sin            
Calculates the sine of the angle in radians

Sinh           
Returns the hyperbolic sine of an angle

SmartName      
Calculate a "smart name" for any string

Sort           
Sort data by any column or columns

SpeedMode      
Turns macro speed mode on or off

SplitScreen    
Turn on/off split screen display

Sqr            
Returns the square of a number

Sqrt           
Returns the square root of a number

StopRead       
Terminate FILEREAD

Str            
Converts a number into a right justified string with decimals digits following the decimal point

StrToBool       
Convert a string value to Boolean

StringToDate   
Convert a string literal to a date type variable

SubStr         
Get a substring from a string

SysInfo        
Retrieve system information

Table          
Select the active table (Caches, Logs, Waypoints)

Tan            
Calculates the tangent

Tanh           
Calculates the hyperbolic tangent

TextOut        
Generate CSV and tab delimited text files

Time           
Returns the system time as a string in the form HH:MM:SS

Timer          
Macro stopwatch

TotChild       
Get the total number of child waypoints

Trim           
Removes trailing spaces from a string expression

Upper          
Convert a string to all uppercase

UserFlag       
Set/Clear user flags

UTF8       
UTF8 encode/decode a string

Val            
Convert a string to a number

VarExists       
Test for existence of a variable

VerCheck       
Check GSAK version macro can run under

View           
Select a GSAK grid view

Vsub           
Toggle variable substitution on and off

Web            
Run any URL and show in current browser

While          
Run macro commands while a certain condition exists (looping)

ZipFile       
Zip File zip/unzip support

<Data>         
Static allocation of large text to a variable


BEGINSUB <Name=SubrName>

Denotes the beginning of a subroutine. A subroutine is a block of code that you wish to reuse. You call the block of code with the GoSub command.
Note: global scoping of subroutines is not supported (for example, trying to use subroutines from another macro file opened with the MACRO command). Subroutines are only available in the macro file they are defined.
Summary

BREAK

The BREAK command should only be used in a WHILE loop and causes the macro to immediately exit the current While loop (that is, the next macro command that is executed is the one after the corresponding ENDWHILE)
Summary

CACHEMATE [<Settings="name">]  [<File="path\file">] 

Load CacheMate logs and finds from a CM2GPX generated file
Summary

Settings = Name of the corresponding settings you would like to use for this load. You must have previously created these settings from the File=>Load CacheMate logs and finds dialog.

File=  Fully qualified file name. For example, "c:\program files\GSAK\My Files\1234.GPX". If you have provided a settings token, then the File= Token will override the file name in those settings.
Summary

CANCEL  [<Msg="Cancel Message">]

Cancel the current macro and return to the GSAK GUI (unlike the EXIT command which cancels the macro command and shuts down/exits GSAK)
If you include the optional Msg= parameter, a message box will show and the user must click on OK before the macro ends. 
Summary

CANCELFILTER

Cancel the current filter. All records in the database will now be in your current sub set.
Summary

CENTRE [<LOCATION="name">] [<COORDINATES=LatLon string>]

This command will set your current centre point. CENTER (American spelling) is also supported.

Location - If you do not enter the LOCATION token then GSAK will set the current waypoint as centre, otherwise your centre point will be set to the location you specify. If you do specify a location, GSAK will check to make sure this is a valid location you have set up (See Tools=>Options=>Locations), unless you also enter COORDINATES

Coordinates - If you only enter the LOCATION parameter you will get an error if the LOCATION name does not exist as one of your locations (Tools=>Options=>Locations) If you add Coordinates=, then the LOCATION= is used only to name your center point and the coordinates you enter are used.  Another words, the LOCATION name is only validated if COORDINATES= is not used.

Name = A location name (Tools=>Options=>Locations) to set as the centre point
Summary

CHOOSE [<Msg="message">] [<opt1="option 1">] [<opt2="option 2">] [<opt3="option 3">] [<opt4="option 4">] [<opt5="option 5">] [<Delay=nnn>]

This command enables you to solicit information from the user for up to 5 options (an alternative to the input command when there are a fixed number of alternatives). The option number selected is placed in the variable $Result (note this is a numeric variable). If you need more information from the user see the ShowForm() function.

Msg = Enter the message which will display in the dialog heading. This is usually a description about what your choices are.
opt1-opt5 = Enter the description for each option, up to a maximum of 5 (but not all 5 need to be entered)
Delay - Allows the dialog to automatically close after nnn seconds. This will allow you to run macros unattended and accept default values if you are not there to enter anything. The left most section of the dialog caption will show a count down timer with the number of seconds ticking over before the dialog will close. If you want to stop the dialog from closing, any mouse click on the dialog will terminate the count down timer. This effectively enables you to convert the form on the fly to a normal dialog (without automatic close) if you do want to enter data.

Summary

CLIP <DATA=data> 

Use this command to copy information to the windows clipboard. 

Data = Any literal, variable, or special tags  

Note: Pre version 6 the token used was TAGS. Prior to version 6 this command only supported special tags but version 6 introduced support for variables so the TAGS descriptions is misleading. For backwards compatibility TAGS is still supported but it is deprecated and DATA should be used instead.

Examples:

Literal =>     CLIP Data="Hello world"
Variable=>     $CacheName = $d_Name
               CLIP Data=$CacheName
Special tags=> CLIP Data=%name
Summary

DATABASE <Name="Database"> [<Action=select|create|delete>] [<Settings=Name>]

The DATABASE command allows you to select, create, or delete a GSAK database. When you select or create a database, it will remain current until another DATABASE or MOVECOPY command is used, or you specify a different database on a LOAD command.

Name = Name of the database, and you need to enclose in double quotes if the name contains spaces.
Action = Action to perform. Select = Select a database, Create = Create a new database, Delete = Delete a database. The default is Select.
Settings = Only used when Action=create. If left out, then the default database properties are used (same behaviour as if you checked the "use defaults" box when creating a database via the menu option Database=>New
Summary

DATARESTORE <Data=DB field(s)>

Restore database fields saved in the DATASAVE command. For a more complete explanation see the DATASAVE command
Summary

DEBUG <STATUS=on|off> [<Height=nnn>] [<Width=nnn>] [<Left=nnn>] [<Top=nnn>]

The DEBUG command allows you to step through a macro. Each command in the macro will come up with a dialog showing the actual command and the value of all variables, just before the command is run. From this dialog you have the option to accept the command, skip the command, or stop the macro. You can turn DEBUG on and off anywhere in the macro by using the corresponding status token.

Height, Width, Left and Top are all optional and allow you to change the size and position of the debug dialog. All measurements (nnn) are in screen pixels. 
Summary

DELAY <MS=MilliSeconds>

Delay the running of the macro by the required Milliseconds. Use to slow down the macro without having to issue PAUSE commands. Useful to see what is happening after a command or for general debugging. Each time you use the DELAY command the macro "sleeps" for the given amount of time in milli seconds. 

MS = The number of milli seconds to delay, 1000 = 1 second
Summary

DELETE <Settings="name">

Delete waypoint(s) from the current database

Settings = Name of the corresponding settings you would like to use for this delete. You must have previously created these settings from the delete dialog.
Summary

ELSE

The ELSE command can only be used between the IF and ENDIF commands. The IF command evaluates to a True or False result, all commands before the ELSE are executed if the result is True. All commands after the ELSE are executed if the result is False.
Summary

ENDREAD

See the FILEREAD command
Summary

ENDSUB 

Denotes the end of a subroutine. For more information see BeginSub and GoSub
Summary

EXIT 

This EXIT command will cause GSAK to exit. Handy if you are running a batch file and waiting for GSAK to end before continuing. 
Summary

EXITSUB 

Use this command to immediately exit from a subroutine. The ExitSub is similar in function to the BREAK command in a WHILE loop. Also see the GoSub command
Summary

EXPORT <Type=ExportType>  [<Settings="name">]  [<File="path\file">] [<From=nnn>] [<To=nnn>] [<max=nnn>]

The EXPORT command enables you to export the current subset of waypoints to your desired "Type". 

Type = The required export type. Codes for each export type are:
  • OZI - Ozi Explorer
  • HTML - Html output
  • GPS - output to GPS
  • MAGSD - Magellan SD card
  • GPX - output to GPX
  • POI - TomTom POI file
  • MXF - Maptech eXchange format
  • SNT - Microsoft Streets & Trips CSV format
  • CMT - CacheMate
  • MPS - MapSource
  • SAT - Street Atlas
  • WPT - MapSend
  • CUS - Custom 
  • FUG = Fugawi
  • PSP = Microsoft Pocket Streets
  • TPG = National Geographic Topo
  • DEL - Delorme Topo USA, Street Atlas Plus, etc
  • MEM - Memory map
  • USR - Lowrance USR
  • CSV - CSV/TXT file

    Settings = Name of the corresponding settings you would like to use for this export. You must have previously created these settings from that export dialog. If you do not provide a settings parameter, then the current values for the corresponding export dialog will be used.

    File = The fully qualified path to the file that you want the export to generate.  For example, "c:\program files\GSAK\My Files\auto.GPX"  For the HTML export, this parameter should be a folder only (that is, the path to the folder where GSAK creates the sub folder "cache" and places all the HTML files). If you leave this parameter out the file/folder name will be taken from the current dialog setting, or from the Settings token if you have used it. Note: The file token is not used/supported for the CUS type 

    From = There are times when you do not want to export all of the waypoints in your current sub set (for example you only want to export the first 200 waypoints). Use the From and To tokens to limit the waypoints exported. The from and to numbers a calculated using your current sort sequence (as displayed in the grid). To see the actual number of a waypoint in the grid, right mouse click on it and select "show current row number". The from number is your starting waypoint and is included in the export. From and to are both optional.

    To = See From. The to number is ending waypoint and is included in the export. 

    Max = The maximum number of waypoints to be exported. If this parameter is omitted then "maximum waypoints to send" value from the corresponding settings is used.
    Summary

    FILECOPY <From=Filename> <To=Filename> [<OnError=Abort|Prompt|Continue>]

    This command allows you to copy files natively from the macro language.

    From = Absolute path to the file being copied
    To = Absolute path to the destination file
    OnError = Action to take if files can't be deleted:

    Abort - If there is an error deleting the file GSAK stops the macro with the familiar error box. The macro cannot proceed and will abort after clicking on OK.
    Prompt - The macro will bring up a pause dialog showing the error giving you the option to continue or abort
    Continue - The error is ignored and the macro automatically continues to the next line without any error messages or intervention.
    Summary

    FILEERASE <File=FileName> [<OnError=Abort|Prompt|Continue>]

    This command allows you to delete files natively from the macro language. Optional OnError token (default is abort):

    File = The absolute path to the file(s) to delete.  Wild cards are supported.
    OnError = Action to take if files can't be deleted:

    Abort - If there is an error deleting the file GSAK stops the macro with the familiar error box. The macro cannot proceed and will abort after clicking on OK.
    Prompt - The macro will bring up a pause dialog showing the error giving you the option to continue or abort
    Continue - The error is ignored and the macro automatically continues to the next line without any error messages or intervention.
    Summary

    FILEOPEN <File="file name"> [<wait=yes|no>]

    The FILEOPEN command is similar to the RUNPGM command. The difference being that GSAK will open the given file with what ever is associated with that file extension. For example the file "test.txt" will open in your default text editor. "test.htm" will open in your default browser, etc.
    File = The fully qualified path to the file to open
    Wait = Yes will stop the macro and wait for the application that opened the file to terminate. No (the default) will open the file then move on to the next command in the macro. This parameter is optional.

    Note: Prior to version 6.5 this command was OPENFILE. OPENFILE is still valid for backwards compatibility, but the name was changed to make it consistent with the other file commands
    Summary

    FILEREAD <File=FileName>

    Use this command to read a text file.The GetFile function reads all the data into the one variable. The FileRead command allows you to iterate through any size text file and read in the lines one at a time. The opening, reading, and closing of the text file is all done for you. All you need to do is place your macro code between the FileRead and EndRead commands, using the automatically generated macro variable $line to represent the current line in the text file. If at any time you would like to terminate reading the file before the end of file is reached, use the STOPREAD command.  For example, to count the number of blank lines in a text file:
      

    $blank = 0
    FileRead File=c:\temp\test.txt
    If IsEmpty($line)
       $blank = $blank + 1
    EndIf
    EndRead
    Pause Msg=Number of blank lines in file: $blank
     


    File - The fully qualified text file to read

    Note1: Each FileRead command must have a corresponding EndRead command. 
    Note2: Currently, the FileRead command can only process one file handle per macro [1] so you can't nest this command in while or if statements. The work around  to use the MACRO command. As this command creates another complete new instance of the macro engine, you get another file handle and it works.
    [1] Simultaneous access that is. You can open and close (fileread - endread) as many files as you like in the same macro, but they cannot be nested.
    Summary

    GETMAIL <Settings="name"> [<OnError=Prompt|Abort|Continue>] [<ShowStats=No|Yes>]

    The GETMAIL command allows you to download attachments from a POP3 mail account

    Settings = Name of the corresponding settings you would like to use for this GETMAIL. You must have previously created these settings from the GETMAIL dialog (File=>Get data via email)

    OnError  = Action to take if an error occurs (optional, default = Prompt)

    Prompt - Display a message and allow the user to select what action to perform after the error (default value)
    Abort - Abort the macro immediately without any messages
    Continue - Ignore the error and continue on with the next macro command

    ShowStats - Optional, default = No. The macro language has been designed to "automate GSAK". One of default behaviours of this automation is to suppress all GUI type notification messages. This ensures that when you run a macro it "automates" and you are not constantly having your macro stopped by informational messages.However, some messages you may like to still see - like the "statistics box" after load GPX files downloaded with GetMail. This option allows you to view these statistics (Note: this option only applies if your GetMail settings have the "Load folder of saved attachments" box ticked)
    Summary

    GETSPECIAL <Data="special tags">

    Use this command to convert the value of any special tag(s) to a string variable. The command returns the converted special tag(s) in the $result variable (you can also include string literals. For example if the current waypoint has the code of "GCABCD" and smart name of "BigRed", then:
     

    GetSpecial data=%smart 
    $result = "BigRed".

    GetSpecial data=The code is %code
    $result = "The code is GCABCD"

    Summary

    GOSUB <Name=SubrName>

    The GoSub command allows you to re use code by means of subroutines. The name token must be a valid subroutine name as created with the BeginSub and EndSub commands. The Code inside the BeginSub and EndSub block is executed, and when finished the next line in the macro after the GOSUB is run. To immediately exit the subroutine block use the ExitSub command. Note: global scoping of subroutines is not supported (for example, trying to use subroutines from another macro file opened with the MACRO command). Subroutines are only available in the macro file they are defined.

    Summary 

    GOTO <POSITION=Top|Bottom|Next|Previous|nn> [<OnError=Abort|Ignore>]

    Position the record in the current Table.

    Top = Top or the first record in the current sub set
    Bottom = Bottom or last record in the current sub set
    Next = The next record in the current subset
    Previous = The previous record in the current subset
    nn = number of records to skip (relative to the current record - use negative values to move backwards)

    Note: Any position that would take you ouside the current subset will set the system variable $_EOL to true. For example if you were on the last waypoint and used "Position=Next" or the First waypoint and used "Position=Previous"

    OnError - Action to take if the position= token tries to move to a non-existent position in the table. Abort - You get an error message and the macro aborts. Ignore - the error is ignored, you are left at the current waypoint, and the macro continues to execute the next instruction.
    Summary

    GRAB <Settings=Name> [<ShowStats=No|Yes>]

    This command allows you to grab waypoints using the macro language. If you want to do this using the GUI, then use the Tools=>Grab coordinates instead

    Settings = Name of the corresponding settings you would like to use for this grab. You must have previously created these settings from  the grab dialog. If you do not provide a settings parameter, then the current values for the corresponding load dialog will be used.

    ShowStats - Optional, default = No. The macro language has been designed to "automate GSAK". One of default behaviours of this automation is to suppress all GUI type notification messages. This ensures that when you run a macro it "automates" and you are not constantly having your macro stopped by informational messages. However, some messages you may like to still see - like the "statistics box" after load GPX files downloaded with GetMail. This option allows you to view the grab totals.
    Summary

    IF <expression>

    Use this command to execute a group of macro commands only if a certain condition exists. The expression used must return a Boolean true or false value. You must end the group of statements being executed with the ENDIF command. To execute other commands for the false condition use the ELSE command. For example:
     

    IF FileExists("c:\mail\12345.GPX")
       DATABASE Name="Default"
       LOAD Settings="12345 settings" File="c:\mail\12345.GPX"
    ELSE
      PAUSE Msg="File 12345.GPX not found"
    ENDIF

    Summary

    INCLUDE <File=FileName>

    Use this command to insert common code into a macro. It is similar, but not the same in function to the MACRO command. Instead, the command will replace this line of code with the contents of the specified file. Consider it exactly the same as if you copy then pasted the code into the original macro at this position. However, the macro file itself is not actually updated - just the contents in memory that GSAK runs. This will allow you to keep code libraries of subroutines in a single file, then get access to them via this single command. Subroutines are not global in scope, hence you can't do this same thing via the GOSUB command. 

    Note: the "FileName" must be a literal and not a variable. The INCLUDE command is processed by the macro pre processor (before any code is actually run) and macro variables are not resloved in this phase.
    Summary

    INPUT <Msg="message"> [<Default="">] [<VarName=$Result>] [<Browse=None|Folder|File>] [<Delay=nnn>]

    Msg = The message to display when the input dialog shows
    Default = The default value that will be assigned to VarName if nothing is entered (optional, default is blank)
    VarName = The Macro variable that will contain the data entered (optional, default is $Result)
    Browse = Folder - use when the input dialog is asking for a Folder path. This will add a Folder browse button to the dialog so you can use the windows GUI to select the folder. File - use when the input dialog is asking for a File name. This will add a File browse button to the dialog so you can use the windows GUI to select the file name. This token is optional and the default is None
    Delay - Allows the dialog to automatically close after nnn seconds. This will allow you to run macros unattended and accept default values if you are not there to enter anything. The left most section of the dialog caption will show a count down timer with the number of seconds ticking over before the dialog will close. If you want to stop the dialog from closing, any mouse click on the dialog will terminate the count down timer. This effectively enables you to convert the form on the fly to a normal dialog (without automatic close) if you do want to enter data.

    The INPUT command allows you to get information from the user while the macro is running and place the result in a variable.
    The optional Default token allows you to specify a value that will show in the input field in the prompt. $Result is the default variable name (automatically allocated if you leave off this token) but you can declare any variable name here.

    If you need more information from the user see the ShowForm() function.
    Summary

    MACRO <File="path\file">

    This command allows you to run another GSAK macro file. This allows you to reuse macro code (kind of like subroutines). Multiple levels are supported, that is Macro A can call Macro B, which call Macro C, which calls Macro D etc. At any stage you can check the calling level by using the $_MacroLevel system variable. 
    Summary

    MACROFLAG <type=set|clear|swap> <range=all|filter|nn>

    The poor old UserFlag often gets over used. Macro users often find they want to update the user flag for a new condition but not disturb the setting for the old condition. The macro flag addresses this problem (database variable $d_MacroFlag). The syntax for the MACROFLAG command is exactly the same as for USERFLAG but obviously all the options work on the MacroFlag instead. This will enable you to set/clear/filter/Test on the MacroFlag when you don't want to disturb the settings of the UserFlag. The new MacroFlag is only available in a macro ( you do not have access to it in the GSAK GUI).

    Type = The type of userflag manipulation to perform
    set - set all user flags as specified in the range parameter
    clear - clear all user flags as specified in the range parameter
    swap - reverse the setting of the userflags specified in the range parameter (if set, then unset and vice versa)

    Range = The range of records to manipulate:
    All - includes all waypoints in the database, regardless what your current filter is.
    Filter - includes only the waypoints in your current filter
    nn -  the number of waypoints (starting from the current one) to set, clear, or swap
    Summary


    Note: The boolean values "True" and "False" are case sensative. You must enter them exactly as "True" or "False" (without the double quotes) or unexpected results will occur
    Summary

    MOVECOPY <Settings="name">

    Move or Copy waypoints from one database to another

    Settings = Name of the corresponding settings you would like to use for this move/copy. You must have previously created these settings from the move/copy  dialog (Database=>Move/Copy Waypoints...)
    Summary

    PAUSE <Msg="Pause Message">

    The PAUSE command enables you to stop your macro with a message. This will cause GSAK to pause the macro with the message shown as per the Msg= parameter. You also have 3 options:
    Continue - macro will continue as per normal to the next command
    Skip next command - GSAK will skip the next command in the macro
    Stop macro now - GSAK will terminate macro processing immediately

    You could use this when you want to perform some action before the next command starts - connecting your GPSr for example.  
    Summary

    PURGELOGS <Settings="Name">

    This command allows you to purge out log records from your GSAK database. You must first create a "Setting" from the Purge Logs Dialog. 
    Summary

    PURGENOTE <Type=Full|NoteOnly|LogOnly> <Range=Current|All>

    Enables you to remove information from the User Notes. 

    Type = This is the type of information you would like to purge/delete
    Full - The complete user note, including everything in the user note section and user log section
    NoteOnly - Only the user note section - Not the user log
    LogOnly - Only the user log section - Not the user note

    Range = The range of records this purge should apply to 
    Current - the current record only
    All - all records in the current sub set (That is, if a filter is set only the records in the filter will be updated)
    Summary

    REPLACE <Settings="name">

    Global replace of data fields

    Settings = Name of the corresponding settings you would like to use for this replace. You must have previously created these settings from the global replace dialog (Database=>Global replace...)
    Summary

    RETURN   [<Msg="Cancel Message">]

    The RETURN command terminates the current macro file only. So if macro A calls macro B, and you use the RETURN command in Macro B, then all remaining commands in Macro B are ignored and control returns to Macro A. If you include the optional Msg= parameter, a message box will show and the user must click on OK before the macro ends. Just to summarise the ending of Macro commands:

    RETURN - ends the current macro file only
    CANCEL - ends macro at any depth and returns to the GSAK GUI
    EXIT - ends macro at any depth, and also ends/exits GSAK
    Summary

    RUNPGM <pgm="ProgramName.exe" [<parms=Parameters>] [<Wait=No|Yes>]

    Run any external program

    Pgm = The program name to execute. The file name must be full qualified (For example, "c:\program files\MyProgram.exe")
    Parms = Any parameters to pass to the program before running it. The Parms= gets special treatment in the macro language. Anything after the Parms= is passed verbatim as parameters to the program being called. If the parameters to your program require quotes, then be sure to include these. However, if your program does not require double quotes for the parameter(s) then do not use double quotes here as your program may produce unexpected results.
    Wait = No (the default) continues on to the next line in the macro regardless if the program has terminated. Yes tells GSAK to wait until the program has terminated before running the  next macro command.
    Summary

    SET $VarName = <expression>

    The set command allows you to create and change variables using a combination of literals, variables, and functions (known as an expression). For more information please see variables and expressions. Note: As of version 6.0 the SET command is now optional. Therefore the following two commands are equivalent in the macro language:

    SET $var = "this is a string variable"
    $var = "this is a string variable"
    Summary

    SetColor <Color=9999999|clear> [<Column=All|name>] [<Row=All|Current>]

    Color = The numeric color number for the colour you want. Use "Macro=>Color Picker" to get the numbers for the colors you intend using. The special reserved word "clear" can be used when you want to clear out a color for that record. If you are more familiar with RGB colors, then you can use the macro function RGBColor(nRed,nGreen,nBlue) to convert RGB colors to an number you can use for this parameter.  
    Column = All will set all columns (except the code column) to this color. If you only want a particular column to be set then enter the column name. The column names are exactly the same as used in the SORT command. 
    Row = All will set all the records in your current filter. Current will set only the current record

    This command will allow you to set the row or column colors under the control of a macro. Let us take a simple example, you want to set all caches with a difficulty of 1 = blue, 2=red, 3=yellow. The color picker will let you pick any color on your palette (see picture and notes below) but you must use the generated number. For clarity you may want to allocate these numbers to meaningful variable names first:
     

    $blue = 16744448
    $red = 255
    $yellow = 8454143
    Mfilter if=$d_Difficulty = 1
    SetColor Color=$blue
    Mfilter if=$d_Difficulty = 2
    SetColor Color=$red
    Mfilter if=$d_Difficulty = 3
    SetColor Color=$yellow
    CancelFilter



    Note: The colouring of rows/columns is static. What do I mean by this? Currently the colouring of found, placed, etc is dynamic. This means if you change a waypoint such that it meets a new criteria for colouring then it instantly changes color. SetColor does not work this way. For example, if you ran a macro to highlight all "Difficulty 1" rows, it would highlight all the current rows that have a difficulty of 1. If you now load a GPX file that has new caches with a difficulty of 1, they do not get the new color until you run the macro again. Conversely, if you manually set the difficulty from 1 to 2, the waypoint will still have the color set by the original running of the macro - until you ran the macro again. 

    You can clear out the effects of colouring from using this command at any time by taking the menu option "Macro=>Clear macro set colors"
    Summary

    SHOWSTATUS <Msg="Status message"> [<Height=nnn>] [<Width=nnn>] [<Left=nnn>] [<Top=nnn>] [<Display=On|Off>]

    One of the problems with having GSAK run in SpeedMode is that there is no feedback to the user when iterating through the database or running a large number of macro commands. The SHOWSTATUS command can address this problem. If you use this command it brings up the same dialog as the SHOWSTOP command (you can still use SHOWSTOP but it is no longer needed if you now use SHOWSTATUS) which now has a status bar added to the bottom. Any text you place in the MSG parameter is displayed in this status bar. Run the sample macro "_Summary.txt" to see this in action.

    Height, Width, Left and Top are all optional and allow you to change the size and position of this dialog. All measurements (nnn) are in screen pixels. 

    Display - On (the default) will show the status box, Off will remove it from the display.

    Summary
     
    SHOWSTOP

    Use the SHOWSTOP macro command to show a small stop dialog when running a macro. You would usually place this as the first command in a macro with many commands. This will allow you to terminate the macro at any time, however I have set this up so your macro only terminates after the current command has finished. 
    Summary

    STOPREAD

    The STOPREAD command should only be used in a FILREAD loop and causes the macro to immediately exit the current FileRead/EndRead loop (that is, the next macro command that is executed is the one after the corresponding ENDREAD)
    Summary


    USERFLAG <type=set|clear|swap> <range=all|filter|nn>

    Use this command to manipulate the user flags.

    Type = The type of userflag manipulation to perform
    set - set all user flags as specified in the range parameter
    clear - clear all user flags as specified in the range parameter
    swap - reverse the setting of the userflags specified in the range parameter (if set, then unset and vice versa)

    Range = The range of records to manipulate:
    All - includes all waypoints in the database, regardless what your current filter is.
    Filter - includes only the waypoints in your current filter
    nn -  the number of waypoints (starting from the current one) to set, clear, or swap
    Summary

    VERCHECK <version=x.x.x.xx>

    This command should be placed as the very first line in your macro. You really only need to use this command when your macro will only work with a certain version of GSAK (or higher)

    The Version= parameter is the minimum version required to run this macro.

    As an added feature you can specify a comment in parenthesis () - open and closed brackets. Anything after and including an open bracket is ignored in the parameter for the version checking. The reason for doing it this way is that it also provides a meaningful error message when used on previous versions of GSAK that do not support this command. For Example, the following code:

    VerCheck Version=6.6.1.15 (please update GSAK to the latest version to run this macro - see http://gsak.net)

    On releases that don't support this command, the error will look something like:



    On releases that do support the command, you will get a specific version check error message, and the text in brackets will just show as a comment.

    VIEW <name="view name">

    Use this command to select and change your current grid view

    Name = The name of the view to select.  
    Summary

    VSUB <STATUS=on|off>

    This command allows you to toggle the support for variable substitution on and off. The default behaviour without this command, is to begin your macro with variable substitution turned on. 
    Summary

    WEB <URL="url name">

    Use this command to run any URL and show in current browser
    Summary

    URL  = For Example, WEB URL="http://www.geocaching.com/seek/log.aspx?ID=%gcid" will open your browser at the Geocaching.com log page for the current cache. Special tags can be used to vary the information used in these URLs (in the same fashion you generate custom URLs)  
    Summary

    WHILE <expression>

    Use this command to repeat a sequence of statements while a certain condition exists. The expression used must return a Boolean true or false value. You must end the group of statements being executed with the ENDWHILE command. For example
     

    # Test to see if the 10 files test1.zip to test10.zip exist, then do some action
    SET $Count = 1
    SET $File = "Test"
    WHILE $Count <= 10
    IF FileExists($File + "$Count" + ".zip")
       commands ...
    ENDIF
    $Count = $Count + 1
    ENDWHILE
     


    Notice the use of the "$Count" (using double quotes) in the FileExists expression. By surrounding the Numeric variable $Count in double quotes, you are typecasting it on the fly to a string value. This enables the expression to work because you can't just add a numeric variable to a string variable as in $File + $Count
    Summary

    <DATA> VarName=<$Variable>

    This command enables you to easily enter large amounts of text in a macro. It's main purpose is to be used in conjunction with the MacroSet command, but you could also use in commands like MSG for standard messages. You can use the <data> command anywhere in the macro, but the actual allocation to the variable is only done at startup as its usage is really for large static amounts of text, so it is probably best if you always put these statements at the end of the macro. This will keep the macro code at the beginning and make for easier reading of the actual code.
     

    . Macro commands 
    Pause Msg=$message
    .. More commands

    <data> VarName=$Message
    Check the GPSr is switched on
    Also make sure you are in the
    Correct database and have selected
    All the correct settings
    <enddata>
     

    Summary
    __________________________________________________________________________
    Examples:
    __________________________________________________________________________

    The example commands are in uppercase for clarity only. All commands, and parameters are NOT case sensitive.

    Keeping it simple, all exports will use the exact same settings as per your last export for that format. 

    As we are trying to automate commands with no user interaction, message boxes have been suppressed. This includes warnings about files already existing (they will automatically be overridden) and summary totals when loading a GPX file.

    Example 1,  from the command line load a GPX file, export to Ozi, then exit GSAK:
     
    GSAK /run c:\temp\clyde.txt

    Commands in clyde.txt
     

    # Load latest pocket query of my finds into Ozi explorer, then exit GSAK
    LOAD file=c:\temp\latest.GPX
    FILTER name="Only found caches"
    EXPORT Type=Ozi File="c:\temp\test.wpt"
    EXIT


    Example 2 - Combine the results of multiple filters (enter into a text file, then run via File=>Run Macro)
     

    #example of macro to combine the results of 3 different filters
    #
    # clear all user flags first
    USERFLAG type=clear range=all
    # load first filter
    FILTER name="filter1"
    # set user flags for this filter
    USERFLAG type=set range=filter
    # load second filter
    FILTER name="filter2"
    # set user flags for this filter
    USERFLAG type=set range=filter
    # load the 3rd filter
    FILTER name="filter3"
    # set user flags for this filter
    USERFLAG type=set range=filter
    # now finally set a filter on User flags = set
    FILTER Name="User flag set"


    Example 3 - Send waypoints to GPS with different custom icon overrides. (For this to work you must have set up icon override settings for the various overrides using the "All waypoints" override)
     

    # example of macro to send override icons to GPS
    #Load first filter condition
    FILTER name="Found by my friend Bozo"
    EXPORT type=gps settings="set icon to funny face"
    # Load second filter condition
    FILTER name="Difficulty 5 caches"
    EXPORT type=gps settings="set icon to sad face"


    Example 4 - For a complete macro that will enable you to do a "Cache Raid" please see the CacheRaid.txt macro 

    For real world working macros take a look at user created ones here

    Summary
  • Copyright 2004-2007 CWE Computer Services  
    Privacy Policy Contact