Introduction To TCL SCL
Introduction To TCL SCL
Introduction To TCL SCL
Surpac 6.6
Copyright © Dassault Systèmes GEOVIA Inc.
All rights reserved. Dassault Systèmes GEOVIA Inc. publishes this documentation for the sole use of
GEOVIA product licensees.
Without written permission, you may not sell, reproduce, store in a retrieval system, or transmit any
part of this documentation. For such permission, or to obtain extra copies please contact your local
GEOVIA office, or visit www.3ds.com/GEOVIA.
This software and documentation is proprietary to Dassault Systèmes GEOVIA Inc. and, except where
expressly provided otherwise, does not form part of any contract. Changes may be made in products or
services at any time without notice.
While every precaution has been taken in the preparation of this manual, neither the authors nor
GEOVIA assumes responsibility for errors or omissions. Neither will be held liable for any damages
caused or alleged to be caused from the use of the information contained herein.
Dassault Systèmes GEOVIA Inc. offers complete 3D software tools that let you create, simulate, publish,
and manage your data.
GEOVIA, the GEOVIA logo, combinations thereof, and GEMS, Surpac, Minex, MineSched, Whittle, PCBC,
InSite, and Hub are either trademarks or registered trademarks of Dassault Systèmes or its subsidiaries
in the US and/or other countries.
Product
Surpac™ 6.6
Last modified: Friday, 27 May 2013
Table of Contents
Introduction to Tcl/Scl Surpac 6.3....................................................................................................... 1
Introduction ...................................................................................................................................... 7
Overview................................................................................................................................................... 7
Requirements ........................................................................................................................................... 7
Workflow .................................................................................................................................................. 7
Setup for this tutorial ........................................................................................................................ 8
Setting the work directory........................................................................................................................ 8
Task: Set the work directory .................................................................................................................. 8
Logicals, command aliases, and hotkeys ............................................................................................. 9
Logicals ..................................................................................................................................................... 9
Task: Create a user logical ................................................................................................................... 11
Command alias ....................................................................................................................................... 11
Task: Create a command alias ............................................................................................................. 13
Keymaps ................................................................................................................................................. 14
Task: Create a hotkey .......................................................................................................................... 14
Creating menus and toolbars ........................................................................................................... 15
Invoking the menu and toolbar editor tool ............................................................................................ 15
Task: Creating a menu from system menu items ................................................................................ 16
Task: Copy and paste an existing menu .............................................................................................. 16
Creating your own menu items .............................................................................................................. 16
Task: Create menu items ..................................................................................................................... 16
Creating a custom toolbar ...................................................................................................................... 18
Task: Create a custom toolbar ............................................................................................................. 18
Task: Create a custom button to put onto a toolbar........................................................................... 18
Summary ................................................................................................................................................ 19
Recording tasks in a Tcl script........................................................................................................... 20
Macro record .......................................................................................................................................... 20
Task: Record a macro .......................................................................................................................... 20
Macro playback ...................................................................................................................................... 21
Task: Playback the macro .................................................................................................................... 21
Task: Run a script without the macro playback form .......................................................................... 21
Structure of a Tcl macro ......................................................................................................................... 22
SclFunction ............................................................................................................................................. 25
Task: Record a script to rotate data .................................................................................................... 25
Using the _action switch ........................................................................................................................ 26
Task: Record a script to create a DTM ................................................................................................. 27
Task: Record a script to perform inquire point ................................................................................... 29
Summary ................................................................................................................................................ 29
Some required Tcl basics to get working ........................................................................................... 30
What is Tcl? ............................................................................................................................................ 30
What is Scl? ............................................................................................................................................ 30
Tcl Syntax ................................................................................................................................................ 31
Commands.............................................................................................................................................. 31
Page 3 of 89
set ........................................................................................................................................................ 31
puts ...................................................................................................................................................... 32
Variables and substitution...................................................................................................................... 32
Grouping constructs ............................................................................................................................... 33
Command substitution ........................................................................................................................... 33
Summary ................................................................................................................................................ 34
Creating user forms for scripts ......................................................................................................... 35
Guido ...................................................................................................................................................... 35
Guido command syntax .......................................................................................................................... 36
Guido command switches ...................................................................................................................... 37
GuidoForm.............................................................................................................................................. 38
SclCreateGuidoForm .............................................................................................................................. 38
SclRun ..................................................................................................................................................... 39
Tying Guido together with the Scl form functions ................................................................................. 40
Task: Create your first form ................................................................................................................. 40
GuidoField .............................................................................................................................................. 41
Task: Create a form containing a GuidoField ...................................................................................... 41
GuidoComboBox..................................................................................................................................... 43
Task: Create a form containing a GuidoComboBox............................................................................. 43
GuidoCheckBox ...................................................................................................................................... 45
Task: Create a form containing a GuidoCheckBox .............................................................................. 45
GuidoRadioButton and GuidoButtonGroupPanel .................................................................................. 47
Task: Create a form with GuidoRadioButtons and GuidoButtonGroupPanel ..................................... 47
GuidoFileBrowserField ........................................................................................................................... 49
Task: Create a form containing a GuidoFileBrowserField ................................................................... 49
GuidoLabel.............................................................................................................................................. 51
Task: Create a form containing a GuidoLabel...................................................................................... 51
Dependencies in Guido .......................................................................................................................... 52
Task: Create a form with a dependency .............................................................................................. 52
Summary ................................................................................................................................................ 53
Automating a recorded script........................................................................................................... 54
Task: Automate a common string maths operation ............................................................................ 54
Summary ................................................................................................................................................ 57
A better way to select points in graphics .......................................................................................... 58
The SclSelectPoint function .................................................................................................................... 58
Task: A simple example to show usage ............................................................................................... 58
Piping point data back into Surpac ......................................................................................................... 59
Task: Use SclSelectPoint and then pass xyz values back to Surpac ..................................................... 59
Summary ................................................................................................................................................ 60
Useful Tcl commands ....................................................................................................................... 61
Working with numbers ........................................................................................................................... 61
The incr command ............................................................................................................................... 61
Task: Use incr ....................................................................................................................................... 61
The expr command .............................................................................................................................. 62
Task: Use expr...................................................................................................................................... 63
The SclExpr command ......................................................................................................................... 63
Page 4 of 89
Table of Contents
Page 5 of 89
Opening and closing files........................................................................................................................ 86
open <file name> <access>.................................................................................................................. 86
close <file reference variable> ............................................................................................................ 86
Reading from a file ................................................................................................................................. 86
gets <file reference variable> <variable for read data> ...................................................................... 87
eof <file reference variable> ............................................................................................................... 87
Writing to a file ....................................................................................................................................... 87
puts <file reference variable> <text string> ........................................................................................ 87
A file-processing template...................................................................................................................... 88
Task: Create a file-processing template .............................................................................................. 88
Summary ................................................................................................................................................ 88
Tcl references .................................................................................................................................. 89
Surpac help ............................................................................................................................................. 89
Text books .............................................................................................................................................. 89
WWW resources..................................................................................................................................... 89
Page 6 of 89
Introduction
Overview
GEOVIA Surpac provides tools that allow the software to be customised and many repetitive tasks
automated into a single control script. These control scripts tell the software to perform a series of
functions in an ordered manner. Control scripts are commonly called macros, Tcl scripts, or just scripts.
The Surpac scripting language is an extension to an independent (nonproprietary) scripting language
called Tcl. Tcl has been distributed freely since 1990 and is now used in thousands of applications world-
wide.
The scripting engine (macro interpreter) contained within Surpac, processes scripts that can contain
standard Tcl statements as well as Surpac extension commands called Scl. Tcl is an acronym for Tool
command language while Scl is an acronym for Surpac command language.
Requirements
This tutorial assumes that you have a basic knowledge of Surpac. If you are a new Surpac user, you
should complete the Introduction to Surpac tutorial before beginning this tutorial. This tutorial also
assumes that you have basic skills in using a text editor such as ConTEXT or Notepad. The tutorial does
not assume you have any previous scripting/programming background.
You will also need:
Surpac installed on your computer
a text editor application installed on your computer, preferably ConTEXT
Workflow
Record Script
Modify Script
Debug Script
Note: This workflow demonstrates the steps in this tutorial. There are other ways to achieve a result.
Page 7 of 89
Setup for this tutorial Setting the work directory
The name of the work directory is displayed in the title bar of the Surpac window.
Page 8 of 89
Logicals, command aliases, and hotkeys Logicals
Logicals
‘Logical’ is a Surpac term that refers to the use of a known name to map to a physical directory. The
known name, or ‘logical’, is mapped to a directory on your hard disk at runtime. Using this system your
macros do not have to refer to a hard coded directory, which might be different on every installation of
Surpac, to access files.
For example, the logical name SSI_ETC: (the known name) can be mapped to a directory named
c:/users/Public/GEOVIA/Surpac/66/share/etc on one system or s:/software/Surpac/v6/share/etc on
another. Surpac uses the known name SSI_ETC: to refer to the directory, this means it does not need to
know where this directory actually exists because it is mapped at runtime.
The reasons logicals are used are:
to insulate the software from the file system
to shorten notation for accessing long directory paths
to standardise data
Logicals come in three types:
System – defined in the translate.ssi file
User – define in the SSI_ETC:logicals.ssi file
Personal – defined in any file and specified to Surpac using the Customise > Default Preferences
function
System logicals are defined by the software installation procedure and are stored into a file that is
usually called translate.ssi. The system logicals are mandatory. You should never modify a system
logical. Below is an example translate.ssi file.
MACHINE=WIN32
SSI_ETC: c:\Users\Public\GEOVIA\Surpac\66\share\etc\
SSI_STYLES: c:\Users\Public\GEOVIA\Surpac\66\share\styles\
SSI_PLOTTING: c:\Users\Public\GEOVIA\Surpac\66\share\plotting\
SSI_PROFILES: c:\Users\Public\GEOVIA\Surpac\66\share\profiles\
SSI_HMF: c:\Program Files (x86)\GEOVIA\Surpac\66\share\hmf\
SSI_MESSAGES: c:\Program Files (x86)\GEOVIA\Surpac\66\share\msg\
SSI_REFMAN: c:\Program Files (x86)\GEOVIA\Surpac\66\share\refman\
SSI_RESOURCE: c:\Users\Public\GEOVIA\Surpac\66\share\resource\
SSI_JAVA: c:\Program Files (x86)\GEOVIA\Surpac\66\share\java\
SSI_BIN: c:\Program Files (x86)\GEOVIA\Surpac\66\nt_i386\bin
SSI_LIB: c:\Program Files (x86)\GEOVIA\Surpac\66\nt_i386\lib\
END
Page 9 of 89
Logicals, command aliases, and hotkeys Logicals
Caution: Do not add user logicals to the translate file. This is because at each new installation of the
software this file is created and so you will lose any changes that you had made.
User logicals are optional and you can use them to make finding your macros and data easier. In the
same way that system logicals make it easy for Surpac to locate files, user logicals make it easy for you
to locate your data and macros. For example, you could define logicals to centralise the storage of your
survey pickups, or make a repository used to store all macros so that each user on a site can access
them using a consistent name. Using a logical to access macros and data using a standard naming
convention, where the physical location of files on a disk does not matter, can be very helpful when you
are working in a network environment, especially when users have different physical drive mappings.
User logicals are also a valuable tool when you are designing menu systems and macros. By using
logicals, the menu definitions and macros can be kept insulated from the file system because there is no
need to worry about physical drive mappings. This way when menus and scripts are transferred to other
computers, it is only the logical reference in the logicals.ssi file that needs to be changed and not the
actual script or menu definitions.
User logicals are defined in a file called logicals.ssi that is stored in the SSI_ETC: directory. This is a
system logical that maps to the directory where the etc files are stored. The logicals.ssi file is optional, if
this file does not exist is does not cause an error in Surpac. However, if it does exist then Surpac will load
the file and add any defined logicals to the system logical map.
Personal logicals are similar to user logicals except that they can be defined in a file with any name. For
example, you can store personal logicals in a file called mylogicals.txt .To make Surpac load a personal
logicals file you must define it in Surpac using the alias tab of the Settings form. You can access this form
by choosing Customise > Default preferences. The format of a personal alias file is exactly the same as
the logicals.ssi file.
When Surpac starts, it will load logical definitions in the following order:
1. System logicals from SSI_ETC:translate.ssi.
2. User logicals from SSI_ETC:logicals.ssi.
3. Personal logicals from your defined logical file.
If there are duplicate logical definitions then the last one read is the one that takes precedence. It is not
an error to define duplicate logicals and you might have good reasons to do so, such as redefining the
location of the SSI_PLOTTING: logical in your personal logicals file.
Below is an example of a logicals.ssi file or a personal logicals file.
MINESOLUTIONS: c:/minesolutions/
MS_SPOOLER: c:/minesolutions/spooler/
MS_STRING: c:/minesolutions/string/
MS_RINGKING: c:/minesolutions/ringking/
MY_MACROS: c:/macros/
The structure of the file is quite basic. You first define the logical name, leave some white space, this can
be one or more spaces, then define the physical directory mapping followed by a trailing slash.
Note: The trailing slash is mandatory, but it can be either a forward or backslash.
Page 10 of 89
Logicals, command aliases, and hotkeys Command alias
Tips:
Use the full colon at the end of each logical. It provides a consistent end-of-logical marker and
makes file paths easier to read when using logicals.
Forward slashes are recommended over backslashes for your physical paths. Backslashes can
sometimes cause obscure problems due to their use as an escaping function in Tcl scripts.
Make sure your physical directory names are correct; Surpac does not check to see if they
actually exist.
MY_WORK: c:/Users/Public/GEOVIA/Surpac/66/demo_data/tutorials/tcl_scl/
Tip: If you cannot find your MY_WORK: logical in the list check that you have named the logicals file
correctly as described in step six. Make sure you know what the actual pathname for SSI_ETC is on your
computer. You can identify this pathname by finding the SSI_ETC logical in the Surpac Navigator and
expanding it.
Command alias
A command alias is a system that provides a mechanism for you to rename commands in Surpac to
something that you find more suitable or easier to remember. It is often quicker for experienced Surpac
users to make use of these short cut alias names than it is to type the full command name or find the
function on a menu or toolbar.
Command aliases are defined in a text file with a set syntax. First, the alias name is given, enclosed in
double quotes, followed by any amount of white space, and then the actual command name, enclosed
in double quotes. An extract from the distributed short.mst alias file follows:
Page 11 of 89
Logicals, command aliases, and hotkeys Command alias
Tip: When defining alias names that clash, the last one Surpac reads is the one that takes
precedence. There is no warning message for a duplicate name so be careful when writing your alias
file.
As well as allowing you to rename existing commands, the alias system also allows you to define new
command names that you can associate with your Tcl/Scl scripts. For example, if you have defined two
scripts, one to import a csv file and load into a database table, and another to export a database table to
a csv file, you can create keyboard commands that will run these scripts. The following alias file defines
two new commands import_csv and export_csv to run macros stored in the MY_WORK: logical.
"IMPORT_CSV" “MACRO:MY_WORK:IMPORT_CSV"
"EXPORT_CSV" “MACRO:MY_WORK:EXPORT_CSV"
Later you will learn how to attach these two scripts to menus.
Note: The keyword MACRO: is used in the path above. This keyword tells Surpac that it is not
mapping to an internal Surpac command but instead is going to run a Tcl script that is stored on the
hard disk. Notice the use of the logical MY_WORK: which will map to the actual directory path where
the macro is stored. This logical is assumed to be previously defined in logicals.ssi.
Surpac allows you to specify up to nine alias files.
To define an alias file in Surpac, choose Customise > Default Preference, select the Alias files folder and
enter the name of your alias file including any logical or physical directory name.
Page 12 of 89
Logicals, command aliases, and hotkeys Command alias
Note: Make sure you type exactly as shown, taking care with upper and lower case letters.
4. Choose File > Save As.
5. Navigate to the current work directory, and type hello.tcl for the file name, then click Save.
6. Choose File > New.
7. Now create a new command alias definition called HELLO that will run the script created in steps
2 and 3. Your alias definition in the editor should look as follows:
“HELLO” “MACRO:MY_WORK:hello.tcl”
Note: The MY_WORK: logical is the logical name created in the previous task. Using the
logical name as part of the alias definition means that the command will work from any
directory. If you do not use a logical the macro will work only if the current work directory is the
one the macro is stored in.
8. Choose File > Save As.
9. Leave the location as the current work directory, and type myCommands.txt for the file name,
then click Save.
Page 13 of 89
Logicals, command aliases, and hotkeys Keymaps
10. In Surpac, choose Customise > Default preferences. Then enter the full pathname to the alias
file you have created in steps 6 to 9.
11. Exit Surpac and then restart.
12. In the Function choose, type HELLO.
You should see the following output in the message window:
Tip: When defining alias commands to run scripts it is safer to make use of logicals as in the
example above.
Keymaps
The keymaps file is a historical file used in earlier versions of Surpac to map the keyboard keys to
characters. In Surpac, the only real purpose of the file is to define actions associated with the function
keys. You can use the keymaps file to define your own hotkeys to run scripts that you have written.
Using the csv example from the previous discussion of the alias, the following keymaps.ssi file extract
shows how to define hot keys on the F7 and F8 keys to run the import/export csv scripts.
Tip: When defining hot keys the key name must be in lowercase characters (for example, f10 not
F10).
Note: The MY_WORK: section is the logical name created in a previous task. Using the logical
name as part of the hotkey definition means that the command will work from any directory.
Otherwise the hotkey would work only if the macro is saved in the current work directory.
4. If you are running Surpac, exit and then restart.
5. Press F11.
You should see the following output in the message window:
Page 14 of 89
Creating menus and toolbars Invoking the menu and toolbar editor tool
Page 15 of 89
Creating menus and toolbars Creating your own menu items
You can attach any existing menu tree to this new menu using the copy and paste buttons.
The New, Edit, Copy, and Paste functions are also available on the shortcut menu, when you
right-click in this form.
Page 16 of 89
Creating menus and toolbars Creating your own menu items
Page 17 of 89
Creating menus and toolbars Creating a custom toolbar
3. Fill in the Create Toolbar Item form as shown, and click Apply.
Page 18 of 89
Creating menus and toolbars Summary
Input Description
Tips:
Icons that you link in with your buttons using the Image item are optimal at 24X24 pixel icon.
This is the standard for Surpac toolbar icons.
Toolbar buttons are far more effective when there is an associated ToolTip that will be displayed
when the mouse pointer is positioned over the button.
Summary
In this chapter you have been introduced to the toolbar and menubar editor. You were shown how to
create both menubars and toolbars. You should now know how to:
cut and paste items between menus and toolbars
Page 19 of 89
Recording tasks in a Tcl script Macro record
Macro record
The act of recording a series of steps that you perform in Surpac is a very simple operation. You just
need to click a button to start recording a macro, and then click that same button to finish recording.
When you start recording a macro you will be prompted to enter a name for the .tcl file. You can use a
new name to create a new file, or use an existing name to record over an existing script.
2. Type the name that you want to use for the macro, and click Apply.
A message is written to the message window stating that recording has started.
3. Perform the tasks you want to record.
Page 20 of 89
Recording tasks in a Tcl script Macro playback
Macro playback
Task: Playback the macro
After you have recorded your tasks, you will want to play them back.
Note: The ten fields to Define arguments for macro are provided for backward
compatibility with the superseded V3.2 macro language.
2. Click the Filename drop down to select the macro you want to play, and click Apply.
Page 21 of 89
Recording tasks in a Tcl script Structure of a Tcl macro
######################################################################
#
# Macro Name : c:/users/public/geovia/surpac/66/demo_data/createdtm.tcl
#
# Version : Surpac 6.6
#
# Creation Date :
#
# Description :
#
######################################################################
A recorded macro will always contain a header block at the top. This section of the script is non-
functional but describes the script name, version of Surpac that created it and the date recorded. There
is also a section for a description of the script. It is good practice to insert some comments about the
purpose of, or how to use, the use of the macro. This will make it easier if you or someone else ever
needs to modify the macro later.
The header block makes use of the Tcl comment character hash (#). If the first non-blank character on
the line is a hash then the Tcl interpreter ignores everything afterwards. You can include comments
throughout your scripts by adding lines that start with a hash. It is also good practice to include
comments through your script to describe what is happening at different points, especially for large
macros.
Page 22 of 89
Recording tasks in a Tcl script Structure of a Tcl macro
Following the header block are the actual functions that you performed while recording the macro. The
previous example shows how a Surpac function is recorded making use of the Scl extension command
SclFunction.
The SclFunction command takes two parameters, the Surpac function name and then any extra
information that is required by that particular function grouped by curly braces. A function that includes
interaction with a form will always be recorded with the form identifier (in the case above, frm00126)
followed by a list of the fields on the form and their entered values.
You don’t interact with all Surpac functions using forms. Some functions just require you to click the
appropriate button. For example, ZOOM ALL as shown in the following.
######################################################################
#
# Macro Name : c:/users/public/geovia/surpac/66/demo_data/2_zoom_all.tcl
#
# Version : Surpac 6.6
#
# Creation Date :
#
# Description :
#######################################################################
Other functions can be graphical in nature, and need you to input information using the mouse pointer.
For example, IDENTIFY POINT as shown in the following example.
######################################################################
#
# Macro Name : c:/users/public/geovia/surpac/66/demo_data/3_identify_point.tcl
#
# Version : Surpac 6.6
#
# Creation Date :
#
# Description :
#######################################################################
Page 23 of 89
Recording tasks in a Tcl script Structure of a Tcl macro
When you record a graphical function that consists of more than one point selection, the format of the
script is a little different to the previous example. The example below shows how the BEARING AND
DISTANCE function uses a tabular format to record the selected in a macro.
######################################################################
#
# Macro Name : c:/users/public/geovia/surpac/66/demo_data/4_bearing_and_distance.tcl
#
# Version : Surpac 6.6
#
# Creation Date :
#
# Description :
#
######################################################################
In Surpac 6 and later versions, a new style of function has been introduced that does not contain the
traditional form structure. The way that these functions appear in a macro is shown in the following
example, using the OPEN FILE function.
######################################################################
#
# Macro Name : c:/users/public/geovia/surpac/66/demo_data/5_open_file.tcl
#
# Version : Surpac 6.6
#
# Creation Date :
#
# Description :
#
######################################################################
Page 24 of 89
Recording tasks in a Tcl script SclFunction
SclFunction
The SclFunction command is a Surpac extension that provides the mechanics of invoking a function
from within your script. A call to the SclFunction command is recorded automatically by Surpac and it
would be unusual that you would ever hand code one.
Syntax
SclFunction FunctionName FunctionParameters
Where
FunctionName is the name of the Surpac function to execute, enclosed in double quotes
FunctionParameters are any further information that the Surpac function requires to run,
enclosed in curly braces
Return Values
Returns either the Scl constant SCL_OK, if the function ran correctly, or SCL_ERROR , if the
function failed to run, or did not run correctly
The function returns a value that will be stored in a variable called status. The status variable can then
be checked for success or failure. A later chapter will provide you with the skills to do check variables to
assess success or failure of a script.
Note: When recording macros, movements you perform with the mouse are not recorded. The
graphics viewer does not interface with the macro system. This means you cannot record things like
rotating data using the mouse. If you want to rotate data in your macro script, you can use the following
functions that are available from View > Rotate image submenu:
Orbit up
Orbit down
Orbit left
Orbit right
Roll left
Roll right
Page 25 of 89
Recording tasks in a Tcl script Using the _action switch
_action="apply" – This applies the form without displaying it, using the parameters recorded in
the macro.
Notes:
Page 26 of 89
Recording tasks in a Tcl script Using the _action switch
You must use the double quotes surrounding the keywords to the right of the equal.
The _action switch has no effect on the new style functions, such as OPEN FILE.
Another feature of the SclFunction command is that all of the parameters for fields on a form that are
not defined in your macro will take on the default value for that field when the macro plays. This stops
macros from crashing if there is a field that is not set for a function. So if in a later release of Surpac a
new field is added to a form, your macro will continue to work, using the default value for the new field.
For example, if your macro for CREATE DTM only included then fields for the location of the string file,
as shown in the following, the function would still run on playback with all of the other fields on the
form taking on default values.
Page 27 of 89
Recording tasks in a Tcl script Using the _action switch
Page 28 of 89
Recording tasks in a Tcl script Summary
Summary
In this chapter you learnt how to record macro scripts and how to play them back. You were introduced
to the SclFunction command, and you were shown how to use the _action switch to make your macros
more interactive and useful.
Page 29 of 89
Some required Tcl basics to get working What is Tcl?
What is Tcl?
Tcl is both a scripting language and an interpreter. As a scripting language, Tcl provides you with a
standard syntax, variables, flow control, and procedures. It is an extensible language that allows third
parties to add their own functionality.
As an interpreter, Tcl can be embedded into an application such as Surpac. Many other software
vendors worldwide have also adopted Tcl as an embedded scripting language. The function of the
interpreter is to process scripts line by line to produce a result.
Tcl is public domain software that is freely available and can be used in commercial applications. It is
available on a number of platforms including Windows NT/98/2000/Vista/7, Unix varieties, and
Macintosh.
What is Scl?
Scl commands are extensions to the Tcl interpreter that give you great flexibility in your scripts to
manipulate both the externals and internals of Surpac. Using Scl commands, you can:
Page 30 of 89
Some required Tcl basics to get working Tcl Syntax
Tcl Syntax
The language syntax used to write Tcl is quite simple. A generic statement in Tcl would be;
Syntax
command parameter1 parameter2 …
Where
Command is the name of a Tcl internal command or defined procedure
Parameter1, and all subsequent parameters, are optional
Note: The parameters that you define for a command will depend on the requirements of the
command.
Commands and parameters are separated by white space. The end of line signifies the end of the
command’s arguments. If the command and arguments run over two or more lines, use a backslash
character (\) to continue the command over onto the next line. You can insert comments in Tcl by using
the hash character (#) as the first non-white-space character on a line.
Commands
Everything that causes the Tcl interpreter to do something is a command. Each new line in a Tcl script
begins with a command. Commands can have optional parameters; the number and type of parameters
depend on the specified command.
Two commands that you will use frequently are the set and put commands.
set
The set command is used to create variables in your script. A variable is simply a named location in
memory used to store information. Think of a variable as a bucket that contains something
(information) with a label on the front (its name) that you can use to identify it from other buckets. The
syntax for set is as follows.
Syntax
set varName value
Where
varName is the name you want to call the variable
value is the value assigned to the variable
Examples
set tableName assay
set dip 49.5
set sectionName temp_sec
Page 31 of 89
Some required Tcl basics to get working Variables and substitution
puts
The puts command is used to print messages to the Surpac message window. It takes one argument,
which is the message to print.
Syntax
puts message
Where
message is the text and/or variables to print to the message window
Example
puts “Hello Surpac user”
puts “The DB table being reported is $tableName”
To substitute a variable for the information contained within it, prefix the name of the variable with the
dollar character ($). The following example outputs the of the variable sectionNumber to the message
window
puts “The current section is $sectionNumber”
Executing this command in Surpac results in the following text being displayed in the message window:
Page 32 of 89
Some required Tcl basics to get working Grouping constructs
Grouping constructs
The previous example demonstrated the first grouping construct. Double quotation marks (“ ”) are used
to group string tokens together and have them treated as one autonomous object.
The puts command (as used in the example) expects one argument, the text to write to the message
window. If the double quotes were not used in the example, puts would be given six parameters instead
of one, because white space is used to separate parameters.
The other grouping construct used in Tcl is curly braces ({ }). The difference between curly braces and
double quotes as grouping constructs is that double quotes permit variable substitution, and further
command processing, and curly braces do not.
If we change the puts example to use curly braces then
set sectionNumber “6800”
puts {The current section is $sectionNumber}
Command substitution
Only the first token encountered on a line is treated as a Tcl command. Sometimes you will have to
execute another Tcl command as part of an original Tcl command. This will become obvious in examples
later in this tutorial.
To execute a command as part of another command you enclose the secondary command in square
brackets ([ ]). Whenever you want to get the result of a command and use it as a parameter to another
command you use square brackets.
set drillholeId “rc0001”
puts “Drill Hole ID = [string toupper $drillholeid]”
This will result in the message below being written to the message window.
Note: The “string toupper” command used in the previous example will be explained in a later topic
in this tutorial.
Another example:
set number 100
set new_number [expr $number * 10]
puts “The new number is $new_number”
This will result in the message below being written to the message window.
Page 33 of 89
Some required Tcl basics to get working Summary
Note: The “expr” command used in the previous example will be explained in a later topic in this
tutorial.
Summary
In this chapter you learnt some Tcl basics in the areas of:
syntax
variables
variable substitution
grouping using double quotes and curly braces
command substitution.
You should now be able to record scripts and make useful adjustments to the scripts.
Page 34 of 89
Creating user forms for scripts Guido
Guido
Guido commands are Surpac extensions to the Tcl interpreter.
There are two types of GUIDO commands, Guido container objects and Guido widgets. A Guido
container object consists of other Guido objects. A container can contain other containers, widgets, or
both other containers and widgets. A container object is used to organise the layout and appearance of
your form. A Guido widget is an object that is used to retrieve information from a user.
GuidoForm GuidoField
GuidoPanel GuidoComboBox
GuidoScrollPane GuidoCheckBox
GuidoTable GuidoRadioButton
GuidoTabbedPane GuidoButtonGroupPanel
GuidoFileBrowserField
Page 35 of 89
Creating user forms for scripts Guido command syntax
Syntax
GuidoCommand name commandBody
Where
GuidoCommand is the name of the actual Guido command
name is the name you have assigned to the Guido command (like a variable name)
Note: This name will be used to reference the command later to retrieve data that is entered
into it.
commandBody is enclosed in braces and will contain all switches used to define the look of the
Guido widget or container on the form
Note: If the command is a Guido container, the other Guido commands will also be contained
within these braces.
Page 36 of 89
Creating user forms for scripts Guido command switches
Switch Description
Page 37 of 89
Creating user forms for scripts GuidoForm
GuidoForm
The GuidoForm command is used to define a form that will contain any number of containers and
widgets.
Switch Description
-default_buttons Place the standard Apply, Cancel and Help buttons on the form
Example
GuidoForm form {
-label “An Example Form”
-default_buttons
-defaults_key abc_mines
# insert other guido objects here
}
SclCreateGuidoForm
The SclCreateGuidoForm function will turn a Guido form definition into a computer representation in
memory, so that it is ready to be displayed on the screen.
Syntax
SclCreateGuidoForm FormHandle FormDefinition Body
Where
FormHandle is a named variable that you use to make reference to the created form
FormDefinition is usually the variable name that contains the actual form definition
For example, $myForm. It can also be the name of an external file that contains the definition
prefixed with the at character (@). For example, @section_form.tcl.
Body is the command body
It can contain statements to set default values for form fields. It is usually a pair of curly braces {}.
Return Values
SCL_OK if the function creates the form object with no error
SCL_ERROR if something goes wrong
Example
An example that will create a form from the definition stored in a Tcl variable named sectionForm.
Page 38 of 89
Creating user forms for scripts SclRun
An example that will create a form from the definition stored within a file called gradecontrol.frm.
SclCreateGuidoForm form_handle @gradecontrol.frm {}
SclRun
The SclRun command will display and execute a Guido form that has previously been created with the
SclCreateGuidoFormCommand.
Syntax
FormHandle SclRun Body
Where
FormHandle is the named variable that you use to reference the form created with the
SclCreateGuidoForm command
Body is the command body can contain extra statements
It is usually enclosed by a pair of curly braces {}.
Return Values
SCL_OK if the function creates the form object with no error
SCL_ERROR if something goes wrong
Example
$section_form SclRun {}
The SclRun command creates a Tcl variable for each Guido widget defined on the form except if the user
clicks the Cancel button. The variables created use the same name as was defined for each Guido widget
in the form definition.
A special variable with the name _status is created by the SclRun command with a value that represents
the button that was clicked to dismiss the form. For example, if the Apply button is clicked, _status will
have the value apply. Whereas, if the Cancel button is clicked, _status will have the value cancel.
The following example code segment allows you to test to see if the user clicked Cancel, and, if so, to
exit the script gracefully.
$grade_control_form SclRun {}
if {“$_status” == “cancel”} {
return
}
Note: The “if” statement and “return” statement are discussed in topics later in this tutorial.
Page 39 of 89
Creating user forms for scripts Tying Guido together with the Scl form functions
set form_def {
GuidoForm form {
-label "My First Form"
-default_buttons
-defaults_key “my_form”
}
}
Note: The actual form definition is stored into a Tcl variable called form_def. This is the usual
way to define a form, but you can also define a form in an external file, and then specify the
external file to SclCreateGuidoForm command using the at character (@). The following code
sample shows what you would write to create a form using a definition stored in a file called
my_form.tcl.
SclCreateGuidoForm form_handle @my_form.tcl {}
Page 40 of 89
Creating user forms for scripts GuidoField
GuidoField
A GuidoField is the most common Guido widget you will use. It will accept input that the user will type
at the keyboard. It can contain all the various switches described previously to setup labels, field widths,
and validation criteria.
set form_def {
GuidoForm form {
-label "GuidoField Form"
-default_buttons
GuidoField number {
-label "Enter a real number"
-format double
-width 10
-low_bound 0
-high_bound 100
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 41 of 89
Creating user forms for scripts GuidoField
The form will not apply if the number does not fit the validation criteria that were set in the
definition.
7. Type a number inside the range 0 and 100, and click Apply.
Because of the final line of the script using the ‘puts’ command the message, The number is
80, is written to the message window.
Page 42 of 89
Creating user forms for scripts GuidoComboBox
GuidoComboBox
A GuidoComboBox is similar to a field. The difference is that you can provide a set of values that the
user can choose from, as a drop-down list. GuidoComboBoxes can be exclusive or non-exclusive.
Exclusive combo boxes allow only an entry from the list, non-exclusive combo boxes allow the user to
enter any value, so long as it meets the validation criteria.
Any of the switches described previously can be used on a GuidoComboBox. There are also some
special switches that can only be used with combo boxes.
Switch Description
-exclusive If true, only values from the list can be selected. If false, any
value will only allow values to be selected from the list
otherwise any text can be entered
-value_in Specify a list of space separated values. If a particular value
contains spaces then enclose it in double quotes
set form_def {
GuidoForm form {
-label "GuidoComboBox Form"
-default_buttons
GuidoComboBox plot_size {
-label "Select the plot size"
-width 10
-null false
-exclusive true
-value_in A0 A1 A2 A3 A4
}
}
}
Page 43 of 89
Creating user forms for scripts GuidoComboBox
6. Type a value that was not in the list and press Apply.
Because you set exclusive to true, the form cannot be applied with a value other than those
available in the drop-down list.
Page 44 of 89
Creating user forms for scripts GuidoCheckBox
GuidoCheckBox
A GuidoCheckBox is a widget that is used to select one of two possible states, for example, yes/no,
on/off up/down. When the check box is selected it will return the text true and when cleared it will
return the text false. These default values can be changed using switches.
Switch Description
set form_def {
GuidoForm form {
-label "GuidoCheckBox Form"
-default_buttons
GuidoCheckBox save_on_exit {
-label "Save file on exit"
-height 1
-caption yes
-selected_value yes
-unselected_value no
}
}
}
Page 45 of 89
Creating user forms for scripts GuidoCheckBox
Tip: If you specify –height 1 when you define your check box, the box will line up correctly with its
label.
Page 46 of 89
Creating user forms for scripts GuidoRadioButton and GuidoButtonGroupPanel
Switch Description
set form_def {
GuidoForm form {
-label "GuidoButtonGroup Form"
-default_buttons
GuidoButtonGroupPanel section_direction {
-label "Section direction"
GuidoRadioButton button1 {
-caption "North"
-height 1
-selected_value "north"
}
GuidoRadioButton button2 {
-caption "South"
-height 1
-selected_value "south"
}
}
}
Page 47 of 89
Creating user forms for scripts GuidoRadioButton and GuidoButtonGroupPanel
You can select only one button or the other, not both.
6. Select North, and click Apply.
Section direction north is written to the message window. The reference in the macro to
GuidoButtonGroup means the message will return with north or south depending on which
button you select.
Tip: If you specify –height 1 when you define your radio button, the button will line up correctly with
its label.
Page 48 of 89
Creating user forms for scripts GuidoFileBrowserField
GuidoFileBrowserField
A GuidoFileBrowserField is a special purpose widget that you can use to ask the user to type or select a
valid filename. The field looks like a combo box, and a user can type in a filename for the working
directory. However, if the user clicks on the drop-down arrow, a file chooser widget is invoked, which
allows the user to navigate within folders on their computer to select a file. There are a number of
switches associated with file browsers.
Switch Description
-file_access Specify the access of the selected file, this can be read, write, or
exist
-file_mask Specify a file mask, for example, *.* or *.tcl
-start_dir Specify a default directory to begin the browser in
-multiple_selection Specify that you wish to select more than one filename in the
browser
-link Link this field to another field that will contain the id part of the
filename when using location and id
-extension Specify if you want the file extension trimmed off the return
name, this can be true or false
set form_def {
GuidoForm form {
-label "GuidoFileBrowserField Form"
-default_buttons
GuidoFileBrowserField csv_filename {
-label "Filename"
-width 25
-file_mask "*.csv *.txt"
-file_access read
-format none
-translate lower
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
Page 49 of 89
Creating user forms for scripts GuidoFileBrowserField
$form_handle SclRun {}
puts "File name is $csv_filename"
Page 50 of 89
Creating user forms for scripts GuidoLabel
GuidoLabel
A GuidoLabel is not a true widget but it does relate to the widgets, and it is appropriate to discuss how
to use it along with how to use widgets. A GuidoLabel is used to put a text or informational messages
onto your form to help users understand your macro.
set form_def {
GuidoForm form {
-label "Example Form"
-default_buttons
GuidoLabel info {
-label "Some information message"
}
}
}
Page 51 of 89
Creating user forms for scripts Dependencies in Guido
Dependencies in Guido
Any Guido object can contain a dependency switch. A dependency will make a particular widget or
container dependent upon the value of another widget on the form. The effect of a dependency is to
turn the dependant object on or off. When Guido Widgets are turned off (that is, their dependency
condition is false) they appear greyed out. When GuidoPanels are turned off they become invisible as
does everything that is contained within them.
set form_def {
GuidoForm form {
-label "Dependency Form"
-default_buttons
GuidoCheckBox plotting {
-label "Plot after processing?"
-caption yes
-selected_value yes
-unselected_value no
}
GuidoButtonGroupPanel plotSize {
-label "Plot size"
GuidoRadioButton radioButton1 {
-caption "A0 plot"
-height 1
-selected_value A0
-dependency {"[$plotting getCurrentValue]" == "yes"}
}
GuidoRadioButton radioButton2 {
-caption "A4 plot"
-height 1
-selected_value A4
-dependency {"[$plotting getCurrentValue]" == "yes"}
}
}
}
}
Page 52 of 89
Creating user forms for scripts Summary
Note: When you select the check box the radio buttons for plot size will appear as normal,
when you clear the check box the radio buttons are greyed out.
Summary
In this chapter you were introduced to some of the Guido widgets that you can use to get input from the
user. You were shown how to turn your form definition into a computer representation using the
SclCreateGuidoForm function, and how to interact with the user using the SclRun function. You were
shown how to access the inputs made by users on a form.
Page 53 of 89
Automating a recorded script Summary
Page 54 of 89
Automating a recorded script Summary
Page 55 of 89
Automating a recorded script Summary
All fields should have appropriate validation settings for format and nulls. The input location is a
file browser field linked to the id. Inserting the following form definition code at line 1 of the
script, prior to the recorded section, will produce this form.
set adjustCoordsForm {
GuidoForm adjustCoordsForm {
-label "Adjust Coordinates"
-default_buttons
GuidoFileBrowserField in_location {
-label "Input location"
-width 20
-format none
-null false
-file_mask "*.str"
-link in_id
}
GuidoField in_id {
-label "Id"
-format float
-null false
}
GuidoField out_location {
-label "Output location"
-width 20
-format none
-null false
}
GuidoField adjust_x {
-label "Adjust X"
-format float
-null false
-default 0
}
GuidoField adjust_y {
-label "Adjust Y"
-format float
-null false
-default 0
}
GuidoField adjust_z {
-label "Adjust Z"
-format float
-null false
-default 0
}
}
}
# create and display the form
SclCreateGuidoForm adjustCoordsFormHandle $adjustCoordsForm
{}
$adjustCoordsFormHandle SclRun {}
Page 56 of 89
Automating a recorded script Summary
The final step will remove the hard coded values as were saved into the SclFunction when you
recorded the macro, and replace them with the appropriate variables from the GuidoForm.
9. Edit the macro again and modify the SclFunction statement to look like the following.
11. In Surpac, drag 19_adjust_coordinates.tcl into Graphics, and make sure it runs as expected.
Note: To test the completed macro, open pit1.str in Graphics, then drag the macro into
Graphics, and then drag the output file into Graphics. You should see that the new file is
‘shifted’ by the values that you entered on your form.
Summary
This application shows how easy it is to automate a mundane task that is performed regularly. It is far
easier to use the script than it is to remember the syntax required by the string maths function. You
could easily modify this script to perform another string maths function that you perform frequently.
Page 57 of 89
A better way to select points in graphics The SclSelectPoint function
Syntax
SclSelectPoint handle prompt layer stringNo segNo pointNo x y z desc
Where
Handle is a returned reference variable that you can use to modify the selected point using other
Scl extension functions
Note: How to modify a selected point using other functions is not covered in this tutorial.
Prompt is any text that you want to appear on the screen to ask the user to select something
Layer is a variable into which the layer name of the selected point is returned
stringNo is a variable into which the string number of the selected point is returned
segNo is a variable into which the segment number of the selected point is returned
pntNo is a variable into which the point number of the selected point is returned
x y z are variables into which the x, y, and z coordinates of the selected point are returned
desc is a variable into which the entire description field of the selected point is returned
Return values
Returns either the Scl constant SCL_OK or SCL_ERROR depending on whether the script runs
successfully or fails
Note: The backslash ( \ ) used on line 1 of the example is a continuation character to extend
line 1 onto line 2. In your example you can combine lines 1 and 2 onto the same line.
Page 58 of 89
A better way to select points in graphics Piping point data back into Surpac
Task: Use SclSelectPoint and then pass xyz values back to Surpac
1. In Surpac, open pit1.str in Graphics.
2. Click Start/end recording an SCL script.
3. In Filename, type 21_bearing_and_distance, and click Apply.
4. Choose Inquire > Bearing and distance between two points.
5. Choose two points in Graphics.
6. Press ESC.
7. Click Start/end recording an SCL script.
8. Drag 21_bearing_and_distance.tcl into Graphics.
It performs the same bearing and distance calculation, then exits.
9. Open ConTEXT.
10. Choose File > Open, and select 21_bearing_and_distance.tcl.
11. Edit the script to use the _action=”display” switch.
Note: If you cannot remember where to insert this switch refer back to the earlier chapter of
this tutorial.
12. In Surpac, in the Navigator, right-click the working folder and click Refresh.
13. Drag 21_bearing_and_distance.tcl into Graphics.
You can now select any points for the bearing and distance calculation, and the script returns to
the selection cycle instead of exiting.
14. In ConTEXT, modify the script so that it looks like the following.
Page 59 of 89
A better way to select points in graphics Summary
Note: The backslashes ( \ ) used the example are continuation characters to extend a line
onto the next line. In your example you can combine these lines together.
15. Choose File > Save.
16. In Surpac, in the Navigator, right-click the working folder and click Refresh.
17. Drag 21_bearing_and_distance.tcl into Graphics.
You can now select any points for the bearing and distance calculation, and the script exits the
bearing and distance function after your selection.
Summary
In this chapter you have learnt how to use the SclSelectPoint function to better handle recorded Surpac
graphics functions.
Page 60 of 89
Useful Tcl commands Working with numbers
set i 0
incr i
puts $i
set section 1000
incr section 100
puts $section
set counter 100
incr counter -10
puts $counter
Page 61 of 89
Useful Tcl commands Working with numbers
1
1100
90
Operator Meaning
Function Description
abs(arg) Returns the absolute value of arg. Arg may be either integer or floating-point,
and the result is returned in the same form
double(arg) If arg is a floating value, returns arg, otherwise converts arg to floating and
returns the converted value.
int(arg) If arg is an integer value, returns arg, otherwise converts arg to integer by
truncation and returns the converted value.
rand() Returns a floating point number from zero to just less than one or, in
mathematical terms, the range [0,1). The seed comes from the internal clock of
the machine or may be set manual with the srand function.
round(arg) If arg is an integer value, returns arg, otherwise converts arg to integer by
rounding and returns the converted value.
srand(arg) The arg, which must be an integer, is used to reset the seed for the random
number generator. Returns the first random number from that seed.
Page 62 of 89
Useful Tcl commands Working with numbers
set x1 1000
set y1 1000
set x2 2000
set y2 2000
-1000
1000
1414.21356237
Page 63 of 89
Useful Tcl commands Working with numbers
exponential functions
conversion functions
numeric constant functions
random number generation functions
datetime functions
miscellaneous functions
Note: For further information about these expressions see the Surpac help.
set rad 3
set cos_radians [SclExpr COS($rad)]
puts $cos_radians
-0.9899924966004454
171.88733853924697
-0.9899924966004454
-0.990
Page 64 of 89
Useful Tcl commands Working with text strings
string length
string index
string first
string range
string trim
string tolower
string toupper
13
Page 65 of 89
Useful Tcl commands Working with text strings
2
9
3
8
Page 66 of 89
Useful Tcl commands Working with text strings
123
789
Page 67 of 89
Useful Tcl commands Working with text strings
456
456
ore grade
ORE GRADE
Page 68 of 89
Useful Tcl commands Working with the File System
Page 69 of 89
Useful Tcl commands Working with the File System
Page 70 of 89
Useful Tcl commands Working with the File System
in temp
removed temp
Summary
In this chapter you have learnt some native Tcl commands to use when you write scripts. You can now:
perform mathematical expressions
manipulate strings
interact with the file system including using wildcards
Page 72 of 89
Basic flow control in Tcl Boolean expressions
Boolean expressions
Flow control constructs, for example, branching to a section of code or repeating a number of
commands, are based on a conditional test. An example of this construction in English is:
“If the user selected to plot then perform the plotting code”
The keywords in the example are if and then; they describe some action. The “user selected to plot” is
the condition or test criteria that determines whether the plotting code is executed. This condition can
evaluate to only true or false. Another example:
“While there is another section number continue processing sections”
The keywords in this example are while and continue. The “is another section number” is the condition
or test that determines if the software will continue extracting sections. Again, this test can only
evaluate to true or false.
A Boolean expression is an expression that can result in only one of two possible outcomes that are true
or false. The outcomes are based on testing something, whether it be comparing simple numbers or
text strings, or some complicated arithmetic expression, or even combinations of numbers, text, and
arithmetic.
When you write a Boolean expression it is best to sound out what you are trying to test for in English
first. This helps you make sure you have your logic correct.
Common operators you can use to write Boolean expressions (grouped by decreasing precedence)
&& (and)
True False
True true false
False false false
|| (or)
True False
True true true
Note: The actual representation in Tcl for false is 0 and for true is anything but 0.
Page 74 of 89
Basic flow control in Tcl The if Command
The if Command
The Tcl if statement is used to branch to a section of code to be executed based on a Boolean
expression. There are four possible forms of the if command.
set form_def {
GuidoForm form {
-label "GuidoField Form"
-default_buttons
GuidoField bearing {
-label "Enter a bearing"
-format float
-width 10
-low_bound 0
-high_bound 360
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 75 of 89
Basic flow control in Tcl The if Command
GuidoField bearing {
-label "Enter a bearing"
-format float
-width 10
-low_bound 0
-high_bound 360
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 76 of 89
Basic flow control in Tcl The if Command
set form_def {
GuidoForm form {
-label "GuidoField Form"
-default_buttons
GuidoField bearing {
-label "Enter a bearing"
-format float
-width 10
-low_bound 0
-high_bound 360
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 77 of 89
Basic flow control in Tcl The if Command
GuidoField bearing {
-label "Enter a bearing"
-format float
-width 10
-low_bound 0
-high_bound 360
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 78 of 89
Basic flow control in Tcl while {expression} {commands}
d1
d2
d3
d4
d5
Page 79 of 89
Basic flow control in Tcl for {start} {expression} {next} {commands}
Note: The incr command used in the example adds 1 to the variable count. incr can take a second
parameter such as incr count –1 which will be added to the variable. This is useful when you need to
loop backwards.
Page 80 of 89
Basic flow control in Tcl Changing loop behaviour with continue and break
# loop forever
while {1} {
# select a point from the graphics viewport
set status \
[SclSelectPoint point "Select a point (Esc 2 exit)" \
layer str_No seg_no pnt_no x y z desc]
if {$status != $SCL_OK} {
# if user pressed escape exit the loop
break
}
Summary
In this chapter you have learnt about the basic flow control structures of Tcl. You can now create simple
scripts that can perform conditional tests on variables and branch or loop depending upon these tests.
Page 81 of 89
Manipulating Surpac ranges with Scl SclRangeExpand
SclRangeExpand
The SclRangeExpand command takes a Surpac range specification like “100, 200, 10” and then expands
it out into its individual components in memory. Once a range specification has been expanded in
memory you can access information on it using the other SclRange functions.
Syntax
SclRangeExpand RangeHandle RangeExpression
Where
RangeHandle is a reference variable that you will use to access the expanded range
For example, secRange, inputRange, and fileld.
RangeExpression is the actual range that is being expanded i.e. 1000, 2000, 100
Return Values
SCL_OK if the function creates the form object with no error
SCL_ERROR if something goes wrong
For example, the range specification 1000, 2000, 100 would expand into the following series of values in
memory:
1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000
SclRangeGetCount
The SclRangeGetCount command will get a count of the number of items in a range that has been
expanded in memory using the SclRangeExpand function.
Syntax
SclRangeGetCount RangeHandle
Where
RangeHandle is the reference handle (variable) that was created after performing
SclRangeExpand For example, $secRange, $inputRange, and $fileIds.
Return Values
SCL_OK if the function creates the form object with no error
SCL_ERROR if something goes wrong
In the previous example the returned range count would be 11 for the range 1000, 2000, 100.
Page 82 of 89
Manipulating Surpac ranges with Scl SclRangeGet
SclRangeGet
The SclRangeGet command will get a range value at the specified position in a range, which has been
expanded in memory using the SclRangeExpand function.
Syntax
SclRangeGet RangeHandle RangePosition RangeValue
Where
RangeHandle is the reference handle (variable) that was created after performing
SclRangeExpand For example, $secRange, $inputRange, and $fileIds.
RangePosition is the position in the range to get the value for
Note: The first item in the range is at position 0.
RangeValue is the name of a variable to store the range value into
For example, secNum, Id, and bench. If the variable doesn’t exist it is created.
Return Values
SCL_OK if the function creates the form object with no error
SCL_ERROR if something goes wrong
Note: The range position starts at zero and not one. The following example uses the range 1000,
2000, 100.
0th 1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
1000 1100 1200 1300 1400 1500 1600 1700 1800 1900 2000
Page 83 of 89
Manipulating Surpac ranges with Scl Summary
6. In ConTEXT, add a form that will get any value for the sec_range variable to the beginning of the
script.
Note: You can use the following code sample to add this form.
set form_def {
GuidoForm form {
-label "Surpac Ranges"
-default_buttons
GuidoField sec_range {
-label "Enter a range"
-format range
-width 20
-null false
}
}
}
SclCreateGuidoForm form_handle $form_def {}
$form_handle SclRun {}
Page 84 of 89
Manipulating Surpac ranges with Scl Summary
Summary
In this chapter you learnt about Scl commands that you can use to manipulate Surpac ranges. The basic
range template will handle any Surpac range the user inputs, regardless of whether the range is
uniform, non-uniform, or both.
Page 85 of 89
File input and output – reading and writing files Opening and closing files
Examples
set read_file [open “datafile.dat” “r”]
set write_file [open “newfile.dat” “w”]
Note: Note that the open command returns a reference value that you store into a variable. You use
this variable to later refer to the opened file with other Tcl commands that you use to access the file.
Examples
close $read_file
close $write_file
Page 86 of 89
File input and output – reading and writing files Writing to a file
Examples
gets $read_file line
gets $input_file inputData
Note: With the examples above the actual data is placed into memory variables called line and
inputData.
Example
gets $read_file line
while {![eof $read_file} {
# file processing stuff
gets $read_file line
}
Writing to a file
There are two Tcl commands that you can use to write to files, called puts and write. The write
command is more advanced and allows block input/output. The puts command is simple and outputs a
single line. You have already used the puts command for writing to the message window. You can also
use the puts command to write a line to a file that has been opened for writing.
Examples
puts $write_file “some text to write to the file”
puts $write_file “$processedData”
Page 87 of 89
File input and output – reading and writing files A file-processing template
A file-processing template
The commands discussed previously in this tutorial are all you need to write simple file processing
scripts. The following example gives you a template that you can base most of your scripts on. It opens
one file for reading, one for writing, reads each line from the read file, and writes the lines to the new
file for writing, and closes both files.
Summary
In this chapter you have learnt about the basic commands for performing file input/output. You now
have a basic file processing template to use in your scripts.
Page 88 of 89
Tcl references Surpac help
Tcl references
Surpac help
Surpac includes a complete Tcl on-line reference manual that describes each of the Tcl commands in
detail. It also includes a complete Scl and GUIDO reference manual, with code samples to demonstrate
how you can use each of the Scl commands.
Text books
Practical Programming in Tcl and Tk
Brent Welch. Prentice Hall, 1999. 3rd Ed
ISBN: 0-13-022028-0.
WWW resources
There are many internet sites dedicated to the Tcl language, a number of which offer Tcl solutions. The
Scriptics site is a good place to begin, and it contains a link page to a number of other resources.
http://www.tcl.tk http://dev.scriptics.com/resource/community/websites/
The mine solutions initiative is dedicated to promoting third party Surpac developments. It contains
resources, and tips and tricks for using Tcl/Scl. vComp Pty Ltd manages the development and associated
web site.
www.minesolutions.com [email protected]
The GEOVIA software and GEOVIA support web sites provide links to a number of third party Tcl
resources, as well as free scripts for download.
http://www.3ds.com/GEOVIA www.GEOVIAsupport.com
Page 89 of 89