Chapter 4

LEARNING THE
MACRO PROGRAMMING LANGUAGE

Being able to record a series of keystrokes for later recall is power enough, but WordPerfect's macro feature also includes a method of programming your macros so that they behave like stand-alone applications.

With just a little bit of ingenuity, you can create macros that create, from scratch, a complete invoice for services or products, an electronic while-you-were-out telephone note pad, a note pad, mini calculator, a self-testing and scoring quiz game, a text adventure game, and much, much more. In short, there is almost no limit to what you an do with WordPerfect's macro programming language.

This chapter explains how how to access the programming feature and the meaning of the various programming commands or instructions. This chapter does not delve too deeply in actually employing the various programming commands in real macros -- the rest of the book is devoted to that. If you are serious about macro programming, be sure to also read Part Three of this book. The chapters in this section provide additional insights on applying the macro programming language, as well as how to avoid its frustrating pitfalls.

 

THINKING LIKE A PROGRAMMER

Although you don't need any previous training or experience at computer programming to master WordPerfect's programming language, it does help. At the very least, you should learn how to think like a programmer.

It is not the intent of this book to teach programming principles; that would require far too much space. However, you can gain a good grasp of programming fundamentals by concentrating on 10 main areas of macro design:

Let's take a closer look at each.


Going With the Flow

Simple, one-function macros can be created without a blueprint or flow chart but you should give extra thought and consideration to macros that are more complex in nature. You may find it helpful to draw a programming flow chart that includes the basic steps of the macro. In each box is a complete step; arrows connect the boxes to indicate the progress of steps throughout the macro. Flow charts are particularly handy when creating chained and nested macros, or macros that consists of many self-contained routines, because the drawing helps you visualize the function and flow of each macro.

While you are planning the macro, note the steps required to create it. On a scrap document, go through the motions of executing the macro -- but don't record it just yet. On a piece of paper, note the commands and menu options you choose to complete the task. Don't forget the [Enter]key, as well as all other keys you must press to make the macro work properly. Be sure to note each time you press it. When you think you have the procedure mapped out, define the macro and record it.

If you make a mistake, you can either cancel the recording by pressing [Ctrl]-[F10] again or edit out the errors later. Small mistakes usually make no difference, but you'll want to get into the habit of cleaning up your macros once you have created them.

After defining the macro, try it out to make sure it works the way you originally planned. If you spot a mistake, double-check the steps you took and redefine the macro.


The Benefit of Routines

One of the first things a programmer does when he or she starts on a project is to map out the individual segments, or routines, that make up the software. Even the longest, most complex program -- and this includes macros -- consist of little more than bite-size routines. The macro progresses from one routine to the next in an orderly and logical fashion.

What's a routine? A routine is any self-contained segment of code that performs a basic action. In the context of macros, a routine can be a single command or character of text, or it can take up the majority of a mammoth 20K macro. Suppose your macro resets the active printer, formats the document to legal size, and prints it. The macro can be divided into three distinct routines:

While there's no need to physically separate these routines within a macro, or even create separate macros and chain to each one in turn (although this can be done, as explained in Chapter 2), it helps to think of the macro as being composed of these more basic parts. If the macro doesn't work properly, you can more easily analyze the problem if you can narrow it down to a specific segment of the code. For example, if the macro is resetting the active printer and printing the document, but not properly formatting the document to legal size, you can readily trace the problem to the number 2 routine.

Many macros simply start at the beginning and advance one step at a time to the end, taking each instruction in turn and acting upon it. This is the approach of our example macro just cited.

But some WordPerfect macros jump around. They may start with routine 1, but then jump to routine 3, back to 1, then move on to 2. Jumping around within the macro pays off when you need to re-use a routine two or more times. Instead of repeating the steps of the routine each time, you can simply direct the macro to repeat the same routine. All it takes is a single command, which you'll learn about later in this chapter.

Here's another benefit of working with discrete routines. Depending on the application of the macro, it may behave one way when used with a particular type of document, and behave in a totally different way with another document. This concept may take some time to get used to, but it lends a great deal of power and flexibility to your macros. Instead of your macros conforming to a strict procedure, they are free to interact and adapt with your documents. In other words, your macros are "intelligent," automatically adapting to the situation and document at hand.

WordPerfect macros don't use line numbers, as found on some other programming languages, such as BASIC. You identify routines by name, or label. When you instruct WordPerfect to jump from one routine to another, you tell it which label to go to. Of course, if your macro is designed to go from beginning to end without stopping, you don't need labels, but it's still a good idea to think of the construction of the macro as discrete routines.


Subroutines

Subroutines are similar to routines, but are specifically designed to be used by the macro as a sub-component. Most often, subroutines are activated only when certain criteria exists -- an error occurs or a search fails, for instance. These are routines that the macro branches off to temporarily, in order to accomplish some task or to wait until a certain condition is met. When the subroutine ends, the macro jumps back to where it left off.

Like a routine, a subroutine consists of a label (so the macro can find it), but it also has a return identifier. The return marks the end of the subroutine, and instructs the macro to go back to where it first left off.


Variables

A variable is a special holding tank for information, sort of a placeholder. WordPerfect has three types of variables, numbered, named, and internal.

Numbered variables, a hold-over from version 5.0 of WordPerfect, are identified by a single-digit number, from 0 to 9. You can access these numbered variables at any spot within WordPerfect by pressing a number with the [Alt] key. For instance, suppose you've previously assigned the text

Hello there

to variable 4. Press [Alt]-4 and WordPerfect types "Hello there" at the cursor.

You'll have plenty of cause to use variables in more sophisticated programmed macros, but you can also use the feature to create up to 10 more temporary macros (in addition to the one that you can create with the [Enter] key). The limitations of variables is that they can contain numbers and text only, making them best suited for adding boilerplate text. Unless you use more sophisticated programming, you can't code them with commands, cursor movements, or other keyboard functions.

WordPerfect macros also support named variables. These are variables you assign within the macro editor, and are used to "remember" a piece of vital information so that it can be used elsewhere in the macro, or even in another macro.

Internal variables are variables generated by WordPerfect and reflect certain operating characteristics or states. For example, one internal variable keeps track of the current page number; another contains the absolute position of the cursor on the page.


Expressions

The term expressions, as used in WordPerfect macros, is a programmer's word that means pretty much what it means to the rest of the world. You'll be seeing the word many times throughout this book, so it's a good idea to learn how it relates to macro programming.

An expression is a procedure a WordPerfect macro must follow to complete a task you've given it. Sometimes the expression is a simple variable -- "take the contents of this variable and apply it to that command." Often times, the expression is a little more complex, like take the number already in a variable, and add another one to it.

When you ask a WordPerfect macro to perform some type of calculation or thinking process, you're asking it to evaluate the expression. For example, if the expression reads "1+1," then the macro must first evaluate it (add one and one to make two) before proceeding.

Some more advanced macro expressions may appear exotic, but you'll have plenty of chance to use them. The most common is the evaluating if a statement is TRUE or FALSE (the words TRUE or FALSE are capitalized, to show you we're dealing with logical functions). Here's a good example of a TRUE/FALSE expression that must be evaluated by the macro:

IF variable 1 = 10 THEN QUIT

In reading the expression (which isn't in acceptable macro notation, by the way, but it's close), it reads "IF the contents of variable 1 is equal to 10, then stop." Before proceeding with the remainder of the macro, WordPerfect must pause, take a peek inside variable 1, and apply it to the logical equation. If the result is TRUE, then the macro ends. If it's FALSE (variable 1 has a number other than 10), then something else happens.


Strings

A common term in programming circles is the string. A string is simply a sequence of alphabet or number keys. In the context of macros, strings are used in variables. Once stored in a variable, the string can be acted upon by the macro.

For example, if the string is a number, you can multiply it with another number or the numeric contents of another variable. If the string is text, you can compare it with another string to see if the two are the same. The concept of comparing string comes in handy when designing interactive macros. The advanced macros in Part Two of this book rely heavily on comparing strings.


Conditional Statements

You've already learned that macros can be constructed so that they perform certain routines in one instance, and other routines in another. The macro is responding to specific conditions, set either by the user, by the document, by information in the document, or by some other variable.

A conditional statement is a fork in the road with a choice of two directions to take, depending on the response to a simple true/false question. WordPerfect macros provide many ways to create conditional statements, but they all have one thing in common: to activate a certain routine (or path of routines) depending on external data.

Here's an example of a conditional statement. "If it's cold outside, I'll wear my jacket. Otherwise, I'll leave the jacket at home." The statement can be broken down into three segments:

Obviously, this isn't the kind of conditional statement you'll write with WordPerfect macros. But you may design a conditional statement that starts one macro depending on one type of user input, or another macro depending on other types of user input.

All conditional statements have a condition that must be met, and a specified action if the condition is TRUE or FALSE. Not all conditional statements specify an action for both a TRUE or FALSE, but most do.


Branching

Akin to the conditional statement is the branch, where the macro has two or more paths to take depending on external criteria. A good example of a branch is a menu selection. Here, you have four choices:

Each of these choices is a branch. Each branch specifies one or more unique routines in the macro. The Edit a Document branch, for example, will not use the same routines as Print a Document, Format a Document, or Quit WordPerfect.


Looping

A loop is a routine that is repeating two or more times. A typical loop is a "keyboard scan" where the macro constantly checks the keys you press. If you press the key the loop routine is looking for, the macro breaks out of the loop and continues on with some other routines. If the key isn't the one that the loop is looking for, the routine is restarted again.

Loops are really specialized versions of conditional statements. Instead of stopping to provide a choice of two directions, the macro is designed to continue the loop until a certain condition is met. WordPerfect macros contain many sophisticated ways to construct loops. You'll find loops helpful in tackling the most demanding macro assignments.


Entering Data

The basic WordPerfect macro is merely a recording of a series of keystrokes. But you can also program macros to stop and wait for user input. Once the user has entered the data, the macro uses the information -- be it text, a number, or a single keypress -- to complete its task.

You might pause a macro to allow the user to enter her name, the current date, or some other variable information. Your macro may then use that information to create a mailing label, or to date a series of database entries. Input data can be entered directly into the document, or can be temporarily stored in a variable. The macro can then sample the contents of the variable, and use it in a conditional statement, a branch, or a loop -- or even save it for use later on.


Outputting Data

WordPerfect macros output data in two basic ways:

ACCESSING MACRO COMMANDS

The commands in WordPerfect's macro programming language is available while in the macro editing window. To access the programming statements while editing a macro, press [Ctrl]-[Page Up]. A pop-up menu appears over the editing box. Use the up and down arrow keys to scroll through the contents of the programming menu. You can quickly shuttle to a particular statement by typing the first couple of characters in its name.

Each statement, such as {DISPLAY ON} and {CHAIN}, is enclosed in brackets. Some statements are followed by one or more arguments. These arguments tell WordPerfect what to do with the statement. For example, the {CHAIN} statement is followed by a macro file name argument. To complete the statement in an actual macro, you'd enter:

{CHAIN}filename~

WordPerfect uses tilde character as a delimiter. The program knows that the argument is done when it reaches the tilde, and that it should expect text or another programming code to follow.

To enter a programming command (otherwise known as a statement; we'll use the two words interchangeably throughout the book) in the macro editing box, select it and press [Enter]. Note that the text for the argument is not included, only the command itself, and that the command is shown in bold.

You may exit the pop-up menu without making a selection by pressing the [Esc] key. If you press [Ctrl]-[Page Up] or [Esc] again, WordPerfect re-selects the macro command that you last used. This allows you to quickly enter a series of the same statements in the macro editing box.

 

MACRO COMMAND TYPES

It's helpful to categorize WordPerfect's macro commands into discrete types. For consistency, we'll retain the categorization that WordPerfect uses in its documentation (and we've added one of our own).

There are nine categories of macro commands:

Note that some commands serve double duty. For example, the {DISPLAY OFF} command is found in both the macro execution control and programming aides categories.


User Interface Commands

The user interface commands allow input from the user and/or display a message on the screen. The user interface commands are:

{BELL}
Sounds a short warning tone.
{CHAR}
Allows for single character user input.
{INPUT}
Allows for multiple character user input.
{LOOK}
Samples the key you just pressed.
{PAUSE}
Pauses macro execution and allows for keyboard entry.
{PROMPT}
Displays a message on the screen.
{STATUS PROMPT}
Displays a semi-permanent message on the screen.
{TEXT}
Allows for multiple character user input.
 

Flow Control Commands

Flow control commands redirect macro execution depending on external criteria (such as user input). The flow control commands are:

{BREAK}
Prematurely terminates a conditional statement, loop, or macro.
{CALL}
Calls a subroutine.
{CASE}
Establishes one or more branches.
{CASE CALL}
Establishes one or more branches, with each branch executed as a subroutine.
{CHAIN}
Executes another macro.
{ELSE}
Establishes a FALSE condition for an IF statement.
{END FOR}
Ends a FOR and FOR EACH loop.
{END IF}
Ends an IF statement.
{END WHILE}
Ends a WHILE loop.
{FOR}
Establishes a self-contained "counter" loop.
{FOR EACH}
Applies one or more commands or routines to a single variable.
{GO}
Jumps to a labeled routine.
{IF}
Establishes an IF conditional statement and what happens when the statement is TRUE.
{IF EXISTS}
Checks if a variable is empty (doesn't exist).
{LABEL}
Names a routine.
{NEST}
Temporarily executes another macro, then returns to the original macro.
{NEXT}
Increments the counter in a FOR, FOR EACH, and WHILE loop.
{ON CANCEL}
Provides an alternative response in case the macro is canceled.
{ON ERROR}
Provides an alternative response in case an error occurs during macro execution.
{ON NOT FOUND}
Provides an alternative response in case a search fails during macro execution.
{QUIT}
Stops the macro.
{RESTART}
Stops all macro execution at the end of a nested macro.
{RETURN}
Returns from a nested macro or a subroutine.
{RETURN CANCEL}
Generates a "cancel condition."
{RETURN ERROR}
Generates an "error condition."
{RETURN NOT FOUND}
Generates a "not found condition."
{SHELL MACRO}
Starts a shell macro.
{WHILE}
Runs a self-repeating loop until a condition is met.
 

Macro and Subroutine Termination Commands

The macro and subroutine termination commands end macro execution, or break out of subroutines and continues with the rest of the macro. The macro and subroutine termination commands are:

{BREAK}
Prematurely terminates a conditional statement or macro.
{QUIT}
Stops the macro.
{RESTART}
Stops all macro execution at the end of a nested macro.
{RETURN}
Returns from a nested macro or a subroutine.
{RETURN CANCEL}
Generates a "cancel condition."
{RETURN ERROR}
Generates an "error condition."
{RETURN NOT FOUND}
Generates a "not found condition"

External Condition Handling Commands

The external condition handling commands specify how a condition that occurs outside the macro is handled. In the case of the RETURN commands, they generate or create the condition. The external condition handling commands are:

{CANCEL OFF}
Disables the Cancel key.
{CANCEL ON}
Enables the Cancel key.
{ON CANCEL}
Provides an alternative response in case the macro is canceled.
{ON ERROR}
Provides an alternative response in case an error occurs during macro execution.
{ON NOT FOUND}
Provides an alternative response in case a search fails during macro execution.
{RETURN CANCEL}
Generates a "cancel condition."
{RETURN ERROR}
Generates an "error condition."
{RETURN NOT FOUND}
Generates a "not found condition."
 

Macro Execution Commands

The macro execution commands run a macro.

{CHAIN}
Starts a new macro.
{NEST}
Temporarily executes another macro, then returns to the original macro.
{SHELL MACRO}
Starts a Shell macro.
 

Macro Execution Control Commands

Macro execution commands affect the operation of macros by either controlling the display, macro execution speed, or delay until the next command is executed. The macro execution control commands are:

{DISPLAY OFF}
Turns the display off.
{DISPLAY ON}
Turns the display on.
{MENU OFF}
Turns menu display off.
{MENU ON}
Turns menu display on.
{SPEED}
Slows down macro execution.
{WAIT}
Waits a predetermined time before continuing.
 

Variable Commands

The variable commands assign values to variables or determines some characteristic or state of a variable. The variable commands are:

{ASSIGN}
Assigns a value to variable.
{CHAR}
Displays a message on the screen and assigns the next keypress to a variable.
{IF EXISTS}
Checks if a variable is empty.
{LEN}
Counts the number of characters in a variable.
{LOOK}
Assigns the next keypress to a variable.
{MID}
Captures a sub-string of a variable.
{SYSTEM}
Contains any of several internal WordPerfect variables.
{TEXT}
Displays a message on the screen and assigns one or more keypresses to a variable.
{VARIABLE}
Displays the contents of variable.
 

Programming Aid Commands

Programming aid commands help make programming and "debugging" macros easier. The programming aid commands are:

{;}
Provides non-executing comment within the macro.
{BELL}
Sounds a short tone (audible feedback).
{SPEED}
Slows down macro execution.
{STEP OFF}
Disables {STEP OFF}.
{STEP ON}
Executes one character or command at a time.
 

Special Purpose Commands

Some WordPerfect Macro commands defy easy categorization. These extend the usefulness of the macro language and are most often used with other commands, like {ASSIGN} or {IF}.

{KTON}
Translate a key (alphabetic, numeric, symbol, or WordPerfect function) to its numbered equivalent.
{NTOK}
Translates a number to its key equivalent.
{ORIGINAL KEY}
Echos the last key pressed.
{STATE}
Indicates one or more current operating states of WordPerfect.
 

Additional Macro Codes

Some useful macro codes are not found in the macro command list. These are:

 

FOR BASIC PROGRAMMERS:
COMPARING WORDPERFECT COMMANDS

If you're familiar with BASIC you'll find many of WordPerfect's macro commands are similar in function and syntax. A comparison of the functions may help you to understand how WordPerfect macro commands work.

Macro Command   BASIC Keyword or Code
{;}     	REM
{ASSIGN}    	LET
{BELL}      	BEEP  
{BREAK}     	EXIT, EXIT FOR
{CALL}      	CALL, GOSUB
{CANCEL OFF}   	KEY OFF ([F1] key only)
{CANCEL ON}     KEY ON ([F1] key only)
{CASE}      	SELECT CASE, ON...GOTO
{CASE CALL}     ON...GOSUB
{CHAIN}     	CHAIN, RUN
{CHAR}      	INPUT (single character), INKEY$
{DISPLAY OFF}   CLS
{ELSE}      	ELSE
{END FOR}   	EXIT
{END IF}    	END IF
{END WHILE}     WEND
{FOR}   	FOR  
{GO}    	GOTO
{IF}    	IF (THEN implied)
{IF EXISTS}     IF var=""
{KTON}      	STR$    
{LABEL}     	LABEL:, LineNumber
{LEN}   	LEN
{LOOK}      	INKEY$
{MID}   	MID$
{NEST}      	RUN
{NEXT}      	NEXT
{NTOK}      	CHR$
{ON CANCEL}     ON KEY (3B) (ON Cancel key event trap)
{ON ERROR}  	ON ERROR
{PAUSE}     	INPUT (no message)
{QUIT}      	STOP
{RETURN}    	RETURN
{RETURN ERROR}  ERROR
{STATE}     	PEEK (specific internal variables only)
{STEP OFF}  	TROFF
{STEP ON}   	TRON
{SYSTEM}    	ENVIRON$, PEEK (specific variables only) 
{TEXT}      	INPUT (multiple character)
{WAIT}      	WAIT
{WHILE}     	WHILE

DEFINITION OF MACRO STATEMENTS

The example macros presented in Part Two of this book rely heavily on macro programming commands. You will learn, first hand, how to use the statements in actual macros. As a reference, the following is a summary of all macro statements and what they do.

{;}comment~

Used to document a macro; the text before the tilde delimiter is ignored during execution.

Example:

{;}This section checks to see if the Enter key is pressed, then
continues on.~ 


{ASSIGN}variable~value~

Assigns a value to a variable.

Example:

{ASSIGN}1~1000~

Assigns the number 1000 to variable number 1. 

Variables can contain text or whole numbers. When entering fractional numbers, or those with non-numeric characters, WordPerfect treats it as text.

{BELL}

Produces a short tone through the computer's speaker. Used without an argument.

{BREAK}

Moves the macro to the end of an IF...ELSE structure, or breaks out of a FOR, FOR EACH, or WHILE loop. If an IF...ELSE structure doesn't exist, it ends the macro. Used without an argument.

Example:

{FOR}variable~1~10~1~
{CHAR}1~Enter a number~
{IF}{VAR 1}=1~
	{BREAK}
{ELSE}
	{NEXT}
{END IF}
{END FOR}

This example shows a FOR loop that repeats a total of ten times. With each loop, the macro asks to "Enter a number," and stores the number into variable 1. If variable 1 is equal to 1, then the FOR loop is broken before the count gets to 10. If the numeral 1 is never entered, the loop will end by itself at the 10th excursion.

{CALL}label~

Calls a subroutine inside the current macro. After the subroutine is finished, the macro returns to the point immediately after the {CALL} statement and continues on. Each {CALL}ed subroutine must end with a {RETURN} statement.

Example:

{CALL}loop~

Calls the subroutine that begins with the label "loop."

{CANCEL OFF}

Inhibits the use of the Cancel key. Used without an argument.

{CANCEL ON}

Allows the use of the Cancel key. Used without an argument.

{CASE}expression~case1~label1~...case#~label#~~

Checks the expression (usually a variable) and compares it against each case number in the argument string. When (and if) the macro finds a match, WordPerfect branches off to the corresponding label. You can use any number of case/label arguments that you wish. Remember to end the {CASE} statement with two tildes -- one tilde is the delimiter for the last label, and the other tilde is the delimiter for the {CASE} instruction.

Example:

{CASE}{VAR 1}~
	1~end~
	2~start~
~

Compares the value variable 1 against cases the numbers 1 and 2. If the value in variable in variable 1 is 1, then the macro jumps to the "end" label. If the value is 2, then the macro jumps to the "start" label.

{CASE CALL}value~case1~label1~...case#~label#~~

Same as {CASE}, above, but calls the subroutine identified with the corresponding label. After the subroutine is finished, the macro returns to the {CASE CALL} statement and continues on. Each {CASE CALL}ed subroutine must end with a {RETURN} statement.

{CHAIN}macro~

Executes the named macro, leaving the current one.

Example:

{CHAIN}dolist~

Immediately switches off to a macro named "dolist."

{CHAR}variable~message~

Prompts you with the message and stores the next keystroke you type in the variable indicated. Causes a pause in the macro; the message stays until you press a key.

Example:

{CHAR}0~Type Y or N.~

Assigns the next keystroke to variable 0.

{DISPLAY OFF}

Turns the display off during macro execution. Used without an argument.

{DISPLAY ON}

Turns the display on during macro execution. Used without an argument.

{ELSE}

Used with the {IF} and {END IF} statements. Indicates what should happen if the {IF} statement is FALSE. Should the {IF} instruction be TRUE, {ELSE} terminates the IF...ELSE structure (put another way, instructions following {ELSE} are NOT executed when the {IF} instruction is TRUE). See the description of {IF} for an example of how the {ELSE} statement is used. The {ELSE} command can optionally be used with the {CASE} and {CASE CALL} commands. It has the same function with these commands as it does with the {IF} statement.

{END FOR}

Ends a FOR or FOR EACH loop. See the {FOR} command (above) for a description of how to use {END FOR}. Used without an argument.

{END WHILE}

Ends a WHILE loop. See the {WHILE} command (below) for a description of how to use {END WHILE}. Used without an argument.

{END IF}

Ends the IF...ELSE structure. See the description of {IF} for an example of how the {END IF} statement is used.

{FOR}variable~start~stop~step~

Repeats a loop the specified number of times. The loop itself normally consists of one or more commands as a repeating routine. This routine is enclosed between the {FOR} command and a terminating {END FOR} command.

The {FOR} command uses four arguments: variable, start, stop, and step. Variable is a unique variable name that will, when the FOR loop is run, contain a number beginning with start and ending with stop. The start argument is often 0 or 1, but it can be any number. The step variable indicates how you want the FOR loop to count, by 1s, 2s, 5s, 10s, etc.

The {NEXT} command is not strictly required when using a FOR loop, but you may wish to include it in any case. The {NEXT} command signals that the repeating loop is finished and that the macro should increment the FOR counter and restart the loop. You can use the {NEXT} command to end the routine before it completes all the steps -- for instance, if a certain {IF} condition is TRUE.

Example:

{FOR}variable~10~100~10~
	{VARIABLE}variable~
{NEXT}
{END FOR}

The FOR counter counts from 10 to 100, stepping 10 digits at a time (10, 20, 30, 40, etc.). With each loop, the contents of variable ("10," "20," "30," etc.) is printed in the document.

{FOR EACH}variable~expression1~expression#~~

{FOR EACH} is a unique looping command. It uses a variable as a temporary placeholder and allows you to assign a series of expressions to the variable with each cycle of the loop. When running, the {FOR EACH} command evaluates the expressions and inserts the result into the variable. The "expressions" can be simple numbers, text, calculations, and just about anything else that can be stored in a variable.

Additional codes you add between the {FOR EACH} command and {END FOR} command are repeated with each cycle of the loop. Note: The {FOR EACH} command expects a tilde delimiter after each argument, including all the expressions you use, plus an additional tilde to end the {FOR EACH} command itself. Don't forget this last tilde, or the macro will not function properly. You may wish to format the {FOR EACH} command within the macro as shown in the example. That way, you can readily identify each of the expressions and remember to enter the last tilde.

Example:

{FOR EACH}variable~
	2+2~
	2+4~
	2+6~
	2+8~~
	{VARIABLE}variable~
	{NEXT}
{END FOR} 

The {FOR EACH} loop is repeated a total of four times, one for each expression. On the first loop, the expression "2+2" is evaluated, and the result (4) is placed into thevariable "variable." The contents of the variable is then printed in the document, and the loop repeats. With each pass, another expression in the list is evaluated, until all expressions are complete.

{GO}label~

Go to the named label inside the current macro. You can go to labels that are in front of or behind the {GO} statement.

Example:

{GO}testrun~

Goes to the label identified as "testrun."


{IF}expression~

If the expression is TRUE, perform the very next command or jump to the point after the {END IF} instruction. If the value is FALSE, go to the command immediately after the {ELSE} instruction, if any.

Example1:

{IF}{VAR 0}=10~
	{GO}start~
{ELSE}
	{QUIT}
{END IF}

Example 2:

{IF}{VAR 0}=10~
	{ELSE}
{QUIT}
{END IF}
{GO}start~

Both examples do the same thing. If the value in variable number 0 is equal to 10 (true), go to the label named "start." If the value in variable 0 is not equal to 10 (false), quit the macro.

Note that the equal sign is not the only operator you can use with the {IF} statement, although it is the most common. You can also test for not equal to, greater than, less than, and others. See Chapter 5, "Making More of Macros," for more information on WordPerfect's operators.

{IF EXISTS}variable~

If the variable has something in it (text or numbers), then the IF instruction is true. If the variable is empty (undefined), then the IF statement is false. Follow the same logic described above for the {IF} statement.

Example:

{IF EXISTS}0~
	{ELSE}
{QUIT}
{END IF}
{GO}start~

If variable number 0 has something in it (TRUE), skip to the next instruction after {END IF} (in this example, there is nothing immediately after the {IF EXISTS} statement, so the macro jumps to the end of the IF...ELSE structure). If the variable is empty, quit the macro.

{INPUT}message~

The {INPUT} command displays a message on the screen that remains until the user presses the [Enter] key. The message is then removed. Note that the {INPUT} and {STATUS PROMPT} commands operate inclusively. Messages displayed with either command will erase a message displayed by the other.

Example:

{INPUT}This is a sample message~

Displays "This is a sample message" along the bottom of the screen.

{KTON}key~

{KTON} stands for key-to-number. It translates the value of a key to its ASCII equivalent, as used by WordPerfect. Normally, you'd use the {KTON} command to convert some alphabetic key to its ASCII equivalent, but you can also convert WordPerfect function keys and special characters to their equivalents. The {KTON} key is complemented by the {NTOK} (number-to-key) command.

Example:

{KTON}A~

Prints the number 65 in the document (65 is the ASCII equivalent of the letter A). Chapter 18, "Macro Strategies," includes a key-to-ASCII conversion chart you can refer to when using the {KTON} command.

{LABEL}label~

This command identifies the macro codes that follows with a unique name. It's used with the {GO}, {CALL}, {CASE}, and {CASE CALL} statements. Text or macro commands after the label are executed.

Example:

{LABEL}start~
This is the text for the "start" routine.

Identifies the label as "start," and prints the text that follows.

Label names can only be used once in a macro. The names can use any characters and can be any length. To avoid typing errors, however, try to limit label names to one or two short words.

{LEN}variable~

The {LEN} command counts the number of characters in a variable. You can use {LEN} to limit text entry, to determine if a variable contains more characters that it should, or to develop sophisticated macros that "parse" the contents of variables.

Example:

{ASSIGN}0~{LEN}1~~
{PROMPT}Variable 1 contains {VAR 0} characters.~ 

Assigns the length of variable 1 to variable 0, then displays the message "Variable 1 contains nnnn characters."

For instance, if variable 1 contains the text "this is a test," the result stored in variable 0 is 14 (the number of characters in the string "this is a test"). The message would then read "Variable 1 contains 14 characters."

{LOOK}variable~

Scan the keyboard and assign the next keystroke to the variable. If a key isn't pressed, continue on with the macro (the macro doesn't stop). Most often used with a repeating loop to continually check for key presses.

Example:

{LOOK}1~

Assigns the next key pressed to variable number 1.

{MID}variable~offset~count~

The {MID} command is used to sample, or "return," a portion of the contents of a variable (called a sub-string). The command can be used to return the entire contents of the variable, but in most cases, you'll use it to return only one or two characters. The variable argument is the variable that contains the string you want to sample. The offset is the number of characters you want to start counting from. Character 0 is the beginning of the string. The count argument is the number of characters from the string you want to return.

Example:

{MID}string~0~2~

Returns the first two characters in the variable "string."

The {MID} command returns nothing if you try to extract a sub-string that goes beyond the bounds of the variable. For example, if the string in the variable is only five characters long, you try to extract characters starting from the eight character position, the {MID} command returns nothing.

{NEST}macro~

Nest the named macro. After the named macro finishes, WordPerfect returns to the original one and continues execution where it left off.

Example:

{NEST}dolist~

Temporarily branches off to a macro named "dolist."

{NEXT}

Increments the counter in a FOR, FOR EACH, or WHILE loop, and restart the loop. Used without an argument.

{NTOK}

{NTOK} stands for number-to-key. It translates an ASCII number to its key equivalent, as used by WordPerfect. Normally, you'd use the {NTOK} command to generate keys from numeric input -- print the alphabet from A to Z using a incrementing loop counter, for instance. The {NTOK} key is complemented by the {KTON} (key-to-number) command.

Example:

{NTOK}65~

Prints the letter A in the document (65 is the ASCII equivalent of the letter A).

Chapter 18, "Macro Strategies," includes a key-to-ASCII conversion chart you can refer to when using the {NTOK} command.

{ON CANCEL}command~

If the [Cancel] key is pressed, or a macro encounters a cancel from within itself or in a nested macro, this statement indicates what should happen next. The default instruction, when no {ON CANCEL} statement is provided, is RETURN CANCEL.

Example:

{ON CANCEL}{RESTART}~

When Cancel is encountered, the {RESTART} instruction terminates all macro execution at the end of current subroutine or nested macro.

Only a limited number of programming instructions are allowed with {ON CANCEL}:

IF no instruction is included with the {ON CANCEL} statement, it is ignored and the macro continues. The {GO} and {CALL} statements require arguments of their own, which need a tilde as a delimiter. When used with these statements, you must provide two tildes at the end of the {ON CANCEL} instruction, such as {ON CANCEL}{GO}label~~.

Note: The {ON CANCEL} command is ignored if you've preceded the code with {CANCEL OFF} command. {CANCEL OFF} cancels the action of the [Cancel] key, as well as internally generated cancel conditions. If you want to use {ON CANCEL} be sure to enable cancel (use the {CANCEL ON} command).

{ON ERROR}command~

Tells WordPerfect what to do if an error is detected during macro execution. The error can occur in the macro, in WordPerfect, or in DOS. The default command, when no {ON ERROR} statement is included, is RETURN ERROR. The syntax and use is the same as with {ON CANCEL}.

{ON NOT FOUND}command~

Tells WordPerfect what to do if a search ends with a *not found* message. The default command, when no {ON NOT FOUND} statement is included, is RETURN NOT FOUND. The syntax and use is the same as {ON CANCEL}.

{ORIGINAL KEY}

Echos the key you last typed. The value of key is the un-reassigned version. That is, if you have reassigned the [Esc] key to something else, WordPerfect still echos back the original definition for the [Esc] key. The {ORIGINAL KEY} statement is used without an argument.

{PAUSE}

Pauses macro execution. Press [Enter] to restart. Used without an argument.

{PROMPT}message~

Displays the message in the status line. The {PROMPT} statement must be nested in a loop or pause or the message will only flash on the screen and disappear as the macro continues execution. You can also keep the prompt message on the screen during the execution of a long macro by turning the display off. However, you must be sure to move the prompt message up a line, as detailed in the following chapter, or the *waiting* message that appears during macro execution will erase the prompt massage.

Example:

{PROMPT}When you are ready, press Enter and the macro will begin.~ 

 

{QUIT}

Terminates all macro execution. Used without an argument.

{RESTART}

Stops all macro execution (including nested macros) at the end of the current subroutine or nested macro. Used without an argument.

{RETURN}

Used with the {CALL} and {CASE CALL} instructions. Marks the end of a subroutine. When {RETURN} is encountered, the macro jumps back to the point immediately after the {CALL} or {CASE CALL} instruction. When {RETURN} is placed by itself without a subroutine, it terminates the macro (used most often in this application to return from a nested macro). The {RETURN} statement is used without an argument.

{RETURN CANCEL}

Return from a subroutine or nested macro and indicate a cancel condition to the main routine or macro. Used without an argument.

{RETURN ERROR}

Return from the subroutine or nested macro and indicate an error condition to the main routine or macro. Used without an argument.

{RETURN NOT FOUND}

Return from the subroutine or nested macro and indicate an error condition to the main routine or macro. Used without an argument.

{SHELL MACRO}shell_macro~

This command lets you execute a Shell macro from a WordPerfect macro. You must have the Library program (which contains the Shell program) to use this command. Conversely, you can start WordPerfect 5.1 macros from within Shell (requires Shell version 2.1 or later). Use the {SHELL MACRO} to quickly transfer between WordPerfect Corp. programs, or to automate DOS or Library tasks.

Example:

{SHELL MACRO}shell~

Starts the Shell macro named "shell."

{SPEED}1/100th secs~

Slow down macro execution by the indicated amount, or wait the amount of time indicated between each key input.

Example:

{SPEED}50~

Slows down macro execution by an extra 50/100ths (equal to 5/10 or 1/2) of a second.

{STATE}

Returns a number that represents the current operating state of WordPerfect. The number is in binary form and adds together if more than one state applies.

State Number Condition
1 Document 1 current
2 Document 2 current
4 Main editing screen
8 Editing structure other than main screen
16 Macro definition active
32 Macro execution active (always on)
64 Merge active
128 Block active
256 Typeover active
512 Reveal Codes display active
1024 Yes/no prompt active
2048 Cursor currently inside table

Example:

Assuming assuming document 1, block active, and typeover active

{STATE}

Prints the number 417 (1+32+128+256).

You can check for specific conditions using the AND logical operator, expressed as &. For example, {STATE}&256 checks to see if typeover is active.

The {STATE} instruction is not used with an argument, but is often coupled with other programming statements. You can combine the {STATE} instruction with {ASSIGN}, {IF}, {CASE}, and {CASE CALL} statements. The instruction {ASSIGN}1~{STATE}~ assigns the {STATE} number to variable number 1.

{STATUS PROMPT}

The {STATUS PROMPT} command prints a semi-permanent message on the screen. The message stays until you quit WordPerfect, or write another message using the {STATUS PROMPT} or {INPUT} commands (in addition, messages with the {CHAR}, {PAUSE}, and {TEXT} commands temporarily over-write the {STATUS PROMPT} display.

{STEP OFF}

Turns stepping off. Used without an argument.

{STEP ON}

Slows down macro execution to one step at a time. You manually advance the macro by pressing a key. You can cancel the macro at any time by pressing [F1]. During stepping, the contents of the macro appears in the status line. Text is shown normally but programming statements are given command numbers. These numbers are detailed in Chapter 20. {STEP ON} is used without an argument.

{SYSTEM}system_variable~

The {SYSTEM} command is an internal variable that reports any of several attributes and conditions of WordPerfect and the document currently open. For example, you can determine the current page page number of the document with:

Example:

{SYSTEM}page~

Chapter 5, "Making More of Macros," presents a complete list of {SYSTEM} variables and what they do.

{TEXT}variable~message~

Prompts you with the message and stores your keystrokes in the variable. The instruction ends when you press [Enter]. Each variable can hold a maximum of about 120 characters.

Example:

{TEXT}7~Enter name and address.~

Displays "Enter name and address" and stores the answer in variable number 7.

{VARIABLE}variable~

The {VARIABLE} command retrieves the contents of the named variable. You can use the {VARIABLE} command to print the contents of a variable in the document, assign one variable to another, and so forth. In the following examples, assume the text "WordPerfect 5.1 Macros and Templates" has been assigned to the variable "text."

Example:

{VARIABLE}text~

Prints "WordPerfect 5.1 Macros and Templates" in the document.

Example:

{ASSIGN}new_var~{VARIABLE}text~~

Assigns the contents of variable "text" to a new variable, "new_var." Now, "new_var" also contains the text, "WordPerfect 5.1 Macros and Templates."

{WAIT}1/10th secs~

Wait the specified period of time before continuing.

Example:

{WAIT}15~

Wait 1.5 seconds (15/10ths) then continue.

{WHILE}expression~

The {WHILE} command sets up a unique WHILE loop that causes the macro to repeat a given set of instructions until a certain condition is met. {WHILE} is a simpler way of producing a keyboard loop where is a routine is to be repeated until a certain key is pressed.

Example:

{WHILE} "{VAR 1}"~!="{Enter}"~
	{LOOK}1~  
	{VAR 1}
	{NEXT}
{END WHILE} 

This example repeatedly tests the keys you press and looks for the [Enter] key. If you don't press the [Enter] key (variable 1 does not equal {Enter}), the routine is repeated. When the [Enter]key is struck, the WHILE loop is terminated and the macro continues.

 

ADDITIONAL MACRO CODES

The commands list in the pop-up macro editor window includes several other items that aren't really true "commands." These items, for moving the cursor to the next or previous paragraph, or to move the cursor within columns and tables, are duplicated with [Ctrl] and [Alt] keyboard equivalents. But these equivalents only work with enhanced keyboards (such as the 101-key keyboards found on the IBM PS/2 and similar models). If your keyboard can't generate these codes you can still access them in the macro editor.

Common keyboard codes found in macros are {Enter}, {Tab}, {ALTx}, and {VAR x}. These are not found in the pop-up commands list, but are entered directly from the keyboard. Here's what they do and how to enter them:


{Enter}

The {Enter} code within the macro indicates you want a hard return in the macro, or else want to simulate pressing the [Enter] key while in a menu, list, etc. Normally, pressing the [Enter]key inserts a blank line only. To include the {Enter} code in a macro, press [Ctrl]-V first, then press [Enter].

{Tab}

The {Tab} key code within the macro indicates you want to tab some text to the next tab stop. Normally, pressing the [Tab] key inserts a empty spaces in a line, and is most often used to "format" the macro code for readability. To include the {Tab} code in a macro, press [Ctrl]-V first, then press [Tab].


{ALTx}

The {ALT x} code ("x" is a letter of the alphabet) commands the macro to either nest to or chain to an [Alt]-key macro. The {ALTx} code is the same as:

{NEST}altx~

when the {ALTx} code is not at the end of the macro.

{CHAIN}altx~

when the {ALTx} code is at the end of the macro.

To enter the {ALTx} code, first press [Ctrl]-V, then press the [Alt] key and a letter key. For example, to enter {ALTZ}, press [Ctrl]-V, [Alt]-Z.

{VAR x}

The {VAR x} code ("x" is a number from 0 to 9} indicates a numbered variable. You'll use the {VAR x} code to print the contents of a variable in a document, to assign one variable to another, and for many other tasks.

To enter the {VAR x} code, first press [Ctrl]-V, then press the [Alt] key and a number key (use the numbers along the top of the keyboard, not the ones in the numeric keypad). For example, to enter {VAR 1}, press [Ctrl]-V, [Alt]-1.

 

IMPORTANT TOPICS

You've learned the basics of WordPerfect macro programming, and about the various commands used to produce sophisticated macros. You also learned:

---

 Top Contents

WordPerfect 5.1 Macros and Templates
Electronic Edition
Copyright 1990, 1997, Gordon McComb.  All Rights Reserved.
First published by Bantam Electronic Publishing, 1990.
http://www.gmccomb.com/