Search

2D Drafting3D Modelling

Writing Macros and Diesel Code – Customizing BricsCAD® – P9

By Ralph Grabowski 35 min September 26, 2020
Customizing-BricsCAD-–-Introduction-–-P9.png

Writing Macros and Diesel Code

In this post, you learn how to write macros for CAD software and then how to add more power to macros through one-line programs written in Diesel code.

When you click a button or make a menu selection, BricsCAD behind the scenes executesmacro. This is a series of one or more commands assigned to the button or menu item.

With the Customize command, you can change the macros that lie behind buttons, menu selections, mouse clicks, and other actions. Toolbars, ribbons, and most other parts of the BricsCAD user interface, all use the same format for macros. This is good news for this reason:

When you learn to write a macro for one, then you know how to write macros for all

There is just one difference, however: menus have more user interface options than the others, and so they have more capabilities when it comes to macros.

Some macros use Diesel code, a simplistic programming language. It is used for special effects, such as toggling check marks in front of menu items. The coding used by Diesel is really, really arcane. Fortunately, the same bits of Diesel code can be used over again, and so it is enough for you to recognize what the code does.

For a full overview of Diesel for BricsCAD, you can view the official, BricsCAD diesel Developer Guide.


The following topics are covered in this post:

  • Learning the macro syntax
  • Writing macros specific to menus
  • Coding with Diesel
  • Cataloging Diesel functions

QUICK SUMMARY OF METACHARACTERS IN MACROS

Macros use command and option names, metacharacters, Diesel code, and LISP functions in menus, toolbars, and other areas of the Customize dialog box. Metacharacters consist of punctuation that represents actions. Here are the metacharacters used by BricsCAD:

^--- (carat) represents the Ctrl key. These following control-key combinations are valid in macros:

  • ^B Toggles snap mode
  • ^C Cancels the current command
  • ^D Toggles coordinate format
  • ^E Changes to the next isometric plane
  • ^G Toggles the grid display
  • ^O Toggles orthographic mode
  • ^S Selects the entity under the cursor
  • ^T Toggles tablet mode
  • ; (semi-colon) represents the Enter key.
  • ' (single quote) forces the use of commands in transparent mode.
  • _ (underscore) forces the use of English versions of command names.
  • -- (dash) forces the use of command-line versions of commands.
  • \ (backslash) pauses the macro for user input.
  • ( (open parenthesis) signals the start of a LISP function.
  • $( signals the start of a Diesel statement.
  • ) (close parenthesis) signals the end of LISP functions and Diesel statements.

The following metacharacters are used only by menu macros:

1-768x287

  • $M signals the start of a complex macro.
  • .! displays a checkmark, to indicate the toggle is turned on.
  • ~ (tilde) grays out a menu item, to indicate it is not available.
  • &  (ampersand) signals the accelerator key, to access menu items with the Alt key.

For more details see BricsCAD's Developer Reference Overview.

Simple Macros

A simple macro consists of a single command, prefixed by some unusual-looking characters. For instance, here is the macro attached to the Line button in Draw toolbar:

^c^c_line

The exact same macro is used for toolbars and macros, as shown below by Line in the Draw menu:

2-768x570

A basic macro shown in the Command property

The ^c^c_ characters in the macro have the following meanings:

  • ^c --- is a control character. It imitates pressing Esc on the keyboard, canceling the command currently in progress. The carat symbol ( ^ ) alerts BricsCAD that the character following is a control character and not part of a command name or an alias.
    (What does 'c' have to do with the Esc key? Back in the 1980s and 1990s, when desktop computers used MS-DOS for their operating system, users pressed Ctrl+C to cancel a command; the C was short for "cancel." With Windows, Microsoft changed the meaning of Ctrl+C to mean "copy to Clipboard," but in macros, it continues to mean "cancel.")
  • ^c^c --- most macros start with two ^cs because many BricsCAD commands are two levels deep.
    Extra ^cs do no harm; indeed, older releases of BricsCAD prefixed all macros with three ^cs. to handle commands like PEdit, whose options can go three levels deep. When a macro is transparent (starts with the ' apostrophe), then you can't prefix it with the Cancel characters; more on this later in this section.
  • _ --- the underscore is a convention that internationalizes the command.
    Prefixing the command name with the underscore ensures the English-language version of the command always works, whether used with a German, Japanese, or Spanish versions of BricsCAD.
  • line --- is the name of the command to be executed.
    In macros, you type BricsCAD commands and their options exactly the way you would type them on the keyboard at the ':' command prompt. Nothing is needed at the end to terminate the command. BricsCAD automatically does the "pressing Enter" for you.

| TIP Macros are case-insensitive. This means that the characters in macros can be upper, lower or mixed case; it matters not to BricsCAD. The following have the same effect:

  • ^C^_LINE
  • ^c^c_line
  • ^C^c_Line

|

TRANSPARENT COMMANDS IN MACROS

Most macros start by canceling existing commands. But sometimes you want to use a command transparently; i.e, during another command. For example, you might want to zoom into the drawing during a command.

Transparent commands are indicated by the apostrophe prefix ( ' ), like this:

'_zoom

Dashed Commands

A few commands in BricsCAD start with a dash; these are ones that operate at the command line, instead of displaying a dialog box.

One example is the View command: View displays a dialog box, while -View display prompts at the command line. To force View to display its prompts at the command line, enter this:

^c^c_-view

OPTIONS & USER INPUT

Macro can specify commands options, as well as wait for input from users.

Options

Options are just like commands; you just write out the option name. The only thing to watch is that you should use semicolons ( ; ) to separate options from commands and each other.

Here is an example with the Layout command and its New option:

^c^c_layout;_new

Notice that options can also receive the underscore ( _ ) prefix to internationalize them.

You can spell out the name of the option in full ( _new ) or use the approved abbreviation, such as _n ). Recall that approved abbreviations are indicated by capitalized letters in the option names displayed at the command prompt, such as these:

: layout

Enter layout option [Copy/Delete/New/Rename/Set/SAve/Template/? to list] : n

You can use "n" for the New option and "s" for the Set option but must use "sa" for the Save option.

It is perfectly valid to use "?" (as in "? to list") in macros, but you cannot use spaces, because these are interpreted as pressing Enter.

Pausing for User Input

To allow users to input data, macros employ the backslash character ( \ ). This forces the macro to wait for the user to do something. Commonly, the expected action is for the user to input one of these:

  • Pick a point on the screen, or
  • Enter x,y-coordinates at the keyboard

The macro waits for the user to enter the center point of the circle; the circle is always 1 unit in radius:

^C^C_circle;\1

When you execute this macro, such as from a menu pick or toolbar button, the following occurs at the command line:

  • : _circle Macro begins the command

  • 2Point/.../

    : (User picks a point) Macro waits for the user to pick a point in the drawing (or enter a coordinate pair)

  • Diameter/ <5>: 1 Macro enters 1 (for the radius) and then ends the command

But the expected action can be other things, too, depending on the command. Options in the Rotate command expect an angle (the user picks two points on the screen or enters a single number), in the Text command a line of text (the user enters one or more words) and so on.

When a command expects more than one input from the user, you can type several backslashes in a row, as you see next.

Combining Options and Pauses

Options and pauses can be combined together. In this example, the macro draws an ellipse after the user specifies a center point and the rotation angle:

^c^c_ellipse;_c;\_r

Here is what the code means:

  • ^c^c cancel any other command that might be active at the time
  • Ellipse is the name of the command, while the underscore ( _ ) prefix internationalizes it.
  • ; (semicolon) is just like pressing Enter or the spacebar on the keyboard.
  • C is the Ellipse command's Center option. Just as you enter an abbreviation for options at the keyboard, so you can use the same abbreviations in macros --- or you can spell out the entire option name, such as "Center."
  • \ (backslash ) pauses the macro, waiting for the user. Two backslashes in a row means that the macro expects the user to make two picks.
  • R is short for the Ellipse command's Radius option.

Let's look again at the macro, this time in parallel with the command's prompts:

  • ^C^C (Press Esc, Esc.)
  • _ellipse; : ellipse
  • ; (Press Enter.)
  • _C; Arc/Center/: c (Press Enter.)
  • \ Center of ellipse: (Pick point.)
  • \ Endpoint of axis: (Pick point.)
  • _R Rotation/: r (Press Enter.)
    Rotation around major axis: (Pick point)

A final semicolon (i.e. Enter) and backslash (i.e. pause for user input) are not needed at the end of the macro, because the macro no longer needs to wait for the user.

| TIP You can include aliases, Diesel code and LISP routines in toolbar and menu macros. There is no "debugger" for macros, and so you have to figure out the errors on your own. |

Other Control Keys

You've met ^C, the control key for canceling a command. BricsCAD also supports all these control key combinations using the ^-prefix:

customising bricscad

Think of these control-key combos as abbreviations, like aliases. You can use these control keys as shortcuts in macros all by themselves, like this:

3

Macro consisting solely of a Ctrl-key macro

MENU-SPECIFIC METACHARACTERS

Menus use additional metacharacters that are not needed by toolbars. Here is the complete set:

metacharacters

TIP Some of AutoCAD®'s metacharacters don't work, such as [ ] , + , \t , and *. |

Diesel Coding

Sometimes you need additional code to help macro perform decisions. For example, the View menu lists three items that have checkmarks beside them: Command Bar, Status Bar, and Scroll Bars. When the three bars are displayed, the checkmarks appear in the menu; when not displayed, the checkmarks are not shown.

5-1024x209

Left: Checkmarks indicate UI elements are turned on.
Right: No checkmarks mean the elements are turned off.

It is easy to get a menu to display the checkmark: just add the !. metacharacter to the macro. It is difficult, however, to get BricsCAD to do the actual turning on and off, because the display of checkmarks is a logical function. It should appear in the menu only when the UI element is turned on.

This is where Diesel code comes in.

ABOUT DIESEL

Diesel has two purposes in macros: one is for making decisions and the other is for customizing the status bar. The name is short for "direct interactively evaluated string expression language," *and its programming logic is as clear as the acronym's meaning --- as clear as mud.

QUICK SUMMARY OF DIESEL FUNCTIONS

The following Diesel functions are supported by BricsCAD:

MATH FUNCTIONS

  • + Addition
  • --  Subtraction
  • *  Multiplication
  • / Division

LOGIC FUNCTIONS

  • = Equal
  • < Less than
  •  Greater than

  • != Not equal
  • <= Less than or equal
  • =  Greater than or equal
  • and Logical bitwise AND
  • eq Determines if all items are equal
  • if If-then
  • or Logical bitwise OR
  • xor Logical bitwise XOR

NUMERIC CONVERSION FUNCTION

  • fix Truncates real numbers to rounded-down integers
  • angtos Formats angles (short for angle to string)
  • rtos Formats numbers with units (short for real to string)

STRING (TEXT) FUNCTIONS

  • index Extracts one element from a comma-separated series
  • nth Extracts the nth element from one or more items
  • strlen Returns the number of characters in the string (short for string length)
  • substr Returns a portion of a string (short for substring)
  • upper Converts a text string to uppercase characters

SYSTEM FUNCTIONS

  • edtime Formats the system time.
  • eval Passes a string to Diesel.
  • getenv Gets the value of an environment variable.
  • getvar Gets the value of a system variable.
  • linelen Returns the length of the display

|

Diesel has an unusual format for a macro language. Every function begins with a dollar sign and a parenthesis, like this:

$ (function,variable)

The purpose of the initial $ sign is to alert BricsCAD that a Diesel expression is on its way, just as the ( symbol alerts BricsCAD that a LISP expression is coming up. The $ symbol is often used by programmers to indicate a string of text.

The opening and closing parentheses signal the beginning and end of the Diesel function. Functions can be nested, where one Diesel function is inside the parentheses of a second one. You use nesting to have one function evaluate the result of the second one. Diesel is completely reentrant.

Because Diesel programs consist of just one line --- at most! --- nesting is the only way to carry out more than one function during a macro.

For some functions, Diesel can operate on as many as nine values at a time, such as adding several values together. The closing parenthesis alerts Diesel to the end of the list of values.

BricsCAD provides a catalog of 26 Diesel functions. Most of them use at least one variable, some as many as nine. A comma always separates the function name from its variable(s), as well as the variables themselves. Diesel tolerates no spaces.

Diesel functions can be run at the command line, in toolbar and menu macros, in LISP code and in other areas of BricsCAD, such as the status bar. To work in the status bar, you use the ModeMacro command, followed by the Diesel expression.

(John Walker, the Autodesk® programmer who created Diesel, notes that additional functions, such as setvar and time, could be implemented but never were. He provides instructions for accessing the Diesel source code and recompiling it with other functions. He named Diesel as "Dumb Interpretively Executed String Expression Language.")

HOW TO TOGGLE CHECK MARKS

BricsCAD primarily uses Diesel to toggle checkmarks in menus:

  • A checkmark means the option is turned on
  • No checkmark means the option is turned off

To switch between the two states, BricsCAD uses the .! metacharacter in code that looks like this:

$(if,$(=,$(getvar,FILLMODE),0),,!.)

It may look weird, but don't worry: you don't need to know how to write that code from scratch, ever. All you need to do is: (a) copy and paste it, and then (b) change just one word (FILLMODE, in this case).

Here is what the Diesel code says: "If the value of FillMode equals 0, display nothing; otherwise, display the checkmark." BricsCAD uses the .! metacharacter to instruct menus to display checkmarks.

Here is another way of looking at the Diesel code. This is called "parsing," where each line of code is given its own, indented line:

indent-1024x190

Here is what the code does: it checks the value in system variable FillMode. If the value is 0, then the checkmark is not displayed; if the value is 1, then the checkmark is displayed.

To use this code for other menu items, copy and paste the text and then change the name of the system variable. For example, to add a checkmark toggle to the Limits command, use LimCheck system variable. Simply copy, paste, and edit the Diesel string to make it look like this:

$(if,$(=,$(getvar,LIMCHECK),0),,!.)

Reuse the same code for the Grid command, which uses the GridMode system variable:

$(if,$(=,$(getvar,GRIDMODE),0),,!.)

So, you don't really need to know what the Diesel code does, you just need to know which word to change!

Toggling Grayouts

To toggle the color of menu text between black and gray, you use the tilde ( ~ ) character:

  • Black text means the menu item is available
  • Gray text means the menu item is unavailable

REPORTING VALUES OF SYSTEM VARIABLES

Being the customizers that we are, we won't stop at toggling mere check marks or text colors. We've figured out how to use Diesel to do more.

For instance, to display the values of system variables, we can use the $(getvar function. This Diesel function *gets *the value of a system variable and then displays it in the menu.

In the following tutorial, you change the Elevation menu item so that it reports its current value. (Elevation is found in the Settings menu.) The figures below illustrate how the menu looks before and after this tutorial. In the "after" picture, Elevation reports its current value of 10.9000:

elevation-1024x513

Left: The default version of Elevation in the Settings menu. Right: Elevation modified to show value, using Diesel code

To modify a menu item so that it reports values, follow these steps:

  1. Enter the Cui alias, and then choose the Menus tab.
  2. Expand the Settings node, and then select the Elevation item.

6-768x694

Elevation command in the Customize dialog box
  1. Shift your attention to the Menu Item area, the macro pane at the bottom of the dialog box. Click the field next to Diesel, and then enter the following code:
    *             $(getvar,elevation)*
    This piece of Diesel code gets the value of the Elevation system variable and then displays it.

    7

    Adding Diesel code to the macro

  2. Click OK to apply the change and exit the Customize dialog box.

  3. Choose the Settings menu, and then notice the change to the Elevation item. It will probably be prefixed with 0.0000 --- the current elevation.

  4. Choose Elevation to run the command, and then enter a different value, like 1.23:
    : elevation
    Enter current new value for ELEVATION <0.0000>: 1.23

  5. Choose the Settings menu again. Notice that the value next to Elevation has changed to 1.2300.

    8

    Actual elevation value added to the menu

You've customized the display of the Elevation item! But there is a small problem with the display: it doesn't look very good, with the "1.2300" jammed up against the word "Elevation."

In this next tutorial, you fix the spacing problem:

    1. Reenter the Cui alias and then return to the Settings | Elevation item.

    2. Edit the field next to Title so that it changes from:
      *        Ele&vation*
      to this:
      *        = Ele&vation
      *Just add a space, equals sign, and another space.

      9

      Enhancing the macro

    3. Click OK to exit, and try the Settings menu again. That looks better!

      10

      Enhanced look of the menu item

The number will always appear in front of the word. The reason? Recall that the Diesel code was meant to toggle checkmarks, which appear in front of words. Since displaying values is a hack, we are stuck with the backward-looking "1.2300 = Elevation." There is, however, a workaround, as described later under "How to Deal with Two Sysvars."

APPLYING VARIABLES EVERYWHERE

You can apply the same sort of change to other items in the Settings menu. Here are the names of the system variables for some of them:

settings menu

After the changes are applied, the Settings menu looks like this:

11

Additional menu items reporting values

There are some special things to notice about the menu illustrated above. Let's go through them.

How to Add Units

The value of 10 shown for Entity Snap Precision is somewhat meaningless, so I added the word "pixels" to the Title parameter, like this:

pixels = Entity Snap &Precision

12

Adding units to values

How to Solve Check Marks that Conflict with Icons

I found that the image (icon) for Fill seems to override the checkmark. In the figures below, which is on and which is off? When a toggle is on, the icon gets a thin black border, which I find is easy to miss with the Fill, because it already has a black border. This is why I prefer the bold-looking checkmark over the essentially-invisible border.

One solution is to remove the icon from the Image field:

14

Top: which is on which is off?
Bottom Left: Fill is off with blank icon Bottom Right: Fill is on with checkmark icon

How to Deal with Two Sysvars

At first, I could not get the Drawing Limits item to work correctly. It extracts values from two system variables, LimMin and LimMax, which is tricky. After some fiddling around, I found that I could get the Diesel code to work by placing part of it in the Title parameter, like this:

14

Code for reporting two variables

Notice that the pieces of Diesel code are surrounded by parentheses, and separated by a comma.

This makes the pair of 2D coordinates more legible.

&Drawing Limits = ($(getvar,limmin)), ($(getvar,limmax))

This macro displays the limits as follows:

(0,0), (12,9)

15

Menu item reporting the values of two variables

Reporting Through Diesel

Other menus can take advantage of Diesel's reporting feature. Here are examples of what's possible:

  • File | Close can report the name of the drawing file with the DwgName system variable.
  • Edit | Undo can report the name of the command being undone with CmdName.
  • View | Set Viewpoint can report the coordinates of the current view with VPointX, VPointY, and VPointZ.
  • Insert| Insert Block can report the name of the last-inserted block with InsBase.
  • Draw | Circle can report the current radius with CircleRad.
  • Dimension | Restore Dimension Style can report the name of the current dimensions style with DimStyle.
  • Modify | Fillet can report the current fillet radius with FilletRad.
  • Settings | TextStyle can report the name of the current text style with TextStyle.
  • Tools | Inquiry | Time Variables can report the duration the drawing has been open with TdInDwg.

Formatting Units

In the figure above, the values of Base Point and Drawing Limits are shown in architectural units. This should come as a surprise you because normally they would be displayed by default as decimal units. In this case, I cheated: I didn't use Diesel, but simply changed the format of the units with the Units command.

This example illustrates that some values in menus are affected by the current setting of Units. Other values, such as Elevation and Thickness, are, however, still shown by four decimal places. This can be overridden using Diesel code, as described next.

Formatting Diesel Output

You can apply formatting to the numbers and text generated by Diesel.  Numbers and angles can be formatted for units, while text can be converted to uppercase or be truncated.

Formatting Numbers

Diesel provides functions for rudimentary formatting of numbers and coordinates.

Fix

The Fix function truncates real numbers to rounded-down integers. For example, if a Diesel calculation returns the value of 5.321, then applying the Fix function changes the value to 4. "Rounding down" means that a value like 5.987 (which you would expect to be rounded up to 6) is also truncated to 4:

$(fix,4.321)                returns 5

Index

The Index function extracts a single coordinate value from a comma-separated series. For example, the BasePoint system variable returns an x,y,z coordinate like this:

(4,11,16)

You use the Index function to extract the x coordinate from (4,11,16), like this:

$(index,0,($getvar,basepoint))                  returns 4

Notice that Diesel uses a radix of 0, meaning it starts counting with 0, instead of 1 as we humans do. Thus, the 0 in the function above extracts the first coordinate, x:

index number

(When we count, we count like this: 1, 2, 3...; but when Diesel counts, it counts like this: 0, 1, 2... This makes counting in Diesel complex because you have use a digit that's one less than you would expect.)

Nth

The Nth function extracts the nth element from one or more items. Here, the 2 returns the third element of the string of numbers, 8 (because Diesel starts counts with 0, not 1).

$(nth,2,10,9,8,7)                                 returns 8

Both Index and Nth work with numbers and text.

Rtos

The Rtos function formats numbers with units. The function name is short for "real to string," but has nothing to do with strings! (A similar function, Angtos, formats angles.) Here is how to use it.

Say a drawing has units that are architectural, but you want Diesel to report numbers in decimal notation, with one decimal place of accuracy. In the following example, the Rtos function formats the first chamfer distance, ChamferA:

$(rtos,($getvar,chamfera),2,1)

Where:

($getvar,chamfera) -- name of the system variable, the source of the real number that you want to format.

2 -- format of the number, decimal in this case. Diesel uses the same code as LUnits; see the table below for more info. When you leave out this digit, BricsCAD reads the value found in the LUnits (linear units) sysvar.

mode lunits

1 --- precision of the number, one decimal place in this case. When this digit is left out, then the value of LuPrec (linear units precision) is used by default. The range is 0 to 8, meaning zero to eight decimal places but the precision itself varies depending on the units of the angle, as shown by the table below:

angular units

Formatting Angles

Angles are formatted through the Angtos function, short for "angle to string." In this example, the Angtos function formats the chamfer angle, ChamferD:

$(angtos,($getvar,chamferd),2,1)

Where:

($getvar,chamferd) --- specifies the name of the system variable, the source of the angle.

2 --- specifies the format of the angle, grads in this case. Diesel uses the same code as the AUnits (angle units) system variable. When this digit is left out, BricsCAD reads the current value in AUnits.

mode aunits

1 --- specifies the precision of the angle, one decimal place in this case. When this digit is left out, then AuPrec (angular units precision

FORMATTING TEXT

Diesel provides the most rudimentary of functions for formatting text.

Upper

Diesel includes an Upper function that converts the entire text string to uppercase. This useful for comparing two text strings, to ensure they are identical. There is no "Lower" function.

StrnLen

The StrLen function determines the number of characters in a string, while the Substr extracts a portion of a string. Details on these and other functions are found later in this post.

Other types of text formatting, such as boldface and coloring, are not available in Diesel.

VARIABLES IN DIESEL

You can use variables with Diesel functions. When you have the result of one calculation, you may wish to store it for use later on by another second calculation --- kind of like using memory on a calculator. Here is how you accomplish this:

  1. First, you use the SetVar command to store the value in one of the user system variables, such as UserR1. (This must be done outside of the menu macro.)
    Command: setvar
    Enter the variable name or [?]: userr1
    Enter new value for USERR1 <0.0000>: 3.141
  2. Then you can access it inside the menu macro with the $(getvar function: $(+,$(getvar,userr1),25)

The following user system variables can be used with Diesel:

  • UserR1 through UserR5 to store reals (numbers with decimals)
  • UserI1 through UserI5 to store integers (numbers without decimals)
  • UserS1 through UserS5 to store strings (text)

Actually, you can store anything you want in these 15 sysvars; it's just handy that they are labeled with R (for real), I (for integer), and S (for string). Careful though: the contents of these sysvars are wiped clean when BricsCAD closes. The next time you start BricsCAD, their values are all 0.

Complete Catalog of Diesel Functions

Here are details on all Diesel functions supported by BricsCAD.

MATH FUNCTIONS

Diesel supports the four basic arithmetic functions.

+

The + (Addition) function adds together up to nine numbers:

$(+,2,3.4,10,5)                   returns 20.4

The function works with as little as one value, adding the value to 0:

$(+,2)                             returns 2

--

The -- (Subtraction) function subtracts as many as eight numbers from a ninth. For example, the following equation should be read as 2 -- 3.4 -- 10 -- 5 = -16.4:

$(--,2,3.4,10,5)                   returns -16.4

As another example, this equation should be read as 2 -- 0 = 2:

$(-,2)                             returns 2

*

The * (Multiplication) function multiplies together up to nine numbers.

$(*,2,3.4,10,5)                   returns 340

When you store the value of pi (3.141) in UserR1, you can perform calculations that involve circles. For instance, recall that to find the area of a circle the formula is pi * r2. Diesel doesn't support squares or exponents, so you need to multiple r by itself: pi * r * r.

To find the area of a 2.5"-radius circle:

$(*,$(getvar,userr1),2.5,2.5) returns 19.63125

/

The / (Division) function divides one number by up to eight other numbers.

$(/,2,3.4,10,5)                   returns 0.01176471

This one reads as 2 / 3.4 / 10 / 5 = 0.1176471.

LOGIC FUNCTIONS

The logic functions test to see if two (or more) values are equal (or not).

=

The = (Equal) function determines if two numbers (or strings) are equal. If so, the function returns 1; if not, it returns 0.

$(=,2,2)                           returns 1

$(=,2,3.4)                        returns 0

<

The < (Less than) function determines if one number is less than another. If so, the function returns 1; if not,  it returns 0.

$(<,2,2)                           returns 0

$(<,2,3.4)                        returns 1

>

The > (Greater Than) function determines if one number is greater than another. If so, the function returns 1; if not, it returns 0.

$(>,2,2)                           returns 0

$(>,2,3.4)                        returns 1

!=

The != (Not Equal) function determines if one number is not equal to another. If not equal, the function returns 1; if equal, it returns 0.

$(!=,2,2)                          returns 0

$(!=,2,3.4)                        returns 1

<=

The <= (Less Than or Equal) function determines if one number is less or equal than another. If so, the function returns 1; if not, it returns 0.

$(<=,2,2)                          returns 1

$(<=,2,3.4)                        returns 1

$(<=,9,0.5)                        *returns *0

>=

The >= (Greater Than or Equal) function determines if one number is greater than or equal to another. If so, the function returns 1; if not, it returns 0.

$(>=,2,2)                          *returns *1

$(>=,9,0.5)                        returns 1

$(>=,2,3.4)                        returns 0

AND

The and (Logical Bitwise AND) function returns the bitwise logical "AND" of two or more integers.

This function operates on up to nine integers.

EQ

The eq (Equality) function determines if two numbers (or strings) are equal. If identical, the function returns 1; otherwise, it returns 0.

$(eq,2,2)                          returns 1

$(eq,9,0.5)                        returns 0

The values have to be exactly equal; for instance, a real number is not the same as an integer number, as the following example illustrates:

$(eq,2.0,2)                        returns 0

Normally, you wouldn't test two numbers; instead, you would test a number and a value stored in a variable. For example, to check if LUnits is set to 4 (architectural units):

$(eq,$(getvar,lunits),4)         returns 1 when LUnits = 4

returns 0 if LUnits = any other number

IF

The if function checks if two expressions are the same. If so, the function carries out the first option, and ignores the second option; if false, it carries out the second option. In generic terms:

$(if,test,true,false)

where:

*test *--- specifies another logic function, such as $(eq,clayer,0); *test *expects a value of 1          (true) or  0 (false).

*true *---     indicates the action to take when the test is true.

*false *---    indicates the action to take when the test is false.

For example, the following test checks to see if the current layer is not 0. If so, it then gets the name of the layer. Notice that the *true *parameter is missing.

$(if,$(eq,clayer,"0"),,$(getvar,clayer))

OR

The or (Logical OR) function returns the bitwise logical "OR" of two or more integers.

XOR

The xor (Logical Bitwise Xor) function returns the bitwise logical "XOR" (eXclusive OR) of two or more integers.

CONVERSION FUNCTION

The conversion functions change the state of numbers.

FIX

The fix function removes the decimal portion from real numbers, converting them to integers. This function can be used to extract the number before the decimal point from a real number. (There is no "round" function.)

$(fix,3.99)                        returns 3

STRING FUNCTIONS

The string functions manipulate text (and sometimes numbers).

INDEX

The index function extracts one element from a comma-separated series. Autodesk® suggests using this function to extract the x, y, and z coordinates from variables returned by the ($getvar function.

In generic terms, the function looks like this:

$(index,item,string)

where:

*item *--- a counter;  starts with 0.

*string *---  the text being searched; contains comma-separated items.

Note that the *item *counter starts with 0, instead of 1; the first item is #0:

$(index,0,"2,4,6")                returns 2

*String *must be text surrounded by quotation marks; leave out the quotation marks, and Diesel ignores the function. The string consists of one or more items separated by commas.

Here is an example of extracting the y coordinate from the LastPoint system variable:

$(index,1,$(getvar,lastpoint)) returns 64.8721

(The result will differ, depending on the coordinate stored in LastPoint.) Use the following *item *values to extract specific coordinates:

  • 0                    X
  • 1                    Y
  • 2                    Z

NTH

The nth function extracts the nth element from one or more items. This function handles up to eight items. Like index, the first item in the list is #0. In generic terms, the function looks like this:

$(nth,item,n1,n2,...)

where:

*item *--- a counter; range is 0 to 7.

*n *--- a list of items separated by commas; maximum of eight items in the list.

If *item *exceeds n, then Diesel ignores this function.

Here are examples of using the function with numbers and text:

$(nth,2,2.3,4.5,6.7)              returns 6.7

$(nth,1,Tailoring,BricsCAD,CAD) returns BricsCAD

STRLEN

The strlen (String Length) function returns the number of characters in the string.  This function is useful for finding the length of a string before applying another function, such as substr.

$(strlen,Tailoring BricsCAD)     returns 18

If the string is surrounded by quotation marks, Diesel ignores them.

$(strlen,"Tailoring BricsCAD") also returns 18

This function also works with numbers and system variables:

$(strlen,3.14159)                 returns 7

$(strlen,$(getvar,platform))     returns 38

SUBSTR

The substr (SubString) function returns a portion of a string. This is useful for extracting text from a longer portion. Generically, the function looks like this:

$(substr,string,start,length)

where

*string *---  specifies the text to be handled.

*start *--- indicates the starting position of the substring; first character is #1.

*length *--- specifies the length of the substring; optional.  If left out,  the entire rest of the string is returned.

Here are some examples of this function at work:

$(substr,Tailoring BricsCAD,5) returns oring BricsCAD

$(substr,Tailoring BricsCAD,5,7) returns oring B

If the string is surrounded by quotation marks, Diesel ignores them.

$(substr,"Tailoring BricsCAD",5) *also returns *oring BricsCAD

This function also works with numbers and system variables:

$(substr,3.14159,1,4)            returns 3.14

$(substr,$(getvar,platform),5,15) returns osoft Windows N

UPPER

The upper (uppercase) function converts text strings to uppercase characters. (There is no "lower" function in Diesel.) It works with text and system variables, as follows:

$(upper,"Tailoring BricsCAD") returns TAILORING BRICSCAD

$(upper,$(getvar,platform)) returns MICROSOFT WINDOWS NT VERSION 5.0

The function also works with numbers but leaves them unchanged.

SYSTEM FUNCTIONS

The system functions are a collection of miscellaneous functions.

EDTIME

The edtime (Evaluate Date Time) function formats the display of the system time. This function reads the date and time from the Date system variable, and then formats it according to your instructions. Generically, the function looks like this:

$(edtime,$(getvar,date),format) where

*format *--- specifies how the date and time should be displayed, as illustrated by the table below.

When *format *contains text that Diesel cannot interpret, it is displayed literally. The table shows date formatting codes for a date of September 5, 2006:

date formats

The table below lists time formatting codes for a time of 1:51:23.702AM:

Time Formats

TIP To use commas in the format code, surround them with ","" so that Diesel does not read the comma as an argument separator.

The quotation-mark trick does not work for words like "Date" and "Month": Diesel returns 1date and 7onth.

The date and time codes are case-insensitive; D and d work the same. The exceptions are for the AM/PM and am/pm codes.

When the AM/PM and A/P format codes are used, Diesel displays the 12-hour clock; when they are left out, Diesel displays the 24-hour clock.

The AM/PM and A/P format codes must be entered with the slash. If, say, PM is entered, then Diesel returns P literally and reads M as the single-digit month code.

Here are some examples of using the EdTime function:

$(edtime,$(getvar,date),H:MMam/pm)                returns 11:58am

$(edtime,$(getvar,date),DDD"," DD-MO-YY)         returns Fri, 01-07-05

$(edtime,$(getvar,date), DDD"," d mon"," YYYY) returns Fri, 1 Jul, 2015

EVAL

The eval (Evaluate) function displays text on the status bar:

Command: modemacro

Enter new value for MODEMACRO, or . for none <"">: $(eval,"This is text")

It is equivalent to using the ModeMacro command without Diesel:

Command: modemacro

Enter new value for MODEMACRO, or . for none <"">: This is text

GETENV

The getenv (Get Environment) function gets the values stored in environment variables. This function was designed for use with AutoCAD® LT, which has two commands not found in AutoCAD®: SetEnv sets values in environment variables, and GetEnv reads the values. These environment variables were originally stored in a file named aclt.ini, but are now stored in the Windows Registry.

$(getenv,maxarray)                         returns 10000

As of BricsCAD V12, the behavior of $(getenv) is now consistent with that of LISP and SDS/BRX: it searches for environment variables in the BricsCAD environment registry; in Windows, Linux, or Mac process environment; and in BricsCAD CFG settings. The read sequence is:

  1. BricsCAD Windows registry
  2. Linux, Mac or  Windows process environment
  3. BricsCAD configuration

The Write sequence is (a) BricsCAD configuration (if a key is present) and (b) BricsCAD Windows registry.

GETVAR

The getvar (Get Variable) function gets the values of system variables.

$(getvar,lunits)                  returns 4

LINELEN linelen (line length) function returns the maximum length of display.

$(linelen)                        returns 240

DIESEL PROGRAMMING TIPS

Here are some tips for working with Diesel:

  • Each argument must be separated by a comma; there must be no spaces within the expression.
  • The maximum length of a Diesel macro is 240 characters; the maximum display on the status bar is 32 characters.
  • The ModeMacro system variable outputs text directly to the status bar until it reaches a $(, and then it begins evaluating the macro.
  • Use the MacroTrace system variable to debug macros.
  • Use LISP's (strcat) function to string together Diesel macros within LISP.
  • Use the $M= construct to use Diesel expressions in menu and toolbar macros.

Debugging Diesel

The purpose of the MacroTrace system variable is to help track down bugs in Diesel macros. When on, a step-by-step evaluation of the Diesel macro should be displayed in the Text window. Although MacroTrace exists in BricsCAD, it is not yet implemented.

Instead, BricsCAD displays errors directly, whether in a menu or on the command line. Below, I entered Diesel code with a non-exist ant sysvar, "nonsense."

diesel code lesson

Error reported by Diesel

ModeMacro: Displaying Text on the Status Bar

The purpose of the ModeMacro command is to display text on the status bar.

Should BricsCAD ever get this function, then here is how to use it. First, let's see how to display text to the status bar:

  1. Enter the ModeMacro system variable at the 'Command:' prompt, and then type something:
    *Command: modemacro
    New value for MODEMACRO, or . for none <"">: *Customizing BricsCAD
    The words "Customizing BricsCAD"  should appear at the far left of the status bar:

17

Using Diesel to display text on the status bar

(You cannot change the location where the text is positioned on the status bar.)
  1. To remove the text from the status bar, type the ModeMacro system variable with a.  (null string), as follows:
    Command: modemacro
    New value for MODEMACRO, or . for none <"Customizing BricsCAD">: .

18

Removing user-defined text from the status bar

Ralph Grabowski

by Ralph Grabowski - CAD Writer, publisher of upFront.eZine

Ralph is the publisher of the weekly 'upFront.eZine' e-newsletter on the business of CAD and the 'WorldCAD Access' blog on technology. Author of 240+ books and ebooks about computer-aided design, and producer of 220+ videos on using CAD.

Follow us on social media