7. Simple use of named variables

The following macro is used to insert a DocBook ulink element at caret position, the URL referenced by the inserted ulink being chosen from a predefined list.

Command pick has been created to display a dialog box which lets the user choose one item from a list. This command returns the selected item (a string) to its invocation environment.

Command pick can always be executed, but it returns a special value when the user has canceled its execution by clicking on the Cancel button of its dialog box.

<command name="insertFamousUlink">
  <macro undoable="true" label="Insert Favorite">
    <sequence>
      <command name="pick" 
               parameter="Favorites true
                          W3C
                          http://www.w3.org/
                          'DocBook Home Page'
                          http://www.docbook.org/
                          Java
                          http://www.java.com/" />
      <set variable="url" expression="%_" plainString="true" />

      <command name="insert" parameter="into ulink" />

      <get expression="$url" />
      <command name="putAttribute" parameter="url %_" />

      <get expression="$url" />
      <command name="insertString" parameter="%_" />
    </sequence>
  </macro>
</command>

The above macro stores the result returned by command pick in a user variable called url. The value of the url variable is then used twice: one time to set the value of attribute url of element ulink, a second time to specify the text of element ulink.

Macro variable "%_" is extremely volatile. For example, the following sequence cannot be used to add attribute url to newly inserted element ulink, because command insert, which does not return a result, clears "%_".

<sequence>
  <command name="pick" 
           parameter="Favorites true
                      W3C
                      http://www.w3.org/
                      'DocBook Home Page'
                      http://www.docbook.org/
                      Java
                      http://www.java.com/" />
  <command name="insert" parameter="into ulink" />
  <command name="putAttribute" parameter="url %_" />
</sequence>

The only easy way to reuse what has been returned by command pick is to immediately save the value of "%_" in a user-defined variable.

User-defined variables are not related to macro-variables. They are set using special construct set and are read using special construct get. These constructs have expression attributes which have been designed to contain arbitrarily complex XPath expressions (more info. about this in following sections).

The above macro illustrates a trivial use of set and get. This means that you don't need to learn XPath to use set and get to do simple things. However, it is important to remember this: