Documente Academic
Documente Profesional
Documente Cultură
R E L E A S E
Visual LISP
Guide
Autodesk Trademarks
The following are registered trademarks of Autodesk, Inc., in the USA and/or other countries: 3D Plan, 3D Props, 3D Studio, 3D Studio
MAX, 3DSurfer, ADCADD, ADE, ADI, Advanced Modeling Extension, AEC AUTHORITY, AEC-X, AME, Animator Pro, Animator Studio,
ATC, Auto-Architect, AutoCAD, AutoCAD Data Extension, AutoCAD Development System, AutoCAD LT, AutoCAD Map, Autodesk,
Autodesk Animator, the Autodesk logo, Autodesk University, Autodesk View, AutoLISP, AutoShade, AutoSketch, AutoSolid, AutoSurf,
AutoVision, CAD OVERLAY, DesignBlocks, Design Companion, DRAFIX, Education by Design, Generic, Generic CADD, Generic Software,
Generic 3D Drafting, Geodyssey, Heidi, HOOPS, Inside Track, Kinetix, MaterialSpec, Mechanical Desktop, Multimedia Explorer, NAAUG,
Office Series, Opus, Picture This Home!, PLANIX, RASTATION, Softdesk (goods), Softdesk (services), Solution 3000, STAR DESIGN,
TECHTALK, Texture Universe, THE AEC AUTHORITY, THE AUTO ARCHITECT, TinkerTech, WHIP!, Woodbourne, WorkCenter, and WorldCreating Toolkit.
The following are trademarks of Autodesk, Inc., in the USA and/or other countries: 3D for the PC, 3D Studio VIZ, ACAD, Advanced User
Interface, AEC Office, AME Link, Animation Partner, Animation Player, Animation Pro Player, A Studio in Every Computer, ATLAST,
Auto-Architect, AUGI, AutoCAD Learning Assistance, AutoCAD LT Learning Assistance, AutoCAD Simulator, AutoCAD SQL Extension,
AutoCAD SQL Interface, AutoCDM, Autodesk Animator Clips, Autodesk Animator Theatre, Autodesk Device Interface, Autodesk
MapGuide, Autodesk PhotoEDIT, Autodesk Software Developers Kit, Autodesk View DwgX, Autodesk WalkThrough, Autodesk World,
AutoEDM, AutoFlix, AutoLathe, AutoSnap, Biped, bringing information down to earth, Built with ObjectARX, Carpe Datum, Character
Studio, Concept Studio, Content Explorer, cornerStone Toolkit, DESIGNX, DesignScape, Designers Vision, Design Your World, DXF,
DWG Unplugged, Exegis, FLI, FLIC, GDX Driver, Generic 3D, Home Series, HyperWire, MAX DWG, Multiped, NetHead, ObjectARX,
ObjectDXF, Octoped, PeopleTracker, PHOTO LANDSCAPE, PHOTOSCAPE, Physique, PolarSnap, Power and Light, Powered with
Autodesk Technology, Quadruped, QuickCAD, RadioRay, SchoolBox, SketchTools, Smoke and Mirrors, Suddenly Everything Clicks,
Supportdesk, Total House, Transforms Ideas Into Reality, and Visual LISP.
GOVERNMENT USE
Use, duplication, or disclosure by the U. S. Government is subject to restrictions as set forth in FAR 12.212 (Commercial Computer
Software-Restricted Rights) and DFAR 267.7202 (Rights in Technical Data and Computer Software), as applicable.
Quick Tour
18
22
Getting Started 23
Before You Begin 23
Starting Visual LISP 23
Overview of the Visual LISP User Interface 24
The Visual LISP Text Editor 25
Other Visual LISP Windows 26
Menu Overview 26
Variable Menu Contents 26
Menu Summary 27
The Console 28
Text Editor Overview 29
Loading and Running AutoLISP Programs 30
Running Selected Lines of Code 32
Exiting the Visual LISP Environment 32
iv
Chapter 2
AutoLISP Basics
34
AutoLISP Expressions 35
AutoLISP Data Types 36
Integers 36
Reals 36
Strings 37
Lists 37
Selection Sets 37
Entity Names 38
VLA Objects 38
File Descriptors 38
Symbols and Variables 39
AutoLISP Function Syntax 39
AutoLISP Program Files 40
Formatting AutoLISP Code 40
Spaces in AutoLISP Code 41
Comments 41
Visual LISP Comment Styles 42
Color Coding 42
AutoLISP Variables 42
Displaying the Value of a Variable 43
Nil Variables 43
Predefined Variables 44
Number Handling 44
String Handling 45
Basic Output Functions 47
Displaying Messages 48
Exiting Quietly 48
Control Characters in Strings 49
Wild-Card Matching 50
Equality and Conditional 52
List Handling 52
Point Lists 54
Dotted Pairs 56
Symbol and Function Handling 57
C:XXX Functions 58
Adding Commands 60
Redefining AutoCAD Commands 60
Local Variables in Functions 62
Local Variables Versus Global Variables
Example Using Local Variables 63
Functions with Arguments 64
Contents
62
Chapter 3
Using AutoLISP to
Communicate with
AutoCAD 66
Query and Command Functions 67
Command Submission 67
Foreign-Language Support 68
Pausing for User Input 68
Passing Pick Points to AutoCAD Commands 69
System and Environment Variables 69
Configuration Control 70
Display Control 70
Controlling Menus 70
Control of Graphics and Text Windows 73
Control of Low-level Graphics 74
Getting User Input 74
The getxxx Functions 75
Control of User-Input Function Conditions 77
Input Options for User-Input Functions 77
Key Word Options 78
Arbitrary Keyboard Input 79
Input Validation 79
Geometric Utilities 80
Object Snap 80
Text Extents 81
Conversions 84
String Conversions 85
Angular Conversion 87
ASCII Code Conversion 88
Unit Conversion 89
Converting from Inches to Meters 90
The Unit Definition File 90
Coordinate System Transformations 92
Point Transformations 94
File Handling 95
File Search 95
Accessing Help Files 96
Device Access and Control 97
Accessing User Input 97
Calibrating Tablets 98
Chapter 4
Using AutoLISP to
Manipulate AutoCAD
Objects 102
Selection Set Handling 103
Contents
vi
Developing Programs
With Visual LISP 138
Getting Organized 139
The System Console 139
System Console Behavior 140
The System Console Context Menu 141
Separators Processing 142
Color Coding of Console Input 143
Contents
vii
174
Contents
viii
Contents
ix
Building Applications
214
Contents
244
Advanced Topics
268
Contents
xi
AutoLISP
Function Reference 302
Selection Set Filters 422
Relational Tests 422
Logical Grouping of Filter Tests
424
Contents
xii
Contents
xiii
Introduction
In this chapter
For years, AutoLISP has set the standard for customizing
Recommendations on
Using this Guide
Document Conventions
AutoCAD. Visual LISP now adds significantly more capabilities to AutoLISP for AutoCAD. It extends the language to
interface with objects via the Microsoft ActiveX Automation interface, and adds the ability to have AutoLISP
respond to events via object reactors. As a development
tool, Visual LISP provides a complete integrated development environment (IDE), including a compiler, debugger,
and other tools to increase productivity in rapidly customizing AutoCAD.
14
Visual LISP
Visual LISP(VLISP) is a software tool designed to expedite AutoLISP program
development. VLISPs integrated development environment provides features to help ease the tasks of source-code creation and modification, program testing, and debugging. In addition, VLISP provides a vehicle for delivering stand-alone ObjectARX applications written in AutoLISP.
In the past, developing AutoLISP programs for AutoCAD meant working with
some text editor (which you had to provide) to write your code, then loading
the code into AutoCAD and running it. Debugging your program meant adding statements to print the contents of variables at strategic points in your
program. You had to figure out what were good points in your program to do
this, and what variables you needed to look at. If you discovered you still
didnt have enough information to determine the error, you had to go back
and change the code again, adding more debugging points. And finally,
when you got the program to work correctly, you needed to either comment
out or remove the debugging code you added.
Introduction
15
16
ment, you will need to interact with AutoCAD in order to work with graphics
and, in some instances, to respond to prompts for input.
TIP
LISP.
Keep AutoCAD open on your desktop whenever you work with Visual
If AutoCAD is minimized when Visual LISP turns control over to it, you have
to manually restore and activate the AutoCAD window in order to continue.
Visual LISP will not restore the AutoCAD window for you. Instead, the following symbol appears in the Visual LISP window
and remains there until you activate AutoCAD and respond to the prompts
at the AutoCAD Command prompt. The Quick Tour chapter shows an
example of this; see Loading and Running AutoLISP Programs on page 30.
Introduction
17
If you are already familiar with AutoLISP, you may want to go right to the
tutorial after reading Chapter 1. This is a matter of personal comfort: if
you feel you need to understand how everything works before using a
tool, you might be better off reading some or all of chapters 5 through 9
before trying the tutorial. See Using the Heart of the Manual (below) for
a brief description of each chapter.
If you do not already know AutoLISP, read all of Chapter 2, AutoLISP
Basics, and at least browse Chapters 3 and 4 (Using AutoLISP to Communicate with AutoCAD and Using AutoLISP to Manipulate AutoCAD
Objects. After that, you can either work through the tutorial or choose
from the chapters described below.
If youre ready to tackle the tutorial, here is one more word of caution: the
tutorial is somewhat irreverent -- well, for Autodesk, at least.
18
Document Conventions
This document follows a number of stylistic and naming conventions when
describing actions or defining terms. Often, distinct typefaces are used to distinguish items from the rest of the text. The following table lists some of the
conventions used in the Visual LISP Guide:
Typographical conventions
Text element
Example
Introduction
19
Example
File names and directory names are Double-click the file name drawline.lsp.
shown in italics, when referred to in a The default install directory is
C:\Program Files\AutoCAD R14\VLISP
sentence
In definitions that include variable
text, the variable is in italics
Document Conventions
20
Introduction
21
1
Quick Tour
In this chapter
Getting Started
Menu Overview
Console Overview
22
Getting Started
Before You Begin
Before you start, note where the Visual LISP program files are installed on
your computer. By default, it installs in a folder named VLISP, as a subdirectory of the AutoCAD install directory. For example:
C:\PROGRAM FILES\AUTOCAD R14\VLISP
If you changed the default when you installed Visual LISP, substitute that
directory path anywhere you see
C:\PROGRAM FILES\AUTOCAD R14\VLISP referenced in this document.
Chapter 1
23
Quick Tour
from the Tools menu, this file name will automatically be listed in the Load
dialog box.
5 Click the Load button to start Visual LISP.
As VLISP loads, one or more VLISP windows display momentarily, then the
AutoCAD window returns.
If the Visual LISP window is not the active window (that is, if AutoCAD is on
top), type vlide in the AutoCAD command area, then press ENTER.
Toolbars
Console
Status
Bar
The areas shown in the Visual LISP screen are:
Menu. You can issue VLISP commands by selecting from the various
menus items. If you highlight an item on a menu, VLISP displays a brief
description of the commands function in the status bar at the bottom of
the screen.
24
You may also see a minimized Trace window. At start-up, this window contains informational messages about the current release of Visual LISP, and
may contain additional information if VLISP encounters errors during startup.
Chapter 1
25
Quick Tour
Menu Overview
You can issue VLISP commands by selecting from the various menus items.
For example, from the File menu you can create a new AutoLISP program file,
select an existing program file to edit, and print the file youre editing.
Menu Overview
26
The last items on the menu are Parentheses Matching and Extra Commands.
Now click in the title bar of the AutoLISP Console window, then select the
Edit menu item again:
Notice that Extra Commands is no longer the last item on the menu.
Parentheses Matching is followed by two new items, Console History Up
and Console History Down; these items apply only to a Console window.
Menu Summary
Here is a brief summary of the contents of each menu item; you will learn
how to use the various menu commands as you proceed to learn Visual LISP:
Chapter 1
27
The File menu allows you to create a new AutoLISP program file for editing, open an existing file, save changes you make to program files, and
print the program file.
The Edit menu allows you to copy and paste text, undo the last change
you made to text (or undo the last command entered in the Console window), select text in the editor or Console windows, match parentheses in
Quick Tour
expressions, and redisplay previous commands youve entered at the Console prompt.
The Search menu allows you to find and replace text strings, set bookmarks, and navigate among bookmarked text. See Developing Programs
With Visual LISP for information on these topics.
The View menu contains commands for finding and displaying the value
of variables and symbols in your AutoLISP code. For more information on
this topic, see Debugging Programs.
The Project menu contains commands for working with projects and
compiling programs.
The Debug menu allows you to set and remove break points in your program, and to step through program execution one expression at a time.
You can then check the state of variables and the results of expressions.
See Debugging Programs.
The Tools menu contains commands for setting Visual LISP options for
text formatting, and for setting various environment options such as the
placement of windows and toolbars.
The Window menu allows you to organize the windows currently displayed in your VLISP session, and to activate another Visual LISP or
AutoCAD window.
The Help menu displays online Help.
The Console
From the Console window, you can enter and run AutoLISP commands and
see the results of those commands. This is similar to what you can do in the
AutoCAD command window, but Visual LISP contains its own distinctive
command interpreter for executing commands. As a result, there are a few
differences -- some subtle -- in how you accomplish the same task in each
interface. For example, to display the current value of an AutoLISP variable
in Visual LISP, you simply type the variable name in the Console window and
press ENTER. To view the value of a variable in AutoCAD, you must precede
the variable name with an exclamation point (!) when you type it in the command window.
The Console is also where Visual LISP displays AutoLISP diagnostic messages
and displays the result of many AutoLISP functions. For example, output
from the print and princ functions are displayed in the Console window.
You can scroll through the Console window to view previously entered text
and output.
The Console
28
You can enter an AutoLISP expression for Visual LISP to read, evaluate,
and display the results. If you need more than one line to type your
expression, press CTRL+ENTER to continue it on a second line.
You can enter more than one expression before pressing the ENTER key.
You can copy and transfer text between the Console and the text editor
window. Most text editor commands are also available in the Console.
Pressing the TAB key retrieves the previous command you entered in the
Console. You can press TAB repeatedly to retrieve earlier commands. Pressing SHIFT+TAB key retrieves commands in the opposite direction.
The TAB key lets you perform an associative search in the input history.
For example, if you begin an expression with (+ and then press TAB,
VLISP retrieves the last command you entered that begins with (+. To
reverse the direction of the search, press SHIFT+TAB.
The ESC key clears any text following the Console prompt.
Pressing SHIFT+ESC leaves the text you typed at the Console prompt without interpreting it, and displays a new Console prompt.
Clicking the right mouse button, or pressing SHIFT+F10 anywhere in the
Console window, displays a menu of Visual LISP commands and options.
For example, you can use this feature to copy and paste text in the Console command line, search for text, and initiate VLISP debugging features.
Note that if you type text at the Console prompt, but switch to the AutoCAD
window before pressing ENTER, the text is lost from the prompt when you
return to the Visual LISP window.
Chapter 1
29
Quick Tour
Color Coding. The editor identifies different parts of an AutoLISP program and assigns distinct colors to them. This allows you to easily find
program components such as function calls and variable names, and can
help you find typographical errors.
Text Formatting. The editor can format AutoLISP code for you, making
it easier to read. You can choose from a number of different formatting
styles.
Parenthesis Matching. AutoLISP code contains many parentheses. The
editor can help you find the close parenthesis that goes with an open
parenthesis, and help you detect missing parentheses.
Execution of AutoLISP Expressions. You can test expressions and
lines of code without leaving the text editor.
Searching Through Multiple Files. You can search for a word or
expression in several files with a single command.
Syntax Checking. You can use Visual LISP syntax-checking features
from within the editor.
Details on using the Visual LISP text editor are in Developing Programs With
Visual LISP.
30
The drawline program doesnt do much: it asks you to specify two points in
an AutoCAD graphics window, and then it draws a straight line between
those points.
Because drawline asks for user input, Visual LISP turns control over to
AutoCAD, where you have the option of specifying points in the graphics
window or the command line. What you see next depends on whether or not
the AutoCAD windows are currently displayed on your desktop. If they are,
youll see the AutoCAD windows. But if AutoCAD is currently minimized on
your desktop, it wont automatically be restored and displayed. Instead,
Visual LISP will remain visible and your mouse pointer will change to the following icon:
This indicates that the Visual LISP window is no longer active. If this is the
case, you need to manually switch to the AutoCAD window. Click the
AutoCAD icon on the Windows task bar to activate AutoCAD.
Notice that prompts for input are displayed in the AutoCAD command window:
4 After you respond to all the prompts, control returns to Visual LISP and youll
once again see the VLISP window.
When you enter commands in the Visual LISP Console or run a program
loaded from the text editor, you may frequently be switching back and forth
between the Visual LISP and AutoCAD windows. Besides using the standard
Windows methods of switching between applications, you have a couple of
alternate methods of switching between Visual LISP and AutoCAD windows:
Chapter 1
31
From Visual LISP, you can activate the AutoCAD window by either
choosing Window>Activate AutoCAD from the menu, or clicking on the
Activate AutoCAD button on the Run toolbar.
Quick Tour
If you are in AutoCAD and want to return to the Visual LISP environment,
you can enter the command vlide in the command window.
Click the Load Selection button on the Run toolbar. VLISP immediately runs
the code through its command interpreter, and turns control over to
AutoCAD to prompt you for input.
You can either save all the changes youve made (Yes) or none of the changes
(No).
If you exit Visual LISP while there are still programs open in text windows,
Visual LISP automatically opens those same programs the next time you start
a VLISP session.
32
Chapter 1
33
Quick Tour
2
AutoLISP Basics
In this chapter
AutoLISP Expressions
AutoLISP Program
Files
AutoLISP Variables
Number Handling
String Handling
List Handling
34
AutoLISP Expressions
An AutoLISP program consists of a series of expressions. AutoLISP expressions
have the following form:
(function arguments)
If you enter this code at the Visual LISP Console prompt, Visual LISP invokes
its AutoLISP interpreter to process the code. The first function, fun1, has two
arguments, and the other functions, fun2 and fun3, have one argument each.
The functions fun2 and fun3 are surrounded by function fun1, so their return
values are passed to fun1 as arguments. Function fun1 evaluates those two
arguments and returns the value to Visual LISP, which in this case was the
calling function. Visual LISP displays the returned value in the Console window.
The following example shows the use of the * (multiplication) function,
which accepts one or more real numbers as arguments.
_$ (* 2 27)
54
Because this code example has no surrounding expression, it returns the
result to Visual LISP.
Chapter 2
35
AutoLISP Basics
Expressions nested within other expressions return their result to the surrounding expression. The following example uses the result from the
+ (addition) function as one of the arguments for the * (multiplication)
function.
_$ (* 2 (+ 5 10))
30
If you enter the incorrect number of closing (right) parentheses, Visual LISP
displays the following prompt:
(_>
The number of left parentheses in this prompt indicates how many levels of
left parentheses remain unclosed. If this prompt appears, you must enter the
required number of right parentheses for the expression to be evaluated.
_$ (* 2 (+ 5 10
((_> ) )
30
A common mistake is to omit the closing quotation mark (") in a text string,
in which case the right parentheses are interpreted as being part of the string
and have no effect in resolving the open parentheses. To correct this condition, cancel the function by pressing SHIFT+ESC and re-enter it correctly.
Integers
Integers are whole numbers that do not contain a decimal point. AutoLISP
integers are 32-bit signed numbers with values ranging from +2,147,483,648
to 2,147,483,647. When you explicitly use an integer in an AutoLISP expression, that value is known as a constant. Numbers such as 2, 56, and
1,200,196 are valid AutoLISP integers.
Reals
A real is a number containing a decimal point. Numbers between 1 and 1
must contain a leading zero. Real numbers are stored in double-precision
floating-point format, providing at least 14 significant digits of precision.
Note that Visual LISP does not show you all of the significant digits.
AutoLISP Expressions
36
Reals can be expressed in scientific notation, which has an optional e or E followed by the exponent of the number (for example, 0.0000041 is the same
as 4.1e-6). Numbers such as 3.1, 0.23, 56.123, and 21,000,000.0 are valid
AutoLISP reals.
Strings
A string is a group of characters surrounded by quotation marks. Within
quoted strings the backslash (\) character allows control characters (or escape
codes) to be included. When you explicitly use a quoted string in an
AutoLISP expression, that value is known as a literal string or a string constant.
Examples of valid strings are "string 1" and "\nEnter first point:".
Lists
An AutoLISP list is a group of related values separated by spaces and enclosed
in parentheses. Lists provide an efficient method of storing numerous related
values. AutoCAD expresses 3D points as a list of three real numbers.
Examples of lists are (1.0 1.0 0.0), ("this" "that" "the other"), and (1 "ONE").
Selection Sets
Selection sets are groups of one or more objects (entities). You can interactively add objects to, or remove objects from, selection sets with AutoLISP
routines.
Chapter 2
37
AutoLISP Basics
The following example uses the ssget function to return a selection set containing all of the objects in a drawing.
_$ (ssget "X")
<Selection set: 1>
Entity Names
An entity name is a numeric label assigned to objects in a drawing. It is actually a pointer into a file maintained by AutoCAD, and can be used to find the
objects database record and its vectors (if they are displayed). This label can
be referenced by AutoLISP functions to allow selection of objects for processing in various ways. Internally, AutoCAD refers to objects as entities.
The following example uses the entlast function to get the name of the last
object entered into the drawing.
_$ (entlast)
<Entity name: 27f0540>
VLA Objects
Objects in a drawing may be represented as VLA objects, a data type introduced with Visual LISP. (VLA stands for Visual LISP ActiveX.) When working with ActiveX functions, you must refer to VLA objects, not the ename
pointer returned by functions such as entlast. For information on working
with ActiveX objects, see Using ActiveX Objects with Visual LISP on
page 269.
File Descriptors
File descriptors are alphanumeric labels assigned to files opened by AutoLISP
functions. When an AutoLISP function needs to read or write to a file, the
label of the file must be referenced.
The following example opens the file myinfo.dat for reading. The open function returns the file label:
_$ (setq file1 (open "c:\\myinfo.dat" "r") )
#<file "c:\\myinfo.dat">
In this example, the file label is stored in variable file1.
Files remain open until you explicitly close them in your AutoLISP program.
The close function closes a file. The following code closes the file whose
label is stored in variable file1:
_$
nil
(close file1)
AutoLISP Expressions
38
Chapter 2
39
AutoLISP Basics
In the preceding example, the function foo has one required argument,
string, and one optional argument, number. Additional number arguments
can be provided. Frequently, the name of the argument indicates the
expected data type. The examples in the following table show both valid and
invalid calls to the foo function.
Valid and invalid calls to the foo function
Valid calls
Invalid calls
(foo "catch")
(foo 44 13)
(foo)
40
ter issues an error message if the text you selected is not a sequence of valid
AutoLISP expressions.
You can set a number of options to customize the way the code formatter lays
out your code. See Formatting Code with the Visual LISP Formatter on
page 162 for more details on using the Visual LISP code formatter.
Comments
It is a good practice to include comments in AutoLISP program files. Comments are useful to both the programmer and future users who may need to
revise a program to suit their needs. Use comments to
Comments begin with a semicolon (;) and continue through the end of the
line.
; This entire line is a comment
(setq area (* pi r r)) ; Compute area of circle
The following example shows a comment that continues for multiple lines:
(setvar "orthomode" 1) ;|comment starts here
and continues to this line,
but ends way down here|; (princ "\nORTHOMODE set On.")
Chapter 2
41
AutoLISP Basics
Color Coding
Visual LISP provides an additional solution to making AutoLISP text easier to
read: color coding. Visual LISP looks at each word of text and tries to determine what type of AutoLISP language element it represents (for example, a
built-in function, a number, a string). Every type of element is assigned its
own color, so you can easily distinguish among them when viewing the code.
Keep in mind that color coding is a Visual LISP editor feature, and it is possible that someone who does not have access to Visual LISP may need to read
your code some day. For this reason, you should still use indentation and
alignment to enhance your programs readability.
AutoLISP Variables
An AutoLISP variable assumes the data type of the value assigned to it. Until
they are assigned new values, variables retain their original values. You use
the AutoLISP setq function to assign values to variables.
(setq variable_name1 value1 [variable_name2 value2 ...])
The setq function assigns the specified value to the variable name given. It
returns the value as its function result. If you issue setq at the Visual LISP
Console prompt, the result is displayed in the Console window:
_$ (setq val 3 abc 3.875)
3.875
_$ (setq layr "EXTERIOR-WALLS")
"EXTERIOR-WALLS"
_$
AutoLISP Variables
42
Nil Variables
An AutoLISP variable that has not been assigned any value is said to be nil.
nil is different from blank, which is considered a character string, and 0,
which is a number. So in addition to checking a variable for its current value,
you can test to determine whether or not the variable has been assigned a
value.
Each variable consumes a small amount of memory, so it is good programming practice to reuse variable names or to set variables to nil when their
values are no longer needed. Setting a variable to nil releases the memory
used to store that variables value. If you no longer need the val variable, you
can release its value from memory with the following expression:
_$
nil
Chapter 2
43
AutoLISP Basics
Predefined Variables
The following predefined variables are commonly used in AutoLISP applications:
PAUSE
PI
NOTE You can change the value of these variables with the setq function.
However, other applications might rely on their values being consistent; therefore, it is recommended that you do not modify these variables. Visual LISP, by
default, protects these variables from redefinition. You must override this protection through the Symbol Service feature in order to modify a predefined variable.
Number Handling
AutoLISP provides functions for working with integers and real numbers. The
number-handling functions are as follows:
+ (addition)
abs
gcd
minusp
(subtraction)
atan
log
rem
* (multiplication)
cos
logand
sin
/ (division)
exp
logior
sqrt
~ (bitwise NOT)
expt
lsh
zerop
1+ (increment)
fix
max
1 (decrement)
float
min
Number Handling
44
bolt that is 0.5" in diameter, how many threads are there if this bolt has 13
threads per inch? Use the * (multiplication) function at the Console prompt.
_$ (* 2.5 13)
32.5
The arithmetic functions that have a number argument (as opposed to num or
angle, for example) return different values if you provide integers or reals as
arguments. If all arguments are integers, the value returned is an integer.
However, if one or all of the arguments are reals, the value returned is a real.
To ensure that your application passes real values, make sure that at least one
of the arguments is a real.
_$ (/ 12 5)
2
_$ (/ 12.0 5)
2.4
NOTE In some cases, you can use integers and reals interchangeably. This is
not the case, however, when using ActiveX function. See Converting Arguments on page 287 in chapter 9.
String Handling
AutoLISP provides functions for working with string values. The string-handling functions are as follows:
strcase
strlen
strcat
substr
wcmatch
The following functions convert string values into numeric values and
numeric values into string values.
Chapter 2
45
angtof
atof
distof
angtos
atoi
itoa
ascii
chr
rtos
AutoLISP Basics
AutoLISP provides numerous control characters for use in strings; for a complete listing, see Control Characters in Strings on page 49.
The strcase function returns the conversion of all alphabetic characters in a
string to upper or lower case. It accepts two arguments: a string, and an
optional argument that specifies the case in which the characters are
returned. If the optional second argument is omitted, it evaluates to nil and
strcase returns the characters converted to upper case.
_$ (strcase "This is a TEST.")
"THIS IS A TEST."
If the second argument is provided and has a non-nil value, the characters
are returned as lower case. AutoLISP provides the predefined variable T to use
in situations like this where a non-nil value is used as a type of true/false toggle. However, you dont need to use T here; if it suits your application better,
you can use any non-nil value.
_$ (strcase "This is a TEST." T)
"this is a test."
The strcat function combines multiple strings into a single string value.
This is useful for placing a variable string within a constant string. The following code sets a variable to a string value and then uses strcat to insert
that string into the middle of another string.
_$ (setq str "BIG") (setq bigstr (strcat "This is a " str " test."))
"This is a BIG test."
If the variable bigstr is set to the preceding string value, you can use the
strlen function to find out the number of characters (including spaces) in
that string.
_$ (strlen bigstr)
19
The substr function returns a substring of a string. It has two required arguments and one optional argument. The first argument is the string. The second argument is an integer that specifies the first character of the string that
you want to include in the substring. If the third argument is provided, it
specifies the number of characters to include in the substring. If the third
argument is not provided, substr returns all characters including and following the specified start character.
You can use the substr function to strip off the three-letter extension from a
file name. First, set a variable to a file name. (Depending on the application,
String Handling
46
prin1
princ
prompt
The remaining display functions are covered in the Using AutoLISP to Communicate with AutoCAD chapter.
The following file-handling functions can also display output to the command line area.
read-char
Chapter 2
47
AutoLISP Basics
read-line
write-char
write-line
Displaying Messages
The basic output functions are prompt, princ, prin1, and print. The prompt
function displays a message (a string) on the AutoCAD command line and
returns nil to the Visual LISP Console. The princ, prin1, and print functions all display an expression (not necessarily a string) at the AutoCAD command line and return the expression to the Visual LISP Console. Optionally,
these functions can send output to a file. The differences are:
displays strings without the enclosing quotation marks
displays strings enclosed in quotation marks
print also displays strings enclosed in quotation marks, but places a blank
line before the expression and a space afterward.
princ
prin1
The following example demonstrates the differences between the four basic
output functions and how they handle the same string of text. The text following prints is what you would see at the AutoCAD Command prompt;
text following returns would appear within the Visual LISP Console or within
an application. See the following section for an explanation of the control
characters used in the example.
(setq str "The \"allowable\" tolerance is \261 \274\"")
(prompt str)
prints
The "allowable" tolerance is
and returns nil
(princ str)
prints
The "allowable" tolerance is
1/4"
and returns
"The \"allowable\" tolerance is
1/4""
prints
"The \"allowable\" tolerance is
1/4""
and returns
"The "\allowable\" tolerance is
1/4""
(prin1 str)
(print str)
prints
1/4"
<blank line>
1/4""
Exiting Quietly
If you invoke the princ function without passing an expression to it, it displays nothing and has no value to return. So if you write an AutoLISP expression that ends with a call to princ without any arguments, the ending nil is
suppressed (because it has nothing to return). This practice is called exiting
quietly.
48
Description
\\
\ character
\"
" character
\e
Escape character
\n
Newline character
\r
Return character
\t
Tab character
\nnn
\U+xxxx
\M+nxxxx
The prompt and princ functions expand the control characters in a string
and display the expanded string in the AutoCAD command window.
If you need to use the backslash character (\) or quotation mark (") within a
quoted string, it must be preceded by the backslash character (\). For example, if you enter
_$
Chapter 2
49
AutoLISP Basics
Name
Office
Sue
101
Joe
102
Sam
103
Wild-Card Matching
The wcmatch function enables applications to compare a string to a wild-card
pattern. You can use this facility when you are building a selection set (in
conjunction with ssget) and when you are retrieving extended entity data
by application name (in conjunction with entget).
The wcmatch function compares a single string to a pattern. It returns T if the
string matches the pattern, and nil if it does not. The wild-card patterns are
similar to the regular expressions used by many system and application
programs. In the pattern, alphabetic characters and numerals are treated literally; brackets can be used to specify optional characters or a range of letters
or digits; a question mark (?) matches a single character; an asterisk ( *)
matches a sequence of characters; and certain other special characters have
special meanings within the pattern. When you use the * character at the
beginning and end of the search pattern, you can locate the desired portion
50
The following code illustrates the use of brackets in the pattern. In this case,
wcmatch returns T if matchme contains "test4", "test5", "test6", or "test9"
(note the use of the * character).
_$
nil
However,
_$
T
Chapter 2
51
AutoLISP Basics
= (equal to)
and
or
Boole
repeat
cond
while
eq
equal
if
List Handling
AutoLISP provides functions for working with lists. The list-handling functions are as follows:
append
foreach
listp
reverse
assoc
last
mapcar
subst
length
member
cons
list
nth
This section provides examples of the append, assoc, car, cons, list, nth,
and subst functions. Each list-handling function is described in AutoLISP
Function Reference.
Lists provide an efficient and powerful method of storing numerous related
values. After all, LISP is so-named because it is the LISt Processing language.
52
Once you understand the power of lists, youll find that you can create even
more powerful and flexible applications.
Several AutoLISP functions provide a basis for programming two-dimensional and three-dimensional graphics applications. These functions return
point values in the form of a list.
The list function provides a simple method of grouping related items. These
items do not need to be of similar data types. The following code groups
three related items as a list.
_$ (setq lst1 (list 1.0 "One" 1))
(1.0 "One" 1)
You can retrieve a specific item from the list in variable lst1 with the nth
function. The nth function accepts two arguments. The first argument is an
integer that specifies which item to return. A 0 specifies the first item in a list,
1 specifies the second item, and so on. The second argument is the list itself.
The following code returns the second item in lst1.
_$ (nth 1 lst1)
One
The car and cdr functions provide another way to extract items from a list.
For examples on using car and cdr, and combinations of the two, see Point
Lists on page 54.
Three functions let you modify an existing list. The append function returns
a list with new items added to the end of it, and the cons function returns a
list with new items added to the beginning of the list. The subst function
returns a list with a new item substituted for every occurrence of an old item.
These functions do not modify the original list, they return a modified list.
To modify the original list, you must explicitly replace the old list with the
new list.
The append function takes any number of lists and runs them together as one
list. Therefore, all arguments to this function must be lists. The following
code adds another "One" to the list lst1. Note the use of the quote (or )
function as an easy way to make the string "One" into a list.
_$ (setq lst2 (append lst1 (One)))
(1.0 "One" 1 "One")
Chapter 2
53
AutoLISP Basics
The cons function combines a single element with a list. You can add another
string "One" to the beginning of this new list, lst2, with the cons function.
_$ (setq lst3 (cons "One" lst2 ))
("One" 1.0 "One" 1 "One")
You can substitute all occurrences of an item in a list with a new item with
the substr function. The following code replaces all strings "One" with the
string "one".
_$ (setq lst4 (subst "one" "One" lst3))
("one" 1.0 "one" 1 "one")
Point Lists
AutoLISP observes the following conventions for handling graphics coordinates. Points are expressed as lists of two or three numbers surrounded by
parentheses.
2D points
3D points
List Handling
54
To assign particular coordinates to a point variable, you can use one of the
following expressions:
_$ (setq pt1 (list 3.875 1.23))
(3.875 1.23)
_$ (setq pt2 (list 88.0 14.77 3.14))
(88.0 14.77 3.14)
_$ (setq abc 3.45)
3.45
_$ (setq pt3 (list abc 1.23))
(3.45 1.23)
The latter uses the value of variable abc as the X component of the point.
If all of the members of a list are constant values, you can use the quote function to explicitly define the list, rather than use the list function. The quote
function returns an expression unevaluated.
_$ (setq pt1 (quote (4.5 7.5)))
(4.5 7.5)
The single quotation mark () can be used as shorthand for the quote function. The following code produces the same result as the preceding code.
_$ (setq pt1 (4.5 7.5))
(4.5 7.5)
You can refer to X, Y, and Z components of a point individually, using three
additional built-in functions called car, cadr, and caddr. The following
examples show how to extract the X, Y, and Z coordinates from a 3D point
list. The variable pt is set to the point (1.5 3.2 2.0).
_$ (setq pt (1.5 3.2 2.0))
(1.5 3.2 2.0)
The car function returns the first member of a list. In this example it returns
the X value of point pt to the variable x_val.
_$ (setq x_val (car pt))
1.5
Chapter 2
55
AutoLISP Basics
The cadr function returns the second member of a list. In this example it
returns the Y value of point pt to the variable y_val.
_$ (setq y_val (cadr pt))
3.2
The caddr function returns the third member of a list. In this example it
returns the Z value of point pt to the variable z_val.
_$ (setq z_val (caddr pt))
2.0
You can use the following code to define the lower-left and upper-right (pt1
and pt2) corners of a rectangle.
_$ (setq pt1 (1.0 2.0) pt2 (3.0 4.0))
(3.0 4.0)
You can use the car and cadr functions to set variable pt3 to the upper-left
corner of the rectangle, by extracting the X component of pt1 and the Y component of pt2.
_$ (setq pt3 (list (car pt1) (cadr pt2)))
(1.0 4.0)
The preceding expression sets pt3 equal to point (1.0,4.0).
Dotted Pairs
Another way AutoCAD uses lists to organize data is with a special type of list
called a dotted pair. A dotted pair is a list that must always contain two members. When representing a dotted pair, AutoLISP separates the members of
the list with a period (.). Most list-handling functions will not accept a dotted
pair as an argument, so you should be sure you are passing the right kind of
list to a function.
In addition to adding an item to the beginning of a list, the cons function
can create a dotted pair. If the second argument to the cons function is a constant or quoted value, it creates a dotted pair.
_$ (setq sublist (cons lyr "WALLS"))
(LYR . "WALLS")
The car, cdr, and assoc functions are useful for handling dotted pairs. The
following code creates an association list. An association list is a list of lists
List Handling
56
and is the method that AutoCAD uses to maintain entity definition data. The
following code creates an association list of dotted pairs.
_$ (setq wallinfo (list sublist(cons len 240.0) (cons hgt 96.0)))
( (LYR . WALLS) (LEN . 240.0) (HGT . 96.0) )
The assoc function returns a specified list from within an association list
regardless of the specified lists location within the association list. The assoc
function searches for a specified key element in the lists.
_$ (assoc len wallinfo)
(LEN . 240.0)
_$ (cdr (assoc lyr wallinfo))
"WALLS"
_$ (nth 1 wallinfo)
(LEN . 240.0)
_$ (car(nth 1 wallinfo))
LEN
atom
not
quote
atoms-family
null
set
boundp
numberp
setq
type
apply
eval
progn
defun
lambda
trace
untrace
This section provides examples of the defun function. Each function-handling function is described in AutoLISP Function Reference.
Chapter 2
57
AutoLISP Basics
With AutoLISP you can define your own functions. Once they are defined,
you can use these user-defined functions at the Visual LISP Console prompt
or within other AutoLISP expressions just as you use the standard functions.
You can also create your own AutoCAD commands, because commands are
just a special type of function.
The defun function (see defun in AutoLISP Function Reference) combines a group of expressions into a function or command. This function
requires at least three arguments, the first of which is the name of the function (symbol name) to define. The second argument is the argument list (a
list of arguments and local variables used by the function). The argument list
can be nil or an empty list ( ). Argument lists are discussed in greater detail
in Functions with Arguments on page 64. If local variables are provided,
they are separated from the arguments by a slash ( / ). Local variables are discussed in Local Variables in Functions on page 62. Following these arguments are the expressions that make up the function; there must be at least
one expression in a function definition.
(defun symbol_name ( args / local_symbols )
expressions
)
The following code defines a simple function that accepts no arguments and
displays a message in the AutoCAD command line. Note that the argument
list is defined as an empty list ( () ).
_$ (defun DONE ( ) (prompt "\nbye! "))
DONE
Now that the DONE function is defined, you can use it as you would any other
function. Because it prints the message bye! to a new line at the command
line, you might use the DONE function in the following manner:
_$ (prompt "The value is 127. ")(DONE)(princ)
The value is 127
bye!
Functions that accept no arguments may seem useless. However, you might
use this type of function to query the states of certain system variables or
conditions and to return a value that indicates those values.
C:XXX Functions
If an AutoLISP function is defined with a name of the form C:XXX, it can be
issued at the AutoCAD Command prompt in the same manner as a built-in
AutoCAD command. This is true regardless of whether you define and load
the function in the Visual LISP environment or in the AutoCAD environ-
58
ment. You can use this feature to add new commands to AutoCAD or to redefine existing commands.
There are two important things to note about using functions named C:XXX
in the Visual LISP environment:
1 When you execute a C:XXX-named function from within the Visual LISP environment, you cannot omit the c: or parentheses when you type the function
name.
2 The ability to define a function named c:xxx in Visual LISP and have it automatically recognized as an AutoCAD command is controlled by a VLISP variable named *C-COLON-EXPORT*. By default, this feature is enabled.
To use functions as AutoCAD commands, be sure that they adhere to the
following rules:
The function name must use the form C:XXX (upper- or lowercase characters). The C: portion of the name must always be present; the XXX portion
is a command name of your choice. C:XXX functions can be used to
override built-in AutoCAD commands. (See Redefining AutoCAD Commands on page 60.)
NOTE In this case, C: is not a reference to a disk drive. Its a special prefix that
denotes a command line function.
The function must be defined with no arguments. However, local variables are permitted and it is a good programming practice to use them.
Chapter 2
59
AutoLISP Basics
Adding Commands
Using the C:XXX feature, you can define a command that displays a simple
message.
_$ (defun C:HELLO () (princ "Hello world. \n") (princ))
C:HELLO
HELLO is now defined as a command, in addition to being an AutoLISP function. This means that you can issue the command from the AutoCAD Command prompt.
Command: hello
Hello world.
This new command can be issued transparently because it does not call the
command function itself. At the AutoCAD Command prompt, you could do
the following:
Command: line
From point: hello
Hello world.
From point:
Remember: to run this function from the Visual LISP Console prompt, you
need to issue the function call using the parentheses, since the Visual LISP
environment cannot execute AutoCAD commands:
_$ (c:hello)
Hello world.
If you follow your function definition with a call to the setfunhelp function,
you can associate a Help file and topic with a user-defined command. When
a user calls help transparently (help) at a prompt within the user-defined
command the topic specified by setfunhelp displays.
You cannot usually use an AutoLISP statement to respond to prompts from
an AutoLISP-implemented command. However, if your AutoLISP routine
makes use of the initget function, you can use arbitrary keyboard input
with certain functions. This allows an AutoLISP-implemented command
to accept an AutoLISP statement as a response.
60
You can always activate an undefined command by specifying its true name,
which is the command name prefixed by a period. For example, if you undefine QUIT, you can still access the command by entering .quit at the
AutoCAD Command prompt. This is also the syntax that should be used
within the AutoLISP command function.
Consider the following example. Whenever you use the LINE command, you
want AutoCAD to remind you about using the PLINE command. You can
define the AutoLISP function C:LINE to substitute for the normal LINE
command as follows:
_$ (defun C:LINE ( )
1> (princ "Shouldnt you be using PLINE?\n")
1> (command ".LINE") (princ) )
C:LINE
In this example, the function C:LINE is designed to issue its message and
then to execute the normal LINE command (using its true name, .LINE).
Before AutoCAD will use your new definition for the LINE command, you
must undefine the built-in LINE command. At the Visual LISP Console
prompt, enter the following command:
_$
Now, if you enter line at the AutoCAD Command prompt, AutoCAD uses the
C:LINE AutoLISP function:
Command: line
Shouldnt you be using PLINE?
.LINE From point:
From point:
The previous code example assumes that the CMDECHO system variable is set
to 1 (On). If CMDECHO is set to 0 (Off) AutoCAD does not display prompts
Chapter 2
61
AutoLISP Basics
that are the result of a command function call. The following code uses the
CMDECHO system variable to control the display of command prompts.
_$ (defun C:LINE (/ cmdsave )
(_> (setq cmdsave(setvar "cmdecho" 0))
(_> (princ "Shouldnt you be using PLINE?\n")
(_> (command ".LINE")
(_> (setvar "cmdecho" cmdsave)
(_> (princ) )
C:LINE
You could use this feature in a drawing management system, for example.
You could redefine the NEW, OPEN, QUIT, and END commands to write billing information to a log file before you terminate the editing session.
NOTE It is recommended that you protect your menus, scripts, and AutoLISP
programs by using the period-prefixed forms of all commands. This ensures that
your applications use the built-in command definitions rather than a redefined
command.
Using local variables will save you from a lot of debugging headaches
62
There are some legitimate uses for global variables, but these should be kept
to a minimum. It is also a good practice to indicate that you intend a variable
to be global. A common way of doing this is to add an opening and closing
asterisk to the variable name, for example, *default-layer*.
aaa
bbb
Chapter 2
63
aaa
bbb
AutoLISP Basics
64
Chapter 2
65
AutoLISP Basics
3
Using AutoLISP to
Communicate with
AutoCAD
In this chapter
Display Control
Geometric Utilities
Conversions
File Handling
66
NOTE The AutoLISP examples in this chapter show code entered from the
AutoCAD Command prompt, not the Visual LISP Console.
getcfg
getvar
setvar
command
getenv
setcfg
ver
Examples of the command, getcfg, getvar, setcfg, and getvar functions are
provided in this section. The help, getenv, and ver functions are described
in the AutoLISP Function Reference. Access to the AutoCAD help system is
implemented by the help function.
Command Submission
The command function sends an AutoCAD command directly to the AutoCAD
Command prompt. The command function has a variable-length argument
list. These arguments must correspond to the types and values expected by
that commands prompt sequence; these may be strings, real values, integers,
points, entity names, or selection set names. Data such as angles, distances,
and points can be passed either as strings or as the values themselves (as integer or real values, or as point lists). An empty string ("") is equivalent to
entering a space or ENTER on the keyboard.
There are some restrictions on the commands that you can use with the
command function. See the AutoLISP Function Reference definition of this
function for more information.
The following code fragment shows representative calls to command.
(command "circle" "0,0" "3,3")
(command "thickness" 1)
(setq p1 (1.0 1.0 3.0))
(setq rad 4.5)
(command "circle" p1 rad)
Chapter 3
67
1 The first call to command passes points to the CIRCLE command as strings
(draws a circle centered at (0.0,0.0) and passes through (3.0,3.0)).
2 The second call passes an integer to the THICKNESS command (changes the
current thickness to 1.0).
3 The last call uses a 3D point and a real (floating-point) value, both of which
are stored as variables and passed by reference to the CIRCLE command
(draws another [extruded] circle centered at (1.0,1.0,3.0) with a radius of 4.5).
Foreign-Language Support
If you develop AutoLISP programs that might be used with a foreign-language version of AutoCAD, the standard AutoCAD commands and key words
are automatically translated if you precede each command or key word with
an underscore (_).
(command "_line" pt1 pt2 pt3 "_c")
If you are using the dot prefix (to avoid using redefined commands), you can
place the dot and underscore in either order. Both "._line" and "_.line" are
valid.
68
Draws circle
Draws line
Gets last entity name
Sets point pt
Performs trim
Chapter 3
69
An additional function, getenv, provides AutoLISP routines access to the currently defined operating-system environment variables.
Configuration Control
AutoCAD uses the acad14.cfg file to store configuration information. The
AppData section of this file is provided for users and developers to store configuration information that pertains to their applications. The getcfg and
setcfg functions allow AutoLISP applications to inspect and change the
value of parameters in the AppData section.
Display Control
AutoLISP includes functions for controlling the AutoCAD display, including
both text and graphics windows. Some of these functions prompt for, or
depend on, input from the AutoCAD user. The display-control functions are
as follows:
graphscr
menucmd
textpage
grdraw
menugroup
prompt
textscr
grtext
prin1
redraw
vports
grvecs
princ
terpri
The prin1, princ, print, and prompt functions are the primary text output
functions and are described in AutoLISP Basics. The terpri and vports
functions are described in the AutoLISP Function Reference.
Controlling Menus
The menucmd function controls the display of the graphics window menus. It
displays, modifies, or queries one of the submenus of the current menu, and
accepts a string argument that specifies the submenu and the action to
perform on that submenu.
The menucmd function takes a string argument that consists of two fields,
separated by an equal sign, in the following form:
"menu_area=action"
Display Control
70
This syntax can load a submenu into a specified menu area, or perform an
action on a menu item or a currently loaded menu area. The menu_area field
specifies which part of the menu is to receive the action. This field can specify
a menu area, such as P0 (for the cursor menu) or S (for the screen menu), or
a specific menu item. The action field specifies the action to perform on the
menu area or menu item, or a submenu to load into the menu area. The
menu areas that can receive an action are the same as those used in menu file
submenu references.
Every menu area has a currently loaded submenu. By default the first submenu following a menu section label is loaded into that menu area.
If menu_area specifies a pull-down menu or image tile menu, action can be
an asterisk (*). This causes the menu to displayed (pull-down menus and
image tile menus are not automatically displayed when they are called). On
Windows, only the P0 (cursor) menu and image tile menus are displayed
with the asterisk.
NOTE Do not include the dollar sign that introduces the similar instructions
in a menu file in the string argument. Also, do not include the asterisks that precede submenu labels in the menu file in the action field of the string argument.
The following menucmd function call causes the **OSNAP screen submenu
defined in the current menu file to be displayed (assuming that the screen
menu is currently enabled).
(menucmd "S=OSNAP")
In Windows, you can reference the menu group. This can be useful if there
may be multiple menus loaded that contain the same submenu name. The
following code displays the **OSNAP screen submenu in the ACAD menu
group.
(menucmd "S=ACAD.OSNAP")
The menucmd function can load submenus into the BUTTONS and AUX menu
areas. You might want your digitizer buttons to function differently depending on whether Tablet mode is On or Off. You could have two submenus
defined in the ***BUTTONS1 section, **DIG-BUTTONS and **TAB-BUTTONS, and
switch between them with the following code.
(menucmd "B1=DIG-BUTTONS")
(menucmd "B1=TAB-BUTTONS")
Chapter 3
71
The following code loads the ***POP0 menu into the P0 (cursor) menu area
and displays it.
(menucmd "P0=POP0")
(menucmd "P0=*")
If you are sure that the correct menu is loaded into a particular menu area,
you do not need to specifically load it each time you want to display it.
The following call displays the pull-down menu currently loaded in the P1
(first pull-down menu) location.
(menucmd "P1=*")
Using "P1=*" without previously loading the menu can result in unexpected
behavior. Although you can load virtually any menu at a pull-down or cursor
menu location, it is best to use only menus specifically designed for that
menu area. For example, if you have a submenu called **MORESTUFF, you can
load it at the P1 location with the following code:
(menucmd "P1=MORESTUFF")
(menucmd "P1=*")
This menu remains in this location until you replace it by loading another
menu, as in the following:
(menucmd "P1=POP1")
If your menu uses the disabling (graying-out) and marking features, you can
retrieve and change the state of a menu label with the menucmd function. The
following call retrieves the current state of the fourth label in the pull-down
menu P2.
(menucmd "P2.4=#?")
If disabled returns
"P2.4=~"
You can also place and remove marks to the left of menu labels.
The previously described method of menu item handling works relatively
well with a single static menu. However, it becomes unreliable when menu
item locations change when you load multiple partial menu files. You can
make use of the menu-group and name-tag features to keep track of menu
items. Instead of specifying a menu item by its location in the menu file, you
specify the menu group and name tag associated with the menu item.
Display Control
72
When you use the menu group to enable, disable, and mark menu labels, you
must precede the group name with a G, as shown in the following examples.
(menucmd "Gacad.ID_New=~")
(menucmd "Gacad.ID_New=")
Not only can an AutoLISP function enable and disable menu labels, it can
also modify the text displayed in the label by placing a DIESEL string expression in the label itself. Because DIESEL accepts only strings as input, you can
pass information to the DIESEL expression through a USERS15 system variable that has been set to a value returned by your function.
You can use the menucmd function also to evaluate DIESEL string expressions
within an AutoLISP function. The following routine returns the current time:
(defun C:CTIME ( / ctim)
(setq ctim
(menucmd "M=$(edtime,$(getvar,date),H:MMam/pm)"))
(princ (strcat "\nThe current time is " ctim ))
(princ)
)
Chapter 3
73
getfiled
getpoint
nentsel
getangle
getint
getreal
nentselp
getcorner
getkword
getstring
getdist
getorient
initget
74
getint
getreal
getstring
getpoint
getcorner
getdist
getangle
An angle value (in the current angle format) on the command line or
based on selected points on the screen
getorient
An angle value (in the current angle format) on the command line or
based on selected points on the screen
getkword
NOTE Although the getvar, getcfg and getenv functions begin with the letters g, e, and t, they are not user-input functions.
The functions getint, getreal, and getstring pause for user input on the
AutoCAD command line. They return a value only of the same type as that
requested.
The getpoint, getcorner, and getdist functions pause for user input on the
command line or from points selected on the graphics screen. The getpoint
and getcorner functions return 3D point values, and getdist returns a real
value.
Both getangle and getorient pause for input of an angle value on the command line or as defined by points selected on the graphics screen. For the
Chapter 3
75
getangle
getorient
0.0
1.5708
90
1.5708
3.14159
180
3.14159
4.71239
90
4.71239
0.0
The getangle function honors the settings of ANGDIR and ANGBASE when
accepting input. You can use getangle to obtain a rotation amount for a
block insertion, because input of 0 degrees always returns 0 radians. The
getorient function honors only ANGDIR. You use getorient to obtain
angles such as the baseline angle for a text object. For example, given the
preceding settings of ANGBASE and ANGDIR, for a line of text created at an
angle of 0, getorient returns an angle value of 90.
The user-input functions take advantage of the error-checking capability of
AutoCAD. Trivial errors are trapped by AutoCAD and are not returned by the
user-input function. A prior call to initget provides additional filtering
76
Chapter 3
77
to the getint function, the user is forced to enter an integer value greater
than 0.
To set more than one condition at a time, add the values together (in any
combination) to create a bits value between 0 and 255. If bits is not
included or is set to 0, none of the control conditions apply to the next
user-input function call. (For a complete listing of initget bit settings, see
initget in AutoLISP Function Reference.)
(initget (+ 1 2 4))
(getint "\nHow old are you? ")
This sequence requests the users age. AutoCAD displays an error message
and repeats the prompt if the user attempts to enter a negative or zero value,
press ENTER only, or enter a string (the getint function rejects attempts to
enter a value that is not an integer).
This initget call inhibits null input (bits = 1) and establishes a list of two
key words, "Pi" and "Two-pi". The getreal function is then used to obtain
a real number, issuing the following prompt:
Pi/Two-pi/<number>:
The result is placed in local symbol num. If the user enters a number, that
number is returned by C:GETNUM. However, if the user enters the key word Pi
78
(or simply P), getreal returns the key word Pi. The cond function detects this
and returns the value of p in this case. The Two-pi key word is handled
similarly.
NOTE You can also use initget to enable entsel, nentsel, and nentselp
to accept key word input. For more information on these functions, see Object
Handling and entsel, nentsel, and nentselp in the AutoLISP Function Reference.
If both the C:ARBENTRY and REF functions are loaded into the drawing, the
following command sequence is acceptable.
Command: arbentry
Point: (ref)
Reference point: Select a point
Next point: @1,1,0
Input Validation
You should protect your code from unintentional user errors. The AutoLISP
user input getxxx functions do much of this for you. However, its dangerous
to forget to check for adherence to other program requirements that the
getxxx functions do not check for. If you neglect to check input validity, the
programs integrity can be seriously affected.
Chapter 3
79
Geometric Utilities
A group of functions allow applications to obtain pure geometric information and geometric data from the drawing. The geometric utility functions
are as follows:
angle
inters
polar
distance
osnap
textbox
The angle function finds the angle in radians between a line and the X axis
(of the current UCS), distance finds the distance between two points, and
polar finds a point by means of polar coordinates (relative to an initial
point). The inters function finds the intersection of two lines. The osnap
and textbox functions are described separately.
The following code fragment shows calls to the geometric utility functions:
(setq
(setq
(setq
(setq
(setq len
(setq endpt
The call to polar sets endpt to a point that is the same distance from (1,7) as
pt1 is from pt2, and at the same angle from the X axis as the angle between
pt1 and pt2.
Object Snap
The osnap function can find a point by using one of the AutoCAD Object
Snap modes. The Snap modes are specified in a string argument.
The following call to osnap looks for the midpoint of an object near pt1:
(setq pt2 (osnap pt1 "midp"))
The following call looks for the midpoint, the endpoint, or the center of an
object nearest pt1:
(setq pt2 (osnap pt1 "midp,endp,center"))
In both examples, pt2 is set to the snap point if one is found that fulfills the
osnap requirements. If more than one snap point fulfills the requirements,
the point is selected based on the setting of the SORTENTS system variable.
Otherwise, pt2 is set to nil.
Geometric Utilities
80
Text Extents
The textbox function returns the diagonal coordinates of a box that encloses
a text object. It takes an entity definition list of the type returned by entget
(an association list of group codes and values) as its single argument. This list
can contain a complete association list description of the text object or just
a list describing the text string.
The points returned by textbox describe the bounding box (an imaginary
box that encloses the text object) of the text object as if its insertion point
were located at (0,0,0) and its rotation angle were 0. The first list returned is
the point (0.0 0.0 0.0) unless the text object is oblique or vertical or it contains letters with descenders (such as g and p). The value of the first point list
specifies the offset distance from the text insertion point to the lower-left
corner of the smallest rectangle enclosing the text. The second point list specifies the upper-right corner of that box. The returned point lists always
describe the bottom-left and upper-right corners of this bounding box,
regardless of the orientation of the text being measured.
The following example shows the minimum allowable entity definition list
that textbox accepts. Because no additional information is provided,
textbox uses the current defaults for text style and height.
Command: (textbox ((1 . "Hello world")) )
((0.0 0.0 0.0) (2.80952 1.0 0.0))
The actual values returned by textbox will vary depending on the current
text style.
Chapter 3
81
If the text is vertical or rotated, pt1 is still the bottom-left corner and pt2 is
the upper-right corner; the bottom-left point may have negative offsets if
necessary.
The following figure shows the point values (pt1 and pt2) that textbox
returns for samples of vertical and aligned text. In both samples, the height
of the letters is 1.0. (For the aligned text, the height is adjusted to fit the
alignment points.)
Geometric Utilities
82
pt2 = 1.0,0.0
insertion
point: (0,0)
When using vertical text styles, the points are still returned in left-to-right,
bottom-to-top order as they are for horizontal styles, so the first point list will
contain negative offsets from the text insertion point.
Regardless of the text orientation or style, the points returned by textbox are
such that the text insertion point (group code 10) directly translates to the
origin point of the Object Coordinate System (OCS) for the associated text
object. This point can be referenced when translating the coordinates
returned from textbox into points that define the actual extents of the text.
The two sample routines that follow use textbox to place a box around
selected text regardless of its orientation.
The first routine uses the textbox function to draw a box around a selected
text object.
pt1 =
0.5,20.0
The second routine, which follows, accomplishes the same task as the first
routine by performing the geometric calculations with the sin and cos
AutoLISP functions. The result is correct only if the current UCS is parallel to
the plane of the text object.
Chapter 3
83
Conversions
The functions described in this section are utilities for converting data types
and units. The conversion functions are as follows:
angtof
atof
cvunit
rtos
Conversions
84
angtos
atoi
distof
ascii
chr
itoa
trans
String Conversions
The functions rtos (real to string) and angtos (angle to string) convert
numeric values used in AutoCAD to string values that can be used in output
or as textual data. The rtos function converts a real value, and angtos converts an angle. The format of the result string is controlled by the value of
AutoCAD system variables: the units and precision are specified by LUNITS
and LUPREC for real (linear) values and by AUNITS and AUPREC for angular
values. For both functions, the dimensioning variable DIMZIN controls how
leading and trailing zeros are written to the result string.
The following code fragments show calls to rtos and the values returned
(assuming that the DIMZIN system variable equals 0). Precision (the third
argument to rtos) is set to 4 places in the first call and 2 places in the others.
(setq x 17.5)
(setq str "\nValue formatted as ")
Chapter 3
85
Mode 1 = scientific
displays
Value formatted as 1.7500E+01
Mode 2 = decimal
displays
Value formatted as 17.50
Mode 3 = engineering
displays
Value formatted as 1-5.50"
Mode 4 = architectural
displays
Value formatted as 1-5 1/2"
Mode 5 = fractional
displays
Value formatted as 17 1/2
When the UNITMODE system variable is set to 1, specifying that units are displayed as entered, the string returned by rtos differs for engineering (mode
equals 3), architectural (mode equals 4), and fractional (mode equals 5) units.
For example, the first two lines of the preceding sample output would be the
same, but the last three lines would appear as follows:
Value formatted as 15.50"
Value formatted as 15-1/2"
Value formatted as 17-1/2
Because the angtos function takes the ANGBASE system variable into
account, the following code always returns "0".
(angtos (getvar "angbase"))
There is no AutoLISP function that returns a string version (in the current
mode/precision) of either the amount of rotation of ANGBASE from true zero
(East) or an arbitrary angle in radians.
To find the amount of rotation of ANGBASE from AutoCAD zero (East) or the
size of an arbitrary angle, you can do one of the following:
Add the desired angle to the current ANGBASE, and then check to see if
the absolute value of the result is greater than 2 (2 * pi). If so, subtract 2;
if the result is negative, add 2. Then use the angtos function on the
result.
Store the value of ANGBASE in a temporary variable, set ANGBASE to 0, and
evaluate the angtos function. Then set ANGBASE to its original value.
Subtracting the result of (atof (angtos 0)) from 360 degrees (2 radians or
400 grads) also yields the rotation of ANGBASE from 0.
The distof (distance to floating point) function is the complement of rtos,
so the following calls, which use the strings generated in the previous examples, all return the same value: 17.5. (Note the use of the backslash (\) with
modes 3 and 4.)
(distof "1.7500E+01" 1)
Mode 1 = scientific
(distof "17.50" 2)
Mode 2 = decimal
(distof "1-5.50\"" 3)
Mode 3 = engineering
Mode 4 = architectural
Mode 5 = fractional
Conversions
86
The following code fragments show similar calls to angtos and the values
returned (still assuming that DIMZIN equals 0). Precision (the third argument
to angtos) is set to 0 places in the first call, 4 places in the next three calls,
and 2 places in the last.
(setq ang 3.14159 str2 "\nAngle formatted as ")
(setq fmtval (angtos ang 0 0))
(princ (strcat str2 fmtval))
Mode 0 = degrees
displays Angle formatted as 180
Mode 1 = deg/min/sec
displays Angle formatted as 180d00"
Mode 2 = grads
displays Angle formatted as 200.0000g
Mode 3 = radians
displays Angle formatted as 3.1416r
Mode 4 = surveyors
displays Angle formatted as W
The UNITMODE system variable also affects strings returned by angtos when
it returns a string in surveyors units (mode equals 4). If UNITMODE equals 0,
the string returned can include spaces (for example, "N 45d E"); if UNITMODE equals 1, the string contains no spaces (for example, "N45dE").
The angtof function complements angtos, so all of the following calls return
the same value: 3.14159.
(angtof
(angtof
(angtof
(angtof
(angtof
"180" 0)
"180d00\"" 1)
"200.0000g" 2)
"3.14159r" 3)
"W" 4)
Mode 0 = degrees
Mode 1 = deg/min/sec
Mode 2 = grads
Mode 3 = radians
Mode 4 = surveyors
When you have a string specifying a distance in feet and inches, or an angle
in degrees, minutes, and seconds, you must precede the quotation mark with
a backslash (\") so that it doesnt look like the end of the string. The preceding examples of angtof and distof demonstrate this.
Angular Conversion
If your application needs to convert angular values from radians to degrees,
you could use the angtos function, which returns a string, and then convert
that string into a floating point value with atof.
(setq pt1 (1 1) pt2 (1 2))
(setq rad (angle pt1 pt2))
(setq deg (atof (angtos rad 0 2)))
Chapter 3
87
returns
90.0
After this function is defined, you can use the Radian->Degrees function
throughout your application, as in
(setq degrees (Radian->Degrees rad))
returns
90.0
You may also need to convert from degrees to radians. The following code
shows this.
; Convert value in degrees to radians
(defun Degrees->Radians (numberOfDegrees)
(* pi (/ numberOfDegrees 180.0))
) ;_ end of defun
Conversions
88
Unit Conversion
The file acad.unt defines various conversions between real-world units such
as miles to kilometers, Fahrenheit to Celsius, and so on. The function cvunit
takes a value expressed in one system of units and returns the equivalent
value in another system. The two systems of units are specified by strings
containing expressions of units defined in acad.unt.
The cvunit function does not convert incompatible dimensions. For example, it does not convert inches into grams.
Chapter 3
89
The first time that cvunit converts to or from a unit during a drawing editor
session, it must look up the string that specifies the unit in acad.unt. If your
application has many values to convert from one system of units to another,
it is more efficient to convert the value 1.0 by a single call to cvunit and then
use the returned value as a scale factor in subsequent conversions. This works
for all units defined in acad.unt, except temperature scales, which involve an
offset as well as a scale factor.
You can specify multiple expressions (singular and plural). They dont have
to be located at the end of the word, and a plural form isnt required.
*inch(es)
*milleni(um.a)
*f(oot.eet) or (foot.feet)
The line following the *unit name line defines the unit as either fundamental
or derived.
Conversions
90
Fundamental Units
A fundamental unit is an expression in constants. If the line following the
*unit name line begins with something other than an equal sign (=), it defines
fundamental units. It consists of five integers and two real numbers in the
following form:
c, e, h, k, m, r1, r2
electron charge
Plancks constant
Boltzmans constant
Chapter 3
91
; Units of area
*township(s)
=93239571.456 meter^2
List the acad.unt file itself for more information and examples.
The following AutoCAD coordinate systems can be specified by the from and
to arguments.
WCS
World Coordinate System: the reference coordinate system. All other coordinate systems are defined relative to
the WCS, which never changes. Values measured relative
to the WCS are stable across changes to other coordinate
systems.
UCS
User Coordinate System: the working coordinate system. The user specifies a UCS to make drawing tasks easier.
All points passed to AutoCAD commands, including those
returned from AutoLISP routines and external functions,
are points in the current UCS (unless the user precedes
them with a * at the Command prompt). If you want your
Conversions
92
DCS
PSDCS
Chapter 3
93
Paper Space DCS: this coordinate system can be transformed only to or from the DCS of the currently active
model space viewport. This is essentially a 2D transformation, where the X and Y coordinates are always scaled and
are offset if the disp argument is 0. The Z coordinate is
scaled but is never translated; therefore, it can be used to
find the scale factor between the two coordinate systems.
The PSDCS (integer code 2) can be transformed only into
the current model space viewport: if the from argument
equals 3, the to argument must equal 2, and vice versa.
Both the from and to arguments can specify a coordinate system in any of
the following ways:
As an integer code that specifies the WCS, current UCS, or current DCS (of
either the current viewport or paper space).
As an entity name returned by one of the entity name or selection set
functions described in Using AutoLISP to Manipulate AutoCAD Objects.
This specifies the OCS of the named object. For planar objects, the OCS
can differ from the WCS, as described in the AutoCAD Users Guide. If the
OCS does not differ, conversion between OCS and WCS is an identity
operation.
As a 3D extrusion vector. Extrusion vectors are always represented in
World coordinates; an extrusion vector of (0,0,1) specifies the WCS itself.
The following table lists the valid integer codes that can be used as the to and
from arguments.
Coordinate system
World (WCS)
The following example translates a point from the WCS into the current
UCS.
(setq pt (1.0 2.0 3.0))
(setq cs_from 0)
(setq cs_to 1)
(trans pt cs_from cs_to 0)
WCS
UCS
disp = 0 indicates that pt is a point
(2.0,1.0,3.0)
Point Transformations
If you are doing point transformations with the trans function and you need
to make that part of a program run faster, you can construct your own
Conversions
94
transformation matrix on the AutoLISP side by using trans once to transform each of the basis vectors (0 0 0), (1 0 0), (0 1 0), and (0 0 1). Writing
matrix multiplication functions in AutoLISP can be difficult, so it might not
be worthwhile unless your program is doing a lot of transformations.
File Handling
AutoLISP provides functions for handling files and data I/O. The file-handling functions are as follows:
close
help
read-line
findfile
open
setfunhelp
getfiled
read-char
write-char
write-line
Examples of the findfile, getfiled, and help functions are provided in this
section. The other file handling functions are described in AutoLISP Function Reference.
File Search
An application can use the findfile function to search for a particular file
name. The application can specify the directory to search, or it can use the
current AutoCAD library path.
In the following code fragment, findfile searches for the requested file
name according to the AutoCAD library path:
(setq refname "refc.dwg")
(setq fil (findfile refname))
(if fil
(setq refname fil)
(princ (strcat "\nCould not find file " refname ". " ))
)
If the call to findfile is successful, the variable refname is set to a fully qualified path name string, such as
"/home/work/ref/refc.dwg"
NOTE When specifying a path name, you must precede the backslash (\)
with another backslash so that the path name will be recognized by AutoLISP.
Alternatively, you can use the slash character (/) as a directory separator.
Chapter 3
95
This is a useful utility command. The variable dfil is set to the file you select,
which can then be used by other AutoLISP functions or as a response to a
command line prompt for a file name. To use this variable in response to a
command line prompt, enter !dfil.
NOTE
line.
You cannot use !dfil in a dialog box. It is valid only at the command
You can create a help file that provides information about your applications
or about procedures that you use in your business. The following userdefined command displays your help file morehelp.ahp.
File Handling
96
(defun C:MYHELP ( )
(help "morehelp.ahp")
(princ)
)
See the AutoCAD Customization Guide for information on creating and modifying help files.
The setfunhelp function provides help for user-defined commands. After
the definition of your new command, adding a call to setfunhelp associates
a specific help file and topic with that command. The following example
assigns the help topic Mycmd in the file morehelp.ahp to the user-defined
command MYCMD.
(defun C:MYCMD ( )
.
. Command definition
.
)
(setfunhelp c:mycmd "morehelp.ahp" "mycmd")
tablet
The following file-handling functions can also read input from the keyboard
input buffer. (See the AutoCAD Customization Guide for more information on
these functions.)
read-char
read-line
Chapter 3
97
Calibrating Tablets
AutoCAD users can calibrate a digitizing tablet by using the TABLET command (see the AutoCAD Command Reference for a description of this command). The tablet function enables applications to manage calibration by
setting the calibrations directly and by saving those settings for future use.
The first argument to the tablet function is an integer code. If code is equal
to 0, the function returns the current calibration. If code is equal to 1, the calibration is set according to the remaining arguments. Calibrations are
expressed as four 3D points (in addition to the code). The first three points
row1, row2, and row3are the three rows of the tablets transformation
matrix. The fourth point, direction, is a vector that is normal to the plane
in which the tablets surface is assumed to lie (expressed in WCS, the World
Coordinate System). When the calibration is set with the TABLET command,
the tablets surface is assumed to lie in the XY plane of the current UCS.
NOTE The TABMODE system variable controls whether Tablet mode is
turned on (1) or off (0). You can control it by using the setvar function.
The following sample routine retrieves the current tablet calibration and
stores it in the variable tcal.
(defun C:TABGET ( )
(setq tcal (tablet 0))
(if tcal
(princ
(strcat "\nConfiguration saved, "
"use TABSET to retrieve calibration.")
)
(princ "\nCalibration not obtainable ")
)
(princ)
)
If the preceding routine was successful, the symbol tcal now contains the list
returned by the tablet function. This list might appear as follows:
(1 (0.00561717 -0.000978942 -7.5171)
(0.000978942 0.00561717 -9.17308)
(0.0 0.0 1.0)
(0.0 0.0 1.0)
)
98
To reset the calibration to the values retrieved by the preceding routine, you
can use the C:TABSET routine.
(defun C:TABSET ( )
(if (not (apply tablet tcal))
(princ "\nUnable to reset calibration. ")
(progn
(princ "\nTablet calibration reset. ")
(setvar "tabmode" 1)
(if (= (getvar "tabmode") 0)
(princ "\nUnable to turn on tablet mode ")
)
)
)
(princ)
)
The transformation matrix passed as row1, row2, and row3 is a 33 transformation matrix that is meant to transform a two-dimensional point. The 2D
point is expressed as a column vector in homogeneous coordinates (by appending 1.0 as the third element), so the transformation looks like this:
M 00 M 01 M 02
X
X
Y = M 10 M 11 M 12 Y
1.0
D
M 20 M 21 1.0
The calculation of a point is similar to the 3D case. AutoCAD transforms the
point by using the following formulas:
X = M 00 X + M 01 Y + M 02
Y = M 10 X + M 11 Y + M 12
D = M 20 X + M 21 Y + 1.0
To turn the resulting vector back into a 2D point, the first two components
are divided by the third component (the scale factor D) yielding the point
(X/D,Y/D).
For projective transformations, the most general case, tablet does the full
calculation. But for affine and orthogonal transformations, M20 and M21 are
both 0, so D would be 1.0. The calculation of D and the division are omitted; the resulting 2D point is simply (X,Y).
Chapter 3
99
As the previous paragraph implies, an affine transformation is a special, uniform case of a projective transformation. An orthogonal transformation is a
special case of an affine transformation: not only are M20 and M21 zero, but
M00 = M11 and M10 = M01.
NOTE When you set a calibration, the list returned does not equal the list provided if the direction isnt normalized; AutoCAD normalizes the direction vector
before it returns it. Also, it ensures that the third element in the third column
(row3[Z]) is equal to 1. This situation should not arise if you set the calibration
by using values retrieved from AutoCAD by means of tablet. However, it can
happen if your program calculates the transformation itself.
100
Chapter 3
101
4
Using AutoLISP to
Manipulate AutoCAD
Objects
In this chapter
Selection Set
Handling
Object Handling
Extended Data
Xdata
Xrecord Objects
102
AutoLISP uses symbol tables to maintain lists of graphic and nongraphic data
related to a drawing, such as layers, linetypes, and block definitions. Each
symbol table entry has a related entity name and handle and can be manipulated in a manner similar to the way that other AutoCAD entities are
manipulated.
NOTE The AutoLISP examples in this chapter show code entered from the
AutoCAD Command prompt, not the Visual LISP Console.
ssadd
ssget
ssmemb
ssdel
sslength
ssname
The ssget function provides the most general means of creating a selection
set. It can create a selection set in one of the following ways:
By explicitly specifying the objects to select, using the Last, Previous, Window, Implied, WPolygon, Crossing, CPolygon, or Fence options.
By specifying a single point.
By selecting the entire database.
By prompting the user to select objects.
With either option, you can use filtering to specify a list of attributes and conditions that the selected objects must match.
NOTE Selection set and entity names are volatile; that is, they apply only to
the current drawing session.
The first argument to ssget is a string that describes which selection option
to use. The next two arguments, pt1 and pt2, specify point values for the relevant options (they should be left out if they dont apply). A point list,
pt-list, must be provided as an argument to the selection methods that
allow selection by polygons (that is, Fence, Crossing Polygon, and Window
Polygon). The last argument, filter-list, is optional. If filter-list is supplied, it specifies the list of entity field values used in filtering. The following
table summarizes the available mode values and the arguments used with
Chapter 4
103
Selection method
Prototypes
none
(ssget) or
(ssget pt1)
"L"
(ssget "L")
(0.0
(5.0
(4.0
(2.0
0.0
5.0
1.0
6.0
0.0)
0.0)
0.0)
0.0)
(ssget))
and (2,6)
(setq ss1 (ssget "WP" (list pt1 pt2 pt3)))Creates a selection set of the objects inside the
polygon defined by the point (0,0),(5,5), and
(4,1)
(setq ss1
(ssget "X"))
104
Chapter 4
105
If both the code and the desired value are known, the list may be quoted as
shown previously. If either is specified by a variable, the list must be constructed (using the list and cons functions).
(setq lay_name "FLOOR3")
(setq ss1
(ssget "X"
(list (cons 8 lay_name))
)
)
(list
This code selects only circle objects on layer FLOOR3 that are the color red.
This type of test performs a Boolean AND operation.
The ssget function filters a drawing by scanning the selected entities and
comparing the fields of each main entity against the specified filtering list. If
an entitys properties match all specified fields in the filtering list, it is
included in the returned selection set. Otherwise, the entity is not included
in the selection set. The ssget function returns nil if no entities from those
selected match the specified filtering criteria.
NOTE The meaning of certain group codes can differ from entity to entity,
and not all group codes are present in all entities. If a particular group code is
specified in a filter, entities not containing that group code are excluded from the
selection set that ssget returns.
When ssget filters a drawing, the selection set it retrieves might include entities from both paper space and model space. However, when the selection set
is passed to an AutoCAD command, only entities from the space that is currently in effect are used.
106
This code would select all circles that include extended data for the "APPNAME"
application. If more than one application name is included in the 3 groups
list, an AND operation is implied and the entity must contain extended data
for all of the specified applications. So the following statement would select
all circles with extended data for both the "APP1" and "APP2" applications.
(ssget "X" ((0 . "CIRCLE") (-3 ("APP1")("APP2"))))
Relational Tests
Unless otherwise specified, an equivalency is implied for each item in the
filter-list. For numeric groups (integers, reals, points, and vectors), you
can specify other relations by including a special 4 group code that specifies
a relational operator. The value of a 4 group is a string indicating the test
operator to be applied to the next group in the filter-list. For more
information, see Relational Tests in AutoLISP Function Reference.
The following selects all circles with a radius (group code 40) greater than or
equal to 2.0:
(ssget "X" ((0 . "CIRCLE") (-4 . ">=") (40 . 2.0)))
Chapter 4
107
This code selects all circles with a radius of 1.0 plus all lines on layer "ABC".
The grouping operators are not case sensitive.
Grouping operators are not allowed within the 3 group itself. Multiple
application names specified in a 3 group use an implied AND operator. If
you want to test for extended data using other grouping operators, specify
separate 3 groups and group them as desired. To select all circles having
extended data for either application "APP1" or "APP2" but not both, enter the
following:
(ssget "X"
((0 . "CIRCLE")
(-4 . "<XOR")
(-3 ("APP1"))
(-3 ("APP2"))
(-4 . "XOR>")
)
)
108
You can simplify the coding of frequently used grouping operators by setting
them equal to a symbol. The previous example could be rewritten as follows
(notice that in this example you must explicitly quote each list):
(setq <xor (-4 . "<XOR")
xor> (-4 . "XOR>") )
(ssget "X"
(list
(0 . "CIRCLE")
<xor
(-3 ("APP1"))
(-3 ("APP2"))
xor>
)
)
As you can see, this method may not be sensible for short pieces of code but
can be beneficial in larger applications.
The example runs correctly even if only one entity is in the database (in
which case both entnext and entlast set their arguments to the same entity
name). If ssadd is passed the name of an entity already in the selection set,
it ignores the request and does not report an error. The following function
removes the first entity from the selection set created in the previous
example:
(ssdel fname ourset)
If there is more than one entity in the drawing (that is, if fname and lname
are not equal), then the selection set ourset contains only lname, the last
entity in the drawing.
Chapter 4
109
The function sslength returns the number of entities in a selection set, and
ssmemb tests whether a particular entity is a member of a selection set. Finally,
the function ssname returns the name of a particular entity in a selection set,
using an index to the set (entities in a selection set are numbered from 0).
The following code shows calls to ssname:
(setq sset (ssget))
Prompts the user to create a selection set
(setq ent1 (ssname sset 0))
Gets the name of the first entity in sset
(setq ent4 (ssname sset 3))
Gets the name of the fourth entity in sset
(if (not ent4)
(princ "\nNeed to select at least four entities. ")
)
(setq ilast (sslength sset))
Finds index of the last entity in sset
Gets the name of the last entity in sset
(setq lastent (ssname sset (1- ilast)))
Regardless of how entities have been added to a selection set, the set never
contains duplicate entities. If the same entity is added more than once, the
later additions are ignored. Therefore, sslength accurately returns the number of distinct entities in the specified selection set.
If you want the original selection set to be protected from garbage collection,
then you must not assign the return value of the ObjectARX application to
the AutoLISP variable that already references the selection set. Changing the
previous example as follows prevents the selection set referenced by var1
from being eligible for garbage collection:
(setq var1 (ssget))
(setq var2 (adsfunc var1))
110
Object Handling
AutoLISP provides functions for handling objects. The object-handling
functions are as follows:
entdel
entlast
entmod
entupd
entget
entmake
entnext
handent
Chapter 4
111
(setq e1 (entnext))
(if (not e1)
Sets e1 to name of first entity
(princ "\nNo entities in drawing. ")
(progn
(setq ss (ssadd))
Sets ss to a null selection set
(ssadd e1 ss)
Returns selection set ss with e1 added
(setq e2 (entnext e1))
Gets entity following e1
(ssadd e2 ss)
Adds e2 to selection set ss
)
)
The entlast function retrieves the name of the last entity in the database.
The last entity is the most recently created main entity, so entlast can be
called to obtain the name of an entity that has just been created with a call
to command.
You can set the entity name returned by entnext to the same variable name
passed to this function. This walks a single entity name variable through
the database, as shown in the following example:
(setq one_ent (entnext))
(while one_ent
.
.
Processes new entity
.
(setq one_ent (entnext one_ent))
)
In one particular editing session, this code fragment might display the
following:
<Entity name: 60004722>
Object Handling
112
In another editing session with the same drawing, the fragment might
display an entirely different number. But in both cases the code would be
accessing the same entity.
The handent function has an additional use. Entities that have been deleted
from the database (with entdel, described in the following section) are not
purged until the current drawing ends. This means that handent can recover
the names of deleted entities, which can then be restored to the drawing by
a second call to entdel.
NOTE
Entities in drawings that are cross-referenced by way of XREF Attach are not
actually part of the current drawing; their handles are unchanged but cannot
be accessed by handent. However, when drawings are combined by means of
INSERT, INSERT *, XREF Bind ( XBIND), or partial DXFIN, the handles of entities in the incoming drawing are lost, and incoming entities are assigned new
handle values to ensure that each handle in the current drawing remains
unique.
Chapter 4
113
The second additional element is a list containing the entity name of the
block that contains the selected object. If the selected object is contained in
a nested block (a block within a block), the list also contains the entity names
of all blocks in which the selected entity is nested, starting with the innermost block and continuing outward until the name of the outermost block
that was inserted in the drawing is reported.
(<Entity Name: ename1>
(Px Py Pz)
( (X0 Y0 Z0)
(X1 Y1 Z1)
(X2 Y2 Z2)
(X3 Y3 Z3)
)
(<Entity name: ename2>
.
.
.
<Entity name: enamen>)
)
Name of entity
Pick point
Model to World
transformation matrix
In the following example, create a block to use with the nentsel function.
Command: line
From point: 1,1
to point: 3,1
to point: 3,3
to point: 1,3
to point: c
Command: block
Block name (or ?): square
Insertion base point: 2,2
Select objects: Select the four lines you just drew
Select objects: ENTER
Then insert the block in a UCS rotated 45 degrees about the Z axis:
Command: ucs
Origin/ZAxis/3point/obJect/View/X/Y/Z/Prev/Restore/Save/Del/?/
<World>: z
Rotation angle about Z axis <0>: 45
Command: insert
Block name (or ?): square
Insertion point: 7,0
X scale factor <1> / Corner / XYZ: ENTER
Y scale factor (default=X): ENTER
Rotation angle: ENTER
Object Handling
114
Entity name
Pick point
Model to World
Transformation Matrix
Once you have obtained the entity name and the Model to World Transformation Matrix is obtained, you can transform the entity definition data
points from the MCS to the WCS. Use entget and assoc on the entity name
to obtain the desired definition points expressed in MCS coordinates. Then
pass the points and the Model to World Transformation Matrix data
(obtained in the first nentsel call) to the formulas that follow.
If the selected entity is not a nested entity, the transformation matrix is set
to the identity matrix.
1
0
0
0
0
1
0
0
0
0
1
0
X = XM 00 + YM 10 + ZM 20 + M 30
Y = XM 01 + YM 11 + ZM 21 + M 31
Z = XM 02 + YM 12 + ZM 22 + M 32
The Mij, where 0 i, j 2, are the Model to World Transformation Matrix
coordinates; X, Y, and Z is the entity definition data point expressed in MCS
coordinates; and X, Y, and Z is the resulting entity definition data point
expressed in WCS coordinates.
NOTE To transform a vector (rather than a point), do not add the translation
vector [M30 M31 M32] (from the fourth column of the transformation matrix).
Chapter 4
115
The following example illustrates how to obtain the MCS start point of a line
(group code 10) contained in a block definition. The statement stores the
entity data (using the entity name obtained with nentsel earlier) in the symbol edata. It returns the following:
(setq edata (assoc 10
(10 -1.0 1.0 0.0)
(entget
(car ndata))))
X transformation
Y transformation
Z transformation
Displacement from WCS origin
add:
M00 * X
M10 * Y
M20 * Z
M30
This statement returns 3.53553, the WCS X coordinate of the start point of
the selected line.
Object Handling
116
The entdel function deletes a specified entity. The entity is not purged from
the database until the end of the current drawing session, so if the application calls entdel a second time during that session and specifies the same
entity, the entity is undeleted.
NOTE Attributes and polyline vertices cannot be deleted independently of
their parent entities. The entdel function operates only on main entities. If you
need to delete an attribute or vertex, you can use command to invoke the
AutoCAD ATTEDIT or PEDIT commands.
The entget function returns the definition data of a specified entity. The data
is returned as a list. Each item in the list is specified by a DXF group code. The
first item in the list contains the entitys current name.
In this example, the following (default) conditions apply to the current
drawing:
Layer is 0
Linetype is CONTINUOUS
Elevation is 0
The user has drawn a line with the following sequence of commands.
Command: line
From point: 1,2
To point: 6,6
To point: ENTER
An AutoLISP application can retrieve and print the definition data for the
line by using the following AutoLISP function:
(defun C:PRINTDXF ( )
(setq ent (entlast))
(setq entl (entget ent))
(setq ct 0)
(textpage)
(princ "\nentget of last entity:")
(repeat (length entl)
(print (nth ct entl))
(setq ct (1+ ct))
)
(princ)
Chapter 4
117
If the DXF group code specified is not present in the list (or if it is not a valid
DXF group), assoc returns nil.
The entmod function modifies an entity. It passes a list that has the same format as a list returned by entget but with some of the entity group values
(presumably) modified by the application. This function complements
entget. The primary mechanism by which an AutoLISP application updates
the database is by retrieving an entity with entget, modifying its entity list,
and then passing the list back to the database with entmod.
Object Handling
118
The following code fragment retrieves the definition data of the first entity
in the drawing and changes its layer property to MYLAYER.
(setq en (entnext))
Sets en to the first entity name in the drawing
(setq ed (entget en))
Sets ed to the entity data for entity name en
(setq ed
(subst (cons 8 "MYLAYER")
(assoc 8 ed)
Changes the layer group in ed
ed
to layer MYLAYER
)
)
(entmod ed)
Modifies entity ens layer in the drawing
There are restrictions on the changes to the database that entmod can make;
entmode cannot change the following:
Chapter 4
119
Object type
Layer
Center point
Radius
The first or second member in the list must specify the object type. The
type must be a valid DXF group code. If the first member does not specify
the type, it can specify only the name of the entity: group 1 (the name is
not saved in the database).
AutoCAD must recognize all objects (except layers) that the entity list
refers to. There is one exception: entmake accepts new layer names.
Any internal fields passed to entmake are ignored.
entmake cannot create viewport entities.
Both entmod and entmake perform the same consistency checks on the entity
data passed to them as the DXFIN command performs when reading DXF
files. They will fail if they cannot create valid drawing entities.
You must also scan each block definition for instances of nested blocks.
Anonymous Blocks
The block definitions (BLOCK) table in a drawing can contain anonymous
blocks (also known as unnamed blocks), which AutoCAD creates to support
hatch patterns and associative dimensioning. The entmake function can create anonymous blocks other than *Dnnn (dimensions) and *Xnnn (hatch
patterns). Unreferenced anonymous blocks are purged from the BLOCK table
at the beginning of each drawing session. Referenced anonymous blocks
(those that have been inserted) are not purged. You can use entmake to create
a block reference (insert object) to an anonymous block. (You cannot pass an
anonymous block to the INSERT command.) Also, you can use entmake to
redefine the block. You can modify the entities in a block (but not the block
object itself) with entmod.
Object Handling
120
Chapter 4
121
Object type
Color
Linetype
Vertices follow
Object type
Start point
Object type
Second point
Object type
Third point
Sequence end
NOTE When defining dotted pairs, as in the above example, there must be a
space on both sides of the dot. Otherwise you will get an invalid dotted pair error
message.
Block definitions begin with a block entity and end with an endblk subentity.
Block definitions cannot be nested, nor can they reference themselves. A
block definition can contain references to other block definitions.
NOTE Before you use entmake to create a block, you should use tblsearch
to ensure that the name of the new block is unique. The entmake function does
not check for name conflicts in the block definitions table, so it can redefine
existing blocks.
Block references can include an attributes-follow flag (group 66). If present
and equal to 1, a series of attribute (attrib) entities is expected to follow the
insert object. The attribute sequence is terminated by a seqend subentity.
Polyline entities always include a vertices-follow flag (also group 66). The
value of this flag must be 1, and the flag must be followed by a sequence of
vertex entities, terminated by a seqend subentity.
Complex entities can exist in either model space or paper space but not both.
If you have changed the current space by invoking either MSPACE or PSPACE
(with command) while a complex entity is being constructed, a subsequent call
to entmake cancels the complex entity. This can also occur if the subentity
has a 67 group whose value does not match the 67 group of the entity header.
Object Handling
122
Chapter 4
123
Object Handling
124
the layer symbol table. If a graphic object is passed to entmake, it will reside
in the current space (model or paper).
Symbol table entries can be created through entmake with few restrictions
other than being valid record representations, and name conflicts can
only occur in the VPORT table. *ACTIVE entries can not be created.
Symbol table and symbol table entry object state may be accessed with
entget by passing the entity name. The tblobjname function can be used
to retrieve the entity name of a symbol table entry.
Symbol tables themselves can not be created with entmake, however,
symbol table entries can be created with entmake.
Handle groups (5, 105) may not be changed in entmod, nor specified in
entmake.
Symbol table entries can have many of their fields modified with entmod.
To be passed to entmod, a symbol table record list must include its entity
name, which can be obtained from entget but not from the tblsearch
and tblnext functions. The 70 group of symbol table entries is ignored in
entmod and entmake operations.
entry name
VPORT
*ACTIVE
LINETYPE
CONTINUOUS
LAYER
The following entries may not be renamed, but are otherwise modifiable,
subject to restriction
Entries that cannot be renamed
Chapter 4
125
table
entry name
LAYER
entry name
STYLE
STANDARD
DIMSTYLE
STANDARD
BLOCKS
*MODEL_SPACE
BLOCKS
*PAPER_SPACE
APPID
Dictionary Objects
The following rules apply to dictionary objects:
Dictionary objects can be examined with entget and their xdata modified
with entmod. Their entries cannot be altered with entmod. All access to their
entries are made through the dictsearch and dictnext functions.
Dictionary entry contents cannot be modified through entmod, although
xdata can be modified.
Dictionary entries that begin with ACAD* cannot be renamed.
Extended DataXdata
Several AutoLISP functions are provided to handle extended data, which is
created by applications written with ARX or Visual LISP. If an entity contains
extended data, it follows the entitys regular, definition data.
The extended data-handling functions are as follows:
regapp
xdroom
xdsize
You can retrieve an entitys extended data by calling entget. The entget
function retrieves an entitys regular definition data and the extended data
for those applications specified in the entget call.
Extended DataXdata
126
Group Code
Field
(1, 2
(0239
Entity name)
Regular definition data fields)
.
.
.
Normal entity
definition data
Extended data
(3
(1001
(1000,
10021071
XDATA fields)
.
.
.
(1001
(1000,
10021071
(1001
Extended data
Chapter 4
127
Application
name
Layer name
Database
handle
3D point
Real
Integer
Long
NOTE AutoLISP manages 1071 groups as real values. If you use entget to
retrieve an entitys definition list that contains a 1071 group, the value is returned
as a real, as shown in the following example:
(1071 . 12.0)
If you want to create a 1071 group in an entity with
entmake or entmod, you can use either a real or an integer
((.....
((.....
((.....
((.....
(1071
(1071
(1071
(1071
.
.
.
.
Extended DataXdata
128
NOTE If a 1001 group appears within a list, it is treated as a string and does
not begin a new application group.
Binary data
NOTE AutoLISP cannot directly handle binary chunks, so the same precautions that apply to long (1071) groups apply to binary groups as well.
Chapter 4
129
World space
position
World space
displacement
World
direction
Distance
Scale factor
1042. Also a real value that is scaled along with the parent.
Registration of an Application
To be recognized by AutoCAD an application must register the name or
names that it uses. Application names are saved with the extended data of
each entity that uses them, and also in the APPID table. Registration is done
with the regapp function. The regapp function specifies a string to use as an
application name. If it successfully adds the name to APPID, it returns the
name of the application; otherwise it returns nil. A result of nil indicates
that the name is already present in the symbol table. This is not an actual
error condition but an expected return value, because the application name
needs to be registered only once per drawing.
To register itself, an application should first check that its name is not already
in the APPID table. If the name is not there, the application must register it.
Otherwise, it can simply go ahead and use the data, as described later in this
section.
The following fragment shows the typical use of regapp.
(setq appname "MYAPP_2356")
Unique application name
(if (tblsearch "appid" appname)
Checks if already registered
(princ (strcat
"\n" appname " already registered. "))
(if (= (regapp appname) nil)
Some other problem
(princ (strcat
"\nCant register XDATA for " appname ". "))
)
)
Extended DataXdata
130
As the sample code shows, you can modify extended data retrieved by entget
by using a subsequent call to entmod, just as you use entmod to modify normal
definition data. You can also create extended data by defining it in the entity
list passed to entmake.
Returning the extended data of only those applications specifically requested
protects one application from corrupting another applications data. It also
controls the amount of memory that an application needs to use, and simplifies the extended data processing that an application needs to perform.
NOTE Because the strings passed by application can include wild-card
characters, an application name of "*" will cause entget to return all extended
data attached to an entity.
Chapter 4
131
You must first draw an entity (such as a line or a circle) and then enter the
following code:
(setq lastent (entget (entlast)))Gets the association list of definition
definition data
To verify that your new extended data has been attached to the entity, enter
the following code and select the object.
(entget (car (entsel)) ("NEWDATA"))
This example shows the basic method for attaching extended data to an
entity.
Extended DataXdata
132
unique. The AUDIT command does require that handles in extended data
either be NULL or valid entity handles (within the current drawing). The best
way to ensure that extended entity handles are valid is to obtain a referenced
entitys handle directly from its definition data by means of entget. The handle value is in group 5.
When you reference entities in other drawings (for example, entities that are
attached with XREF), you can avoid protests from AUDIT by using extended
entity strings (group 1000) rather than handles (group 1005), because the
handles of cross-referenced entities are either not valid in the current drawing
or they conflict with valid handles. However, if an XREF Attach changes to
an XREF Bind or is combined with the current drawing in some other way, it
is up to the application to revise the entity references accordingly.
When drawings are combined by means of INSERT, INSERT*, XREF Bind
(XBIND), or partial DXFIN, handles are translated so that they become valid
in the current drawing. (If the incoming drawing did not employ handles,
new ones are assigned.) Extended entity handles that refer to incoming
entities are also translated when these commands are invoked.
When an entity is placed in a block definition (with the BLOCK command),
the entity within the block is assigned new handles. (If the original entity is
restored by means of OOPS, it retains its original handles.) The value of any
extended data handles remain unchanged. When a block is exploded (with
the EXPLODE command), extended data handles are translated, in a manner
similar to the way they are translated when drawings are combined. If the
extended data handle refers to an entity that is not within the block, it is
unchanged. However, if the extended data handle refers to an entity that is
within the block, the data handle is assigned the value of the new (exploded)
entitys handle.
Chapter 4
133
Xrecord Objects
Xrecord objects are used to store and manage arbitrary data. They are composed of DXF group codes with "normal object" groups (that is, non-xdata
group codes), ranging from 1 through 369 for supported ranges. This object
is similar in concept to xdata but is not limited by size or order.
Xrecord objects are designed to work in such a way as to not offend releases
R13c0 through R13c3. However, if read into a pre-R13c4 level of AutoCAD,
xrecord objects disappear.
The following examples provide methods for creating and listing xrecord
data.
(defun C:MAKEXRECORD( / xrec xname )
; create the xrecords data list
(setq xrec ((0 . "XRECORD")(100 . "AcDbXrecord")
(1 . "This is a test xrecord list")
(10 1.0 2.0 0.0) (40 . 3.14159) (50 . 3.14159)
(62 . 1) (70 . 180))
)
; use entmakex to create the xrecord with no owner
(setq xname (entmakex xrec))
; add the new xrecord to the named object dictionary
(dictadd (namedobjdict) "XRECLIST" xname)
(princ)
)
dictsearch
namedobjdict
tblnext
tblsearch
Xrecord Objects
134
dictnext
snvalid
tblobjname
Examples of the tblnext and tblsearch functions are provided in this section. See AutoLISP Function Reference for information on the other symbol table and dictionary access functions.
Symbol Tables
Symbol table entries can also be manipulated by the following functions:
entdel
entmake
entget
entmod
handent
The tblnext function sequentially scans symbol table entries, and the
tblsearch function retrieves specific entries. Table names are specified by
strings. The valid names are "LAYER", "LTYPE", "VIEW", "STYLE", "BLOCK",
"UCS", "VPORT", "DIMSTYLE", and "APPID". Both functions return lists with
DXF group codes that are similar to the entity data returned by entget.
The first call to tblnext returns the first entry in the specified table. Subsequent calls that specify the same table return successive entries, unless the
second argument to tblnext (rewind) is nonzero, in which case tblnext
returns the first entry again.
In the following example, the function GETBLOCK retrieves the symbol table
entry for the first block (if any) in the current drawing, and then displays it
in a list format.
Chapter 4
135
Entries retrieved from the BLOCK table contain a 2 group that contains the
name of the first entity in the block definition. If the block is empty, this is
the name of the blocks ENDBLK entity, which is never seen on nonempty
blocks. In a drawing with a single block named BOX, a call to GETBLOCK
displays the following. (The name value varies from session to session).
Results from GETBLOCK:
(0 . "BLOCK")
(2 . "BOX")
(70 . 0)
(10 9.0 2.0 0.0)
(2 . <Entity name: 40000126>)
As with tblnext, the first argument to tblsearch is a string that names a
table, but the second argument is a string that names a particular symbol in
the table. If the symbol is found, tblsearch returns its data. This function
has a third argument, setnext, that you can use to coordinate operations
with tblnext. If setnext is nil, the tblsearch call has no effect on tblnext,
but if setnext is non-nil, the next call to tblnext returns the table entry following the entry found by tblsearch.
The setnext option is useful when you are handling the VPORT symbol table,
because all viewports in a particular viewport configuration have the same
name (such as *ACTIVE).
If the VPORT symbol table is accessed when TILEMODE is turned off, any
changes have no visible effect until TILEMODE turned on. Do not confuse
VPORTS, which is described by the VPORT symbol table with paper space viewport entities.
136
Dictionary Entries
A dictionary is a container object, similar to symbol tables in function. Dictionary entries can be queried with the dictsearch and dictnext functions.
Each dictionary entry consists of a text name key plus a hard ownership handle reference to the entry object. Dictionary entries may be removed by
directly passing entry object names to the entdel function. The text name
key uses the same syntax and valid characters as symbol table names.
This sets the variable grpdict to the entity definition list of the ACAD_GROUP
dictionary and returns the following:
((-1 . <Entity name: 8dc10468>) (0 . "DICTIONARY") (5 . "D")
(102 . "{ACAD_REACTORS") (330 . <Entity name: 8dc10460>)
(102 . "}") (100 . "AcDbDictionary") (3 . "G1")
(350 . <Entity name: 8dc41240>))
The following code sets the variable group1 to the entity definition list of the
G1 group.
(setq group1 (dictsearch (cdar grpdict) "G1"))
Chapter 4
137
5
Developing Programs
With Visual LISP
In this chapter
Formatting Code
Running Your
Program
138
Getting Organized
Developing an AutoLISP program using Visual LISP involves the following
tasks:
1 Thinking about what tasks you want to accomplish with your program, and
how you might go about doing this
2 Designing the program
3 Writing the code
4 Formatting the code text for readability
5 Checking for errors in the program
6 Testing and debugging the program
This chapter provides you with information you need in order to accomplish
steps 3, 4 and 5. Debugging Programs, describes the debugging features of
Visual LISP. Building Applications, and Maintaining Visual LISP Applications, describe how to package your programs into applications that can be
run by other users, and how to organize application components to facilitate
future updates.
You enter text in the Console window following the Console prompt, which
looks like the following:
_$
Chapter 5
139
Visual LISP saves the text you enter, and any output it displays in response,
so that you can scroll through the Console window and see what has previously transpired. You can copy any text in the window, and paste it following
the Console prompt or in another Windows application.
You can continue an AutoLISP expression on a new line. To continue typing an expression on a new line, press CTRL+ENTER at the point you want
to continue.
In contrast, expressions entered from the AutoCAD Command prompt are
interpreted as soon as you press the ENTER key. AutoCAD treats the
incomplete expression as an error, although it does allow you fix the error
by completing the expression at the Command prompt.
You can enter more than one expression before pressing the ENTER key,
and Visual LISP will evaluate each expression before returning a value to
the Console.
If the cursor is in the Console window but not at the Console prompt,
pressing the ENTER key positions the cursor at the prompt. If you select
some text in the Console window before you press ENTER, (for example,
the result of a previous command or a previously-entered expression),
Visual LISP copies the selected text following the Console prompt.
To retrieve text you previously entered from the Console, press the TAB
key while at the Console prompt. Each time you press TAB, the previously
entered text replaces the text at the Console prompt. You can repeat this
until youve cycled through all the text entered at the Console prompt. If
you repeatedly entered a specific expression, that expression appears only
once in the cycle. After you scroll to the first entered line, the list jumps
back to the last line entered and the cycle is repeated.
SHIFT+TAB acts like TAB, but scrolls the input history in the opposite direc-
tion.
140
The TAB key lets you perform an associative search in the input history.
For example, if you type (+ at the Console prompt and then press TAB,
Visual LISP searches for the last text you entered that began with the (+
characters. If it doesnt find a match, VLISP does nothing (except possibly
emit a beep). Use SHIFT+TAB to perform an associative search from earlier
to later inputs.
The ESC key clears the input area following the Console prompt. Pressing
SHIFT+ESC leaves the text you typed in the Console window, but brings
you to a new prompt without evaluating the text.
Chapter 5
141
Cut
Copy
Paste
Inspect
Add Watch
Apropos Window
Symbol service
Undo
Redo
AutoCAD Mode
Note also that you can cut and paste text between the Visual LISP Console
and the AutoCAD command window.
Separators Processing
The Visual LISP System Console and the AutoCAD command window differ
in the way they process the SPACE and TAB keys. In the Visual LISP Console,
a space plays no special role and serves as a separator only. In the AutoCAD
command window, if you press the SPACE bar outside of an expression, it
causes termination of input and the processing of the text, as if you had
pressed the ENTER key.
142
Choose a directory for the log file and then specify a filename for the log. If
the file already exists, Visual LISP prompts you with the following:
Chapter 5
143
If you reply Yes, Visual LISP will append future Console information to the
current contents of the file. If you reply No, Visual LISP overwrites the file
and the original contents will be lost. Click Cancel to terminate the operation and specify a different file name.
To close the log file and end logging, choose Toggle Console Log from the File
menu again. The state of Console logging is indicated in the Console windows title bar. If logging is in effect, Visual LISP displays the name of the log
file in the title bar. If logging is off, no file name appears in the title bar.
If you do not close the log file before exiting Visual LISP, Visual LISP closes it
automatically upon exit. After a log file is closed, you can view its contents
with any text editor, such as the Visual LISP text editor.
144
rently turned on, choosing it turns it off; if AutoCAD mode is off, choosing
it turns it on.
If this occurs, you need to return control to AutoCAD and press the ESC key
to reset your environment. To return control to AutoCAD, press the
Activate AutoCAD button on the View toolbar:
After you press ESC in the AutoCAD window, youll be able to resume interaction with the Visual LISP Console.
Chapter 5
145
Entering Text
To enter text, begin typing in the active editor window. To start a new line,
press the ENTER key. The text editor does not wrap your text when it reaches
the end of the visible editor window, so everything you type goes on the
same line until you press ENTER.
To indent a line of text, type some spaces or press the TAB key. Eventually,
youll want to use the Visual LISP Code Formatter to automatically indent
and space your code; see Formatting Code with the Visual LISP Formatter
on page 162 for details.
A couple of key combinations result in a new line with automatic indenting:
To insert new text into existing text, click at the place you want the text to
begin and start typing. You can also use the arrow keys to move the cursor to
the desired insertion point.
146
Chapter 5
147
Color Coding
As soon as you enter text in the text editor window, Visual LISP determines
if the entered word is a built-in AutoLISP function, a number, a string, or
some other language element that it is aware of. Every type of element gets
its own color. This helps you detect missing quotes or misspelled function
names. The default color scheme is:
Color
Blue
Strings
Magenta
Integers
Green
Real numbers
Teal
Comments
Parentheses
Red
You can change the default colors from the dialog box displayed by choosing
Tools>Window Attributes>Configure Current from the Visual LISP menu.
NOTE Visual LISP may not recognize every function you use in your programs. Many commonly used functions are not defined as part of the AutoLISP
language, but are instead defined in external applications. If an external function
has not been made known to Visual LISP, it will not be identified and color coded.
See Identifying Functions Defined in External Applications on page 221 for
information on how external functions are defined to Visual LISP.
The Visual LISP editor provides color coding for LISP files, DCL files, SQL files
and C language source files (see LSP, FAS and other File Types on page 245
for a list of file types recognized by Visual LISP ). Visual LISP uses the file
name extension to determine a files type, and selects the color coding
accordingly. You can change the color coding style associated with a file type
by choosing Tools>Window Attributes>Syntax Coloring from the Visual LISP
menu.
148
Chapter 5
149
Cut
Copy
Paste
Find
Go to Last Edited Moves the cursor to the position you last edited
Toggle Breakpoint Sets a breakpoint at the cursor position, or removes a
breakpoint if one currently is set at that position
Inspect
Add Watch
Undo
Redo
space
tab
single quote
left parenthesis
right parenthesis
"
double quote
150
semicolon
\n
Newline
[]
Chapter 5
151
2 Right-click your mouse and select Copy to Clipboard from the list of options
3 Click in the editor window at the point you want to insert the symbol name
4 Right-click your mouse and select Paste from the context menu, or press
CTRL+V to paste the text
If no symbols match what youve entered, Visual LISP displays the Apropos
options dialog box:
The message area of the Apropos options dialog box shows the value that
Apropos could not match.
In the input field of the Apropos options dialog, you change the text you
want Apropos to match. The dialog box contains the following options:
All
No filter
Null value
152
Nonull value
Functions
User function
Built-in function Only built-in Visual LISP functions are considered for matching
EXSUBR
Filter Flags. Lets you choose symbols with matching flag settings. Visual
LISP displays a list of check boxes that correspond to the symbol flags
described in The Symbol Service Dialog on page 199. If the flag filter is
on, only symbols set with the selected flags are considered.
If you specify a filter value or filter flag, the message area of the Apropos
options dialog box indicates your selections.
Chapter 5
153
Indent Block
Indents the selected block of text by adding a tab to the beginning of each line
Unindent
Prefix With
Append With
Comment Block
Uncomment
Block
Save Block As
Upcase
Downcase
Capitalize
Insert Date
Insert Time
Format
Date/Time
Sort Block
Insert File
Insert the contents of a text file into the current editor window at
the cursor position
Delete to EOL
Erase everything from the cursor position to the end of the current line
Delete Blanks
Delete all blank spaces from the cursor position to the first nonblank character in the line
154
Navigation Shortcuts
In addition to using the cursor arrow keys, you can use the following Visual
LISP editor shortcuts to navigate through your text.
To move
Press
CTRL+LEFT ARROW
CTRL+RIGHT ARROW
END
HOME
PAGEDOWN
Up one window
PAGEUP
CTRL+END
CTRL+HOME
CTRL+[
CTRL+[
CTRL+]
CTRL+]
To
Press
CTRL+BACKSPACE
SHIFT+BACKSPACE
Delete characters from the cursor position to the end of CTRL+E and choose Delete
the current line
to EOL from the menu
Delete the current line
Chapter 5
155
CTRL+E
You can also can use overstrike mode to insert text. Overstrike mode is toggled on and off by pressing the INSERT key. When in overstrike mode, each
character you type replaces existing text. The cursor changes shape from vertical to horizontal when in overstrike mode.
To
Press
Expand the selection to the next line, or to abandon selection SHIFT+Down Arrow
of the next line if it is currently selected
Expand the selection to the previous line, or to abandon selec-SHIFT+Up Arrow
tion of the previous line if it is currently selected
Expand the selection to the end of the line
SHIFT+END
SHIFT+HOME
CTRL+SHIFT+Left
Arrow
CTRL+SHIFT+[
CTRL+SHIFT+]
ALT+ENTER
156
Indenting Text
Most indenting of program code is best handled by running the Visual LISP
Code Formatter and customizing the Formatters options (see Formatting
Code with the Visual LISP Formatter). But there are some things you may
want to do by yourself.
To
Do
Chapter 5
157
To indent selected lines of code, press the TAB key or press CTRL+E and
choose Indent Block. Visual LISP inserts a tab character at the beginning of
each line you selected. You can control the indent amount of the tab character by choosing Tools>Window Attributes>Configure Current and setting
the Tab Width value.
In the data entry field labeled Find What, type the character string you
want to search for. If there is text selected when you enter the Find command, this text is automatically placed in the Find What field.
Under the Search heading, indicate the extent of the search you want Visual
LISP to conduct. You can choose one of the following:
Current Selection. Visual LISP searches only the text you have highlighted in the editor window.
Current File. Visual LISP searches through the entire file in the active
editor window.
Find in Project. With this option selected, Visual LISP prompts you to
specify the name of the Visual LISP project you want to search. It will
search all the files in this project and display all matches in a new output
window. See Finding a String in Project Source Files on page 257 for
more information on this option.
Find in Files. If you select this option, Visual LISP allows you to specify
a Windows directory (folder) to search for the text. Optionally, you can
instruct VLISP to search all subdirectories of that directory as well. Visual
LISP will search through all the files and display all matches in a new output window.
When searching for text within the current file, the Direction setting determines where Visual LISP looks next for the search text. Select Down to search
158
forward (toward the end of the file) from the cursor position. Select Up to
search backwards (toward the beginning of the file) from the cursor position.
You can select any or all of the following options:
Match Whole Word Only. If selected, Visual LISP will only match complete words. For example, if the search term is ent and VLISP encounters
the word enter in the text, VLISP does not consider this a match. However, if the Match Whole Word Only option is not selected, Visual LISP
considers the ent within enter to be a match.
Match Case. If selected, Visual LISP only matches text whose case
matches. In this instance, Ent and ent are not considered a match. If
Match Case is not selected, Ent and ent are considered a match.
Mark Instances. If you select this option, the position of the located
text will be added to the Mark Ring (see Bookmarking Text on
page 160). This lets you quickly return to this code position at a later time.
Searches that find all occurrences of a string add each position to the Mark
Ring.
Click the Find button to start the search. When searching through a single
file, press F3 to search for the next occurrence of your search string. Click the
Cancel button to end the search.
Visual LISP saves each search string you enter in a pull-down list on the toolbar:
Click the pull-down arrow and select a search term from the list. Click the
Find Via Toolbar button to conduct the search.
Chapter 5
159
Replacing Text
The Search menu contains a Replace function that allows you to replace
search text with a text string that you specify.
The Replace dialog box is similar to the Find dialog box, but with fewer
options. It contains an additional Replace With entry field, in which you
specify the text you want Visual LISP to substitute for the search text. Specify
the search text in the Find what field.
You can take the following actions from the Replace dialog box:
Press the Find Next button to find the next occurrence of the search string.
Press Replace to replace the found text with the replacement string.
If you dont want to replace this occurrence of the text, press Find Next to
search for the next occurrence of the text, or Cancel to end the search.
Press Replace All to replace all occurrences of the search string with the
replacement string, depending on the search Direction.
Press Cancel to end the Replace function.
Bookmarking Text
The bookmark feature helps you navigate through editor, Console, and other
text-based windows by letting you mark up to 32 positions (bookmarks) in
each window. Each window maintains its own set of bookmarks, and the
bookmark navigation tools let you walk through the marks within each window independently of the other windows. A set of bookmarks within a window is known as a bookmark ring. You can step either forward or backward
through the ring, and eventually get back to the starting point.
Whenever you step to a bookmark, Visual LISP automatically places a marker
at the location you are stepping from. In effect, the marker for the place you
are jumping to is moved to the place you jumped from. This makes it easy
to return back to your original location, just by stepping back in the opposite
direction, or by cycling through all of the bookmarks until you get back to
the starting point.
160
To add a bookmark, move the cursor to the location you want to mark, then
press the Toggle Bookmark button on the toolbar or press ALT+. (ALT key plus
period).
Bookmarks may also be inserted automatically when using the Find command to search for text; see the discussion on search options in Searching
for Text on page 158 for more information on this feature.
When the current window contains bookmarks, you can:
In addition to jumping between bookmarks, you can also jump and select
(highlight) the text between two bookmarks:
Press CTRL+SHIFT+, (Ctrl, SHIFT, and comma keys) to select the text
between the current location and the previous bookmark.
Press CTRL+SHIFT+. (Ctrl, SHIFT, and period keys) to select the text
between the current location and the next bookmark.
Removing Bookmarks
Remove a single bookmark the same way you set the bookmark: move the
cursor to the bookmarked location, then press the Toggle bookmark button
or press ALT+. (ALT key plus period). The Toggle Bookmark command works
as an on/off switch. If you issue the command when a bookmark is set, Toggle Bookmark turns it off. Issue the same command when there is no bookmark set, and Toggle Bookmark inserts a bookmark.
To remove all the bookmarks in your program, press the Clear all bookmarks
button on the toolbar, or choose Search>Bookmarks>Clear All Bookmarks
from the Visual LISP menu.
Chapter 5
161
Click Yes to have Visual LISP add parentheses where it thinks they belong;
click No if you want to fix the parentheses on your own.
NOTE The Formatter can balance the number of parentheses, but usually
does not insert the additional parentheses in the right places. See Checking the
Balance of Parentheses on page 172 for more information on detecting and correcting unmatched parentheses.
162
For a general function call expression, the Formatter applies one of the styles
listed below:
Plane Style
In the Plane style, all arguments are placed in the same line, separated by a
single space:
(autoload "appload" ("appload"))
Chapter 5
163
The plane style is applied to an expression when all of the following conditions are met:
The expressions last character position does not exceed the value of the
environment option Text right margin
The expressions printing length is less than the value of the environment
option Maximum length for plane expression (that is, last character
position minus starting indentation position is less then this value)
The expression does not contain embedded comments with Newline characters
Wide Style
In the Wide style, the first argument is placed in the same line as the function
name, and other arguments are aligned in a column below the first argument.
(autoload "appload"
("appload")
)
The Wide formatting style applies to an expression when the following conditions are met:
Narrow Style
In the Narrow style, the first argument is placed on the next line after the
function name, and other arguments are aligned in a column below the first
argument. The displacement of the first argument's starting position relative
to the expression starting position is controlled by the value of the
Narrow style indentation environment option (in the following example,
this value is equal to 2):
(autoload
"appload"
("appload")
)
The Narrow formatting style applies for PROGN expressions, and for those
instances when the Plane and Wide formatting styles can not be applied.
The Narrow style indentation option (in AutoLISP Format Options) sets the
standard indentation for function arguments that use the Narrow formatting
style.
164
Column Style
In the Column style, all elements are positioned in a column. This style is
appropriate for displaying quoted lists and COND-expression clauses. For
example, the following text:
((10 "{insertion}")
(7 "{style}"))
(1 "{string}")
Close at the new line with inner Close parenthesis on the next line following the
indentation
last line of each formatting expression with the
inner indent
Close at the new line with outer Close parenthesis on the next line following the
indentation
last line of each formatting expression with the
outer indent
Chapter 5
165
Examples:
The initial expression is written as:
(cond
((/= (logand mask flg) 0)
(list (list txton)))
)
Formatting result when Close at the new line with inner indentation
option is selected:
(cond ((/= (logand mask flg) 0)
(list (list txton))
)
)
Formatting result when Close at the new line with outer indentation is
selected:
(cond ((/= (logand mask flg) 0)
(list (list txton))
)
)
166
Example
Initial text:
(autoxload "image"
("gifin" "pcxin" "riaspect" "ribackg" "riedge"
"rigamut" "rigrey" "rithresh" "tiffin"))
Formatted text:
(autoxload "image"
("gifin"
"ribackg"
"rigrey"
)
) ;_ end of autoxload
"pcxin"
"riedge"
"rithresh"
"riaspect"
"rigamut"
"tiffin"
(princ (strcat
Chapter 5
167
Split Comments
When the Split Comments option is on, the Formatter splits long comments that extend past the right margin.
For the previous example, if the Text Right Margin setting is 60, and Single-semicolon comment indentation is 40, the Formatter will split the
comment as follows:
(if (/= s "Function canceled")
(princ (strcat "\nError: " s))
;single
;semicolon cmt
168
The available modes for Longlist format are listed below and illustrated with
an example based on the following list elements:
("aseadmin" "aserows" "aselinks" "aseexport"
"aseselect" "asesqled")
Single-column formatting
("aseadmin"
"aserows"
"aselinks"
"aseexport"
"aseselect"
"asesqled"
)
2-column formatting
("aseadmin"
"aselinks"
"aseexport"
)
Multi-column formatting
("aseadmin"
"aseselect"
)
"aserows"
"aseselect"
"asesqled"
"aserows"
"aseexport"
"aselinks"
"asesqled"
Chapter 5
169
None
downcase
UPCASE
The Unprotected options subgroup controls case conversion of unprotected (user) AutoLISP symbols:
None
downcase
UPCASE
Comment Styles
The Visual LISP AutoLISP Formatter recognizes five types of comments, and
positions each comment according to its type.
Visual LISP Comment Formatting
Comment
Formatted Appearance
;| Inline comment |;
; Single-semicolon comment
;; Current-column comment
170
Formatted text:
(defun foo (x) ;|inline comment |;
(list 1 2 3)
;;current-column comment
;;; heading or 0-column comment
) ;_ function-closing comment
;comment-column comment
Indentation Rules
The Visual LISP Smart Indent feature works in the background as you type
in the text editor. The indent is evaluated up to the current AutoLISP parenthesis nesting level. If before the current expression there is only a sequence
of completed top-level AutoLISP expressions, the indentation will be zero.
The indenting commands use formatting parameters consistently with the
Formatter. Re-indenting after running the Formatter will not change the text
if it was formatted using the same parameter values.
Formatter Restrictions
The following restrictions apply to the Visual LISP AutoLISP Code Formatter:
Chapter 5
171
Match Forward
(CTRL+])
Moves the insertion point (marked by the cursor) just past the
closing parenthesis that matches the next open parenthesis. If
there is no nearby match, it moves you one step up in the nesting
hierarchy.
Match Backward Moves the insertion point to just before the open parenthesis that
matches the previous close parenthesis. If there is no nearby
(CTRL+[)
match, it moves you one step up in the nesting hierarchy.
Select Forward
(CTRL+SHIFT+]) but also selects all text in between the start and end positions.
172
Select Backward Moves the insertion point as the Match Backward command does,
(CTRL+SHIFT+[) but also selects all text in between the start and end positions.
1
2
3
4
5
17
The line numbers are not part of the text; they are used to help explain the
example.
Here is what would happen if you loaded this code in Visual LISP and continually issued the Match Forward command, starting with the insertion
point at the beginning of line 1:
1 Cursor moves to the end of line 1
2 Cursor moves to the end of line 2
3 Cursor moves to the end of line 3
4 Cursor jumps to the last right parenthesis in the program! (17)
In other words, the close parenthesis that matches the open parenthesis on
line 4 is all the way at the end of the program. Notice also that all the
statements after line 4 are indented in a manner unlike that of the preceding
program code. These are 2 clues that indicate something is amiss at this point
of the program. In fact, the close parenthesis to the command on line 4 is
missing.
Chapter 5
173
contains a couple of errors. Open the file in Visual LISP, so that you can see
how color is used in the file:
(defun drawline(/ pt1 pt2); local variables declared
;; get two points from the user
(setq pt1 (getpoint "\nEnter the start point for the line: "))
(setq pt2 (getpoint pt1 "\nEnter the end point for the line: "))
;; check to see that the two points exist
(iff (and pt1 pt2)
(command "_.line" pt1 pt2 "")
(princ "\nInvalid or missing points!")
(princ)
;; exit quietly
)
)
The example above uses different fonts to substitute for the different colors.
If you use the standard Visual LISP syntactic colorations, systems functions
such as setq, defun, getdist, getpoint, and / are displayed in blue. Items
Visual LISP does not recognize, such as user-defined variables, are printed in
black. In this example, if you look at the unrecognized elements in the program, the word iff might easily catch your eye. Change it to the correct
spelling, if, and the color immediately changes to that used for system
functions.
Switch to the editor window containing the code you want to check
Choose Tools>Check Editor from the Visual LISP menu
You can also perform a syntax check on a selected piece of code, instead of
the whole program, by using the Check Selection item on the Tools menu.
Visual LISP displays error messages in a new output window, if it detects any.
The sample code above results in the following error message:
174
This error results from the last princ statement following the if. The if statement only allows two arguments: the statement to execute if the expression
is true, and the statement to execute if the expression is false. The last princ
statement, which is used in this program to cause a quiet exit, belongs after
the close parenthesis that currently follows it. If you move the statement to
the correct location and run Check again, the code should pass as error-free.
Chapter 5
175
6
Debugging Programs
In this chapter
Programs do not always behave in the way they were
intended to. When the results you get appear to be wrong,
Debugging Example
Debugging Features
176
Chapter 6
177
Debugging Programs
Debugging Example
This section takes you through a Visual LISP sample program, using many of
the VLISP debugging facilities along the way. You can find the sample program, yinyang.lsp, in the VLISP \sample directory. Open the file in Visual LISP
so that you can try the examples in this section.
First, load the file and run the yinyang function in order to see what it does.
The function draws the Yin-Yang symbol, which is used symbolically by a
number of religions and philosophies, including Confucianism and Taoism:
When you run the program, Visual LISP passes control to AutoCAD and you
need to respond to the prompts in the AutoCAD command window.
Visual LISP evaluates AutoLISP programs by evaluating the expressions contained in parentheses (parenthetical expressions). Parenthetical expressions
are similar to operators in other programming languages such as C++ and
Visual Basic. The Visual LISP debugger uses an expression-based approach,
unlike the line-by-line debuggers of languages such as C. In this approach,
the debugger can suspend program execution immediately before or after the
evaluation of any expression.
Debugging options are controlled from several different places within Visual
LISP, including the text editor, the System Console, and various menus.
178
Breakpoint
After you reply to the prompts the program displays at the AutoCAD
command line, Visual LISP halts yinyang execution at the breakpoint you
set, and displays the code in the text editor window:
Chapter 6
179
Debugging Programs
1 Click the Step Into button, or choose Debug>Step Into from the Visual LISP
menu. You can also press F8 to issue the Step Into command.
Execution begins and halts before evaluation of the inner parenthetical
expression, that is, before the specified division occurs.
Now look at the Step Indicator button on the Debug toolbar; it is the last button on that toolbar:
Step Indicator
Button
The Step Indicator button is active when you are stepping through a program. It indicates where you are in relation to the expression at the breakpoint. The current symbol indicates that you are stopped just before an open
parenthesis.
2 Click the Step Into button again. The cursor moves to a position directly after
the evaluated expression, and the Step Indicator button indicates this with
the following icon:
3 Click the Step Into button again.The cursor moves to the end of the entire
statement (the expression and all nested expressions).
4 Click the Step Into button again and the cursor moves to a position just
before the beginning of the statement on the next line:
180
5 Now take a bigger step. Click the Step Over button, or choose Debug>Step
Over from the menu; you can also press SHIFT+F8 to issue this command:
With the Step Over command, Visual LISP evaluates an entire expression
(and all nested expressions), then stops at the end of the overall expression.
The cursor moves to the end of the expression.
Chapter 6
181
Debugging Programs
the last evaluated expression. From the Debug menu, choose Watch Last
Evaluation:
VLISP displays the Watch window, which shows the value of the
*LAST-VALUE* system variable. Visual LISP always stores the value of the last
evaluated expression in the *LAST-VALUE* variable.
If the Watch window were not already open and you wanted to view a variables value, you could open the window by choosing View>Watch Window
from the Visual LISP menu.
If you click the Watch windows Add Expr button without double-clicking on
a variable name first, the following window appears:
In this window, you can enter the name of the variable you want to view.
Visual LISP anticipates you by copying the name of the variable nearest the
182
cursor into the window; if this is not the one you want to view, simply type
over the name.
Visual LISP updates the variables in the Watch window after each execution
step.
Click the Step Over button (or press SHIFT+F8) twice. In the Watch window,
note how the value of ORIGIN-Y changes. It was nil at first, but after execution it took on the value corresponding to the point you clicked in the
AutoCAD window:
Debugging Features
In addition to setting breakpoints as you saw in the Introduction section of
this chapter, Visual LISP provides the following options for controlling program execution:
Chapter 6
183
Break on Error. This option activates the interactive break loop automatically whenever your program encounters a runtime error. You turn on
this mode of operation by choosing Debug>Break On Error from the
Visual LISP menu.
Stop Once. This option causes Visual LISP to break unconditionally
when it evaluates the very first LISP expression prepared for debugging.
From the Debug menu, choose Stop Once to initiate this mode.
Break on Function Entry. Setting the Debug-on-entry flag for a functions name symbol causes a break to occur every time you invoke that
function. At the break, the source code for the function will be shown in
a special window. You can set or clear the Debug-on-entry flag interactively with the Symbol Service dialog. See The Symbol Service Dialog on
page 199 for information on setting this flag.
Debug Top-Level Mode allows you to control the loading of a program
from a file or from an editor window. Breaks occur before evaluating every
Debugging Programs
top level expression (such as defun). The Debug Top-Level mode is turned
on by switching off the Do not Debug Top Level option. To find the checkbox for this option, choose Tools>Environment Options>General Options
from the Visual LISP menu, then click the Diagnostic tab.
Note that if Top-Level debugging is turned on, and Stop Once mode is also
turned on, Visual LISP will enter the debugging mode every time you load
a file. This is due to the fact that Visual LISP is debugging defun, setq, and
other functions defined within the file as they are loaded. This is usually
not a helpful debugging technique and should only be required in rare
instances.
Animate Mode operates as if a Step Into command is executed repeatedly with a specified delay. Editor windows in the Animate mode will
highlight expressions being evaluated, and the Watch window will permanently update its data. To turn on Animate mode, choose Debug>Animate
from the Visual LISP menu. When Animate mode is on, Stop Once mode
is ignored.
Animation speed is controlled by the value of the Animation delay environment option. To view and set this option, choose
Tools>Environment Options>General Options from the VLISP menu, and
click the Diagnostic tab.
Starting Debugging
The easiest way to start debugging is to choose Debug>Stop Once from the
Visual LISP menu. When this item is selected, the evaluation of the first LISP
expression will be interrupted. After that you can resume program execution
using various Debugger commands. Another way to enter into the debug
mode is to set a breakpoint, as shown in Setting a Breakpoint to Interrupt
Program Execution on page 178.
When a break occurs, the corresponding Visual LISP text editor window will
show the current LISP expression at the point which the break took place. A
break loop marker will appear in the Console window. Using the Console
window, you can access and manipulate the program environment in which
the break occurred. You can also examine variables using the Watch window.
Debugging Features
184
When you are running an AutoLISP program without any debugging intervention by Visual LISP, you are running in the Top Level read-eval-print
loop. When you evaluate an expression within the Visual LISP Console, and
the normal prompt is displayed, you are also working at the Top Level.
When a programs evaluation is interrupted or suspended in the middle of
execution, Visual LISP passes control to the Console and you enter a break
loop. This break loop is a separate read-eval-print loop, and is nested underneath the original read-eval-print loop. It is possible to interrupt a break loop
and start yet another read-eval-print loop beneath it. The nesting level of a
break loop with respect to the Top Level is called the break level.
When you enter a break loop, Visual LISP prefixes the Console prompt with
a number indicating the level you are at. For example, when you first enter a
break loop in a program, the prompt indicates this with the number 1:
_1_$
While you are in a break loop, you cannot switch control to the AutoCAD
window.
On exiting from a break loop (for example, after issuing the Quit command),
the current read-eval-print loop is terminated and the previous level loop is
resumed. If you change the value of a variable in the break loop, this value
will be used when the program resumes execution.
Turning on the Stop Once mode and reaching an expression with debugging information (that is, an expression that is loaded from source code,
as opposed to from a compiled .exe file
Reaching a function marked for Debug on Entry
Reaching a breakpoint you set in the program
Entering a break loop by pressing the Pause button
Proceeding with a Step Over, Step Into or Step Out command from the
previous break loop state
When the program is interrupted, you enter the break loop. This is apparent
if the Visual LISP Console is active, since the prompt is changed to reflect the
current level of the break loop. In this suspended state, you have read-write
access to all variables in the environment in which the break occurred. For
example, if the break occurred within a function containing several local
variable declarations, those variables are accessible and you can change their
values by issuing setq assignments at the Console prompt.
Chapter 6
185
Debugging Programs
When stopped at a breakpoint, you can control subsequent program execution by choosing one of the following items from the Debug menu, or by
pressing the equivalent toolbar button:
Reset to Top Level. This terminates all currently active break loops and
returns to the Console top-level (the top read-eval-print loop).
Quit Current Level. This option terminates the current break loop and
returns to a break loop one level up. This may be another break loop or
the top level read-eval-print loop.
Continue resumes normal program execution from the breakpoint.
The Step commands evaluate portions of program code before resuming suspended mode:
Step Over looks for the closing parenthesis matching the opening parenthesis where the program is currently paused, and evaluates the expressions in between.
Step Into jumps into a nested expression, if any. If there are no nested
expressions, it jumps to the next expression in sequence.
Step Out searches for the end of the function where the program is currently paused, and evaluates all of the expressions up to that point.
After exiting the break loop to the Console top level, the Console prompt
returns to its original form (without a number prefix).
Breakpoints
A breakpoint allows you to mark a position in a program at which program
execution should be interrupted. You can set breaks to occur before or after
parenthetical expressions.
Debugging Features
186
cution. For example, to halt execution just before the open parenthesis of an
expression, place the cursor just to the left of that open parenthesis. Then
click the Toggle Breakpoint toolbar button or press F9 to set the breakpoint.
(For variety, you can set a breakpoint by choosing Debug>Toggle Breakpoint
from the Visual LISP menu, or by clicking the right mouse button and selecting Toggle Breakpoint from the resulting context menu.)
To remove the breakpoint at a later time, follow the same exact procedure.
The Toggle Breakpoint works as an on/off toggle: when no breakpoint exists,
Toggle Breakpoint adds a break; if a breakpoint already exists at the cursor
position, Toggle Breakpoint removes it. You can also use the Breakpoint service dialog to remove breakpoints; see Listing and Viewing the Breakpoints
in Your Program on page 188 for information on this procedure.
If you move the cursor to an ambiguous position, such as in the middle of an
expression, Visual LISP will move the cursor to the nearest parenthesis and
ask you if you agree with the breakpoint placement:
Click Yes to accept the breakpoint location, or No if that is not where you
want to set the break.
Breakpoint Highlighting
Visual LISP marks each breakpoint position with a colored rectangle, so you
can easily locate the breakpoints in your program. By default, active breakpoints are marked in red. You can change this color by setting the
:BPT-ACTIVE option under Tools>Window Options>Configure Current.
Disabling Breakpoints
When using multiple breakpoints within a source file, it may be useful to
temporarily disable one or more breakpoints, but leave the breakpoint position defined for possible later use. This saves time over deleting and restoring
the breakpoint.
To disable a breakpoint, place the cursor at the breakpoint marker and press
the right mouse button. From the resulting menu, choose Break point service. Visual LISP displays the following dialog box:
Chapter 6
187
Debugging Programs
Click the Disable button in the Breakpoint service dialog window to temporarily disable the breakpoint. Visual LISP changes the color of the breakpoint
marker when it disables the breakpoint. By default, it marks disabled breakpoints in blue. You can change this color by setting the :BPT-DISABLE option.
The Breakpoints window lists the breakpoints in all programs you are editing
in Visual LISP, not just the program in the active editor window. In the example above, only one program (yinyang) is listed, because that is the only one
currently open. But you could be editing and setting breakpoints in any
number of open files.
Each entry in the Breakpoints window shows the name of the source file containing the breakpoint, and the location of the breakpoint in the source. A
leading + or - sign differentiates between active and disabled breakpoints.
The dialog box allows you to delete all breakpoints at once or to edit (or display) one breakpoint at a time. Pressing Show displays the source position of
the breakpoint. The Edit button opens the Breakpoint service dialog, from
which you can disable the breakpoint.
Debugging Features
188
gram, and then add a breakpoint, the breakpoint only takes effect after you
reload the code.
Breakpoints remain in effect during the Visual LISP editing session and will
survive between sessions if you choose Save Settings from the Tools menu.
In addition to removing breakpoints using the methods previously described
in this chapter, program breakpoints are automatically lost when you do any
of the following:
Note also, that if you modify a programs code and run it without reloading
it (with the Load Active Edit Window command), the program will be interrupted when a breakpoint is reached, but the exact source position will not
be shown. The following dialog box indicates that this situation has
occurred:
To enable proper display of a source position, you need to reload the code
and restart the program.
Chapter 6
189
The Watch window displays the current value of any set of variables.
The Trace Stack window displays the most current call hierarchy. At
any level of the stack you can view the corresponding code, the calling
code, the local variables, and more.
Debugging Programs
The Watch window is updated at each step of a Visual LISP interactive session
and always shows the current environment state. In debugger mode, the
Watch window is refreshed automatically at the end of every expression evaluation.
The Watch dialog retains its contents during a Visual LISP session. This
means that if you open the Watch dialog and make it inactive, it will have
the same contents the next time you invoke the Watch command during the
current session.
190
Specify the name of the variable to be watched in this window, then click OK.
The introductory section of this chapter includes an example of using the
Watch window; see Tracing Variables During Program Execution on
page 182.
Watch Toolbar
The toolbar on the Watch window contains the following buttons:
Add Watch
Clear Window
Sort Expressions
Copy to Trace/Log Invokes the log command and copies the contents of the
Watch dialog to the Trace window
Chapter 6
191
Debugging Programs
Inspect value invokes the Inspector dialog for the selected value.
Copy value copies the value of the selected variable into system variable
*obj*.
Print value prints the selected variable value in the Console window,
prefixed with a single quote ().
Symbol... calls the symbol service dialog for the selected variable.
Apropos... calls the Apropos dialog using the selected symbols name as
the Apropos argument.
Remove from Watch removes the selected variable from the Watch
window.
192
The trace stack is used by Visual LISP to remember its way out of a nested
series of expressions. By viewing the stack you can see what is happening
within your program as it is executing (within a suspended, break mode) or
immediately after it crashed.
Before you invoke a function at the Console window or from AutoCAD, the
trace stack is empty. The action of invoking a function causes a record, or element, to be placed on the stack. As that function calls additional nested functions to perform the work of your program, additional elements may be
added to the stack. Visual LISP only needs to place elements on the stack
when it needs to remember its way out of nested functions.
There are two conditions where it is useful to examine trace stacks. The first
is when your program is in a suspended state, such as during a breakpoint
pause. The second is after an error has occurred, causing your program to fail.
Chapter 6
193
Debugging Programs
Arguments within this listing are displayed not by their local parameter
name, but by the values that were actually passed to the function.
Keyword frames are displayed at the very top and bottom of a trace
stack. They are displayed in the form:
level :keyword {optional-data}
The keyword indicates the type of the frame. The optional-data displays
additional information relating to the state of the program.
Top forms indicate an action that was initiated by typing in an expression at the top level Console window, or from the invocation of a function
that was triggered during the loading of a file or selection within a Visual
LISP editor window.
Lambda Forms are placed within a stack whenever a lambda function is
encountered within your program.
Special Forms display the invocation of the foreach and repeat functions. The arguments for these functions are not displayed. They appear
as:
level (function-form ...)
Function Call Frames and Keyword Frames are discussed in more detail in the
following sections. These sections use the following code to demonstrate the
trace stack. If you wish, you can copy this code into a Visual LISP editor window, set a breakpoint as indicated in the code comments, and run this sample:
(defun stack-tracing (indexVal maxVal)
(princ "At the top of the stack-tracing function, indexVal = ")
(princ indexVal)
(if (< indexVal maxVal)
(stack-tracing (1+ indexVal) maxVal)
(princ "Reached the maximum depth.") ; place a breakpoint at the
; beginning of this line
)
)
(defun c:trace-10-deep ()
(terpri)
(stack-tracing 1 10)
)
194
The Trace Stack window displayed above shows a Function Call Frame for the
stack-tracing function. The second element, or frame, in the trace stack is
highlighted:
[2] (STACK-TRACING 10 10)
The number [2] simply identifies it as the second element in the stack. The
numbers following the stack-tracing function name (10 10) indicate the
actual values that were passed to the function.
Active items available on the context menu depend on the type of stack element you selected before right-clicking. Possible menu commands include
the following:
Chapter 6
195
Debugging Programs
Copy copies the selected trace stack element to system variable *obj*.
Local Variables displays the Frame Bindings dialog to allow browsing of
local variable values at the time the function was called; see Frame Binding Window on page 196.
Source Position checks whether the source text is available for the function called at the selected stack frame. If the source code is available, the
text window with the source code is displayed, with the current position
inside the function highlighted.
Call Point Source shows the position of the caller expression, similar to
Source Position.
The Frame Binding window displays information about the local variables in
the frame. In the example above, it lists the parameter names (INDEXVAL,
MAXVAL), along with the values assigned to these parameters. These are the
values that were passed to the function. The parameters are listed in the order
that they are defined within the function.
If you right-click on an entry in the Frame binding window, Visual LISP displays a context menu:
Keyword Frames
A Keyword Frame indicates a specific type of operation that has occurred
within the Visual LISP environment. The keyword indicates the type of oper-
196
ation. Keyword frames will appear in only two locations: at the very top of
the stack, or at the very bottom of the stack.
The following types of Keyword Frames will appear only at the bottom of a
stack:
The following types of keyword frames may appear at the top of a stack:
:BREAK-POINT indicates a user-specified break point.
:ERROR-BREAK indicates a general runtime error. The Show Message rightclick context menu selection allows you to view more specific error messages.
:READ-ERROR indicates an error during a read operation. The Show Message right-click context menu selection provides additional information
about the error.
:SYNTAX-ERROR will appear when Visual LISP encounters incorrect
AutoLISP program syntax.
:FUNCTION-ENTRY indicates that the reason for program interruption is a
debugger break upon entering the function. The stack element following this
message contains the call frame for the function in which the break occurred.
Chapter 6
197
Debugging Programs
AutoLISP functions such as if, cond, and, and setq do not appear on the
stack. They are not necessary because their call position may be viewed
within the source file in the text editor window.
198
An error trace stack cannot display live data, since it is essentially a postmortem record of the events leading to your programs failure.
Refresh
Refresh contents of Trace stack window.
Copy to Trace/Log Copy the window contents to the Trace window or open log
file.
Chapter 6
199
Debugging Programs
A toolbar
The Name field, where you can enter or change the symbol to work on
A Value field displaying the symbols value or its initial substring
Flags, a series of check boxes for symbol flags, which are described in the
Symbol Flags topic.
To update the value of the displayed symbol, enter an expression in the Value
field. When you press OK, Visual LISP evaluates the expression and assigns
its value to the symbol.
If the symbol is flagged Assign protected, this field will be read-only. To
remove the flag, check the Protect Assign check box below the value field.
Use the OK and Cancel buttons to close the dialog and to continue working
in Visual LISP.
Watch
Adds the symbol to the Watch window.
Inspect
Opens the Inspector for the value of the symbol.
Show the function definition If the symbol names a user-defined function, this command
opens the text editor window containing the function definition, and highlights the function.
200
Help
Symbol Flags
The Symbol Service dialog provides direct access to symbol flags and properties of functional objects that may be associated with them. The following
symbol flag options are available:
Trace (Tr). The Trace flag activates the tracing of any user-defined function (shown as a symbol within the symbol service window). Tracing will
only occur when the symbol is a function, and the expression being evaluated uses the symbol name as a function (not as a local variable name,
for example.)
Debug on Entry (De). If this flag is set, a breakpoint occurs at each function invocation, regardless of whether the function was loaded with
debugging information. The De flag is tested at each function invocation,
not during load or defun execution.
Note that Visual LISP ignores the Debug on Entry flag for all SUBR,
EXSUBR and EXRXSUBR symbols.
Export to ACAD (Ea). If the Ea flag is set, a function associated with the
symbol is defined in native AutoLISP as an external subroutine.
Inspector Windows
The Inspector is the component of Visual LISP that provides you with the
ability to browse, examine and modify AutoLISP and AutoCAD objects. It is
a powerful and easy to use tool. You can use the Inspector for the following
purposes:
Chapter 6
201
Debugging Programs
The Inspector also allows you to browse through complex data structures.
The Inspector creates a separate dialog window for each object you inspect.
The Caption of an Inspector dialog box shows the type of the object
being inspected.
The Object Line shows a printed representation of the inspected object.
The Element List displays the components of the inspected object. The
list may vary in size and contents for different object types. Each element
list is shown as a pair: name and contents. The name is enclosed in brackets. Square brackets ([ ]) denote that this item can be modified with a
Modify command from the context menu associated with the item, and
curly brackets ({ }) designate an unmodifiable item.
Both the object line and the element List lines have their own associated context menus.
INT (integer number) Inspector. The element list shows the various
representations of integers.
REAL (floating point number) Inspector. This element list is empty.
STRING Inspector. This element list contains the sequence of characters in the string, which and may in turn be inspected as integers.
SYMBOL Inspector. The symbol element list has 3 elements: value,
print name, and flags.
LIST Inspector for proper lists. This element list displays the items of
the inspected list.
LIST Inspector for improper lists. This list has 2 elements: the car
and cdr fields. It serves for all cases that are not proper LISP lists, that is,
the last cdr is not nil.
FILE Inspector. The File Inspector shows the name of the corresponding
file and the files opening attributes.
SUBR, EXSUBR, and USUBR Inspectors. These Inspectors contain
the name of the function (the name was specified in defun or at load
time).
ENAME (drawing entity) Inspector. The fields in this element list
correspond to the AutoCAD DXF object list, as returned by the AutoLISP
built-in function.
202
PICKSET (selection set) Inspector. This element list is simply the list
of selected AutoCAD objects.
A new Inspector dialog box appears showing the value of the expression you
selected. For example, if you want to inspect a symbol, you should see this
symbol in the form of my-variable.
If you invoke the Inspect command without selecting an object name, Visual
LISP prompts you to specify the object you want to inspect:
Enter the object or expression you want to inspect, then press OK to open the
Inspector window or press CANCEL to cancel the action.
Visual LISP saves the last 15 items you enter in the Inspector prompt box. You
can choose a previously-specified object for inspection by selecting it from
the drop-down list.
Chapter 6
203
Debugging Programs
you can correct the expression in the dialog box and try to evaluate it once
more.
Errors arising from evaluation of the object you entered cannot be investigated from a nested break loop, because all breaks are disabled during such
evaluation. If you wish to examine the error, choose View>Error Trace from
the Visual LISP menu, or copy the expression to the Console prompt and
press ENTER.
When the object line has the focus, these commands are also available as keyboard combinations. The frame status bar should read Print (Alt+P) Update
(Alt+U).
Element Line Commands
The element line (or item) context menu appears after highlighting the element line and right-clicking.
Inspect (ALT+I) calls the Inspector and gives it the element (field) value
as an argument
Descend (ALT+D) calls the Inspector and gives it the element (field) value
as an argument and closes the current Inspector.
Copy copies the value of the inspected element (field) to the
*obj* variable.
204
View source activates a text editor window containing the selected text.
If it was loaded from the Console or from a list representation, this command activates a new text editor window.
The default command for the element line, invoked by pressing ENTER, is the
Inspect command. Other commands available as keyboard combinations can
be seen from the frame status bar prompt field, when the element line has
the focus. However, some lines in the Inspector do not correspond to any
sub-objects, and as a result these lines have no joined pop-up menus. Clicking on these lines has no effect.
Paging
When inspecting long sequences, the Inspector does not show the whole
sequence. Instead, it uses paging. For paging, the special paging element lines
appear in the Element List. If a sequence is too long the special ">>> [Next
page]" element line appears at the end of the Element list. To page the
sequence, follow the same procedure that initiates the element line pop-up
menu.
To page down, choose the ">>> [Next page]" element line and press Alt+E,
double-click, or right-click in that element line.
To page up, choose the "<<< [Previous page]" element line and repeat the
previously-mentioned process.
To return to the first page, choose "<<< [First page]" and repeat the previously-mentioned process.
Chapter 6
205
Debugging Programs
Binary
Octal
Decimal
Hexadecimal
Character
The last representation means that the ASCII character corresponds to the
number (for large numbers it takes the last byte).
The INT Inspector does not have an Element List.
REAL Inspector
Name is the element line that shows the symbol print name (which is
always a string)
Value is the element line that contains the symbol value
Flags are element lines that reflect symbol attributes. These may be:
Pa Protect Assign
Tr Trace
De Debug on entry
Ea Export to ACAD
206
To change a symbols value or flag settings, use the object line menu command Symbol Service, which shows the Symbol Service window.
NOTE The information for the SYMBOL Inspector is available in a more convenient way through the Symbol Service dialog. So, the symbols Inspector is provided mainly to maintain uniform Inspector access for all of AutoLISPs data types.
LIST Inspector
FILE Inspector
Name This field shows the file name string that was used in the AutoLISP
open function.
Mode Can be one of three values: INPUT, OUTPUT, APPEND, or :CLOSED.
id Shows the internal file identifier.
Position Shows the current position in the file.
EOF indicates whether or not the end of the file has been reached. This
field does not appear if a file is open for output.
STRING Inspector
SUBR Inspector
Chapter 6
207
Debugging Programs
USUBR Inspector
Name shows with the symbol print name, which is always a string
Parameters shows the list of user function parameters
Auxiliary displays a list of auxiliary variables listed after the / in the
DEFUN argument list
EXSUBR Inspector
The EXSUBR Inspector contains a Name field showing the symbol print
name.
208
Note that VERTEX and ATTRIB entity types are not included in this list. You
access these entity types through their parent entities, which are available
with the POLYLINE and INSERT Inspectors.
The context menu commands available for the object line in the ACAD Entities Inspector window are Log and Update.
Select the entity you are interested in, then right-click and choose Inspect to
open an Inspector window for the entity:
The title bar of this window identifies the drawing entity type. The object
line of the window displays the entity name:
<Entity name: 27e0540>
The context menu for the object line contains the common Inspector commands Print, Copy, Log, and Update, plus some new items:
Chapter 6
209
Debugging Programs
You can inspect each table as a collection of named attributes. Select and
right-click on a table name, then choose Inspect:
To view a table entry for a selected attribute, right-click and choose Inspect
again:
210
Select the block you are interested in, then right-click and choose Inspect to
open an Inspector window for the block.
Chapter 6
211
Debugging Programs
You can select an entity from the selection set and right-click to invoke the
Inspector for the entity.
212
Chapter 6
213
Debugging Programs
7
Building Applications
In this chapter
This chapter describes Visual LISPs AutoLISP File Compiler.
Building Stand-alone
Applications
Making Application
Modules
214
Chapter 7
215
Building Applications
st
lsm
The standard mode produces the smallest output file and is suitable for programs consisting of a single file.
The optimization options result in more efficient compiled files, which
becomes important as your programs grow in size and complexity. The basic
functions of optimization are to:
216
For example, if you are compiling the yinyang.lsp program file in the Visual
LISP Sample directory, and Support File Search Path is set as indicated in the
window shown above, you can issue this command:
(vlisp-compile st "yinyang.lsp")
If the Visual LISP Sample directory is not in the Support File Search Path, you
would need to include the entire path name when specifying the source file:
(vlisp-compile st "c:/program files/autocad R14/vlisp/sample/yinyang.lsp")
If you omit the file extension from a file name, Visual LISP assumes .lsp.
NOTE When specifying the file path name, replace the backslash symbol (\)
you normally use for file names with a forward slash or double backslash, following the usual AutoCAD convention.
NOTE If you do not specify a path name for either the input or the output file,
Visual LISP places the output file in the AutoCAD install directory! This is probably
not what you want.
In most instances, youll want to specify the full path name of the output file:
(vlisp-compile st yinyang.lsp "c:/program files/.../sample/GoodKarma")
Chapter 7
217
Building Applications
During compilation, the compiler prints function names and various messages about each stage of compilation. The first stage is syntax and lexical
checking of the source code. If the compiler encounters errors, it issues messages and halts the compilation process. The compiler issues warnings if it
encounters expressions it considers dangerous, such as redefining existing
AutoLISP functions or assigning new values to protected symbols.
If compilation is successful, as in the example above, the <Build Output>
window displays the name of the compiled output file.
TIP Remember that, if warning or error messages are displayed, you can view
and edit the source code that caused these messages by double-clicking on the
message in the <Build Output> window.
218
If you do not specify the file extension, Visual LISP assumes .fas. The file
extension FAS is reserved in Visual LISP; .FAS files are assumed to be compiled
AutoLISP files.
If you prefer less typing and more clicking, choose File>Load File from the
Visual LISP menu, and use the Load Lisp File dialog box to select yinyang.lsp.
Remember to use the Files of Type pull-down list in this dialog, and select
Compiled AutoLISP Files, otherwise Visual LISP only lists LSP files in the
dialog.
2 Run the program the same way you would a program loaded from the text
editor window. Issue the following at the Console prompt:
(yinyang)
Chapter 7
219
Building Applications
a subset of the Visual LISP environment and can load and run FAS files in
AutoCAD. You can send customers individual FAS files, or create a single VLX
module (Visual LISP executable) that contains all your FAS and DCL files. In
both cases, though, you need to send the RTS executable along with your
files. The executable is provided in the form of an ObjectARX program. See
Using the Visual LISP Run-Time System on page 223 for more information
about using the RTS.
An alternative method of building applications is to package the RTS along
with your FAS and DCL files into a single ARX module. This results in a much
larger module then either FAS or VLX files, but it is self-contained and can be
loaded and run in AutoCAD like any other ARX application.
Whether you run your Visual LISP application from the Integrated Development Environment (IDE), or run the application from AutoCAD using the
RTS, you are running an application in a Visual LISP environment.
The yinyang.lsp sample program uses this method to make itself known to
AutoCAD:
(vl-acad-defun yinyang)
220
the function name is automatically exported to AutoCAD when you load the
application in the AutoCAD environment. Remember that c: functions can
be issued as AutoCAD commands from the AutoCAD Command prompt.
Refer to C:XXX Functions on page 58 for more information on using c:
functions in Visual LISP and in AutoCAD, including some limitations
imposed on their use.
The automatic export of c: functions by Visual LISP occurs if the VLISP system variable *C-COLON-EXPORT* is set to T. By default, the feature is enabled.
You can disable the feature by setting *C-COLON-EXPORT* to NIL.
If all function names intended for use as AutoCAD commands begin with c:,
you can get by without explicitly exporting any functions.
NOTE You must describe every external function defined in an external ADS
or ARX module, if you call it from a Visual LISP environment (IDE or RTS). If a function description is missing, Visual LISP will be unable to call that function.
If an application is loaded from the AutoCAD Command prompt or from
another application after the Visual LISP IDE or RTS is loaded, Visual LISP will
not be able to correctly recognize the applications functions. If this happens,
Chapter 7
221
Building Applications
The first argument is the applications full name. The remaining arguments
are the application function names to be defined to Visual LISP.
Creating XDF Files
To assist you in the creation of an XDF file for a custom ADS or ARX application, Visual LISP provides the make-xdf utility function. This function
attempts to load your application, so if the application is already loaded in
AutoCAD, you need to unload it. The make-xdf function assumes that your
application defines its function entries after loading, and it retrieves all those
function symbols after the load.
To start make-xdf, first load the make-xdf.lsp file found in the Visual LISP
install directory. Use Tools>Load Application on the AutoCAD menu to load
the file. Then enter the following at the AutoCAD Command prompt:
Command: make-xdf
The command asks for the name of the external application to browse. Either
enter the path name for the application module, or press ENTER without
specifying a name and select the file from a dialog box. The make-xdf function loads your application, looks for new function symbols, and writes definitions for them in an XDF file it creates in your application directory. The
XDF file has the same name as your application module, with an extension
of .xdf.
If you do not want to use the make-xdf function to build your externally
defined functions file, you can use any text editor to create one from scratch.
XDF File Format
The XDF file is a plain ASCII file containing a LISP list for each AutoCAD version used. Blank lines and AutoLISP-style comments are allowed. Each entry
requires the following syntax:
(ACADver* ( application (symbol...) ) ...
222
vlrts.arx
vlarts.arx
Chapter 7
223
Building Applications
These steps, along with requirements for more complex applications, are
explained in the following sections.
If the RTS file is in AutoCADs Support File Search Path, you can simply issue:
(arxload vlrts)
224
Or you might create a file to just load some applications and greet users:
(load karma.fas)
(arxload nirvana.arx)
(princ Hello Earthians)
(princ)
)
If you do not supply a start-up file name to Visual LISP, the RTS looks for a
FAS file named appname-init.fas, where appname is the name of your
applications executable file. If it finds a file with that name, the RTS executes
the instructions in the file. If the RTS does not find a file with that name, it
loads vlrts.fas (or vlarts.fas, if youve loaded the RTS for ActiveX applications).
If VLISP does not find a FAS file of that name, it uses the LSP version of the
file.
In looking for the start-up file, the RTS first searches the Visual LISP install
directory, then the AutoCAD Support File Search Path. If you renamed the
RTS executable, you must also rename the FAS or LSP file accordingly.
To avoid calling the vlrts-init function explicitly, you can provide any
number of end user functions available immediately after loading the application. These functions are called initialization functions. On the first call to
any of these functions, Visual LISP calls the vlrts-init function, which
loads the start-up file. Then the original function definition will be executed.
NOTE
Chapter 7
225
Building Applications
vl-eval-str
c:vl-eval
vl-load
c:vl-load
If the file you want to load is in AutoCADs Support File Search Path, you can
enter the file name without specifying a path. If you do not include the file
extension, vl-load looks for files with either a .vlx, .fas, or .lsp extension, in
that order.
If you press ENTER without specifying a file name, vl-load opens a dialog
box for you to indicate the file you want to load.
If you issue vl-load for the yinyang.lsp file, which includes a vl-acad-defun
call to export the function name, you can verify that yinyang is known to
native AutoLISP. Use the AutoLISP type function to see how yinyang is
defined in AutoLISP:
Command: (type yinyang)
EXRXSUBR
The vl-eval-str function also gives you the ability to set variables in the
Visual LISP RTS environment. For example, if applications test a global variable, you can set the variable with vl-eval-str:
Command: (vl-eval-str "(setq *RUN-WILD* T)")
T
226
To invoke a function and pass it a string, use the backslash (/) escape code for
each quotation mark. For example to pass the following to vl-eval-str:
(setq str "These are \"\" double quotes")
Use the backslash escape code for quotes, and add double escape codes before
any escape codes in the string:
Command: (vl-eval-str "(setq str \"These are \\\"\\\" double
quotes\")")
"These are "" double quotes"
Note that internal functions may not be available if the optimizing compiler
dropped their names from the compiled files.
A load in native AutoLISP loads the LISP file into the native AutoCAD
environment, while a vl-load integrates the files contents into the Visual
LISP RTS environment.
Functions known in the RTS environment are not visible in the native
AutoLISP environment if they were not explicitly exported. Functions
defined in native AutoLISP are not available in the RTS environment.
A setq in native AutoLISP sets a variable in native AutoLISP only. This
variable is unknown in the Visual LISP RTS environment (or worse: it may
have a different value in the Visual LISP RTS). Similarly, any setq in a file
loaded to the Visual LISP RTS or through vl-eval-str will set the variable
in the Visual LISP RTS environment, leaving the AutoLISP environment
unaffected.
Note that AutoCAD automatically loads acad.lsp, acadr*.lsp, and all files with
a *.mnl extension during initialization of the native AutoLISP environment.
Those files are not automatically loaded to the RTS environment during initialization. You can add the vl-init function call to your initialization file
to mimic the AutoCAD initialization procedure and load the aforementioned
LISP files.
The vl-eval and vl-load functions give you access to the internals of the
RTS environment. However supplying vl-eval or vl-load to users also provides a way for them to observe and change variables and symbols in the RTS
environment, which may affect your application. If you are concerned about
this, drop these functions before distributing your application to customers.
Chapter 7
227
Building Applications
Partial initialization preserves Visual LISP function symbols and variable values, so your LISP application environment extends to the new drawing.
If *VL-NEW-FULL-INIT* is set to T, which is the default setting, Visual LISP reloads completely when a new drawing is opened.
NOTE When using partial initialization, your application is responsible for
resetting data handles of global variables related to the previous drawing. Such
handles may turn to hanging references for the new drawing, and using
them may lead to unpredictable results.
228
Chapter 7
229
Gpmain.lsp
Gpdraw.lsp
Gp-io.lsp
Utils.lsp
Building Applications
Choose the path for the output Make file, and enter a name for the file. For
this example, give it the same name as the program, GardenPath. The Wizard
automatically adds a .mkp extension to the file name. Press ENTER or click
Save to proceed.
230
ARX Application with ActiveX Automation. Visual LISP also produces a single ARX module, similar to the Standard option, except that it
employs ActiveX methodology in the module.
WARNING! If any programs in your application use ActiveX methodology,
you must choose this option in order to create an ARX application. If you choose
the ARX Standard option instead, the program will not run in AutoCAD.
VLX. A VLX module contains your application and all supporting files,
but it does not include the Visual LISP RTS. Because the RTS is not
included, the resulting module size is smaller than ARX modules, and you
can use a single RTS for all your VLX modules. However, you are responsible for setting up the run-time environment for VLX modules in
AutoCAD. See Using the Visual LISP Run-Time System on page 223 for
information on setting up the run-time environment for VLX modules.
The Executable prototype identified under the list of application types refers
to the ARX RTS module on which Visual LISP models your executable module.
The tutorial sample programs use ActiveX methodology, so you must choose
the ARX with ActiveX Automation option if you are building an application
from these programs.
Press the NEXT button to continue to step 2.
You can type the full path name in the supplied field, or click the Browse button and use a standard Windows dialog to identify the output destination.
By default, the Wizard assumes that you want the executable file created in
Chapter 7
231
Building Applications
the same directory as the Make file, with the same file name as the Make file
and a file extension of .arx.
If you need to go back to a previous Application Wizard step and change
something, you can click the Previous button. Otherwise, click Next to continue.
If you select the default option, Load all files automatically, Visual LISP creates a start-up file named VLI$prefix.$$$, where prefix is the first 4 characters of the executable file you named in Step 2. The start-up file loads all your
application FAS files. Remember that you can include initialization functions
in your FAS files.
If you choose to supply an initialization file (such as VLARTS.LSP), clear the
Load all files automatically check box and click the Browse button to identify
the name of the initialization file you created. This file will be loaded at startup.
Click Next to continue.
232
Pull-down list to
select type of
program file
You can specify AutoLISP source code files, compiled AutoLISP files, or a
Visual LISP project file. If you specify a project file, all of the projects FAS files
are included in the output module. See chapter 8, Managing Multiple LISP
Files, for information on creating and using project files.
If you specify AutoLISP source files, Visual LISP compiles those program files
when it builds the application.
Click the pull-down button to choose the type of file you want to include. If
you are building the tutorial application, there are no compiled program files
available (unless youve gone ahead and compiled the source files on your
own), so choose LISP Source Files. Then click Add:
You can only select one file at a time using this dialog box. After selecting a
file name, click Open to add it to the application.
Chapter 7
233
Building Applications
For the tutorial application, you need to specify the Lesson5 folder of the
VLISP Tutorial directory. Then add each of the following files from that
folder:
Gpmain.lsp
Gpdraw.lsp
Gp-io.lsp
Utils.lsp
If you need to remove or replace files in the future, select the files you no
longer want and click Remove. You can also select one or more files, rightclick, and choose Remove from the context menu.
If you want to replace all the LSP files with FAS files, click [Un]Select All to
select all the files in your application, then click Remove. Use the Add button
to specify the new files.
Using the Up and Down Buttons to Change Load Order
Visual LISP loads the applications files in the order they are listed. You may
need to reorder the file list in this step of the Application Wizard. For example, if you call a function at load time, the function must be defined before
it is used. In this case, you want to place the file defining that function first.
The Wizard dialog box contains buttons you can use to move files around in
the list. Select a file name, then click either:
You can also right-click and choose these actions from a context menu.
Note that the load order of project files is specified when you define the
project; see Changing the Order in Which Visual LISP Loads Files on
page 251 of the Maintaining Visual LISP Applications chapter.
234
DCL is a tag language that can be used to create custom windows for an application. The Visual LISP tutorial demonstrates how to use DCL in an application. Click the Add button to select the DCL file from the Lesson5 directory;
the file name is Gpdialog.dcl.
After selecting the DCL file and adding it to the application, click Next to
continue.
If your application does not use any XDF files, click Next to continue. Otherwise, use the Add button to specify the XDF file you defined. Refer to Identifying Functions Defined in External Applications on page 221 for information on defining XDF files and calling other ARX or ADS applications.
Chapter 7
235
Building Applications
236
For the tutorial application, a single function is implicitly defined. This is the
function you call to start the application.
Defining Your Own List of Initialization Functions
If you choose neither the Initialize in load time or Form the list automatically
options, you can selectively choose the functions you want to define as initialization functions. An Add button appears where the Preview button previously appeared.
1 Click the Add button to begin the process of specifying initialization functions.
2 Click the Browse button to get a list of exported function names. You may
receive the following message:
Chapter 7
237
Building Applications
This indicates that one or more of the source files in the application have
been modified since their last compile. Click OK to allow Visual LISP to
recompile the changed files.
3 In the tutorial application, there is only one exported function name. Select
the name and click Add.
4 Click the Close button to return to the step 7 window.
Click Next to continue to the final step.
If you do not elect to build the application now, Visual LISP saves the information in a Make (.mkp) file that you can use to build the application later.
To run that Make file, choose File>Load File from the Visual LISP menu, and
specify the Make file name (for this example, GardenPath.mkp).
238
If you are following along using the sample tutorial application, select Make
the application now, then click Finish. Visual LISP builds a Make file and executes the instructions in that file. Output messages from this process appear
in two VLISP windows. These messages are explained in the following section.
Visual LISP displays messages from the Make process in both the Console
window and the <Build Output> window. Here are the Console messages
from the tutorial:
The path and file names of all input and output files are identified in the
Console messages.
If Visual LISP compiles or recompiles any of the source files in the application, compiler messages appear in the <Build Output> window for the Make:
Chapter 7
239
Building Applications
Youll see some compiler warning messages if you compile the tutorial code.
You can safely ignore these message.
The last group of messages in the <Build Output> window show compile
messages for the automatically-generated initialization file Visual LISP builds
for the application:
Note that Visual LISP generates the file name by appending the first 4 characters of the output file name (GardenPath.arx) to the prefix VLI$. The extension for the initialization source file is always $$$.
For filename, specify the full path name of the ARX file, in quotes. For example:
(arxload c:/Program Files/AutoCAD R14/VLISP/Sample/Gardenpath.arx)
If the load fails with no indication why, it is possible that the application is
already loaded. You can issue the arx command at the AutoCAD Command
to view a list of loaded ARX applications:
240
2 If the file name is not listed, click the File button to open a dialog and select
your ARX file. If you select the Save List option, AutoCAD saves the file name
and includes it in this list for future references.
3 Click Load to load the ARX file.
Running the Application
Once the application is loaded, run it from the AutoCAD Command prompt
as you would any AutoLISP function. For example:
Command: (gpath)
Remember that if the function name begins with c:, you can issue it as an
AutoCAD command; that is, without enclosing the name in parentheses. The
gpath function that starts the GardenPath application does not begin with a
c:, so you must include the parentheses. Review C:XXX Functions on
page 58 for more information on this topic.
Chapter 7
241
Building Applications
Once the application is loaded, run it from the AutoCAD Command prompt
as you would any AutoLISP function. Remember that if the name of the function you invoke to start the application begins with c:, you can issue it as an
AutoCAD command; that is, without enclosing the name in parentheses.
Rebuilding an Application
To rebuild your application after you have made changes to the code, either
use the Application Wizard or load the applications MKP file.
NOTE Before you rebuild your application, make sure it is not currently
loaded in AutoCAD. If it is loaded, unload it. For example, if your application is
an ARX module, use ARXUNLOAD to unload it. The application building process
will fail if the target application file is currently loaded, as Visual LISP will not overwrite the existing module.
242
Chapter 7
243
Building Applications
8
Maintaining Visual LISP
Applications
In this chapter
Managing Multiple
LISP Files
244
Check which LSP files have changed and automatically re-compile only
the modified files in your application. This procedure is known as Make.
Simplify access to source files by listing all source files associated with a
project, making them accessible with a single mouse click.
Help you find code fragments by searching for strings when you do not
know which source files contain the text youre looking for.
Optimize compiled code by directly linking the corresponding parts of
multiple source files.
Before discussing how to define and use Visual LISP projects, it may help to
introduce file types used in Visual LISP.
Chapter 8
245
Maintaining Applications
Here is a brief summary of the types of files recognized by Visual LISP project
management functions:
File Ext.
Type of File
Function
dsk
Desktop Save
Contains Visual LISP environment and window settings. (Note: do not edit this file
unless you are certain you know what you are
doing.)
fas
lsp
ob
Object Code
Used internally by Visual LISP, these files contain compiled LISP code used in building FAS
files.
pdb
Project Database
Used internally by Visual LISP, these files contain symbol information used by the compiler.
prj
Project Definition
In addition to the files recognized by the project manager, Visual LISP either
creates or can process a number of additional types of files, summarized
below:
File Ext.
Type of File
Function
_xx
Backup files
arx,
vlx
Stand-alone Applications
246
File Ext.
Type of File
Function
c, cpp,
Language Source Files
cch, hpp, hh
dcl
mkp
Make Application
sql
xdf
Externally Defined Functions Defines ADS and ARX functions to Visual LISP.
XDF files provide information that allows
Visual LISP applications to call ADS and ARX
programs.
xdv
Defining a Project
To demonstrate the use of projects in Visual LISP, you can use the sample programs that come with the Visual LISP tutorial. The files are in the \Lesson5
folder of the VLISP Tutorial directory:
Gpmain.lsp
Gpdraw.lsp
Gp-io.lsp
Utils.lsp
To create a Visual LISP project, choose Project>New Project from the Visual
LISP menu:
Chapter 8
247
Maintaining Applications
Visual LISP displays a standard Windows dialog box for you to specify a file
path and name. For this example, use the name Tutorial. Visual LISP assigns
a .prj extension to the project file name.
Project Home
Directory
List of Selected
Files Displays
in this Window
Click to
Change Source
Directory
248
The projects home directory is identified just below the tabs. This is where
the project file (tutorial.prj) resides. In this example, the home directory is
c:\Program Files\AutoCAD R14\VLISP\Sample. Thats not the directory that
contains the tutorial sample files, though. To identify the source directory,
click the
button:
Use the Browse for Folder window to identify the location of the project
source files. If you select the Lesson5 directory, the Project Properties window
should look like the following:
Visual LISP lists only files that have a .lsp extension to their name, but it does
not display the extension in the list. To include all the source files in your
Chapter 8
249
Maintaining Applications
project, click the button labeled (Un)Select all, then click the right arrow
button ( ); Visual LISP moves the file names to the window on the right:
This window is designed so that, by default, you can select multiple file
names by just clicking each name; you do not have to press and hold CTRL
to select more than one file. To clear a selected name, just click it again.
To remove a file from the project, select it in the right window and click the
left-arrow button( ).
Identifying the Path Name of Project Files
The list of included files does not identify the path name of each file (nor
does the Look In field; this just identifies the path of the files listed in the
left window). Since you can include files from multiple directories in your
project, you need to be able to identify the path name of each file. You can
do this by highlighting one or more file names and right-clicking to display
a context menu:
To display the full path name and the size (in bytes) of source files in the
project, choose Log Filename and Size from the context menu. The informa-
250
tion appears in a small, scrollable window near the bottom of the Project
Properties dialog box:
If a file is in the Home directory shown in the Project Properties dialog box,
Visual LISP does not spell out its path name. Use the scroll bar to see information about all the files in the project.
Note that you cannot include two files of the same name in a project, even
though they are in different directory paths.
This results in a prompt telling users how to invoke the application. If Visual
LISP loads gpmain.lsp last, these instructions will display at the AutoCAD
Command prompt.
After youve moved any files you need to, click Apply.
Chapter 8
251
Maintaining Applications
By default, VLISP lists the project members in the order in which they will be
loaded (as defined in the Project Properties window). You can change this
order by choosing Arrange Files from the context menu for this window (see
below).
The project name appears in the window title bar. Below the title bar are 5
icons. Each icon is a button that performs a function. The button and their
functions are:
Project Properties
Displays the Project Properties window for the project. This allows
you to view the full path name of the files in the project, add,
remove, and reorder project files, and view and change project
compiler options.
Loads all the projects source files, making them available to be run.
Compiles all project source files that have been modified since their
last compile.
Rebuild Project FAS Recompiles all project source files, whether or not they have
changed since their last compile.
252
If you right-click within the file list of the Project window, Visual LISP displays the following context menu:
Many of the functions available from the project context menu can also be
accomplished in other ways. For example, youve already seen how to add
files to projects and remove files from projects. Choosing Remove File from
the context menu is a quick way of removing a file from a project, while
choosing Add File merely brings you to the Project Properties window.
The following summarizes the commands on the context menu:
Chapter 8
253
Edit
Add File
Open the Project Properties dialog, in order to add files to the project.
Remove file
Load
Load the FAS file for the selected project members. If no FAS file exists
for a member, load the LSP file.
Load source
Load the source LSP file for the selected project members.
Check syntax
Check AutoLISP syntax of the source code for the selected members.
Touch
Indicate that the selected source files have been updated, but make no
change to the files. This causes Visual LISP to recompile these programs
the next time you ask to compile all changed project files.
Arrange files
Sort the project member list, according to one of the available suboptions (load order, name, type, or date).
Multiple
Selection
Maintaining Applications
[Un]Select all
Selects all members of the project list, if none are currently selected. If
any members are currently selected, this command un-selects them.
Close project
If you click on the name GPIO, then click on the name GPDRAW, both are
selected.
This is unlike the usual Windows behavior, where selecting the second list
item cancels the first items selection, unless you press CTRL while selecting
it.
You can also use the Project windows context menu to select all members of
the project or cancel selection of all members. If no members are currently
selected, right-click and choose [Un]Select all to select all the members. If any
or all members are already selected, [Un]Select all cancels all selections.
254
detects that some of the source files do not exist in compiled format, it displays a message and asks you if you want to compile those files:
If you click Yes, Visual LISP attempts to compile all LSP files that do not have
a corresponding FAS file. If you click No, VLISP loads all FAS files it finds for
the project, and loads the LSP file for the remaining project. Press Cancel to
abort the load operation.
To load all project source files, instead of their compiled versions, click the
Load Source Files button. Remember that debugging breakpoints may be
saved within source code files, but are removed from the compiled version of
the code. You might want to the load source files in order to debug changes
youve made to your programs.
Using the Project window context menu, you can choose to load just selected
files. Select the files you want to load, then right-click and choose Load to
load FAS files, or Load Source to load the source code. Note that if you choose
Load and a FAS file does not exist for a selected file, Visual LISP loads the
source LSP for that file.
Chapter 8
255
Maintaining Applications
NOTE If the Multiple Selector option is not turned on, you can simply doubleclick a member name to edit it.
Opening a Project
To open an existing project, choose Project>Open Project from the Visual
LISP menu:
If the project file you want to open is in the current directory, you can simply
enter the project name here. If it is not, or if you dont know what the current
directory is, click the Browse button to get a standard Open dialog box.
Note that you can have more than one project open at a time. You can view
a list of all open projects by choosing the Project menu and looking at the
bottom of the menu displayed:
256
At any time, one of the projects is the active one. You can determine which
project is active by the check mark in front of the project name. The commands in the Project menu, such as Load and Build, apply to the active
project. These commands work the same as they do when selected from a
Project window, as described earlier in this chapter.
A Project selection field now appears at the bottom of the Find dialog box. If
the name of the project you want to search is not already displayed in this
field, choose it from the pull-down list. Click the Find button to perform the
search. Visual LISP displays the results in the <Find Output> window:
Chapter 8
257
Maintaining Applications
The output shows that 4 files were searched (there are 4 source files in the
project), and that 4 occurrences of gp:getPointInput were found. The
occurences were found in 2 files; the (defun) for the function is in gp-io.lsp.
You can open an editor window for the file by double-clicking anywhere
within the highlighted text in the <Find Output> window. You can also press
SHIFT+F11 to display the first source location at which the text string was
found, and then repeatedly press F11 to view subsequent occurrences in the
source files.
258
To remove the existing LISP source files from the application definition and
replace them with the tutorial project file:
1 Click the [Un]Select All button.
2 Click Remove.
3 Click in the pull-down list that currently contains LISP Source Files, and
choose Visual LISP Projects.
4 Click Add...
5 Select Tutorial.prj from the Open project dialog box.
From this point forward, you can keep the existing application options. Refer
to Using the Application Wizard in chapter 7 to review all the steps
involved in making an application.
Chapter 8
259
Maintaining Applications
The Build Options dialog box contains a number of options. Some of these
options require extensive background information, which is provided in the
following sections:
Compilation mode. Choose between standard and optimized compilation. Optimized compilation creates smaller and faster programs, but not
every project is suited for optimized compilation.
Merge files mode. Tell the compiler whether to create a separate FAS file
for each source file, or to merge all compiled files into a single FAS file.
Edit Global Declarations. Create or edit a global declarations file for
the project.
Note that this feature is provided for compatability with the Preview version of Visual LISP. The functionality provided by the Global Declarations
file will be provided by other features in futures releases of Visual LISP.
260
FAS directory. Specify the directory for compiled files. If you indicate a
relative path, Visual LISP applies it relative to the projects home directory.
If you leave the field blank, VLISP places compiled files in the same directory as the project definition file.
Tmp directory. Specify the directory for project-related temporary files.
A relative path is applied relative to the projects home directory.
Link mode. Specify how function calls are to be optimized.
Localize variables. Choose whether or not to have the compiler remove
the names of all local symbols from compiled files, where possible.
Safe optimize. Directs the compiler to refuse some types of optimization
if there is a chance it will result in incorrect code.
Message Mode. Select the level of detail you want Visual LISP to produce
in its compilation reports. You can choose to receive a report showing
only fatal errors (those causing compilation failure), a report showing
errors and warning messages, or a full report showing errors, warnings,
and compiler statistics.
Merge files mode specifies whether the compiler will create a separate FAS file
for each source file or whether all compiled files will be merged to create a
single FAS-file. A single FAS file is faster to load and is required for certain
types of optimization. Sometimes, however, you will prefer to load your code
one file at a time. This is important if you have not completed the debugging
or modification of the applications code. FAS files do not allow source code
debugging, so we recommend that you compile your code only after the initial debugging is done.
The Link mode area determines how function calls will be optimized. It is
only available if optimized compilation is on. Linking functions means that
the compiler directly addresses the function definition and all calls where the
function is referenced. The Internal mode additionally removes the function
name from the resulting FAS file(s).
If Localize variables is set, the compiler removes the names of all local symbols from the resulting file(s), if possible.
Safe optimize lets the compiler refuse some types of optimization if there is
a chance to create incorrect code. For more information on optimization see
the corresponding section below.
After closing the dialog the Project Desktop window automatically appears.
Chapter 8
261
Maintaining Applications
When producing standard, non-optimized binary code, the Visual LISP compiler preserves the symbol names associated with functions and global variables, since these symbols may be referenced from other files. When the symbol is referenced, Visual LISP looks in a table to determine what area in memory is assigned to the symbol.
When optimizing code, the Visual LISP compiler assumes that all files in a
project work together to form a complete application. This allows it to discard the symbol names and, when executing the code, jump directly to the
memory region of the code.
262
Outer applications and the AutoLISP console lose access to program functions and symbols.
Functions available from the Console in interpreter mode are unknown in
compiled mode.
Functions are available from the Console, but redefining them does not
change the programs behavior.
Link Mode
If you direct the Visual LISP compiler to link functions in your project, it tries
to directly link all explicit function calls to the function definition, which
may reside in a different source file. In contrast, when you do not link your
functions, the compiler creates references to symbols that Visual LISP uses to
look up the actual memory location of the function. Linking improves the
performance of the compiled code and protects the code against function
redefinition. However, if your application is designed so that it is necessary
to redefine a function in order for it to work properly, you cannot statically
link that function.
The Build Options dialog lists 3 options for link mode:
Dropping Functions
Once function calls are statically linked, the compiler can optimize one level
further by dropping the function name completely. By dropping the function name, the function becomes invisible to users. This feature is selected by
choosing the Internal Link mode option.
Symbols exported to ACAD (for example, function names starting with C:)
will never be dropped.
Chapter 8
263
Maintaining Applications
Localizing Variables
Similar to function symbols, local variables are also subject to optimization.
If the Localize variables option is set, the compiler drops the names of all
local variables and directly links their references. This means that the program code points to the address where a variable is stored, instead of to a
symbol used to find the address of the variable.
Safe Optimization
Choosing the Safe optimize option reduces the amount of compiler optimization but protects your code from compiler-induced errors. Conditions handled by Safe optimizing relate to uncertain effects that can take place at program run-time. They may lead to a failure of the optimized program even
though the source code seems to be correct. For example:
Now there are two possible conditions: if the value assigned through setq is
intended to alter the definition of the function fishlips, static linking will
prevent this from happening. The first definition will be linked and cannot
be changed by the setq function. On the other hand, if the identical names
are handled independently, fishlips can be linked without creating incorrect code.
If Safe optimizing is on, the compiler will always stay on the safe side, even
if the user explicitly requests linking fishlips. This may result in less efficient code, but it ensures code correctness. If Safe optimizing is off, you can
override the compilers not-link recommendation for fishlips: you are
responsible for the link.
The Safe optimize mode is on by default. Be sure that you fully understand
the consequences before you turn it off.
LINK Conditions Ignored if Safe Optimizing is On
If the compiler encounters the following situations while Safe optimize is on,
it ignores any related LINK directive:
264
If Safe optimization is off, but message mode is set to Full report, the same
warnings are prefixed by:
; *** WARNING: Dangerous
Chapter 8
265
Maintaining Applications
DROP Requirements
The compiler tries to drop a function name only if all corresponding function calls could be linked and are actually linked to the function definition.
The compiler does not drop the function name for a function definition if
the program calls a function by its symbol name.
A function is called by name in the following cases:
Note that for functions called from top-level expressions, the DROP declaration will be ignored without any warning messages.
LOCALIZE Requirements
The compiler does not localize a variable in bound lists of defun,lambda,
and foreach expressions if:
Besides these conditions, which always cancel the optimization and result in
warning messages, there are other conditions which may or may not result
in incorrect code. Choosing the Safe optimize option for the project disallows these conditions as well. Disabling of Safe optimization results in com-
266
Chapter 8
267
Maintaining Applications
9
Advanced Topics
In this chapter
Visual LISP not only makes program development easier
Using ActiveX
Objects in AutoLISP
Attaching Reactors to
AutoCAD Drawings
268
Even the drawing and the AutoCAD application itself are considered objects.
In Visual LISP, ActiveX Automation includes much of the functionality provided by LISP functions such as entget, entmod, and setvar. Compared to
these standard AutoLISP functions, ActiveX runs faster, provides easier access
to object properties, and is more readable. For example, to access the radius
of a circle with traditional AutoLISP function, you must use entget to obtain
a list of entities, and assoc to find the property you are looking for. Furthermore, you must know the code number (DXF key value) associated with that
property in order to obtain it with assoc:
(setq radius (cdr (assoc 40 (entget circle-entity))))
With an ActiveX function, you simply ask for the radius of a circle:
(setq radius (vla-get-radius circle-object))
Chapter 9
269
Advanced Topics
Object Properties
All objects in the AutoCAD object model have one or more properties. For
example, a circle object can be described by its radius, area, or linetype; each
of these are properties. An ellipse object also has area and linetype properties,
but it cannot be described in terms of its radius. Rather, you describe it in
terms of its major to minor axis ratio, a property named RadiusRatio in the
270
AutoCAD object model. Youll use property names when accessing AutoCAD
data through ActiveX functions.
Object Methods
ActiveX objects also contain methods, which are simply the actions available
for a particular kind of object. Some methods are applicable to most
AutoCAD drawing objects. For example, the Mirror method (creating a mirror image copy of an object around a mirror axis), and the Move method
(moving a drawing object along a specified vector) are among the methods
that apply to most drawing objects. By contrast the Offset method, which
creates a new object at a specified distance from an existing object, applies
only to a few classes of AutoCAD objects, such as Arc, Circle, Ellipse, and
Line.
In Visual LISP, ActiveX methods are implemented as AutoLISP functions.
Youll see many references to "ActiveX functions" in Visual LISP documentation, but keep in mind that in native ActiveX terminology, these are always
known as methods.
To determine which methods and properties apply to a specific type of
AutoCAD object, refer to the AutoCAD ActiveX Automation Reference. The
Reference is available from the AutoCAD Help menu, or by opening the
acadauto.hlp file in the AutoCAD Help directory.
TIP You will probably want to have the ActiveX Automation Reference open
at all times when you are developing Visual LISP programs that use ActiveX. If you
open the acadauto.hlp file from the AutoCAD Help directory, you can keep the
ActiveX Automation Reference open when you use Visual LISP online help. If you
open the Automation Reference by selecting it from the AutoCAD Help menu, it
closes when you choose an item from the Visual LISP Help menu.
Collections of Objects
All objects in the AutoCAD object model are grouped in collections. For example, the Blocks collection is made up of all blocks in an AutoCAD drawing,
and the ModelSpace collection is comprised of all graphical objects (circles,
lines, polylines, etc.) in the drawings model space. Collections are labeled in
the object model diagram.
Chapter 9
271
Advanced Topics
lowing example:
(setq acadObject (vlax-get-acad-object))
You can readily identify many of the properties listed in the VLA Object
Inspector window. For example, FullName is the file name of the AutoCAD
executable file, Version is the current AutoCAD version, and Caption is
the contents of the AutoCAD window title bar. An [RO] following a property
name indicates that the property is read-only; you cannot change it.
Any property identified as a #<VLA OBJECT...> refers to another AutoCAD
ActiveX object. The Application object has two such properties,
ActiveDocument and Preferences. If you look at the diagram of the
AutoCAD object model, youll see that these two objects are just below the
Application object in the model hierarchy. To view the properties associated
272
with an object, double-click the object line in the Inspector window (or rightclick and choose Inspect). Here is the Inspector window for the Preferences
object:
You may have noticed that the properties of the Preferences object correspond to the settings in the AutoCAD Preferences dialog box. This makes it
easy for you to programmatically access Preferences information. For example, you can identify the AutoCAD configuration file with the following
function call:
$ (vla-get-ConfigFile acadPreferences)
"C:\\Program Files\\AutoCAD R14\\acad14.cfg"
Youll learn more about using ActiveX functions in Using Visual LISP Functions with ActiveX Methods on page 275.
Chapter 9
273
Advanced Topics
model space (through the ModelSpace property) or paper space (through the
PaperSpace property). For example:
(setq mSpace (vla-get-ModelSpace acadDocument))
At this point, you have access to the AutoCAD drawing and can add objects
to the drawing. For example, you can add a circle to the model space with the
following command:
(setq mycircle
acadObject
acadDocument
mSpace
mycircle
(vlax-get-acad-object))
(vla-get-ActiveDocument acadObject))
(vla-get-ModelSpace acadDocument))
(vla-addCircle mSpace (3.0 3.0 0.0) 2.0))
274
Chapter 9
275
Advanced Topics
Sometimes, as in this Circle entry, there is descriptive text that identifies the
method you need. Often, though, youll need to look through the list of
Methods to find the one that matches the action you want to take.
Once youve found the name of the method, add a vla- prefix to the method
name in order to get the name of the Visual LISP function that implements
the method. In this example, it is vla-AddCircle. Note that in Visual LISP
the function name is not case sensitive; vla-addcircle is the same as
vla-AddCircle.
276
Note that you can also get to this page by clicking on the Methods button
near the top of the Help window, and choosing AddCircle from a list of methods.
The syntax definitions in the Automation Reference apply to the Visual Basic
language. For AddCircle, the syntax is defined as:
RetVal = object.AddCircle(Center, Radius)
The return value (RetVal, in Visual Basic) is straight-forward. The Automation Reference defines this as a Circle object. In Visual LISP, whenever an
AutoCAD object is returned by an ActiveX function, it is stored as a
VLA object data type.
The object referred to before the method name (object.AddCircle) is always
the first argument in a vla function call. This is the object you are viewing
or modifying. For example, you add a circle to the drawing model space:
(vla-addCircle
mSpace ...)
In this example, mspace refers to the ModelSpace object. Recall from the discussion on the AutoCAD object model (in Accessing AutoCAD Objects on
page 271), that you use the properties of one AutoCAD object to access
Chapter 9
277
Advanced Topics
The ActiveX Automation Reference explains what these parameters are used
for, but the data types it indicates for these parameters are Visual Basic data
types. You need to convert these to Visual LISP data types. The following
table shows how:
Boolean
Integer
INT
Integer
INT
Real
REAL
Double
REAL
String
STRING
Array
LIST
4 x 4 Array of Doubles
Object
VLA object
In looking up the Visual LISP data type for the Center argument, you need to
convert the data type described in parentheses after the word Variant
(3-element array of doubles). The table shows that an array in Visual Basic is
a list in Visual LISP, and a double in Visual Basic is a real number in Visual
278
LISP. So the Center argument requires a list of real numbers. For example, a
center point of 3.0 on the X and Y axes is:
(3.0 3.0 0.0)
The Radius argument, a Double in Visual Basic, requires a real number in LISP.
Here is a diagram of the translation from Visual Basic to Visual LISP:
When you use ActiveX functions within Visual LISP, you must always provide arguments that are of the data types specified in the ActiveX method
definitions. Failure to do so (for example, passing an integer value when a
real is required) may cause your program to crash. To convert points and
matrices to the appropriate form, use the vlax-3D-point and vlax-tmatrix
functions described in Converting Arguments on page 287.
Then pick a point in the AutoCAD drawing window. This will be the center
point of the circle. You can use a Visual LISP function to identify the center
point.
Reading Object Properties
Functions that read object properties are named with a vla-get prefix and
require the following syntax:
(vla-get-property object)
For example, vla-get-center returns the center point of a circle. You can use
this function to draw a second circle concentric to the first:
(vla-addCircle mSpace (vla-get-center myCircle) 1.0)
#<VLA-OBJECT IAcadCircle 03ad0a1c>
Chapter 9
279
Advanced Topics
For example, vla-put-center changes the center point of a circle. The following sequence of function calls subtracts 1 unit from the X-axis of the original circle, then uses vla-put-center to update the circle with the new Xaxis:
_$ (setq myCenter (vla-get-center myCircle))
(6.98607 4.52594 0.0)
_$ (setq Xaxis (- (car myCenter) 1 )) ;
5.98607
_$ (setq newcenter (list Xaxis (cadr myCenter) (caddr myCenter)))
(5.98607 4.52594 0.0)
_$ (vla-put-center myCircle newcenter)
nil
Note that changing an objects property may not immediately affect the display of the object in the AutoCAD drawing. AutoCAD delays property
changes to allow you to change more than one property at a time. To explicitly update the drawing window, issue the vla-update function:
(vla-update object)
280
These test functions return T if true, nil if false. The following examples test
a line object:
$ (vlax-read-enabled-p WhatsMyLine)
T
$ (vlax-write-enabled-p WhatsMyLine)
T
$ (vlax-erased-p WhatsMyLine)
nil
Chapter 9
281
Advanced Topics
Note that the MinPoint and MaxPoint parameters are described as output
items of data type 3-element array of doubles. In Visual LISP, this is a list
data type. You need to provide these arguments as quoted variable names.
The following example shows a Visual LISP function call to return the minimum and maximum bounding points of a circle, and the results of that call:
_$ (vla-getboundingbox myCircle minpoint maxpoint)
((1.0 1.0 -1.0e-008) (5.0 5.0 1.0e-008))
_$ minpoint
(1.0 1.0 -1.0e-008)
_$ maxpoint
(5.0 5.0 1.0e-008)
_$
(Note that the quoted symbol parameters that you pass to the function
become AutoLISP variables just like ones created through setq. Because of
this, you should include them as local variables in your function definition
so that they do not become global variables by default.)
282
Note that vlax-dump-object displays the information in the Console window or an AutoCAD text window, however the function returns either T or
nil, not a list of strings containing the displayed information.
Chapter 9
283
Advanced Topics
For example:
_$ (vlax-method-applicable-p WhatsMyLine "copy")
T
_$ (vlax-method-applicable-p WhatsMyLine "AddBox")
nil
For example:
_$ (vlax-property-available-p WhatsMyLine "Color")
T
_$ (vlax-property-available-p WhatsMyLine "center")
nil
284
For example, to list all properties of every object in a drawings model space:
$ (vlax-map-collection (vla-get-ModelSpace acadDocument)
vlax-dumpObject)
; IAcadLWPolyline: AutoCAD Lightweight Polyline Interface
; Property values:
;
Application (RO) = #<VLA-OBJECT IAcadApplication 00b3b91c>
;
Area (RO) = 3.67152
;
Closed = -1
;
Color = 256
;
Coordinates = (9.59247 4.44872 9.25814 5.34715 4.1991 5.679 ...)
;
EntityName (RO) = "AcDbPolyline"
;
EntityType (RO) = 24
;
Handle (RO) = "4C"
;
Layer = "0"
;
Linetype = "BYLAYER"
;
LinetypeScale = 1.0
;
Normal = (0.0 0.0 1.0)
;
ObjectID (RO) = 42009888
;
Thickness = 0.0
;
Visible = -1
; IAcadCircle: AutoCAD Circle Interface
; Property values:
;
Application (RO) = #<VLA-OBJECT IAcadApplication 00b3b91c>
;
Area (RO) = 0.661383
;
Center = (8.53948 4.91026 0.0)
;
Color = 256
;
EntityName (RO) = "AcDbCircle"
;
EntityType (RO) = 8
;
Handle (RO) = "4D"
;
Layer = "0"
;
Linetype = "BYLAYER"
;
LinetypeScale = 1.0
;
Normal = (0.0 0.0 1.0)
;
ObjectID (RO) = 42009896
;
Radius = 0.45883
;
Thickness = 0.0
;
Visible = -1
Like the foreach function, vlax-for returns the result of the last expression
evaluated inside the for loop. Note that modifying the collection (that is,
adding or removing members) while iterating through it may cause an error.
Chapter 9
285
Advanced Topics
Heres an example using vlax-for to show color statistics for each object in
the active drawing:
(defun show-Color-Statistics (/ objectColor colorSublist colorList)
(setq modelSpace (vla-get-ModelSpace
(vla-get-ActiveDocument (vlax-get-Acad-Object))
)
)
(vlax-for obj modelSpace
(setq objectColor (vla-get-Color obj))
(if (setq colorSublist (assoc objectColor colorList))
(setq colorList (subst (cons objectColor (1+ (cdr colorSub list)))
colorSublist
colorList
)
)
(setq colorList (cons (cons objectColor 1) colorList))
)
)
(if colorList
(progn (setq
colorList (vl-sort colorList
(lambda (lst1 lst2) (< (car lst1) (car lst2)))
)
)
(princ "\nColorList = ")
(princ colorList)
(foreach subList colorList
(princ "\nColor ")
(princ (car subList))
(princ " is found in ")
(princ (setq count (cdr subList)))
(princ " object")
(princ (if (= count 1)
"."
"s."
)
)
)
)
)
(princ)
)
286
Note that Item and Count also apply to groups and selection sets.
Converting Arguments
When creating AutoCAD entities using the command and entmake functions,
AutoLISP allows a great deal of flexibility regarding the composition of coordinate data lists (that is, 2D or 3D points). When working with ActiveX functions, however, you must be very precise when passing these parameters. A
3D point must consist of three reals. To ensure that points are formatted correctly, you can use the vlax-3D-point function. The function syntax allows
you to specify either a list representing a 2D or 3D point, or coordinate values:
(vlax-3D-point <list>)
(vlax-3D-point x y [z])
For example:
_$ (setq aPoint(vlax-3D-point (list 1 2)))
(1.0 2.0 0.0)
$ (setq aPoint(vlax-3D-point 1 2))
(1.0 2.0 0.0)
The vlax-TMatrix function performs a similar task for transformation matrices, which are required by the vla-TransformBy function. It builds the transformation matrix from four lists of four numbers each, converting all numbers to reals, if necessary. For example:
_$ (vlax-tmatrix (list(list 1 1 1 0)(list 1 2 3 0)(list 2 3 4 5)(list
2 9 8 3)))
((1.0 1.0 1.0 0.0) (1.0 2.0 3.0 0.0) (2.0 3.0 4.0 5.0) (2.0 9.0 8.0
Chapter 9
287
Advanced Topics
3.0))
This function returns T if the object has been released, nil if it has not.
You can compare two VLA objects with the equal function. It returns T if
both objects point to the same drawing object.
To convert VLA objects to enames, use the vlax-vla-object->ename function. For example:
$ (setq new-ename-circle (vlax-vla-object->ename vlaobject-circle))
<Entity name: 27f0538>
288
You may find the same drawing object represented by different data types: a
handle string, an ename, a VLA object, or an ARX Object ID integer. To convert between these types:
To find the handle associated with an ename, use the DXF 5 group of the
enames association list:
_$ (setq handle-circle (cdr (assoc 5 (entget ename-circle))))
"4F
To find the ename associated with a handle, use the handent function:
_$ (handent handle-circle)
<Entity name: 27f0538>
Finally, to translate from an ARX Object ID back to its VLA object, use the
ObjectIDtoObject method on the AutoCAD Document object:
_$ (vla-ObjectIDtoObject acadDocument objid-circle)
#<VLA-OBJECT IAcadCircle 03642c24>
Chapter 9
289
Advanced Topics
The function vlr-types returns a list of Visual LISP reactor types. Currently,
the reactor types it returns are:
For each reactor type there are a number of callback events that notify your
application under specific circumstances. For instance, when a drawing is
saved, a :vlr-beginSave event occurs, the drawing is saved, and finally a
290
For example:
$ (vlr-reaction-names :VLR-Editor-Reactor)
(:vlr-unknownCommand :vlr-commandWillStart :vlr-commandEnded....
You can print out a list of all available reactor events, sorted by reactor type,
by loading and running the following code in Visual LISP:
(progn (foreach rtype (vlr-types)
(terpri)
(princ rtype)
(foreach rname(vlr-reaction-names rtype)
(terpri)
(princ "\t")
(princ
rname
)
)
)
(princ)
)
The AutoLISP Function Reference lists the name and a brief description of
each event available for a reactor type. For each reactor type, you can find
this information by looking up the description of the function you use to
define a reactor of that type. These functions are listed in Creating Reactors
on page 292.
Chapter 9
291
Advanced Topics
Creating Reactors
To add reactor functionality to your application, you first need to write a callback function that performs the tasks needed at the time of the reactor event.
For example, here is a function named saveDrawingInfo that displays file
292
path and size information. This function will be attached to an editor reactor
that will fire when an AutoCAD drawing is saved:
(defun saveDrawingInfo (calling-reactor commandInfo / dwgname filesize)
(setq dwgname (cadr commandInfo)
filesize (vl-file-size dwgname)
)
(alert (strcat "The file size of " dwgname " is "
(itoa filesize) " bytes."
)
)
(princ)
)
The function retrieves the drawing name from the commandInfo parameter,
then uses the vl-file-size function to retrieve the size of the drawing. The
information is then displayed in an alert box in the AutoCAD window.
NOTE After you activate a reactor and its callback function is executed, you
may need to enter vlide at the AutoCAD Command prompt in order to return
to Visual LISP. Simply switching focus to the Visual LISP window will not work.
You link the callback function to an event when you create a reactor. There
is a Visual LISP function to create each type of reactor. These functions are
listed in the following table:
Function
Reactor
Type
Arguments
vlr-acdb-reactor
Database
vlr-editor-reactor Editor
vlr-linker-reactor Linker
vlr-object-reactor Object
The table above indicates that the callbacks argument to these functions is a
list of pairs naming the event and the callback function to be associated with
Chapter 9
293
Advanced Topics
that event. Possible events for each function are listed under the functions
entry in the AutoLISP Function Reference. All of these reactor construction
functions return the reactor object.
Editor reactors monitor AutoCAD commands such as the Save command.
The following defines an editor reactor that responds to a user issuing a save
by invoking the saveDrawingInfo function:
(vlr-editor-reactor nil ((:vlr-saveComplete . saveDrawingInfo)))
294
The code creates a variable called myCircle, which contains a pointer to the
circle object that is drawn. Notice that an ActiveX method is used to draw the
circle. This was not an arbitrary choice: you must use ActiveX methods to create or modify drawing objects from a callback function. ActiveX methods
work with ActiveX (VLA) objects.
To modify ename objects, such as those obtained through entlast and
entsel functions, you must first convert them into VLA objects using the
vlax-ename>vla-object function.
The function that creates object reactors requires three arguments. The first
argument is a list identifying the objects that are to fire notifications to the
reactor. These objects are referred to as the owners of the reactor. The owners
list must consist of VLA objects only; no enames are allowed. The second and
third arguments are those accepted by all reactor types: application-specific
data to attach to the reactor (if any), and a dotted pair list identifying the
events to which to react and the callback function to be invoked by each
event.
Attaching a Reactor to Objects
The following code attaches an object reactor to the myCircle object. It
defines the reactor to respond whenever the object is modified
(:vlr-modified) and to call the print-radius function in such an event:
(setq circleReactor (vlr-object-reactor (list myCircle)
Circle Reactor '((:vlr-modified . print-radius))))
Chapter 9
295
Advanced Topics
The reactor object is stored in variable circleReactor; you can refer to the reactor using this variable, as youll see below in Querying, Modifying and
Removing Reactors.
You may have noticed that the previous example included a string, Circle
Reactor, in the call to vlr-object-reactor. You do not have to specify any
data to be included with the reactor; you can specify nil instead. However,
an object may have several reactors attached to it. Including an identifying
text string, or other data that your application can use, allows you to distinguish among the different reactors attached to an object.
If you load and run each of the code samples in this section in Visual LISP,
you can test how the reactor works by altering the size of the circle drawn.
NOTE If you do not disable all reactors before exiting AutoCAD, you may
crash when you exit. See Disabling Reactors on page 299 for information on
how to disable reactors.
For reactor-type, specify one of the values returned by the vlr-types function;
these are listed in Reactor Types and Events on page 290. For example:
_$ (setq reactorList (vlr-reactors :VLR-Object-Reactor))
(#<VLR-Object-reactor>)
In this case, the return value of the function, stored in variable reactorList, is
a list containing a single object reactor pointer. This represents the reactor
created using the functions in the previous section.
Inspecting Reactors
You can examine reactors using the Visual LISP Inspector tool. For example,
the object reactor defined in Using Object Reactors on page 294 was
returned to a variable named circleReactor. If you open an Inspector window for this variable, Visual LISP displays the following information:
296
The object line indicates that the reactor is enabled (registered) in AutoCAD.
The list items in the Inspector window show the following:
Double-click on the item that begins with {Owners} to view a list of the
owner objects:
Chapter 9
297
Advanced Topics
vlr-data returns the application-specific data value attached to the reactor. You can use this to distinguish among multiple reactors that can fire
the same callback function.
$ (vlr-data circleReactor)
"Circle Reactor"
Modifying Reactors
Visual LISP provides functions to modify reactor definitions:
You can verify that the reactor has changed by using the Visual LISP
Inspector feature. If the Inspector window shown in Inspecting Reactors
on page 296 is still displayed in your Visual LISP session, right-click in the
windows object line and choose Update. If youve modified the
circleReactor reactor as shown in this section, the updated Inspector
window will look like the following:
298
vlr-owner-add adds a database object to the list of owners of the specified reactor. In the following example, an arc object named archie is
added to the owner list of reactor circleReactor:
$ (vlr-owner-add circleReactor archie)
#<VLA-OBJECT IAcadArc 03ad0bcc>
Now, if a user modifies the archie object, the callback function defined
for reactor circleReactor is invoked. You can verify this by inspecting the
reactor. Update the Inspector window for the circleReactor reactor, then
right-click on the list item that begins with {Owners} and choose
Inspect:
Both Arc and Circle objects are listed in the Inspector window.
Disabling Reactors
If you want to disable a reactor, you need to remove it from AutoCAD. Note
that the reactor object still exists. You can activate it again using the vlr-add
function. To determine whether or not a reactor is active (registered to
AutoCAD), use the vlr-added-p function:
_$ (vlr-added-p circleReactor)
T
You can use vlr-added-p to verify that the circleReactor object reactor
has been disabled:
$ (vlr-added-p circleReactor)
nil
Chapter 9
299
Advanced Topics
NOTE If you do not disable all reactors before exiting AutoCAD, you may
crash upon exit.
Each function takes a reactor objects as its only argument. For example:
_$ (vlr-pers-p circleReactor)
nil
300
Chapter 9
301
Advanced Topics
A
AutoLISP
Function Reference
In this appendix
The following is a catalog of all standard AutoLISP functions defined
302
The number argument needs additional information: a number can be a real number, an
integer, or a symbol set to a real or integer value. If all arguments are integers, the result
is an integer. If any of the arguments are real numbers, the integers are promoted to real
numbers and the result is a real number.
Most AutoLISP functions are always available; however, some are defined by a
AutoLISP or ARX applications. The file that contains the externally defined functions is
identified after the heading Externally defined function. Before you attempt to use these
functions, you may want to test for their availability.
The value returned by some functions is specified as indeterminate. This indicates that
you cannot rely on using the value returned from this function.
+ (addition)
Returns the sum of all numbers
returns 3
returns 10.5
returns 10.0
(subtraction)
Subtracts the second and following numbers from the first and returns the
difference
303
only one number argument, this function returns the result of subtracting it from zero; it
returns the number. Supplying no arguments returns 0.
(- 50 40)
(- 50 40.0)
(- 50 40.0 2.5)
(- 8)
returns 10
returns 10.0
returns 7.5
returns -8
* (multiplication)
Returns the product of all numbers
returns 6
returns 6.0
returns 24.0
returns -13.5
returns 3
/ (division)
Divides the first number by the product of the remaining numbers and returns
the quotient
returns 50
returns 50.0
returns 2.5
returns 2
returns 4
* (multiplication)
304
= (equal to)
Returns T if all arguments are numerically equal, and returns nil otherwise
returns T
returns nil
returns T
returns nil
returns T
returns nil
returns T
returns nil
returns T
returns T
305
returns T
returns T
returns nil
returns T
returns nil
returns T
returns T
returns nil
returns T
returns nil
306
returns T
returns T
returns nil
returns T
returns nil
returns T
returns T
returns nil
returns T
returns nil
~ (bitwise NOT)
Returns the bitwise NOT (1s complement) of the argument
(~ int)
(~ 3)
(~ 100)
(~ -4)
returns -4
returns -101
returns 3
307
1+ (increment)
Returns the argument increased by 1 (incremented)
(1+ number)
(1+ 5)
(1+ -17.5)
returns 6
returns -16.5
1 (decrement)
Returns the argument reduced by 1 (decremented)
(1 number)
(1- 5)
(1- -17.5)
returns 4
returns -18.5
abs
Returns the absolute value of the argument
(abs number)
(abs 100)
(abs -100)
(abs -99.25)
returns 100
returns 100
returns 99.25
acad_colordlg
Displays the standard AutoCAD color selection dialog box
1+ (increment)
308
to BYBLOCK, and a value of 256 defaults to BYLAYER. Setting the optional flag argument
to nil disables the BYLAYER and BYBLOCK buttons. Omitting the flag argument or
setting it to a non-nil value enables the BYLAYER and BYBLOCK buttons.
The acad_colordlg function returns the user-selected color number. If the user cancels
the dialog box, acad_colordlg returns nil.
The following code prompts the user to select a color and specifies a default of green:
(acad_colordlg 3)
acad_helpdlg
Invokes the help facility (obsolete)
acad_strlsort
Sorts a list of strings by alphabetical order
309
action_tile
Assigns an action to evaluate when the user selects the specified tile in a dialog
box
add_list
Adds or modifies a string in the currently active dialog box list
(add_list string)
Before using add_list, you must open the list and initialize it with a call to
start_list. Depending on the operation specified in start_list, the string either
is added to the current list or replaces the current list item.
Assuming that the currently active DCL file has a popup_list or list_box with a key of
longlist, the following code fragment initializes the list and adds to it the text strings
in llist.
(setq llist ("first line" "second line" "third line"))
(start_list "longlist")
(mapcar add_list llist)
(end_list)
action_tile
310
After the list has been defined, the following code fragment changes the text in the second
line to "2nd line".
(start_list "longlist" 1 0)
(add_list "2nd line")
(end_list)
ads
Returns a list of the currently loaded ADS applications
(ads)
Each application and its path is a quoted string in the list.
(ads) might return ("files/progs/PROG1" "PROG2")
alert
Displays an alert box with the error or warning message passed as a string
(alert string)
An alert box is a dialog box with a single OK button.
(alert "That function is not available.")
You can display multiple lines by using the newline character in string.
(alert "That function\nis not available.")
Line length and the number of lines in an alert box are platform, device, and window
dependent. AutoCAD truncates any string that is too long to fit inside an alert box.
311
alloc
Sets the segment size to a given number of nodes
(alloc int)
This function returns the previous segment size.
and
Returns the logical AND of a list of expressions
then
(and 1.4 a c)
(and 1.4 a b c)
returns T
returns nil
angle
Returns an angle in radians of a line defined by two endpoints
alloc
312
angtof
Converts a string representing an angle into a real (floating-point) value in
radians
String format
Degrees
Degrees/minutes/seconds
Grads
Radians
Surveyors units
The string must be a string that angtof can parse correctly to the specified mode. It can
be in the same form that angtos returns, or in a form that AutoCAD allows for keyboard
entry.
The angtof and angtos functions are complementary: if you pass angtof a string created by angtos, angtof is guaranteed to return a valid value, and vice versa (assuming
the mode values match).
If angtof succeeds, it returns a real value in radians; otherwise it returns nil.
313
angtos
Converts an angular value in radians into a string
String format
Degrees
Degrees/minutes/seconds
Grads
Radians
Surveyors units
The precision argument is an integer that selects the number of decimal places of precision desired. The mode and precision correspond to the AutoCAD system variables
AUNITS and AUPREC. If you omit these arguments, angtos uses the current settings of
AUNITS and AUPREC, respectively.
The angtos function accepts a negative angle argument, but always reduces it to a positive value between zero and 2 pi radians before performing the specified conversion.
(angtos 0.785398 0 4) returns "45.0000"
(angtos -0.785398 0 4) returns "315.0000"
angtos
314
The UNITMODE variable affects the returned string when surveyors units are selected
(a mode value of 4). If UNITMODE = 0, spaces are included in the string (for example,
"N 45d E"); if UNITMODE = 1, no spaces are included in the string (for example,
"N45dE").
Routines that use the angtos function to display arbitrary angles (those not relative to the
value of ANGBASE) should check and consider the value of ANGBASE.
append
Takes any number of lists and runs them together as one list
apply
Passes a list of arguments to a specified function
315
arx
Returns a list of the currently loaded ARX applications
(arx)
Each application and its path is a quoted string in the list.
(arx) might return ("files/progs/PROG1" "PROG2")
arxload
Loads an ARX application
If you attempt to load an application that is already loaded, arxload issues the following
message and returns the application name.
Application "application" already loaded.
You may want to check the currently loaded ARX applications with the arx function
before using arxload.
arx
316
arxunload
Unloads an ARX application
If the arxunload operation fails, it normally causes an AutoLISP error. However, if the
onfailure argument is supplied, arxunload returns the value of this argument upon
failure instead of issuing an error message. This feature of arxunload is similar to that
in the arxload function.
ascii
Returns the conversion of the first character of a string into its ASCII character
code (an integer)
(ascii string)
(ascii "A")
(ascii "a")
(ascii "BIG")
returns 65
returns 97
returns 66
317
assoc
Searches an association list for an element and returns that association list entry
then
(assoc size al)
(assoc weight al)
Association lists are frequently used for storing data that can be accessed by a key. The
subst function provides a convenient means of replacing the value associated with one
key in an association list.
atan
Returns the arctangent of a number in radians
returns 0.463648
returns 0.785398
returns -0.785398
returns 0.588003
returns 2.55359
returns 1.5708
The angtos function converts the radian value returned from atan into a string value.
assoc
318
atof
Returns the conversion of a string into a real number
(atof string)
(atof "97.1")
(atof "3")
(atof "3.9")
returns 97.1
returns 3.0
returns 3.9
atoi
Returns the conversion of a string into an integer
(atoi string)
(atoi "97")
(atoi "3")
(atoi "3.9")
returns 97
returns 3
returns 3
atom
Verifies that an item is an atom
(atom item)
Returns nil if item is a list; returns T otherwise. Anything thats not a list is considered
an atom.
319
then
(atom a)
(atom a)
(atom b)
(atom b)
(atom (a b c))
returns T
returns nil
returns T
returns T
returns nil
Some versions of LISP differ in their interpretation of atom, so take care when using converted code.
atoms-family
Returns a list of the currently defined symbols
The following code verifies that the symbols CAR, CDR, and XYZ have been defined, and
returns the list as strings:
(atoms-family 1
("CAR" "CDR" "XYZ"))
The preceding return value shows that the symbol XYZ has not been defined.
atoms-family
320
autoarxload
Predefines command names to load an associated ARX file
The commands listed by the cmdlst argument must be defined as commands by the file
specified by filename.
autoload
Predefines command names to load an associated AutoLISP file
321
The following code defines the C:APP1, C:APP2, and C:APP3 functions to load the bounsapp.lsp file. The first time one of the command, APP1, APP2, or APP3 are entered at the
Command prompt the AutoLISP file loads and the command continues.
(autoload "BONUSAPP" ("APP1" "APP2" "APP3"))
The commands listed by the cmdlst argument must be defined as commands by the file
specified by filename.
autoxload
Predefines command names to load an associated ADS application
The commands listed by the cmdlst argument must be defined as commands by the file
specified by filename.
autoxload
322
Boole
Serves as a general bitwise Boolean function
Int2
Func bit
Each bit of int1 is paired with the corresponding bit of int2, specifying one horizontal
row of the truth table. The resulting bit is either 0 or 1, depending on the setting of the
func bit that corresponds to this row of the truth table.
If the appropriate bit is set in func, the resulting bit is 1; otherwise the resulting bit is 0.
Some of the values for func are equivalent to the standard Boolean operations AND, OR,
XOR, and NOT.
Boole function bit values
Func
Operation
Resulting bit is 1 if
AND
XOR
OR
NOR
323
(Boole 1 12 5)
returns 3
You can use other values of func to perform other Boolean operations for which there are
no standard names. For example, if func is 4, the resulting bits are set if the corresponding bits are set in int2 but not in int1. Thus
(Boole 4 3 14)
returns 12
boundp
Verifies if a value is bound to a symbol
(boundp sym)
Returns T if sym has a value bound to it. If no value is bound to sym (or if it has been
bound to nil), boundp returns nil. If sym is an undefined symbol, it is automatically
created and is bound to nil.
For example, given the assignments
(setq a 2 b nil)
then
(boundp a)
(boundp b)
returns T
returns nil
boundp
324
returns A
returns (A B)
returns nil
returns (B C)
returns (C)
returns nil
When the list argument is a dotted pair (see cons), cdr returns the second element
without enclosing it in a list.
(cdr (a . b))
(cdr (1 . "Text"))
returns B
returns "Text"
AutoLISP supports concatenations of car and cdr up to four levels deep. The following
are valid functions:
caaaar
cadaar
cdaaar
cddaar
caaadr
cadadr
cdaadr
cddadr
caaar
cadar
cdaar
cddar
caadar
caddar
cdadar
cdddar
caaddr
cadddr
cdaddr
cddddr
caadr
caddr
cdadr
cdddr
caar
cadr
cdar
cddr
325
These concatenations are the equivalent of nested calls to car and cdr. Each a represents
a call to car, and each d represents a call to cdr. For example:
(caar x)
(cdar x)
(cadar x)
(cadr x)
(cddr x)
(caddr x)
a 2D point
a 3D point
then
(car pt2)
(cadr pt2)
(caddr pt2)
(car pt3)
(cadr pt3)
(caddr pt3)
returns 5.25
returns 1.0
returns nil
returns 5.25
returns 1.0
returns 3.0
chr
Returns the conversion of an integer representing an ASCII character code into
a single-character string
(chr integer)
(chr 65)
(chr 66)
(chr 97)
returns "A"
returns "B"
returns "a"
chr
326
client_data_tile
Associates application-managed data with a dialog box tile
close
Closes an open file
(close file-desc)
The file-desc argument is a file descriptor obtained from the open function. After a
close, the file descriptor is unchanged but is no longer valid. Data added to an open file
is not actually written until the file is closed. The close function returns nil if filedesc is valid, otherwise, it returns an error message.
For example, the following code counts the number of lines in the file somefile.txt and sets
the variable ct equal to that number.
(setq fil "SOMEFILE.TXT")
(setq x (open fil "r") ct 0)
(while (read-line x)
(setq ct (1+ ct))
)
(close x)
command
Executes an AutoCAD command
327
ing ENTER on the keyboard. Invoking command with no argument is equivalent to pressing Esc and cancels most AutoCAD commands. The command function returns nil.
The command function evaluates each argument and sends it to AutoCAD in response to
successive prompts. It submits command names and options as strings, 2D points as lists
of two reals, and 3D points as lists of three reals. AutoCAD recognizes command names
only when it issues a Command prompt.
If you use the command function in an acad.lsp or MNL file, it should be called only from
within a defun statement. Use the S::STARTUP function to define commands that need
to be issued immediately when you begin a drawing session.
The following example sets two variables pt1 and pt2 equal to two point values 1,1 and
1,5. It then uses the command function to issue the LINE command and pass the two point
values.
(setq pt1 (1 1) pt2 (1 5))
(command "line" pt1 pt2 "")
command
328
329
The preceding code fragment sets the current layer to NEW_LAY, pauses for user selection of an insertion point for the block MY_BLOCK (which is inserted with X and Y scale
factors of 1) and pauses again for user selection of a rotation angle. The current layer is
then reset to the original layer.
If the command function specifies a PAUSE to the SELECT command and a PICKFIRST
set is active, the SELECT command obtains the PICKFIRST set without pausing for the
user.
The Radius and Diameter subcommands of the Dim prompt issue additional prompts in
some situations. This can cause a failure of AutoLISP programs written prior to Release
11 that use these commands.
cond
Serves as the primary conditional function for AutoLISP
cond
330
As shown, cond can be used as a case type function. It is common to use T as the last
(default) test expression. Heres another simple example. Given a user response string
in the variable s, this function tests the response and returns 1 if it is Y or y, 0 if it is N or
n, and nil otherwise.
(cond
((= s "Y") 1)
((= s "y") 1)
((= s "N") 0)
((= s "n") 0)
(t nil)
)
cons
Constructs basic lists
returns (A B C D)
returns ((A) B C D)
The cons function also accepts an atom in place of the list argument, constructing a
structure known as a dotted pair. When displaying a dotted pair, AutoLISP prints a period,
or dot, between its first and second elements. You can use the cdr function to return the
second atom of a dotted pair.
(cons a 2)
(car (cons a 2))
(cdr (cons a 2))
returns (A . 2)
returns A
returns 2
A dotted pair is a special kind of list and is not accepted as an argument by some functions
that handle ordinary lists.
331
cos
Returns the cosine of an angle expressed in radians
(cos ang)
(cos 0.0)
(cos pi)
returns 1.0
returns -1.0
cvunit
Converts a value from one unit of measurement to another
If you have several values to convert in the same manner, it is more efficient to convert
the value 1.0 once and then apply the resulting value as a scale factor in your own function
or computation. This works for all predefined units except temperature, where an offset
is involved as well.
cos
332
defun
Defines a function
You cannot define a function with multiple arguments of the same name. But you can
have one argument that defines a local variable with the same name as another local variable or with the same name as one of the arguments:
(defun fubar (a a / b) ...) Not legal
(defun fubar (a b / a a b) ...) Legal, but useless
If the argument/symbol list contains duplicate entries, the first occurrence of each name
is used and the following occurrences are ignored.
One or more expressions following the list of arguments and local symbols are evaluated
when the function is executed.
The defun function returns the name of the function being defined. When the defined
function is invoked, its arguments are evaluated and bound to the argument symbols. You
can use the local symbols within the function without changing their bindings at outer levels. The function returns the result of the last expression evaluated. All previous expressions have only side effects.
333
The following examples define new functions with defun and show the values returned
by the new functions:
(defun add10 (x)
(+ 10 x)
)
(add10 5)
(add10 -7.4)
returns ADD10
returns 15
returns 2.6
and
(defun dots (x y / temp)
(setq temp (strcat x "..."))
(strcat temp y)
)
returns DOTS
(dots "a" "b")
returns "a...b"
(dots "from" "to")
returns "from...to"
Never use the name of a built-in function or symbol as sym. This makes the built-in function inaccessible. To get a list of built-in and previously defined functions, see atomsfamily.
dictadd
Adds a nongraphical object to the specified dictionary
dictadd
334
dictnext
Finds the next item in a dictionary
dictremove
Removes an entry from the specified dictionary
335
By default, removing an entry from a dictionary does not delete it from the database. This
must be done with a call to entdel. Currently the exceptions to this rule are groups and
mlinestyles. The code that implements these features requires that the database and these
dictionaries be up to date, and therefore automatically deletes the entity when it is
removed (with dictremove) from the dictionary.
The dictremove function disallows the removal of an mlinestyle from the mlinestyle
dictionary if it is actively referenced by an mline in the database.
dictrename
Renames a dictionary entry
dictsearch
Searches a dictionary for an item
dictrename
336
distance
Returns the 3D distance between two points
If one or both of the supplied points is a 2D point, then distance ignores the Z coordinates of any 3D points supplied and returns the 2D distance between the points as projected into the current construction plane.
337
distof
Converts a string that represents a real (floating-point) value into a real value
String format
Scientific
Decimal
Fractional
The argument string must be a string that distof can parse correctly to the mode specified by mode. It can be in the same form that rtos returns, or in a form that AutoCAD
allows for keyboard entry. The distof and rtos functions are complementary. If you
pass distof a string created by rtos, distof is guaranteed to return a valid value, and
vice versa (assuming the mode values are the same).
The distof function treats modes 3 and 4 the same. That is, if mode specifies 3 (engineering) or 4 (architectural) units, and string is in either of these formats, distof
returns the correct real value.
If distof succeeds, it returns a real number; otherwise it returns nil.
distof
338
done_dialog
Terminates a dialog box
(done_dialog [status])
You must call done_dialog from within an action expression or callback function (see
action_tile).
If you specify the optional status argument, it must be a positive integer, which
start_dialog will return instead of returning 1 for OK or 0 for Cancel. The meaning
of any status value greater than 1 depends on your application.
The done_dialog function returns a two-dimensional point list that is the (X,Y) location
of the dialog box when the user exited it. You can pass this point to a subsequent
new_dialog call to reopen the dialog box in the user-selected location.
If you provide a callback for the button whose key is "accept" or "cancel" (usually
the OK and Cancel buttons), the callback must call done_dialog explicitly. If it doesnt,
the user can be trapped in the dialog box. If you dont provide an explicit callback for
these buttons and use the standard exit buttons, AutoCAD handles them automatically.
Also, an explicit AutoLISP action for the accept button must specify a status of 1
(or an application-defined value); otherwise, start_dialog returns the default value, 0,
which makes it appear as if the dialog box was canceled.
end_image
Ends creation of the currently active dialog box image
(end_image)
This function is the complement of start_image.
339
end_list
Ends processing of the currently active dialog box list
(end_list)
This function is the complement of start_list.
entdel
Deletes objects (entities) or undeletes previously deleted objects
(entdel ename)
The entity specified by ename is deleted if it is currently in the drawing. The entdel
function undeletes the entity (restores it to the drawing) if it has been deleted previously
in this editing session. Deleted entities are purged from the drawing when the drawing is
exited. The entdel function can delete both graphical and non-graphical entities.
(setq e1 (entnext)) ;Sets e1 to the name of the first
;entity in the drawing
(entdel e1)
;Deletes entity e1
(entdel e1)
;Undeletes (restores) deleted entity e1
The entdel function operates only on main entities. Attributes and polyline vertices cannot be deleted independently of their parent entities. You can use the command function
to operate the ATTEDIT or PEDIT commands to achieve modify subentities.
You cannot delete entities within a block definition. However, you can completely redefine a block definition, minus the entity you want deleted, with entmake.
end_list
340
entget
Retrieves an objects (entitys) definition data
The DXF group codes used by AutoLISP differ slightly from the group codes in a DXF
file.
As with DXF, entity header items (color, linetype, thickness, the attributes-follow flag,
and the entity handle) are exported only if they have nondefault values. Unlike DXF,
optional entity definition fields are exported whether they are equal to their defaults or
not. This simplifies processing. Programs can always assume these fields to be present for
general algorithms that operate on them. Also unlike DXF, associated X, Y, and Z coordinates are grouped together into one point list, as in (10 1.0 2.0 3.0), rather than appearing
as separate 10, 20, and 30 groups.
341
The 1 item at the start of the list contains the entity name of this entity. The individual
dotted pairs that represent the values can be extracted by assoc, using cdr to pull out
their values.
The sublists for points are not dotted pairs like the rest. The convention is that the cdr of
the sublist is the groups value. Because a point is a list of two (or three) reals, the entire
group is a three- (or four-) element list. The cdr of the group is the list representing the
point, so the convention that cdr always returns the value is preserved.
When writing functions to process these entity lists, be sure to make them insensitive to
the order of the sublists. Use assoc to guarantee this. The 1 group containing the entitys
name allows modification operations to accept the entity list, and avoids the need to keep
the entity name in a parallel structure. A seqend entity at the end of a polyline or a set of
attributes contains a 2 group whose cdr is the entity name of the header of this entity.
This allows the header to be found from a subentity by walking forward to the Seqend and
then using the cdr of the 2 group as the entity name to retrieve the associated main
entity.
Before performing an entget on vertex entities, you should read or write the polyline
entitys header. If the most recently processed polyline entity is different from the one to
which the vertex belongs, width information (the 40 and 41 groups) can be lost.
All points associated with an object are expressed in terms of that objects Object Coordinate System (OCS). For point, line, 3dline, 3dface, 3dpolyline, 3dmesh, and dimension
objects, the OCS is equivalent to the WCS (the object points are World points). For all
other objects, the OCS can be derived from the WCS and the objects extrusion direction
(its 210 group). When working with objects that have been drawn using coordinate systems other than the WCS, you might need to convert the points to the WCS or to the current UCS by using the trans function.
entget
342
entlast
Returns the name of the last nondeleted main object (entity) in the drawing
(entlast)
The entlast function is frequently used to obtain the name of a new entity that has just
been added with the command function. The entity need not be on the screen or on a
thawed layer to be selected.
Sets e1 to the name of the last main
entity in the drawing
(setq e2 (entnext e1))
Sets e2 to nil (or to an attribute or vertex
subentity name)
(setq e1 (entlast))
If your application requires the name of the last nondeleted entity (main entity or subentity), define a function such as the following and call it instead of entlast.
(defun lastent (/ a b)
(if (setq a (entlast))
Gets last main entity
(while (setq b (entnext a)) If subentities follow, loops
(setq a b)
)
)
a
)
entmake
Creates a new entity (graphical object) in the drawing
(entmake [elist])
The elist argument must be a list of entity definition data in a format similar to that
returned by the entget function. The elist argument must contain all of the information necessary to define the entity. The entmake function can define both graphical and
nongraphical entities. If any required definition data is omitted, entmake returns nil and
the entity is rejected. If you omit optional definition data (such as the layer), entmake
uses the default value.
If entmake successfully creates a new entity, it returns the entitys list of definition data.
If entmake is unable to create the entity, it returns nil.
One method of creating a new entity is by obtaining an entitys definition data with the
entget function, modifying it, and then passing the revised data to the entmake func-
343
tion. Before creating a new entity, entmake verifies that a valid layer name, linetype
name, and color are supplied. If a new layer name is introduced, entmake automatically
creates the new layer. The entmake function also checks for block names, dimension
style names, text style names, and shape names if the entity type requires them.
The entity type (for example, CIRCLE or LINE) must be the first or second field of the
elist. If it is the second field, it can be preceded only by the entity name. This is the format returned by entget. In such cases, it ignores the entity name when the new entity is
created. If the elist contains an entity handle, it also is ignored.
The following code creates a red circle, centered at (4,4) with a radius of 1. The optional
layer and linetype fields have been omitted and therefore assume default values.
(entmake
((0 . "CIRCLE")
Entity type
(62 . 1)
Color
(10 4.0 4.0 0.0)
Center point
(40 . 1.0)
Radius
)
)
Objects created on a frozen layer are not regenerated until the layer is thawed.
Complex Entities
A complex entity (a block definition, a polyline, or a block reference containing
attributes) can be created by several entmake calls to define its subentities (attributes or
vertices). When entmake sees that a complex entity is being created, it creates a temporary file to gather the definition data. For each entmake, a check is performed to see if
the temporary file exists; if so, the new data is appended to the file. When the definition
of the complex entity is complete (by appending the appropriate seqend or endblk entity),
the supplied data is rechecked and the complex entity is added to the drawing. Completion
of a block definition (entmake of an endblk) returns the blocks name rather than the
entity data list normally returned.
You cannot create viewport objects with entmake.
entmake
344
If data is received that is invalid for that entity type, the entity is rejected as well as the
entire complex entity. A block definition cannot be nested, nor can it reference itself.
However, it can contain references to other block definitions. All entities of a complex
entity can exist in either model space or paper space, but not both.
A group 66 code is honored only for insert objects (meaning attributes follow). For
polyline entities, the group 66 code is forced to a value of 1 (meaning vertices follow), and
for all other entities it takes a default of 0. The only entity that can follow a polyline entity
is a vertex entity.
No portion of a complex entity is displayed on your drawing until its definition is complete. You can cancel the creation of a complex entity by entering entmake with no arguments. This clears the temporary file and returns nil.
The block and endblk entities can be used to create a new block definition. Newly created
blocks are automatically entered into the symbol table where they can be referenced.
Applications can represent polygons with an arbitrarily large number of sides in polyface
meshes. However, the AutoCAD entity structure imposes a limit on the number of vertices that a given face entity can specify. You can represent more complex polygons by
dividing them into triangular wedges. AutoCAD represents triangular wedges as four-vertex faces where two adjacent vertices have the same value. Their edges should be made
invisible to prevent visible artifacts of this subdivision from being drawn. The PFACE
command performs this subdivision automatically, but when applications generate polyface meshes directly, the applications must do this themselves.
The number of vertices per face is the key parameter in this subdivision process. The
PFACEVMAX system variable provides an application with the number of vertices per
face entity. This value is read-only and is set to 4.
When entmake creates a block, it can overwrite an existing block. The entmake function
does not check for name conflicts in the block definitions table, so before you use it, use
the tblsearch function to ensure that the name of the new block is unique. However,
using entmake to redefine anonymous blocks, as described in the following section, can
be useful.
Anonymous Blocks
The block definitions table in a drawing can contain anonymous blocks. Anonymous
blocks are created to support hatch patterns and associative dimensioning. They can also
be created by entmake for the applications own purposes, usually to contain entities that
the user cannot access directly.
The group code 2 (block name) of a dimension entity is optional for the entmake function. If the block name is omitted from the entity definition list, AutoCAD creates a new
one. Otherwise, AutoCAD creates the dimension using the name provided.
345
The name (group 2) of an anonymous block is *Unnn, where nnn is a number generated
by AutoCAD. Also, the low-order bit of an anonymous blocks Block type flag (group 70)
is set to 1. When entmake creates a block whose name begins with * and whose anonymous bit is set, AutoCAD treats this as an anonymous block and assigns it a name. Characters following the * in the name string passed to entmake are ignored. After the block
is created, entmake returns its name. If you are creating the block by multiple entmake
calls, it returns the name after a successful call of
(entmake "endblk")
Whenever a drawing is opened, all unreferenced anonymous blocks are purged from the
block definitions table. Referenced (inserted) anonymous blocks are not purged. You can
use entmake to create a block reference (Insert) to an anonymous block (you cannot pass
an anonymous block to the INSERT command). You can also use entmake to redefine the
block. The entities in a block (but not the block entity itself) can be modified with entmod.
Although a referenced anonymous block becomes permanent, the numeric portion of its
name can change between drawing sessions. Applications cannot rely on anonymous
block names remaining constant.
entmakex
Makes a new object or entity, gives it a handle and entity name (but, does not
assign an owner), and then returns the new entity name
(entmakex [elist])
The elist argument must be a list of entity definition data in a format similar to that
returned by the entget function. The elist argument must contain all of the information necessary to define the entity or object. The entmakex function can define both
graphical and nongraphical objects. If any required definition data is omitted, entmakex
returns nil and the object is rejected. If you omit optional definition data (such as the
layer), entmakex uses the default values.
If entmakex successfully creates a new entity, it returns the entity name. If entmakex is
unable to create the entity, it returns nil.
Objects and entities without owners are not written out to .dwg or .dxf files. Be sure to set
an owner at some point after using entmakex. For example, you can use dictadd to set
a dictionary to own an object.
entmakex
346
entmod
Modifies the definition data of an object (entity)
(entmod elist)
The entmod function is passed a list (elist) in the format returned by entget, and it
updates the database information for the entity name specified by the 1 group in elist.
The primary mechanism through which AutoLISP updates the database is by retrieving
entities with entget, modifying the list defining an entity, and updating the entity in the
database with entmod. The entmod function can modify both graphical and nongraphical
objects.
(setq en (entnext))
(setq ed (entget en))
(setq ed
(subst (cons 8 "0")
(assoc 8 ed)
ed
)
)
(entmod ed)
The entmod function imposes some restrictions on the changes it makes. First of all, an
entitys type and handle cannot be changed. If you want to do this, just entdel it and
make a new entity with the command or entmake functions. All objects referenced by the
entity list must be known to AutoCAD before the entmod is executed. Thus text style,
linetype, shape, and block names must be defined in a drawing before they can be used in
an entity list with entmod. An exception to this is layer names: entmod creates a new
layer with the standard defaults used by the New option of LAYER if a previously undefined layer is named in an entity list.
For entity fields with floating-point values (such as thickness), entmod accepts integer
values and converts them to floating point. Similarly, if you supply a floating-point value
for an integer entity field (such as color number), entmod truncates it and converts it to
an integer.
The entmod function performs consistency checking on the list supplied to it. If a serious
error is detected, the database is not updated and nil is returned. Otherwise, entmod
returns the list given to it as its argument. entmod cannot change internal fields such as
the entity name in the 2 group of a seqend entityattempts to change such fields are
ignored.
When entmod updates a main entity, it modifies the entity and updates its image on screen
(including subentities). When entmod updates a subentity (a polyline vertex or a block
347
attribute), the subentity is updated in the database but the image on the screen is not redisplayed. After all modifications are made to a given entitys subentities, the entupd function can be used to update the image on the screen.
You cannot use the entmod function to modify a viewport entity. You can change an
entitys space visibility field to 0 or 1 (except for viewport objects). If you use entmod to
modify an entity within a block definition, the modification affects all instances of the
block in the drawing.
Before performing an entmod on vertex entities, you should read or write the polyline
entitys header. If the most recently processed polyline entity is different from the one to
which the vertex belongs, width information (the 40 and 41 groups) can be lost.
You can use entmod to modify entities within a block definition, but doing so can create
a self-referencing block, which will cause AutoCAD to stop.
entnext
Returns the name of the next object (entity) in the drawing
(entnext [ename])
If entnext is called with no arguments, it returns the entity name of the first nondeleted
entity in the database. If entnext is called with an entity name argument ename, it
returns the entity name of the first nondeleted entity following ename in the database. If
there is no next entity in the database, it returns nil. The entnext function returns both
main entities and subentities.
The entities selected by ssget are main entities, not attributes of blocks or vertices of
polylines. You can access the internal structure of these complex entities by walking
through the subentities with entnext. Once you obtain a subentitys name, you can operate on it like any other entity. If you obtain the name of a subentity with entnext, you
can find the parent entity by walking forward with entnext until a seqend entity is found,
then extracting the 2 group from that entity, which is the main entitys name.
(setq e1 (entnext))
(setq e2 (entnext e1))
entnext
348
entsel
Prompts the user to select a single object (entity) by specifying a point
(entsel [msg])
The entsel function returns a list whose first element is the entity name of the chosen
object and whose second element is the coordinates (in terms of the current UCS) of the
point used to pick the object. If a string is specified for msg, that string is used to ask the
user for the object. Otherwise, the prompt defaults to Select object.
The pick point returned by entsel does not represent a point that lies on the selected
object. The point returned is the location of the crosshairs at the time of selection. The
relationship between the pick point and the object will vary depending on the size of the
pickbox and the current zoom scale.
A list of the form returned by entsel can be supplied to AutoCAD in response to any of
its object selection prompts. It is treated by AutoCAD as a pick of the designated object
by pointing to the specified point.
The following AutoCAD command sequence illustrates the use of the entsel function
and the list returned:
Command: line
From point: 1,1
To point: 6,6
To point: ENTER
Command: (setq e (entsel "Please choose an object: "))
Please choose an object: 3,3
(<Entity name: 60000014> (3.0 3.0 0.0))
Sometimes when operating on objects, you will want to simultaneously select an object
and specify the point by which it was selected. Examples of this in AutoCAD can be
found in Object Snap and in the BREAK, TRIM, and EXTEND commands. The entsel
function allows AutoLISP programs to perform this operation. It selects a single object,
requiring the selection to be by a point pick. The current Osnap setting is ignored by this
function (no object snap) unless you specifically request it while you are in the function.
The entsel function honors key words from a preceding call to initget.
349
entupd
Updates the screen image of an object (entity)
(entupd ename)
When a polyline vertex or block attribute is modified with entmod, the entire complex
entity is not updated on the screen. The entupd function can be used to cause a modified
polyline or block to be updated on the screen. This function can be called with the entity
name of any part of the polyline or block; it need not be the head entity. While entupd is
intended for polylines and blocks with attributes, it can be called for any entity. It always
regenerates the entity on the screen, including all subentities.
If entupd is used on a nested entity (an entity within a block) or on a block that contains
nested entities, some of the entities might not be regenerated. To ensure complete regeneration, you must invoke the REGEN command.
Assuming that the first entity in the drawing is a polyline with several vertices, then
(setq e1 (entnext))
Sets e1 to the polylines entity name
(setq e2 (entnext e1)) Sets e2 to its first vertex
(setq ed (entget e2)) Sets ed to the vertex data
(setq ed
(subst (10 1.0 2.0)
(assoc 10 ed)
Changes the vertexs location in ed
ed
to point (1,2)
)
)
(entmod ed)
Moves the vertex in the drawing
(entupd e1)
Regenerates the polyline entity e1
eq
Determines whether two expressions are identical
entupd
350
(setq f2 (a b c))
(setq f3 f2)
then
(eq f1 f3) returns nil, f1 and f3 are not the same list
(eq f3 f2) returns T, f3 and f2 are exactly the same list
equal
Determines whether two expressions are equal
then
(equal f1 f3)
returns T
(equal f3 f2)
returns T
(equal a b)
returns nil
(equal a b 0.000001)
returns T
Although two lists that the equal function finds the same might not be found so using the
eq function, atoms that are found to be the same using the equal function are always
found to be the same if you use the eq function. However, if the eq function finds that the
list or atoms are the same, the equal function also finds them to be the same.
351
*error*
A user-definable error-handling function
(*error* string)
If *error* is not nil, it is executed as a function whenever an AutoLISP error condition
exists. AutoCAD passes one argument to *error*, which is a string containing a description of the error.
The following function does the same thing that the AutoLISP standard error handler
does. Print error and the description.
(defun *error* (msg)
(princ "error: ")
(princ msg)
(princ)
)
Your *error* function can include calls to the command function without arguments (for
example, (command)). This will cancel a previous AutoCAD command called with the
command function.
eval
Returns the result of evaluating an AutoLISP expression
(eval expr)
For example, given the assignments
(setq a 123)
(setq b a)
then
(eval 4.0)
(eval (abs -10))
(eval a)
(eval b)
returns 4.0
returns 10
returns 123
returns 123
*error*
352
exit
Forces the current application to quit
(exit)
If exit is called, it returns the error message quit/exit abort and returns to the AutoCAD
Command prompt.
exp
Returns the constant e (a real number) raised to a specified power (the natural
antilog)
(exp num)
(exp 1.0)
(exp 2.2)
(exp -0.4)
returns 2.71828
returns 9.02501
returns 0.67032
expand
Allocates node space by requesting a specified number of segments
(expand int)
353
expt
Returns a number raised to a specified power
returns 16
returns 9.0
fill_image
Draws a filled rectangle in the currently active dialog box image tile
ADI mnemonic
Description
BGLCOLOR
15
DBGLCOLOR
16
DFGLCOLOR
18
LINELCOLOR
The first (upper-left) corner of the rectangle is located at (x1,y1) and the second (lowerright) corner is located the relative distance (wid,hgt) from the first corner (wid and hgt
must be positive values). The origin (0,0) is the upper-left corner of the image. You can
obtain the coordinates of the lower-right corner by calling the dimension functions
dimx_tile and dimy_tile.
expt
354
findfile
Searches the AutoCAD library path for the specified file
(findfile filename)
The findfile function makes no assumption about the file type or extension of filename. If filename does not specify a drive/directory prefix, findfile searches the
AutoCAD library path. If a drive/directory prefix is supplied, findfile looks only in
that directory. The findfile function always returns a fully qualified drive/directory/file
name or nil if the specified file is not found.
Consider the following examples. If the current directory is /acad and it contains the file
abc.lsp.
(findfile "abc.lsp") returns "/acad/abc.lsp"
If you are editing a drawing in the /acad/drawings directory, the ACAD environment variable is set to /acad/support, and the file xyz.txt exists only in the /acad/support directory.
(findfile "xyz.txt") returns "/acad/support/xyz.txt"
355
If the file nosuch is not present in any of the directories on the library search path.
(findfile "nosuch") returns nil
The fully qualified name returned by findfile is suitable for use with the open function.
fix
Returns the conversion of a real number into the nearest smaller integer
(fix num)
The fix function truncates number to the nearest integer by discarding the fractional portion.
(fix 3)
(fix 3.7)
returns 3
returns 3
float
Returns the conversion of a number into a real number
(float num)
(float 3)
(float 3.75)
returns 3.0
returns 3.75
fix
356
foreach
Evaluates expressions for all members of a list
is equivalent to
(print a)
(print b)
(print c) and returns c
except that foreach returns the result of only the last expression evaluated.
gc
Forces a garbage collection, which frees up unused nodes
(gc)
gcd
Returns the greatest common denominator of two integers
returns 3
returns 4
357
get_attr
Retrieves the DCL value of a dialog box attribute
get_tile
Retrieves the current run-time value of a dialog box tile
(get_tile key)
The key argument is a string that specifies the tile and is case-sensitive. It returns the tiles
value as a string.
getangle
Pauses for user input of an angle, and returns that angle in radians
get_attr
358
The user can specify an angle by entering a number in the AutoCAD current angle units
format. Although the current angle units format might be in degrees, grads, or some other
unit, this function always returns the angle in radians. The user can also show AutoLISP
the angle by pointing to two 2D locations on the graphics screen. AutoCAD draws a rubber-band line from the first point to the current crosshair position to help you visualize the
angle.
It is important to understand the difference between the input angle and the angle returned
by getangle. Angles that are passed to getangle are based on the current settings of
ANGDIR and ANGBASE. However, once an angle is provided, it is measured in a counterclockwise direction (ignoring ANGDIR) with zero radians as the current setting of
ANGBASE. The following code examples show how different arguments can be used.
(setq ang (getangle))
(setq ang (getangle (1.0 3.5)))
(setq ang (getangle "Which way? "))
(setq ang (getangle (1.0 3.5) "Which way? "))
The user cannot enter another AutoLISP expression as the response to a getangle
request.
getcfg
Retrieves application data from the AppData section of the acad.cfg file
(getcfg cfgname)
The cfgname argument is a string (maximum length of 347 characters) naming the section and parameter value to retrieve. If cfgname is not valid, getcfg returns nil. The
cfgname argument must be a string of this form:
"AppData/application_name/section_name/.../param_name"
For example, assuming that the WallThk parameter in the AppData/ArchStuff section has
a value of 8,
(getcfg "AppData/ArchStuff/WallThk") returns "8"
359
getcname
Retrieves the localized or English name of an AutoCAD command
(getcname cname)
The cname argument specifies the localized or underscored English command name,
which must be 64 characters or less in length. If cname is not preceded by an underscore
(assumed to be the localized command name), getcname returns the underscored English
command name. If cname is preceded by an underscore, getcname returns the localized
command name. This function returns nil if cname is not a valid command name.
For example, in a French version of AutoCAD, the following is true.
(getcname "ETIRER")
returns "_STRETCH"
(getcname "_STRETCH") returns "ETIRER"
getcorner
Pauses for user input of a rectangles second corner
(getcorner pt [msg])
The getcorner function requires a base point argument, pt, based on the current UCS,
and draws a rectangle from that point as the user moves the crosshairs on the screen. The
msg argument is a string to be displayed as a prompt. The getcorner function returns a
point in the current UCS, similar to getpoint. If the user supplies a 3D point, its Z coordinate is ignored. The current elevation is used as the Z coordinate.
The user cannot enter another AutoLISP expression as the response to a getcorner
request.
getcname
360
getdist
Pauses for user input of a distance
The user cannot enter another AutoLISP expression as the response to a getdist request.
getenv
Returns the string value assigned to a system environment variable
(getenv variable-name)
The variable-name argument is a string specifying the name of the variable to be read.
If this variable does not exist, getenv returns nil. You must enclose the variable name
in quotation marks. Environment variable names must be spelled and cased exactly as
they are stored in the system registry.
361
For example, if the system environment variable ACAD is set to /acad/support and there
is no variable named NOSUCH, then
(getenv "ACAD")
returns "/acad/support"
(getenv "NOSUCH") returns nil
getfiled
Prompts the user for a file name with the standard AutoCAD file dialog box, and
returns that file name
Set this bit when you prompt for the name of a new file to create.
Do not set this bit when you prompt for the name of an existing file
to open. In the latter case, if the user enters the name of a file that
getfiled
362
doesnt exist, the dialog box displays an error message at the bottom
of the box.
If this bit is set and the user chooses a file that already exists,
AutoCAD displays an alert box and offers the choice of proceeding
with or canceling the operation.
Flag value = 4
(bit 2)
Flag value = 8
(bit 3)
If this bit is set and bit 0 is not set, getfiled performs a library
search for the file name entered. If it finds the file and its directory
in the library search path, it strips the path and returns only the file
name. (It doesnt strip the path name if it finds that a file of the same
name is in a different directory.)
If this bit is not set, getfiled returns the entire file name, including the path name.
Set this bit if you use the dialog box to open an existing file whose
name you want to save in the drawing (or other database).
If the dialog box obtains a file name from the user, getfiled returns a string that specifies the file name; otherwise, it returns nil.
The following call to getfiled displays the Select a Lisp File dialog box:
(getfiled "Select a Lisp File" "/acadr14/support/" "lsp" 8)
363
The getfiled function displays a dialog box containing a list of available files of a specified extension type. You can use this dialog box to browse through different drives and
directories, select an existing file, or specify the name of a new file.
getint
Pauses for user input of an integer, and returns that integer
(getint [msg])
The msg argument is an optional string to be displayed as a prompt. The getint function
returns the integer value or nil.
(setq num (getint))
(setq num (getint "Enter a number: "))
Values passed to getint can range from 32,768 to +32,767. The user cannot enter
another AutoLISP expression as the response to a getint request.
getint
364
getkword
Pauses for user input of a key word, and returns that key word
(getkword [msg])
Valid key words are set prior to the getkword call with the initget function. The msg
argument is a string to be displayed as a prompt. The getkword function returns the key
word matching the user input as a string. AutoCAD tries again if the input is not a key
word. If the input is null ( ENTER ), getkword returns nil (if null input is allowed). This
function also returns nil if it wasnt preceded by a call to initget that established one
or more key words.
The following example shows an initial call to initget that sets up a list of key words
(Yes and No) and disallows null input (bits value equal to 1) to the following getkword
call:
(initget 1 "Yes No")
(setq x (getkword "Are you sure? (Yes or No) "))
This code prompts the user for input and sets the symbol x to either Yes or No, depending
on the response. If the response does not match any of the key words, or if the user gives
a null reply, AutoCAD prompts again with the string supplied in the msg argument. If no
msg argument is provided, AutoCAD supplies this prompt:
Try again:
The user cannot enter another AutoLISP expression as the response to a getkword
request.
getorient
Pauses for user input of an angle, and returns that angle in radians
365
The pt argument is a 2D base point in the current UCS, and msg is a string to be displayed
as a prompt. The pt argument, if specified, is assumed to be the first of two points, allowing the user to show AutoLISP the angle by pointing to one other point. You can supply
a 3D base point, but the angle is always measured in the current construction plane.
The getorient function measures angles with the zero-radian direction to the right
(east) and angles that are increasing in the counterclockwise direction. As with
getangle, getorient expresses the returned angle in radians, with respect to the current construction plane. Angles input to getorient are based on the current settings of
ANGDIR and ANGBASE. However, once an angle is provided, it is measured in a counterclockwise direction, with zero radians being to the right (ignoring ANGDIR and ANGBASE). Therefore, some conversion must take place if you select a different zero-degree
base or a different direction for increasing angles by using the UNITS command or the
ANGBASE and ANGDIR system variables.
Use getangle when you need a rotation amount (a relative angle). Use getorient to
obtain an orientation (an absolute angle).
The user cannot enter another AutoLISP expression as the response to a getorient
request.
getpoint
Pauses for user input of a point, and returns that point
The user cannot enter another AutoLISP expression as the response to a getpoint
request.
getpoint
366
getreal
Pauses for user input of a real number, and returns that real number
(getreal [msg])
The msg argument is a string to be displayed as a prompt.
(setq val (getreal))
(setq val (getreal "Scale factor: "))
The user cannot enter another AutoLISP expression as the response to a getreal request.
getstring
Pauses for user input of a string, and returns that string
367
See also the getkword function for a routine that requires the user to enter one of
several known options (key words).
getvar
Retrieves the value of an AutoCAD system variable
(getvar varname)
The varname argument is a string that names the system variable. If varname is not a
valid system variable, getvar returns nil.
For example, assuming that the fillet radius is set to 0.25 units,
(getvar "FILLETRAD")
returns 0.25
You can find a list of the current AutoCAD system variables in the Command Reference.
graphscr
Displays the AutoCAD graphics screen
(graphscr)
The graphscr function always returns nil.
This function is equivalent to the GRAPHSCR command or to pressing the Flip Screen
function key. The textscr function is the complement of graphscr.
getvar
368
grclear
Clears the current viewport (obsolete function)
(grclear)
To preserve limited compatibility with previous releases, the grclear function returns
nil.
grdraw
Draws a vector between two points, in the current viewport
See also the grvecs function for a routine that draws multiple vectors
grread
Reads values from any of the AutoCAD input devices
369
If the track argument is supplied and is not nil, it enables the return of coordinates from
a pointing device as it is moved. If the allkeys argument is present, grread performs
functions depending on the code supplied. The curtype argument can be used to control
the type of cursor displayed. The allkeys and curtype arguments are both integers and
are explained as follows:
allkeys
The allkeys bit code values can be added together for combined
functionality.
1 (bit 0) Return drag mode coordinates. If this bit is set and the
user moves the pointing device instead of selecting a button or
pressing a key, grread returns a list where the first member is a
type 5 and the second member is the (X,Y) coordinates of the current
pointing device (mouse or digitizer) location. This is how
AutoCAD implements dragging.
2 (bit 1) Return all key values, including function and cursor key
codes, and dont move the cursor when the user presses a cursor key.
4 (bit 2) Use the value passed in the curtype argument to control
the cursor display.
8 (bit 3) Dont display the error: console break message when the
user presses CTRL + C .
curtype
The allkeys value for bit 2 must be set for the curtype values to
take effect. The curtype argument affects only the cursor type during the current grread function call.
0 Display the normal crosshairs.
1 Do not display a cursor (no crosshairs).
2 Display the object-selection target cursor.
grread
370
The grread function returns a list whose first element is a code specifying the type of
input. The second element of the list is either an integer or a point, depending on the type
of input. The return values are listed in the following table.
grread return values
First element
Second element
Value
Type of input
Value
Description
Keyboard input
varies
Character code
Selected point
3D point
Point coordinates
0 to 999
1001 to 1999
2001 to 2999
3001 to 3999
and so, to
16001 to 16999
3D point
0 to 999
1000 to 1999
2000 to 2999
3000 to 3999
0 to 32767
0 to 32767
0 to 32767
10
0 to 32767
11
0 to 999
1000 to 1999
2000 to 2999
3000 to 3999
12
3D point
Point coordinates
371
Entering Esc while a grread is active aborts the AutoLISP program with a keyboard
break (unless the allkeys argument has disallowed this). Any other input is passed
directly to grread, giving the application complete control over the input devices.
If the user presses the pointer button within a screen menu or pull-down menu box,
grread returns a type 6 or type 11 code, but in a subsequent call, it does not return a type
12 code: the type 12 code follows type 6 or type 11 only when the pointer button is pressed
while it is in the graphics area of the screen.
It is important to clear the code 12 data from the buffer before attempting another operation with a pointer button or with an auxiliary button. To accomplish this, perform a
nested grread like this:
(setq code_12 (grread (setq code (grread))))
This sequence captures the value of the code 12 list as streaming input from the device.
Because input is handled differently on the various platforms supported by AutoCAD, the
grread function may return unexpected results.
The default pointing device on platforms that use a system mouse returns a code 11,
not a code 6.
On the Macintosh platform, the pop menus return a code 11, not a code 4. Also on the
Macintosh, a double-click returns a code 11 (not a code 6) and is followed by a code
5 coordinate pair if selected in the current viewport. Conversely, a double-click in a
viewport other than the current one returns a code 3 coordinate pair followed by a code
11.
grtext
Writes text to the status line or to screen menu areas
grtext
372
If a box value of 2 is used, grtext writes the text into the coordinate status line area. If
coordinate tracking is turned on, values written into this field are overwritten as soon as
the pointer sends another set of coordinates. For both 1 or 2 box values, the highlight
argument is ignored.
grvecs
Draws multiple vectors on the graphics screen
373
The color value applies to all succeeding vectors until vlist specifies another color.
AutoCAD colors are in the range 0255. If the color value is greater than 255, succeeding
vectors are drawn in XOR ink, which complements anything it draws over and which
erases itself when overdrawn. If the color value is less than zero, the vector is highlighted.
Highlighting depends on the display device. Most display drivers indicate highlighting by
a dashed line, but some indicate it by using a distinctive color.
A pair of point lists, from and to, specify the endpoints of the vectors, expressed in the
current UCS. These can be two-dimensional or three-dimensional points. You must pass
these points as pairstwo successive point listsor the grvecs call will fail.
AutoCAD clips the vectors as required to fit on the screen. If the call to grvecs is successful, it returns nil.
The following code draws five vertical lines on the graphics screen, each a different color:
(grvecs (1 (1 2)(1 5)
2 (2 2)(2 5)
3 (3 2)(3 5)
4 (4 2)(4 5)
5 (5 2)(5 5)
))
The following matrix represents a uniform scale of 1.0 and a translation of 5.0,5.0,0.0. If
this matrix is applied to the preceding list of vectors, they will be offset by 5.0,5.0,0.0.
( (1.0 0.0 0.0 5.0)
(0.0 1.0 0.0 5.0)
(0.0 0.0 1.0 0.0)
(0.0 0.0 0.0 1.0)
)
See also the nentselp function for more information on transformation matrixes
handent
Returns an object (entity) name based on its handle
(handent handle)
Given an entity handle string as the handle argument, the handent function returns the
entity name associated with that handle in the current editing session. The handent function returns the entity name of both graphic and nongraphic entities.
handent
374
If handent is passed an invalid handle or a handle not used by any entity in the current
drawing, nil is returned. The handent function returns entities that have been deleted
during the current editing session. You can undelete them with the entdel function.
An entitys name can change from one editing session to the next, but an entitys handle
remains constant. In a particular editing session, the code
(handent "5A2") might return <Entity name: 60004722>
Used with the same drawing but in another editing session, the same call might return a
different entity name. Once the entity name is obtained, it can be used to manipulate the
entity with any of the entity-related functions.
help
Invokes the help facility
Description
HELP_CONTENTS
HELP_HELPONHELP
HELP_PARTIALKEY
Displays the Search dialog using the string passed as the topic as
the initial search text
If you are specifying a Windows Help file, the command argument can also be a string
used by the fuCommand argument of the WinHelp() function as defined by the WinHelp
API in the Microsoft Windows SDK.
375
The file extension is not required with the helpfile argument. If a file extension is provided, AutoCAD looks only for that file. If no file extension is provided, the following
search rules apply: append .hlp, else append .ahp.
The only error condition that the help function returns to the application is the existence
of the file specified by helpfile. All other error conditions are reported to the user
through a dialog box. The help function returns the helpfile string if it succeeds and
nil if it fails. If you use help without any arguments, it returns an empty string ("") if
successful, and nil if it fails.
The following code calls help to display the information on MYCOMMAND in the help file
achelp.ahp:
(help "achelp.ahp" "mycommand")
See also The setfunhelp function associates context-sensitive help (when the user
presses F1 ) with a user-defined command.
help
376
if
Conditionally evaluates expressions
377
initdia
Forces the display of the next commands dialog box
(initdia [dialogflag])
The dialogflag argument is an integer. If this argument is not present or is present and
nonzero, the next use (and next use only) of a command will display that commands dialog box rather than its command line prompts. Currently, the only commands to make use
of the initdia function are BHATCH, LAYER, IMAGE, IMAGEADJUST, LINETYPE,
MTEXT, PLOT, STYLE, and TOOLBAR.
If the dialogflag argument is zero, then any previous call to this function is cleared, which
restores the default behavior of presenting the command line interface.
This function returns no value.
Externally defined function acadapp ARX application
initget
Establishes key words for use by the next user-input function call
initdia
378
If initget sets a control bit and the application calls a user-input function for which the
bit has no meaning, the bit is ignored. The bits can be added together in any combination
to form a value between 0 and 255. If no bits argument is supplied, zero (no conditions)
is assumed. If the user input fails one or more of the specified conditions (as in a zero
value when zero values are not allowed), AutoCAD displays a message and asks the user
to try again.
Input options set by initget
Bit value
Description
1 (bit 0)
Prevents the user from responding to the request by entering only ENTER .
2 (bit 1)
4 (bit 2)
Prevents the user from responding to the request by entering a negative value.
8 (bit 3)
Allows the user to enter a point outside the current drawing limits. This condition applies to the next user-input function even if the AutoCAD system variable
LIMCHECK is currently set.
16 (bit 4)
32 (bit 5)
Uses dashed lines when drawing rubber-band line or box. For those functions
with which the user can specify a point by selecting a location on the graphics
screen, this bit value causes the rubber-band line or box to be dashed instead of
solid. (Some display drivers use a distinctive color instead of dashed lines.) If the
system variable POPUPS is 0, AutoCAD ignores this bit.
64 (bit 6)
128 (bit 7)
Allows arbitrary input as if it is a key word, first honoring any other control bits
and listed key words. This bit takes precedence over bit 0; if bits 7 and 0 are set
and the user presses ENTER , a null string is returned.
Future versions of AutoLISP might use additional initget control bits, so avoid setting
bits that arent shown in the table.
379
The special control values are honored only by those getxxx functions for which they
make sense.
User-input functions and applicable control bits
Honors
Control bits values
key words
No
No
No
No
negative limits
zero
null
(8)
(4)
(2)
(1)
Function
Uses
dashes
(32)
2D
distance
(64)
Arbitrary
Input
(128)
getint
getreal
getdist
getangle
getorient
getpoint
getcorner
getkword
entsel
nentsel
nentselp
The required portion of the key word is specified in uppercase characters, and the
remainder of the key word is specified in lowercase characters. The uppercase abbreviation can be anywhere in the key word (for example, "LType", "eXit", or "toP").
The entire key word is specified in uppercase characters, and it is followed immediately by a comma, which is followed by the required characters (for example,
initget
380
"LTYPE,LT"). The key word characters in this case must include the first letter of the
key word, which means that "EXIT,X" is not valid.
The two brief examples, "LType" and "LTYPE,LT", are equivalent: if the user types LT
(in either upper case or lower case letters), this is sufficient to identify the key word. The
user can enter characters that follow the required portion of the key word, provided they
dont conflict with the specification. In the example, the user could also enter LTY or
LTYP, but L would not be sufficient.
If string shows the key word entirely in uppercase or lowercase characters with no
comma followed by a required part, AutoCAD recognizes the key word only if the user
enters all of it.
The initget function provides support for localized keywords. The following syntax for
the keyword string allows input of the localized keyword while it returns the language
independent keyword:
"local1 local2 localn _indep1 indep2 indepn"
where local1 through localn are the localized keywords, and indep1 through indepn
are the language-independent keywords.
There must always be the same number of localized keywords as language-independent
keywords, and the first language-independent keyword is prefixed by an underscore as
shown in the following example:
(initget "Abc Def _Ghi Jkl")
(getkword "\nEnter an option (Abc/Def): ")
381
inters
Finds the intersection of two lines
itoa
Returns the conversion of an integer into a string
(itoa int)
The int argument specifies an integer.
(itoa 33)
(itoa -17)
returns "33"
returns "-17"
inters
382
lambda
Defines an anonymous function
and
(setq counter 0)
(mapcar (lambda (x)
(setq counter (1+ counter))
(* x 5)
)
(2 4 -6 10.2)
)
returns (10 20 -30 51.0)
last
Returns the last element in a list
(last lst)
(last (a b c d e))
(last (a b c (d e)))
returns E
returns (D E)
383
length
Returns an integer indicating the number of elements in a list
(length lst)
(length (a b c d))
returns 4
(length (a b (c d)))
returns 3
(length ())
returns 0
list
Takes any number of expressions, and combines them into one list
(list expr...)
(list a b c)
(list a (b c) d)
(list 3.9 6.7)
returns (A B C)
returns (A (B C) D)
returns (3.9 6.7)
This can be useful for creating association lists and defining points.
length
384
listp
Verifies that an item is a list
(listp item)
Returns T if item is a list, and returns nil otherwise.
(listp (a b c))
(listp a)
(listp 4.343)
returns T
returns nil
returns nil
Because nil is both an atom and a list, the listp function returns T when passed nil.
(listp nil)
returns T
load_dialog
Loads a DCL file
(load_dialog dclfile)
The dclfile argument is a string that specifies the DCL file to load. If the dclfile
argument does not specify a file extension, .dcl is assumed. Returns a positive integer
value (dcl_id) if successful, and returns a negative integer if it cant open the file. The
dcl_id is used as a handle in subsequent new_dialog and unload_dialog calls.
The load_dialog function searches for files according to the AutoCAD library search
path.
This function is the complement of unload_dialog. An application can load multiple
DCL files with multiple load_dialog calls.
385
load
Evaluates the AutoLISP expressions in a file
...function body...
)
(defun MY-FUNC2 (x)
...function body...
and that file test2.lsp does not exist, then
(load "/fred/test1")
returns MY-FUNC2
(load "\\fred\\test1")
returns MY-FUNC2
(load "/fred/test1" "bad") returns MY-FUNC2
(load "test2" "bad")
returns "bad"
(load "test2")
causes an AutoLISP error
The load function can be used from within another AutoLISP function, or even recursively (in the file being loaded).
See also the defun function and Symbol and Function Handling.
load
386
log
Returns the natural log of a number as a real number
(log num)
(log 4.5)
(log 1.22)
returns 1.50408
returns 0.198851
logand
Returns the result of the logical bitwise AND of a list of integers
returns 3
returns 2
returns 0
logior
Returns the result of the logical bitwise inclusive OR of a list of integers
returns 7
returns 11
387
lsh
Returns the logical bitwise shift of an integer by a specified number of bits
returns 4
returns 1
returns 160
mapcar
Returns a list of the result of executing a function with the individual elements of
a list or lists supplied as arguments to the function
is equivalent to
(1+ a)
(1+ b)
(1+ c)
lsh
388
(lambda (x)
(+ x 3)
)
(10 20 30)
max
Returns the largest of the numbers given
returns 4.07
returns 19
returns 8.0
mem
Displays the current state of AutoLISPs memory
(mem)
Displays the current state of AutoLISPs memory, and returns nil. It displays the following information:
Nodes is the total number of nodes allocated so far, which should equal the node segment
size multiplied by the number of segments.
Free nodes is the number of nodes currently on the free list as a result of a garbage collection.
Segments is the number of node segments allocated.
Allocate is the current segment size.
Collections is a count of garbage collections, whether automatic or forced.
389
member
Searches a list for an occurrence of an expression and returns the remainder of
the list, starting with the first occurrence of the expression
menucmd
Issues menu commands, or sets and retrieves menu item status
(menucmd string)
The string argument is a string that specifies a menu area and the value to assign to that
menu area. The string argument has the following parameters.
"menu_area=value"
The allowed values of menu_area, shown in the following table, are the same as they are
in menu file submenu references.
Menu_area string values
Menu_area
string
Menu section
B1B4
A1A4
P0P16
member
390
Menu section
T1T4
Gmenugroup.nametag
The following code checks the status of the third menu item in the pull-down menu
POP11. If the menu item is currently enabled, the menucmd function disables it.
(setq s (menucmd "P11.3=?")) Gets the status of the menu item
(if (= s "")
If the status is an empty string,
(menucmd "P11.3=~")
disable the menu item
)
The previous code is not foolproof. In addition to being enabled or disabled, menu items
can also receive marks. The code (menucmd "P11.3=?") could return "!.", indicating
that the menu item is currently checked. This code would make the assumption that the
menu item is disabled and would continue without disabling it. If the code included a call
to the wcmatch function, it could check the status for an occurrence of the tilde (~) character and then take appropriate action.
391
The menucmd function also allows AutoLISP programs to take advantage of the DIESEL
string expression language. Some things can be done much easier with DIESEL than with
the equivalent AutoLISP code. The following code returns a string containing the current
day and date:
(menucmd "M=$(edtime,$(getvar,date),DDDD\",\" D MONTH YYYY)")
returns "Sunday, 16 July 1995"
menugroup
Verifies that a menugroup is loaded
(menugroup groupname)
The groupname argument is a string that specifies the menugroup name. If groupname
matches a loaded menugroup the function returns the groupname string; otherwise, it
returns nil.
min
Returns the smallest of the numbers given
returns -10.0
returns 2
returns 2.0
menugroup
392
minusp
Verifies that a number is negative
(minusp num)
Returns T if number is negative, and returns nil otherwise.
(minusp -1)
(minusp -4.293)
(minusp 830.2)
returns T
returns T
returns nil
mode_tile
Sets the mode of a dialog box tile
Description
Enable tile
Disable tile
393
namedobjdict
Returns the entity name of the current drawings named object dictionary, which
is the root of all nongraphical objects in the drawing
(namedobjdict)
Using the name returned by this function and the dictionary access functions, an application can access the nongraphical objects in the drawing.
nentsel
Prompts the user to select an object (entity) by specifying a point, and provides
access to the definition data contained within a complex object
(nentsel [msg])
The msg argument is a string to be displayed as a prompt. If omitted, the Select objects
prompt is issued.
The nentsel function prompts the user to select an object. The current Object Snap
mode is ignored unless the user specifically requests it. To provide additional support at
the Command prompt, nentsel honors key words defined by a previous call to initget.
When the selected object is not complex (i.e., not a polyline or block), nentsel returns
the same information as entsel. However, if the selected object is a polyline, nentsel
returns a list containing the name of the subentity (vertex) and the pick point. This is similar to the list returned by entsel, except that the name of the selected vertex is returned
instead of the polyline header. The nentsel function always returns the starting vertex
of the selected polyline segment. Picking the third segment of a polyline, for example,
returns the third vertex. The Seqend subentity is never returned by nentsel for a
polyline.
An optimized polyline (lwpolyline entity) is defined in the drawing database as a single
entity; it does not contain subentities.
Selecting an attribute within a block reference returns the name of the attribute and the
pick point. When the selected object is a component of a block reference other than an
attribute, nentsel returns a list containing four elements.
namedobjdict
394
The first element of the list returned from picking an object within a block is the selected
entitys name. The second element is a list containing the coordinates of the point used to
pick the object.
The third element is called the Model to World Transformation Matrix. It is a list consisting of four sublists, each of which contains a set of coordinates. This matrix can be used
to transform the entity definition data points from an internal coordinate system called the
Model Coordinate System (MCS), to the World Coordinate System (WCS). The insertion
point of the block that contains the selected entity defines the origin of the MCS. The orientation of the UCS when the block is created determines the direction of the MCS axes.
The fourth element is a list containing the entity name of the block that contains the
selected object. If the selected object is in a nested block (a block within a block), the list
additionally contains the entity names of all blocks in which the selected object is nested,
starting with the innermost block and continuing outward until the name of the block that
was inserted in the drawing is reported.
(<Entity Name: ename1>
Name of entity
(Px Py Pz)
Pick point
( (X0 Y0 Z0)
Model to World Transformation Matrix
(X1 Y1 Z1)
(X2 Y2 Z2)
(X3 Y3 Z3)
)
(<Entity name:ename2> Name of most deeply nested block
.
containing selected entity
.
.
<Entity name:enamen>) Name of outermost block
)
Once the entity name and the Model to World Transformation Matrix are obtained, you
can transform the entity definition data points from the MCS to the WCS. Use entget
and assoc on the entity name to obtain the definition points expressed in MCS coordinates. The Model to World Transformation Matrix returned by nentsel has the same
purpose as that returned by nentselp, but it is a 4 3 matrixpassed as an array of four
pointsthat uses the convention that a point is a row rather than a column. The transformation is described by the following matrix multiplication:
M 00 M 01 M 02
X Y Z 1.0 = X Y Z 1.0
M 10 M 11 M 12
M 20 M 21 M 22
M 30 M 31 M 32
395
X = XM 00 + YM 10 + ZM 20 + M 30
Y = XM 01 + YM 11 + ZM 21 + M 31
Z = XM 02 + YM 12 + ZM 22 + M 32
The Mij, where 0 i, j 2, are the Model to World Transformation Matrix coordinates;
X, Y, Z is the entity definition data point expressed in MCS coordinates, and X, Y, Z is
the resulting entity definition data point expressed in WCS coordinates.
This is the only AutoLISP function that uses a matrix of this type; the nentselp function
returns a matrix similar to those used by other AutoLISP and ADSRX functions.
See also Entity Name Functions and the entsel and if functions
nentselp
Provides similar functionality to that of the nentsel function without the need
for user input
M 00 M 01 M 02 M 03
M 10 M 11 M 12 M 13
M 20 M 21 M 22 M 23
M 30 M 31 M 32 M 33
The first three columns of the matrix specify scaling and rotation. The fourth column is a
translation vector.
The functions that use a matrix of this type treat a point as a column vector of dimension
4. The point is expressed in homogeneous coordinates, where the fourth element of the
point vector is a scale factor that is normally set to 1.0. The final row of the matrix, the
vector [M30 M31 M32 M33], has the nominal value of [0 0 0 1]; it is currently ignored by
nentselp
396
the functions that use this matrix format. In this convention, applying a transformation to
a point is a matrix multiplication that appears as follows:
M 00
X
M 10
Y
=
Z
M 20
1.0
0.0
M 01 M 02 M 03
X
M 11 M 12 M 13
Y
Z
M 21 M 22 M 23
1.0
0.0 0.0 1.0
X = XM 00 + YM 01 + ZM 02 + M 03 ( 1.0 )
Y = XM 10 + YM 11 + ZM 12 + M 13 ( 1.0 )
Z = XM 20 + YM 21 + ZM 22 + M 23 ( 1.0 )
As these equations show, the scale factor and the last row of the matrix have no effect and
are ignored.
new_dialog
Begins a new dialog box and displays it, and can also specify a default action
397
new_dialog
398
not
Verifies that an item evaluates to nil
(not item)
Returns T if item evaluates to nil, and returns nil otherwise.
(setq a 123 b "string" c nil)
(not a)
returns
(not b)
returns
(not c)
returns
(not ())
returns
nil
nil
T
T
Typically, the null function is used for lists, and not is used for other data types along
with some type of control function.
nth
Returns the nth element of a list
(nth n lst)
The n argument is the number of the element to return (zero is the first element). If n is
greater than lsts highest element number, nth returns nil.
(nth 3 (a b c d e))
(nth 0 (a b c d e))
(nth 5 (a b c d e))
returns D
returns A
returns nil
399
null
Verifies that an item is bound to nil
(null item)
Returns T if item is bound to nil, and returns nil otherwise.
(setq a 123 b "string" c nil)
(null a)
returns
(null b)
returns
(null c)
returns
(null ())
returns
nil
nil
T
T
numberp
Verifies that an item is a real number or an integer
(numberp item)
Returns T if item is a real or an integer, and returns nil otherwise.
(setq a 123 b a)
(numberp 4)
(numberp 3.8348)
(numberp "Howdy")
(numberp a)
(numberp b)
(numberp (eval b))
returns T
returns T
returns nil
returns T
returns nil
returns T
open
Opens a file for access by the AutoLISP I/O functions
null
400
lowercase letter. The following table describes the valid mode letters.
Mode options for the open function
Open
mode
Description
"r"
Open for reading. If filename does not exist, open returns nil.
"w"
Open for writing. If filename does not exist, a new file is created and opened. If
filename already exists, its existing data is overwritten.
"a"
Open for appending. If filename does not exist, a new file is created and opened.
If filename already exists, it is opened and the pointer is positioned at the end of
the existing data, so new data you write to the file is appended to the existing data.
Data passed to an open file is not actually written until th e file is closed with the close
function.
On DOS systems, some programs and text editors write text files with an end-of-file
marker (CTRL Z, decimal ASCII code 26) at the end of the text. When reading a text file,
DOS returns an end-of-file status if a CTRL Z marker is encountered, even if that marker
is followed by more data. If you intend to use OPENs "a" mode to append data to files
produced by another program, be sure that the other program does not insert CTRL Z
markers at the end of its text files.
The open function returns a file descriptor to be used by the other I/O functions. The file
descriptor must be assigned to a symbol that uses the setq function.
(setq a (open "file.ext" "r"))
Assuming that the files named in the following examples do not exist,
(setq f (open "new.tst" "w")) returns <File #nnn>
(setq f (open "nosuch.fil" "r")) returns nil
(setq f (open "logfile" "a")) returns <File #nnn>
The filename argument can include a directory prefix, as in /test/func3. On DOS systems, a drive letter is also permitted, and you can use the backslash (\) instead of the forward slash (/), but remember that you must use two backslashes (\\) to obtain one backslash in a string.
(setq f (open "/x/new.tst" "w")) returns <File #nnn>
(setq f (open "nosuch.fil" "r")) returns nil
401
or
Returns the logical OR of a list of expressions
(or expr...)
The or function evaluates the expressions from left to right, looking for a non-nil
expression. If one is found, or ceases further evaluation and returns T. If all of the expressions are nil, or returns nil.
(or nil 45 ())
(or nil ())
returns T
returns nil
osnap
Returns a 3D point that is the result of applying an Object Snap mode to a
specified point
(osnap pt mode)
The mode argument is a string that consists of one or more valid Object Snap identifiers
such as mid, cen, and so on, separated by commas.
(setq pt1 (getpoint))
(setq pt2 (osnap pt1 "cen"))
(setq pt3 (osnap pt1 "end,int"))
The point returned by osnap depends on the current 3D view and the setting of the APERTURE system variable.
polar
Returns the UCS 3D point at a specified angle and distance from a point
or
402
prin1
Prints an expression to the command line or writes an expression to an open file
Each of the preceding examples is displayed on the screen because no file-desc was
specified. Assuming that f is a valid file-descriptor for a file opened for writing,
(prin1 "Hello" f)
will write "Hello" to the specified file and will return "Hello".
If expr is a string containing control characters, prin1 expands these characters with a
leading \, as shown in the following table.
Control codes
Code
Description
\\
\ character
\"
" character
\e
Escape character
\n
Newline character
\r
Return character
\t
Tab character
\nnn
403
Description
\U+XXXX
\M+NXXXX
The prin1 function can be called with no arguments, in which case it returns (and prints)
the null string. If you use prin1 (with no arguments) as the last expression in a userdefined function, only a blank line is printed when the function is complete, allowing the
application to exit quietly.
princ
Prints an expression to the command line, or writes an expression to an open file
print
Prints an expression to the command line, or writes an expression to an open file
princ
404
progn
Evaluates each expression sequentially, and returns the value of the last
expression
(progn [expr]...)
You can use progn to evaluate several expressions where only one expression is
expected.
(if (= a b)
(progn
(princ "\nA = B ")
(setq a (+ a 10) b (- b 10))
)
)
The if function normally evaluates one then expression if the test expression evaluates
to anything but nil. In this example, we have used progn to cause two expressions to be
evaluated instead.
405
prompt
Displays a string on your screens prompt area
(prompt msg)
On dual-screen AutoCAD configurations, prompt displays msg on both screens and is,
therefore, preferable to princ.
(prompt "New value: ")
displays
New value:
on the screen(s)
quit
Forces the current application to quit
(quit)
If quit is called, it returns the error message quit/exit abort and returns to the AutoCAD
Command prompt.
quote
Returns an expression without evaluating it
(quote expr)
This can also be written
expr
(quote a)
(quote cat)
(quote (a b))
a
cat
(a b)
returns A
returns CAT
returns (A B)
returns A
returns CAT
returns (A B)
prompt
406
The last three examples dont work if entered directly from the keyboard in response to
an AutoCAD prompt. Remember that such input must begin with the character ( or ! to
be recognized as an AutoLISP expression.
read
Returns the first list or atom obtained from a string
(read [string])
The string argument cannot contain blanks except within a list or string. The read function returns its argument converted into the corresponding data type:
(read "hello")
returns the atom
(read "hello there")
returns the atom
(read "\"Hi Yall\"") returns the string
(read "(a b c)")
returns the list
(read "(a b c) (d)")
returns the list
(read "1.2300")
returns the real number
(read "87")
returns the integer
(read "87 3.2")
returns the integer
HELLO
HELLO
"Hi Yall"
(A B C)
(A B C)
1.23
87
87
read-char
Returns the decimal ASCII code representing the character read from the
keyboard input buffer or from an open file
(read-char [file-desc])
If no file-desc is specified and there are no characters in the keyboard input buffer,
read-char waits for keyboard entry (followed by ENTER ). For instance, assuming the
keyboard input buffer is empty,
(read-char)
waits for something to be entered. If you enter ABC followed by ENTER , read-char
returns 65 (the decimal ASCII code for the letter A). The next three calls to read-char
return 66, 67, and 10 (newline), respectively. If another read-char call is made, it again
waits for input.
The various operating systems under which AutoCAD runs use various conventions to
signal the end of a line in an ASCII text file. UNIX systems, for example, use a single
newline character (linefeed [LF], ASCII code 10), whereas DOS systems use a pair of
407
characters (carriage-return [CR]/LF, ASCII codes 13 and 10) for the same purpose. To
facilitate development of AutoLISP programs, read-char accepts all these conventions,
returning a single newline character (ASCII code 10) whenever it detects an end-of-line
character (or character sequence).
read-line
Reads a string from the keyboard or from an open file
(read-line [file-desc])
If read-line encounters the end of the file, it returns nil; otherwise it returns the string
that it read.
For example, assuming that f is a valid open file pointer,
(read-line f)
returns the next input line from the file, or returns nil if the end-of-file has been reached.
redraw
Redraws the current viewport or a specified object (entity) in the current
viewport
Action
Show entity
read-line
408
Action
Highlight entity
Unhighlight entity
If ename is the header of a complex entity (a polyline or a block reference with attributes),
it processes the main entity and all its subentities if the mode argument is positive. If the
mode argument is negative, redraw operates on only the header entity.
The redraw function always returns nil.
The use of entity highlighting (mode 3) must be balanced with entity unhighlighting
(mode 4).
The REDRAW command has no effect on highlighted or hidden entities; however, a
REGEN forces the entities to redisplay in their normal manner.
regapp
Registers an application name with the current AutoCAD drawing in
preparation for using extended object data
(regapp application)
The application argument is a string up to 31 characters long that adheres to the symbol-naming conventions. An application name can contain letters, digits, and the special
characters dollar sign ($), hyphen (-), and underscore (_). It cannot contain spaces. Letters in the name are converted to upper case.
If an application of the same name has already been registered, this function returns nil;
otherwise it returns the name of the application.
If registered successfully, the application name is entered into the APPID symbol table.
This table maintains a list of the applications that are using extended data in the drawing.
(regapp "ADESK_4153322344")
(regapp "DESIGNER-v2.1-124753")
It is recommended that you pick a unique application name. One way of ensuring this is
to adopt a naming scheme that uses the company or product name and a unique number
(like your telephone number or the current date/time). The product version number can
409
rem
Divides the first number by the second, and returns the remainder
repeat
Evaluates each expression a specified number of times, and returns the value of
the last expression
rem
410
reverse
Returns a list with its elements reversed
(reverse lst)
(reverse ((a) b c))
returns (C B (A))
rtos
Converts a number into a string
String format
Scientific
Decimal
Fractional
411
The mode and precision arguments correspond to the system variables LUNITS and
LUPREC. If you omit the arguments, rtos uses the current settings of LUNITS and
LUPREC. The UNITMODE variable affects the returned string when engineering, architectural, or fractional units are selected (a mode value of 3, 4, or 5).
set
Sets the value of a quoted symbol name to an expression
If set is used with an unquoted symbol name, it can assign a new value to another symbol
indirectly. For instance, given the previous examples
(set b 640)
returns 640
and assigns the value 640 to symbol a, because that is what symbol b contains.
set_tile
Sets the value of a dialog box tile
set
412
setcfg
Writes application data to the AppData section of the acad.cfg file
The following code sets the WallThk parameter in the AppData/ArchStuff section to 8
and returns the string "8":
(setcfg "AppData/ArchStuff/WallThk" "8") returns "8"
setenv
Sets a system environment variable to a specified value
413
setfunhelp
Registers a user-defined command with the Help facility so that the appropriate
help file and topic are called when the user requests help on that command
Command: myfun
gimme: help
Assuming that the AutoCAD Help file myhelp.ahp exists in the support path, AutoCAD
displays the Help dialog with the topic myfun from the file myapp.ahp.
setfunhelp
414
setq
Sets the value of a symbol or symbols to associated expressions
returns 5.0
415
and sets the symbol a to 5.0. Whenever a is evaluated, it evaluates the real number 5.0.
(setq b 123 c 4.7)
(setq s "it")
(setq x (a b))
returns 4.7
returns "it"
returns (A B)
setvar
Sets an AutoCAD system variable to a specified value
and sets the AutoCAD fillet radius to 0.5 units. For system variables with integer values,
the supplied value must be between 32,768 and +32,767.
Some AutoCAD commands obtain the values of system variables before issuing any
prompts. If you use setvar to set a new value while a command is in progress, the new
value might not take effect until the next AutoCAD command.
When using the setvar function to change the AutoCAD system variable ANGBASE,
the value argument is interpreted as radians. This differs from the AutoCAD SETVAR
command, which interprets this argument as degrees. When using the setvar function to
change the AutoCAD system variable SNAPANG, the value argument is interpreted as
radians relative to the AutoCAD default direction for angle 0, which is east or 3 oclock.
This also differs from the SETVAR command, which interprets this argument as degrees
relative to the ANGBASE setting.
The UNDO command does not undo changes made to the CVPORT system variable by
the setvar function.
setvar
416
You can find a list of the current AutoCAD system variables in System Variables, in the
Command Reference.
sin
Returns the sine of an angle as a real number expressed in radians
(sin ang)
The ang argument must be an angle expressed in radians.
(sin 1.0)
(sin 0.0)
returns 0.841471
returns 0.0
setview
Establishes a view for a specified viewport
417
slide_image
Displays an AutoCAD slide in the currently active dialog box image tile
The first (upper-left) corner of the slideits insertion pointis located at (x1,y1), and
the second (lower-right) corner is located at the relative distance (wid,hgt) from the first
(wid and hgt must be positive values). The origin (0,0) is the upper-left corner of the
image. You obtain the coordinates of the lower-right corner by calling the dimension
functions (dimx_tile and dimy_tile).
snvalid
Checks the symbol table name for valid characters
slide_image
418
sqrt
Returns the square root of a number as a real number
(sqrt num)
(sqrt 4)
(sqrt 2.0)
returns 2.0
returns 1.41421
ssadd
Adds an object (entity) to a selection set, or creates a new selection set
419
ssdel
Deletes an object (entity) from a selection set
ssget
Prompts the user to select objects (entities), and returns a selection set
ssdel
420
Selection sets can contain objects from both paper and model space, but when the selection set is used in an operation, objects from the space not currently in effect are filtered
out. Selection sets returned by ssget contain main entities only (no attributes or polyline
vertices).
Asks the user for a general object selection
and places those objects in a selection set
(ssget "P")
Creates a selection set of the most recently
selected objects
(ssget "L")
Creates a selection set of the last visible
object added to the database
(ssget "I")
Creates a selection set of the objects in the
implied selection set (those selected while
PICKFIRST is in effect)
(ssget (2 2))
Creates a selection set of the object passing
through (2,2)
(ssget "W" (0 0) (5 5)) Creates a selection set of the objects inside
the window from (0,0) to (5,5)
(ssget "C" (0 0) (1 1)) Creates a selection set of the objects crossing
the box from (0,0) to (1,1)
(ssget "X")
Creates a selection set of all objects in the
database
(ssget "X" filter-list)
Scans the database and creates a selection
set of objects matching the filter-list
(ssget filter-list)
Asks the user for a general object selection
and places only those objects matching the
filter-list in a selection set
(ssget "P" filter-list)
Creates a selection set of the most recently
selected objects that match the filter-list
(ssget)
The following examples of ssget require that a list of points be passed to the function.
The pt_list variable cannot contain points that define zero-length segments.
(setq pt_list ((1 1)(3 1)(5 2)(2 4)) )
(ssget "WP" pt_list)
(ssget "CP" pt_list)
(ssget "F" pt_list)
(ssget "WP" pt_list filter-list)
the filter-list
The selected objects are highlighted only when ssget is used with no arguments. Selection sets consume AutoCAD temporary file slots, so AutoLISP is not permitted to have
more than 128 open at once. If this limit is reached, AutoCAD refuses to create any more
selection sets and returns nil to all ssget calls. To close an unneeded selection set variable, set it to nil.
A selection set variable can be passed to AutoCAD in response to any Select objects
prompt at which selection by Last is valid. It selects all the objects in the selection set variable.
421
Using the ssget filter list, you can select all objects containing extended data for a particular application. You do this by using the 3 group code, as in
(ssget "P" ((0 . "CIRCLE") (-3 ("APPNAME"))))
This selects all circles containing data for the "APPNAME" application.
For more information, see Selection Set Filter Lists and Filtering for Extended Data.
Relational Tests
Unless otherwise specified, an equals test is implied for each item in the filter-list.
For numeric groups (integers, reals, points, and vectors) you can specify other relations
by including a special 4 group code that specifies a relational operator. The value of a 4
group is a string that indicates the test operator to be applied to the next group in the filter
list.
(ssget "X" ((0 . "CIRCLE") (-4 . ">=") (40 . 2.0)))
selects all circles whose radius (group code 40) is greater than or equal to 2.0.
The following table shows the possible operators.
Relational operators for selection set filter lists
Operator
Description
"*"
"="
Equals
"!="
Not equal to
"/="
Not equal to
"<>"
Not equal to
"<"
Less than
"<="
">"
Greater than
ssget
422
Description
">="
"&"
"&="
The use of relational operators depends on the kind of group you are testing:
All relational operators except for the bitwise operators ("&" and "&=") are valid for
both real- and integer-valued groups.
The bitwise operators "&" and "&=" are valid only for integer-valued groups. The bitwise AND, "&", is true if ((integer_group & filter)
/= 0)that is, if any of the bits set in the mask are also set in the integer group. The
bitwise masked equals, "&=", is true if ((integer_group & filter) = filter)that is, if all bits set in the mask are also set in the integer_group (other bits
might be set in the integer_group but are not checked).
For point groups, the X, Y, and Z tests can be combined into a single string, with each
operator separated by commas (for example, ">,>,*"). If an operator is omitted from
the string (for example, "=,<>" leaves out the Z test), the anything goes operator,
"*", is assumed.
Direction vectors (group type 210) can be compared only with the operators "*", "=",
and "!=" (or one of the equivalent not equal strings).
You cannot use the relational operators with string groups; use wild-card tests instead.
423
Encloses
Ending
operator
"<AND"
"AND>"
"<OR"
"OR>"
"<XOR"
Two operands
"XOR>"
"<NOT"
One operand
"NOT>"
With the grouping operators, an operand is an entity-field group, a relational operator followed by an entity-field group, or a nested expression created by these operators. The following is an example of grouping operators in a filter list:
(ssget "X" ((-4 . "<OR")
(-4 . "<AND")
(0 . "CIRCLE")
(40 . 1.0)
(-4 . "AND>")
(-4 . "<AND")
(0 . "LINE")
(8 . "ABC")
(-4 . "AND>")
(-4 . "OR>"))
)
This selects all circles with radius 1.0, plus all lines on layer "ABC".
Because the grouping operators are not case-sensitive, you can also use their lowercase
equivalents: "<and", "and>", "<or", "or>", "<xor", "xor>", "<not", and "not>".
ssget
424
ssgetfirst
Determines which objects are selected and gripped
(ssgetfirst)
Returns a list of two selection sets similar to those passed to sssetfirst. The first element in the list is a selection set of entities that are gripped but not selected. The second
element is a selection set of entities that are both gripped and selected. Either (or both)
elements of the list can be nil.
Only entities from the current drawings model space and paper space, not nongraphical
objects or entities in other block definitions, can be analyzed by this function.
sslength
Returns an integer containing the number of objects (entities) in a selection set
(sslength ss)
The number is returned as a real if it is greater than 32,767. Selection sets never contain
duplicate selections of the same entity.
(setq sset (ssget "L")) Places the last object in selection set sset
(sslength sset)
returns 1
ssmemb
Tests whether an object (entity) is a member of a selection set
425
ssname
Returns the object (entity) name of the indexed element of a selection set
(ssname ss index)
The index argument must be an integer. If index is negative or greater than the highest
numbered entity in the selection set, nil is returned. The first element in the set has an
index of zero. Entity names in selection sets obtained with ssget always are names of
main entities. Subentities (attributes and polyline vertices) are not returned. (The entnext function allows access to them. See entnext.)
(setq sset (ssget))
Creates a selection set named sset
(setq ent1 (ssname sset 0))
Gets name of first entity in sset
(setq ent4 (ssname sset 3))
Gets name of fourth entity in sset
To access entities beyond the 32767th one in a selection set, you must supply the index
argument as a real. For example:
(setq entx (ssname sset 50843.0)) Gets name of 50844th entity in sset
ssnamex
Retrieves information about how a selection set was created
(ssnamex ss [index])
This function returns the entity name of the element specified by index from the selection set ss along with data that describes how the entity was selected. If the index argument is not supplied, this function returns a list containing the entity names of all of the
elements in the selection set along with data that describes how each of the entities was
selected.
ssname
426
The data returned by ssnamex takes the form of a list of lists that contains information
that either describes an entity and its selection method or a polygon that was used to select
one or more entities. Each sub-list that describes the selection of a particular entity comprises three parts: the selection method ID (an integer >= 0), the entity name of the
selected entity, and selection method specific data that describes how the entity was
selected.
((sel_id1 ename1 (data))(sel_id2 ename2 (data)) ... )
Description
Pick
Window or WPolygon
Crossing or CPolygon
Fence
Each sub-list that describes a polygon thats used during entity selection takes the form of
a polygon ID (an integer < 0), followed by point descriptions.
(polygon_id point_description_1 point_description_n... )
427
Description
Infinite line
Ray
Line segment
The unit_or_offset_vector is returned when the view point is something other than
0,0,1.
The data associated with Pick (type 1) entity selections is a single point description. For
example, the following record is returned for the selection of an entity picked at 1,1 in
plan view of the WCS:
(1 <Entity name: 60000064> (0 (1.0 1.0 0.0) ) )
The data associated with an entity selected with the Window, WPolygon, Crossing, or
CPolygon method is the integer ID of the polygon that selected the entity. It is up to the
application to associate the polygon identifiers and make the connection between the
polygon and the entities it selected. For example, the following record is returned for an
entity selected by Crossing (note that the polygon ID is 1).
((3 <Entity name: 60000024> 1) (1 (0 (5.14828 7.05067 0.0) )
(0 (7.13676 7.05067 0.0) ) (0 (7.13676 4.62785 0.0) )
(0 (5.14828 4.62785 0.0) ) ) )
The data associated with Fence selections is a list of points descriptions for the points
where the fence and entity visually intersect. For example, the following record is
returned for a nearly vertical line intersected three times by a Z-shaped fence.
((4 <Entity name: 60000024> (0 (5.28135 6.25219 0.0) )
(0 (5.61868 2.81961 0.0) ) (0 (5.52688 3.75381 0.0) ) ) )
Only selection sets with entities from the current drawings model space and paper
spacenot nongraphical objects or entities in other block definitionscan be retrieved
by this function.
ssnamex
428
sssetfirst
Sets which objects are selected and gripped
startapp
Starts a Windows application
If an argument has embedded spaces, it must be surrounded by literal double quotes. For
example, to edit the file my stuff.txt with Notepad use the following syntax:
(startapp "notepad.exe" "\"my stuff.txt\"")
429
start_dialog
Displays a dialog box and begins accepting user input
(start_dialog)
You must first initialize the dialog box by a previous new_dialog call. The dialog box
remains active until an action expression or callback function calls done_dialog. Usually done_dialog is associated with the tile whose key is "accept" (typically the OK
button) and the tile whose key is "cancel" (typically the Cancel button).
The start_dialog function has no arguments. It returns the optional status passed to
done_dialog. The default value is 1 if the user pressed OK, 0 if the user pressed Cancel,
or -1 if all dialog boxes were terminated with term_dialog. But if done_dialog is
passed an integer status greater than 1, start_dialog returns this value, whose meaning depends on the application.
start_image
Starts the creation of an image in the dialog box tile
(start_image key)
Subsequent calls to fill_image, slide_image, and vector_image affect this image
until the application calls end_image. The key argument is a string that specifies the dialog box tile. The key argument is case-sensitive.
Do not use the set_tile function between start_image and end_image function
calls.
start_dialog
430
start_list
Starts the processing of a list in the list box or in the pop-up list dialog box tile
Description
The index argument is ignored unless the start_list call begins a change operation
(1), in which case index indicates the list item to change by the subsequent add_list
call. The index is zero based. If you dont specify operation, it defaults to 3 (create
new list), and if you specify operation but not index, the index defaults to 0.
Subsequent calls to add_list affect the list started by start_list until the application
calls end_list.
Do not use the set_tile function between start_list and end_list function calls.
431
strcase
Returns a string where all alphabetic characters have been converted to upper
case or lower case
returns "SAMPLE"
returns "sample"
The strcase function will correctly handle case mapping of the currently configured
character set.
strcat
Returns a string that is the concatenation of multiple strings
returns "about"
returns "abc"
returns "ac"
strlen
Returns an integer that is the number of characters in a string
(strlen [string]...)
If multiple string arguments are provided, it returns the sum of the lengths of all arguments. Omitting the arguments or entering an empty string returns 0 (zero).
(strlen "abcd")
returns 4
(strlen "ab")
returns 2
(strlen "one" "two" "four" returns 10
(strlen)
returns 0
strcase
432
(strlen "")
returns 0
subst
Searches a list for an old item and returns a copy of the list with a new item
substituted in place of every occurrence of the old item
When used in conjunction with assoc, subst provides a convenient means of replacing
the value associated with one key in an association list.
(setq who ((first john) (mid q) (last public)))
(setq old (assoc first who) sets old to (FIRST JOHN)
new (first j)
sets new to (FIRST J)
)
(subst new old who) returns ((FIRST J)(MID Q)(LAST PUBLIC))
substr
Returns a substring of a string
433
The first character of string is character number 1. This differs from other functions that
process elements of a list (like nth and ssname) that count the first element as 0.
(substr "abcde" 2)
(substr "abcde" 2 1)
(substr "abcde" 3 2)
returns "bcde"
returns "b"
returns "cd"
tablet
Retrieves and sets digitizer (tablet) calibrations
An integer. If the code you pass equals 0, tablet returns the current calibration; in this case, the remaining arguments must be omitted. If the code you pass equals 1, tablet sets the calibration
according to the arguments that follow; in this case, you must provide the other arguments.
row1, row2,
row3
direction
If the direction specified isnt normalized, tablet corrects it, so the direction it
returns when you set the calibration may differ from the value you passed. In a similar
way, the third element in row3 (Z) should always equal 1: tablet returns it as 1 even if
the row3 in the list specified a different value.
If tablet fails, it returns nil and sets the ERRNO system variable to a value that indicates the reason for the failure. This can happen if the digitizer is not a tablet.
A very simple transformation that can be established with tablet is the identity transformation:
(tablet 1 (1 0 0) (0 1 0) (0 0 1) (0 0 1))
With this transformation in effect, AutoCAD will receive, effectively, raw digitizer coordinates from the tablet. For example, if you pick the point with digitizer coordinates
tablet
434
(5000,15000), AutoCAD will see it as the point in your drawing with those same coordinates.
The TABMODE system variable allows AutoLISP routines to toggle the tablet on and
off.
tblnext
Finds the next item in a symbol table
might return
((0 . "LAYER")
Symbol type
(2 . "0")
Symbol name
(70 . 0)
Flags
(62 . 7)
Color number, negative if off
(6 . "CONTINUOUS")
Linetype name
)
Note that there is no 1 group. AutoCAD remembers the last entry returned from each
table and returns the next one each time tblnext is called for that table. When you begin
scanning a table, be sure to supply a non-nil second argument to rewind the table and to
return the first entry.
Entries retrieved from the block table include a 2 group with the entity name of the first
entity in the block definition (if any). Thus, given a block called BOX,
(tblnext "block")
435
might return
((0 . "BLOCK")
(2 . "BOX")
(70 . 0)
(10 9.0 2.0 0.0)
(-2 . <Entity name: 40000126>)
)
Symbol type
Symbol name
Flags
Origin X,Y,Z
First entity
The entity name in the 2 group is accepted by entget and entnext, but not by other
entity access functions. For example, you cannot use ssadd to put it in a selection set. By
providing the 2 group entity name to entnext, you can scan the entities comprising a
block definition; entnext returns nil after the last entity in the block definition.
If a block contains no entities, the 2 group returned by tblnext is the entity name of its
endblk entity.
tblobjname
Returns the entity name of a specified symbol table entry
tblsearch
Searches a symbol table for a symbol name
might return
((0 . "STYLE")
Symbol name
tblobjname
436
(70 . 0)
(40 . 0.0)
(41 . 1.0)
(50 . 0.0)
(71 . 0)
(3 . "txt")
(4 . "")
Flags
Fixed height
Width factor
Obliquing angle
Generation flags
Primary font file
Bigfont file
Normally, tblsearch has no effect on the order of entries retrieved by tblnext. However, if tblsearch is successful and the setnext argument is present and non-nil, the
tblnext entry counter is adjusted so that the following tblnext call returns the entry
after the one returned by this tblsearch call.
term_dialog
Terminates all current dialog boxes as if the user had canceled each of them
(term_dialog)
If an application is terminated while any DCL files are open, AutoCAD automatically
calls term_dialog. This function is used mainly for aborting nested dialog boxes. The
term_dialog function always returns nil.
terpri
Prints a newline to the command line
(terpri)
The terpri function is not used for file I/O. To write a newline to a file, use prin1,
princ, or print.
437
textbox
Measures a specified text object, and returns the diagonal coordinates of a box
that encloses the text
(textbox elist)
The elist argument is an entity definition list in the form returned by entget. It must
define a text object. If fields that define text parameters other than the text itself are omitted from elist, the current (or default) settings are used. If textbox is successful, it
returns a list of two points; otherwise it returns nil.
The minimum list accepted by textbox is that of the text itself.
(textbox ((1 . "Hello world.")))
In this case, textbox would use the current defaults for text to supply the remaining
parameters.
The points returned by textbox describe the bounding box of the text object as if its
insertion point is located at (0,0,0) and its rotation angle is 0. The first list returned is generally the point (0.0 0.0 0.0) unless the text object is oblique or vertical, or it contains letters with descenders (such as g and p). The value of the first point list specifies the offset
from the text insertion point to the lower-left corner of the smallest rectangle enclosing
the text. The second point list specifies the upper-right corner of that box. Regardless of
the orientation of the text being measured, the point list returned always describes the bottom-left and upper-right corners of this bounding box.
textpage
Switches from the graphics screen to the text screen
(textpage)
The textpage function is equivalent to textscr. This function always returns nil.
textbox
438
textscr
Switches from the graphics screen to the text screen (like the AutoCAD Flip
Screen function key)
(textscr)
The textscr function always returns nil.
trace
Aids in AutoLISP debugging
(trace function...)
The trace function sets the trace flag for the specified functions. Each time a specified
function is evaluated, a trace display appears showing the entry of the function
(indented to the level of calling depth) and prints the result of the function.
(trace my-func)
returns MY-FUNC
and sets the trace flag for function MY-FUNC. The trace function returns the last function
name passed to it.
trans
Translates a point (or a displacement) from one coordinate system to another
439
ment rather than as a point. The from and to arguments can be an integer code (as specified in the following table), an entity name, or a 3D extrusion vector.
Coordinate system codes
Code
Coordinate system
World (WCS)
Display:
DCS of current viewport when used with code 0 or 1
DCS of current model space viewport when used with code 3
If you use an entity name for the from or to arguments it must be passed as returned by
the entnext, entlast, entsel, nentsel, and ssname functions. This lets you translate a point to and from the Object Coordinate System (OCS) of a particular object. (For
some objects, the OCS is equivalent to the WCS; for these objects, conversion between
OCS and WCS is a null operation.) A 3D extrusion vector (a list of three reals) is another
method of converting to and from an objects OCS. However, this does not work for those
objects whose OCS is equivalent to the WCS.
The trans function returns a 3D point (or displacement) in the requested to coordinate
system. For example, given a UCS that is rotated 90 degrees counterclockwise around the
World Z axis,
(trans (1.0 2.0 3.0) 0 1)
(trans (1.0 2.0 3.0) 1 0)
For example, to draw a line from the insertion point of a piece of text (without using
Osnap), you convert the text objects insertion point from the text objects OCS to the
UCS.
(trans text-insert-point text-ename 1)
You can then pass the result to the From point prompt.
Conversely, you must convert point (or displacement) values to their destination OCS
before feeding them to entmod. For example, if you want to move a circle (without using
the MOVE command) by the UCS-relative offset (1,2,3), you need to convert the displacement from the UCS to the circles OCS:
(trans (1 2 3) 1 circle-ename)
Then you add the resulting displacement to the circles center point.
trans
440
For example, if you have a point entered by the user and want to find out which end of a
line it looks closer to, you convert the users point from the UCS to the DCS.
(trans user-point 1 2)
Then you convert each of the lines endpoints from the OCS to the DCS.
(trans endpoint line-ename 2)
From there you can compute the distance between the users point and each endpoint of
the line (ignoring the Z coordinates) to determine which end looks closer.
The trans function can also transform 2D points. It does this by filling in the Z coordinate with an appropriate value. The Z component used depends on the from coordinate
system that was specified and on whether the value is to be converted as a point or as a
displacement. If the value is to be converted as a displacement, the Z value is always 0.0;
if the value is to be converted as a point, the filled-in Z value is determined as shown in
the following table.
Converted 2D point Z values
From
Filled-in Z value
WCS
0.0
UCS
Current elevation
OCS
0.0
441
Filled-in Z value
DCS
PSDCS
type
Returns the type of a specified item
(type item)
The types are returned as one of the atoms shown in the following table:
Symbol types
Type
Description
Type
Description
REAL
Floating-point numbers
SUBR
Internal functions
FILE
File descriptors
EXSUBR
STR
Strings
PICKSET
Selection sets
INT
Integers
ENAME
Entity names
SYM
Symbols
PAGETB
LIST
type
442
then
(type a)
(type a)
(type f)
(type r)
(type s)
(type x)
(type +)
(type nil)
returns SYM
returns INT
returns FILE
returns REAL
returns STR
returns LIST
returns SUBR
returns nil
unload_dialog
Unloads a DCL file
(unload_dialog dcl_id)
Unloads the DCL file associated with dcl_id (which was obtained from a previous
new_dialog call).
Always returns nil.
untrace
Clears the trace flag for the specified functions
(untrace function...)
Returns the last function name.
443
The following code clears the trace flag for function MY-FUNC:
(untrace my-func)
returns MY-FUNC
vector_image
Draws a vector in the currently active dialog box image
(vector_image x1 y1 x2 y2 color)
This function draws a vector in the currently active dialog box image (opened by
start_image) from the point (x1,y1) to (x2,y2). The color parameter is an AutoCAD
color number or one of the logical color numbers shown in the following table.
Symbolic names for the color attribute
Color
number
ADI
mnemonic
Description
BGLCOLOR
15
DBGLCOLOR
16
DFGLCOLOR
18
LINELCOLOR
The origin (0,0) is the upper-left corner of the image. You can obtain the coordinates of
the lower-right corner by calling the dimension functions (dimx_tile and dimy_tile).
vector_image
444
ver
Returns a string that contains the current AutoLISP version number
(ver)
The ver function should be used (with equal) to check the compatibility of programs.
The string takes the form
"AutoLISP Release X.X (nn)"
where X.X is the current version number and nn is a two letter language description.
(ver) might return "AutoLISP Release 14.0 (en)"
(es) Spanish
(de) German
(it) Italian
(fr) French
WARNING! Before using ver in a Visual LISP program, you must initialize the variable *al-ver* in native AutoLISP. Use (setq *al-ver* (ver)) to initialize the variable. An error will result if you try to use ver without initializing *al-ver*.
vl-acad-defun
Defines a Visual LISP function symbol as a function in native AutoLISP (VLISP
Function)
(vl-acad-defun symbol)
symbol - function name.
Returns:
Indeterminate
445
vl-acad-undefun
Undefines a Visual LISP function symbol so that it is no longer recognized as a
function in native AutoLISP (VLISP Function)
(vl-acad-undefun symbol)
symbol - function name.
Returns:
T, if successful
nil, if unsuccessful (for example, the function was not defined in AutoLISP)
vl-consp
Determines whether or not a list is nil (VLISP Function)
(vl-consp list-variable)
The vl-consp function determines whether a variable contains a valid list definition. It
returns T if list-variable is a non-nil list, and nil if it is not.
(vl-consp nil)
returns
(vl-consp t)
returns
(vl-consp (cons 0 "LINE"))returns
nil
nil
T
vl-directory-files
Lists all files in a given directory (VLISP Function)
directory - (string) directory to collect files for; if nil or absent, use current directory
pattern - (string) DOS pattern for file name; if nil or absent, use "*.*"
directories - (fixnum) specifies if returned list should include directory names:
-1 - directories only
0 - files and directories (default)
1 - files only;
vl-acad-undefun
446
Returns a list of the files/sub-directories from the given directory which matches the pattern.
Examples:
_$ (vl-directory-files "c:/acadwin" "acad*.exe")
("ACAD.EXE" "ACADAPP.EXE" "ACADL.EXE" "ACADPS.EXE")
_$ (vl-directory-files "e:/acadwin" nil -1)
("." ".." "SUPPORT" "SAMPLE" "ADS" "FONTS" "IGESFONT" "SOURCE" "ASE")
_$ (vl-directory-files "E:/acad13c4" nil -1)
("." ".." "WIN" "COM" "DOS")
vl-every
Checks whether the predicate is true for every element combination (VLISP
Function)
Examples:
Check whether there are any empty files in the current directory:
_$ (vl-every
(lambda (fnm) (> (vl-file-size fnm) 0))
(vl-directory-files nil nil 1) )
T
447
(0 2 3.14159 3.14159 4)
_$ (vl-every <= nlst (cdr nlst))
T
vl-exe-filename
Returns full filename of the current Visual LISP executable (VLISP Function)
(vl-exe-filename)
Returns:
A string containing the file name
Example:
_$ (vl-exe-filename)
"C:/PROGRA~1/AUTOCA~1/VLISP/VLIDE.ARX"
vl-file-copy
Copies or appends the contents of one file to another file (VLISP Function)
vl-exe-filename
448
Example:
_$ (vl-file-copy "c:/autoexec.bat" "c:/newauto.bat")
1417
vl-file-delete
Deletes a file (VLISP Function)
(vl-file-delete "filename")
filename - string containing name of file to be deleted
Returns:
T, if successful
nil, if delete failed
vl-file-directory-p
Determines if a file name refers to a directory (VLISP Function)
(vl-file-directory-p "filename")
filename - file to be tested
Returns:
T, if filename is the name of a directory, nil if it is not
Examples:
_$ (vl-file-directory-p "sample")
T
_$ (vl-file-directory-p "yinyang")
nil
_$ (vl-file-directory-p "c:/program files/autocad r14")
T
_$ (vl-file-directory-p "c:/program files/autocad r14/vlisp/yinyang.lsp")
nil
449
vl-file-rename
Renames a file (VLISP Function)
Example:
(vl-file-rename "c:/newauto.bat" "c:/myauto.bat")
T
vl-file-size
Determines the size of a file, in bytes (VLISP Function)
(vl-file-size "filename")
filename - name of file to be sized
Returns:
nil - filename is not readable
vl-file-rename
450
vl-file-systime
Returns last modification time of the specified file (VLISP Function)
(vl-file-systime "filename")
filename - name of file to be checked
Returns:
A list containing the modification date and time, or nil, if the file is not found.
The list returned contains the following elements:
year month day-of-week, day-of-month, hours, minutes, seconds
Note that Monday is day 1 of day-of-week, Tuesday is day 2, etc.
Example:
_$ (vl-file-systime "c:/program files/autocad r14/vlisp/sample/yinyang.lsp")
(1998 4 3 8 10 6 52 0)
The file was last modified in1998, in the 4th month of the year (April), the 3rd day of the
week (Wednesday), at 10:06:52.
vl-filename-base
Returns the name of a file, after stripping out the directory path and extension
(VLISP Function)
(vl-filename-base filename)
filename - file name
The vl-filename-base function does not check to see if the file exists.
Returns:
Uppercase filename, with directory and extension stripped
Examples:
_$ (vl-filename-base "c:\\acadwin\\acad.exe")
"ACAD"
_$ (vl-filename-base "c:\\acadwin")
"ACADWIN"
451
vl-filename-directory
Returns the directory path of a file, after stripping out the name and extension
(VLISP Function)
(vl-filename-directory filename)
filename - compete file name, including path
The vl-filename-directory function does not check to see if a file of this name
exists. Slashes (/) and backslashes (\) are accepted as directory delimiters.
Returns:
Directory portion of filename, in upper case
Examples:
_$ (vl-filename-directory "c:\\acadwin\\acad.exe")
"C:\\ACADWIN"
_$ (vl-filename-directory "acad.exe")
""
vl-filename-extension
Returns the extension from a file name, after stripping out the rest of the name
(VLISP Function)
(vl-filename-extension filename)
filename - file name, including extension
The vl-filename-extension function does not check to see if a file of this name
exists
Returns:
Extension portion of filename, starting with a period (.) and converted to uppercase
Examples:
(vl-filename-extension "c:\\acadwin\\acad.exe")
".EXE"
(vl-filename-extension "c:\\acadwin\\acad")
nil
vl-filename-directory
452
vl-filename-mktemp
Calculates a unique file name to be used for a temporary file (VLISP Function)
453
vl-init
Mimics AutoLISP initialization on an Open or New drawing command (VLISP
Function)
(vl-init)
Returns:
T, if initialization is successful
vl-list*
Constructs and returns a list (VLISP Function)
Returns:
An atom, if object is an atom and no more objects are specified
A dotted pair, if object and all more-objects specified are atoms
A dotted list, if the last argument is an atom and neither of the previous conditions are
true
A list, if none of the previous statements are true
Examples:
(vl-list* 1)
1
(vl-list* 0 "text")
(0 . "TEXT")
(vl-list* 1 2 3)
(1 2 . 3)
(vl-list* 1 2 (3 4))
(1 2 3 4)
vl-init
454
vl-list->string
Combines the characters associated with a list of integers into a string (VLISP
Function)
(vl-list->string char-codes-list)
char-codes-list - list of non-negative integers; integer must be less than 256
Returns:
A string of characters, with each character based on one of the integers supplied in
char-codes-list
Examples:
(vl-list->string nil)
""
(vl-list->string (49 50))
"12"
vl-list-length
Calculates list length of a true list (VLISP Function)
(vl-list-length list-or-cons-object)
list-or-cons-object - a true or dotted list.
Returns:
An integer containing the list length, if the argument is a true list
nil, if list-or-cons-object is a circular or dotted list
Compatibility note: The vl-list-length function returns nil for a dotted list, while
the corresponding Common Lisp function issues an error message if the argument is a dotted list.
Examples:
(vl-list-length nil)
0
(vl-list-length (1 2))
2
(vl-list-length (1 2 . 3))
nil
455
vl-member-if
Determines if the predicate is true for one of the list members (VLISP Function)
Examples:
(COMMAND "_.LINE" (0 50) (50 50) nil)
nil
(vl-member-if
(lambda (x) (= (cdr x) "AcDbLine"))
(entget (entlast)))
((100 . "AcDbLine") (10 0.0 50.0 0.0) (11 50.0 50.0 0.0) (210 0.0 0.0 1.0))
vl-member-if-not
Determines if the predicate is nil for one of the list members (VLISP Function)
vl-member-if
456
Examples:
_$ (vl-member-if-not atom (1 "Str" (0 . "line") nil t))
((0 . "line") nil T)
vl-position
Returns the index of the specified list item (VLISP Function)
457
vl-prin1-to-string
Returns the string representation of any LISP object as if it were output by the
prin1 function (VLISP Function)
(vl-prin1-to-string object)
object - any LISP object
Returns:
String-printed representation of object, as output by prin1
Examples:
_$ (vl-prin1-to-string "abc")
"\"abc\""
_$ (vl-prin1-to-string "c:\\acadwin")
"\"C:\\\\ACADWIN\""
_$ (vl-prin1-to-string my-var)
"MY-VAR"
vl-princ-to-string
Returns the string representation of any LISP object as if it were output by the
princ function (VLISP Function)
(vl-princ-to-string object)
object - any LISP object
Returns:
String-printed representation of object, as output by princ
Examples:
_$ (vl-princ-to-string "abc")
"abc"
_$ (vl-princ-to-string "c:\\acadwin")
"C:\\ACADWIN"
_$ (vl-princ-to-string my-var)
"MY-VAR"
vl-prin1-to-string
458
vl-registry-delete
Deletes the specified key or value from the Windows Registry (VLISP Function)
Returns:
T if successful, nil otherwise
Example:
_$ (vl-registry-write "HKEY_CURRENT_USER\\Test" "" "test data")
"test data"
_$ (vl-registry-read "HKEY_CURRENT_USER\\Test")
"test data"
_$ (vl-registry-delete "HKEY_CURRENT_USER\\Test")
T
vl-registry-descendents
Returns a list of subkeys or value names for the specified Registry key (VLISP
Function)
459
Example:
$ (vl-registry-descendents "HKEY_LOCAL_MACHINE\\SOFTWARE")
("Description" "Program Groups" "ORACLE" "ODBC" "Netscape" "Microsoft")
vl-registry-read
Returns data stored in the Windows Registry for the specified key/value pair
(VLISP Function)
vl-registry-write
Creates a key in the Windows Registry (VLISP Function)
vl-registry-read
460
Returns:
val-data, if successful, nil otherwise
Example:
_$ (vl-registry-write "HKEY_CURRENT_USER\\Test" "" "test data")
"test data"
_$ (vl-registry-read "HKEY_CURRENT_USER\\Test")
"test data"
vl-remove
Removes elements from a list (VLISP Function)
(T 0 "abc")
vl-remove-if
Returns all elements of the supplied list which fail the test function (VLISP
Function)
Returns:
A list containing all elements of list for which predicate-function returns nil
461
Examples:
_$ (vl-remove-if vl-symbolp (list pi t 0 "abc"))
(3.14159 0 "abc")
vl-remove-if-not
Returns all elements of the supplied list which pass the test function (VLISP
Function)
Returns:
A list containing all elements of list for which predicate-function returns a non-nil
value
Examples:
_$ (vl-remove-if-not vl-symbolp (list pi t 0 "abc"))
(T)
vl-some
Checks whether the predicate is not nil for one element combination (VLISP
Function)
vl-remove-if-not
462
The vl-some function passes the first element of each supplied list as an argument to the
test function, then the next element from each list, and so on. Evaluation stops as soon as
the predicate function returns non-nil for an argument combination or one of the lists
runs out.
Returns:
predicate value, if predicate function returned non-nil
nil, otherwise
Examples:
Check whether number list NLST has equal elements in sequence:
(setq nlst (list 0 2 pi pi 4))
(0 2 3.14159 3.14159 4)
(vl-some = nlst (cdr nlst))
T
vl-sort
Sorts the elements in a list according to a given compare function (VLISP
Function)
Returns:
A list containing the elements of list in the order specified by less?-function. Duplicate
elements may be eliminated from the list.
Examples:
Sort a list of numbers:
_$ (vl-sort (3 2 1 3) <)
(1 2 3) ; Note that only one 3 remains in the result list
463
vl-sort-i
Sorts the elements in a list according to a given compare function, and returns
the element index numbers (VLISP Function)
Returns:
A list containing the index values of the elements of list, sorted in the order specified
by less?-function. Duplicate elements will be retained in the result.
Examples:
Sort a list of characters in descending order:
_$ (vl-sort-i ("a" "d" "f" "c") >)
(2 1 3 0)
The sorted list order is "f" "d" "c" "a"; "f" is the 3rd element (index 2) in the original list,
"d" is the 2nd element (index 1) in the list, and so on.
Sort a list of numbers in ascending order:
_$ (vl-sort-i (3 2 1 3) <)
(2 1 3 0) ; Note that both occurrences of 3 are accounted for in the result list
vl-sort-i
464
vl-string->list
Converts a string into a list of character codes (VLISP Function)
(vl-string->list string)
Returns:
A list, each element of which is an integer representing the character code of the corresponding character in string
Examples:
_$ (vl-string->list "")
nil
_$ (vl-string->list "12")
(49 50)
vl-string-elt
Returns the ASCII representation of the character at a specified position in a
string (VLISP Function)
465
Example:
_$ (vl-string-elt "May the Force be with you" 8)
70
vl-string-left-trim
Removes the specified characters from the beginning of a string (VLISP
Function)
vl-string-mismatch
Returns the length of the longest common prefix for two strings, starting at
specified positions (VLISP Function)
vl-string-left-trim
466
Returns:
An integer
Examples:
_$ (vl-string-mismatch "VL-FUN" "VL-VAR")
3
_$ (vl-string-mismatch "vl-fun" "avl-var")
0
_$ (vl-string-mismatch "vl-fun" "avl-var" 0 1)
3
_$ (vl-string-mismatch "VL-FUN" "Vl-vAR")
1
_$ (vl-string-mismatch "VL-FUN" "Vl-vAR" 0 0 T)
3
vl-string-position
Looks for a character with the specified ascii code in a string (VLISP Function)
Examples:
_$ (vl-string-position (ascii "z") "azbzc")
1
_$ (vl-string-position 122 "azbzc")
1
_$ (vl-string-position (ascii "z") "azbzc" nil t)
3
Note in the previous example that vl-string-position returned the first occurrence
of the letter "z," but indicated its displacement counting back from the end of the string
467
vl-string-right-trim
Removes the specified characters from the end of a string (VLISP Function)
")
vl-string-search
Searches for the specified pattern in a string (VLISP Function)
vl-string-right-trim
468
vl-string-subst
Substitutes one string for another, within a string (VLISP Function)
vl-string-translate
Replaces characters in a string with a specified set of characters (VLISP
Function)
469
Returns:
The value of str after any substitutions have been made
Examples:
_$ (vl-string-translate "abcABC" "123123" "A is a, B is b, C is C")
"1 is 1, 2 is 2, 3 is 3"
_$ (vl-string-translate "abc" "123" "A is a, B is b, C is C")
"A is 1, B is 2, C is C"
vl-string-trim
Removes the specified characters from the beginning and end of a string (VLISP
Function)
Leave me alone
")
vl-symbol-name
Returns a string containing the name of a symbol (VLISP Function)
(vl-symbol-name symbol)
symbol - any LISP symbol
Returns:
A string containing the name of the supplied symbol argument
Examples:
vl-string-trim
470
_$ (vl-symbol-name S::STARTUP)
"S::STARTUP"
_$ (progn (setq sym my-var) (vl-symbol-name sym))
"MY-VAR"
_$ (vl-symbol-name 1)
; *** ERROR: bad argument type: symbolp 1
vl-symbol-value
Returns the current value bound to a symbol (VLISP Function)
(vl-symbol-value symbol)
symbol - any LISP symbol
This function is equivalent to the AutoLISP EVAL function, but does not call the LISP
evaluator.
Examples:
_$ (vl-symbol-value t)
T
_$ (vl-symbol-value PI)
3.14159
_$ (progn (setq sym PAUSE) (vl-symbol-value sym))
"\\"
vl-symbolp
Identifies whether or not a specified object is a symbol (VLISP Function)
(vl-symbolp object)
object - any LISP object
Returns:
T if object is a symbol
nil if object is not a symbol
Examples:
_$ (vl-symbolp t)
T
_$ (vl-symbolp nil)
471
nil
_$ (vl-symbolp 1)
nil
_$ (vl-symbolp (list 1))
nil
vlax-3D-point
Creates ActiveX-compatible 3D point structure (VLISP Function)
(vlax-3D-point list)
(vlax-3D-point x y [z])
list - a list of 2 or 3 numbers, representing points
x, y - numbers representing X and Y coordinates of a point
z - number (optional) representing Z coordinate of a point
Returns:
The structure created
Examples:
$ (vlax-3D-point 5 20)
(5.0 20.0 0.0)
_$ (vlax-3D-point (33.6 44.0 90.0))
(33.6 44.0 90.0)
vlax-add-cmd
Adds commands to a group (VLISP Function)
vlax-3D-point
472
ACRX_CMD_TRANSPARENT0x01
Command can be invoked while another command is active
Secondary flags:
ACRX_CMD_USEPICKSET0x02
When the pickfirst set is retrieved it is cleared within AutoCAD. Command will be
able to retrieve the pickfirst set. Command cannot retrieve nor set grips.
ACRX_CMD_REDRAW0x04
When the pickfirst set or grip set is retrieved, neither will be cleared within AutoCAD.
Command can retrieve the pickfirst set and the grip set.
If both ACRX_CMD_USEPICKSET and ACRX_CMD_REDRAW are set, the effect is
the same as if just ACRX_CMD_REDRAW is set. For more information on the flags,
refer to ObjectARX documentation.
Commands are added to VLC-<AppName> group (this group is also used in the regapp
function). No more than 50 commands can be added to a group.
Example:
The next function hello-autocad has no C: prefix, but we use vlax-add-cmd to make it visible as an ARX-style command at the Command: prompt
>(defun hello-autocad () (hello "Visual LISP"))
>(vlax-add-cmd "hello-autocad" hello-autocad)
vlax-curve-getArea
Returns the area inside the curve (VLISP Function)
(vlax-curve-getArea curve-obj)
curve-obj - VLA object to be measured
Returns:
Real number if successful, otherwise nil
473
vlax-curve-getDistAtParam
Returns the length of the curves segment from the curves beginning to the
specified point (VLISP Function)
vlax-curve-getDistAtPoint
Returns the length of the curves segment between the curves start point and the
specified point (VLISP Function)
vlax-curve-getEndParam
Returns the parameter of the endpoint of the curve (VLISP Function)
(vlax-curve-getEndParam curve-obj)
curve-obj - VLA object to be measured
Returns:
Real number if successful, otherwise nil
vlax-curve-getDistAtParam
474
vlax-curve-getEndPoint
Returns the end point (in WCS coordinates) of the curve (VLISP Function)
(vlax-curve-getEndPoint curve-obj)
curve-obj - VLA object to be measured
Returns:
3-d point list if successful, otherwise nil
vlax-curve-getParamAtDist
Distance along the curve from the beginning of the curve to the location of the
specified parameter (VLISP Function)
vlax-curve-getParamAtPoint
Returns the parameter of the curve at the point (VLISP Function)
475
vlax-curve-getPointAtDist
Returns the point (in WCS coordinates) along a curve at the distance specified by
the user (VLISP Function)
vlax-curve-getPointAtParam
Determines the point on the curve that corresponds to the param parameter and
returns the point (VLISP Function)
vlax-curve-getStartParam
Returns the start parameter on the curve (VLISP Function)
(vlax-curve-getStartParam curve-obj)
curve-obj - VLA object to be measured
Returns:
Real number if successful, otherwise nil
vlax-curve-getPointAtDist
476
vlax-curve-getStartPoint
Returns the start point (in WCS coordinates) of the curve (VLISP Function)
(vlax-curve-getStartPoint curve-obj)
curve-obj - VLA object to be measured
Returns:
3-d point list if successful, nil otherwise
vlax-curve-isClosed
Determines if the specified curve is closed (i.e., start point is same as end point)
(VLISP Function)
(vlax-curve-isClosed curve-obj)
curve-obj - VLA object to be tested
Returns:
T if the curve is closed, nil otherwise
vlax-curve-isPeriodic
Determines if the specified curve has an infinite range in both directions and
there is a period value dT, such that there is a point on curve at (u + dT) = point
on curve (u), for any parameter u. (VLISP Function)
(vlax-curve-isPeriodic curve-obj)
curve-obj - VLA object to be tested
Returns:
T if the curve is periodic, nil otherwise
477
vlax-curve-isPlanar
Determines if there is a plane that contains the curve (VLISP Function)
(vlax-curve-isPlanar curve-obj)
curve-obj - VLA object to be tested
Returns:
T if the there is a plane that contains the curve, nil otherwise
vlax-curve-getClosestPointTo
Returns the point (in WCS coordinates) on a curve that is nearest to the specified
point (VLISP Function)
vlax-curve-getClosestPointToProjection
Returns the point (in WCS coordinates) on a curve that is nearest to the specified
point (VLISP Function)
vlax-curve-isPlanar
478
vlax-curve-getFirstDeriv
Returns the first derivative (in WCS coordinates) of a curve at the specified
location (VLISP Function)
vlax-curve-getSecondDeriv
Returns the second derivative (in WCS coordinates) of a curve at the specified
location (VLISP Function)
479
vlax-dump-object
Lists an objects methods and properties (VLISP Function)
(vlax-dump-object obj)
obj - VLA object
Returns:
T, if successful, or an error message, if an invalid object name is supplied
Example
_$ (setq aa (vlax-get-acad-object))
#<VLA-OBJECT IAcadApplication 00b3b91c>
_$ (vlax-dump-object aa)
; IAcadApplication: AutoCAD Application Interface
; Property values:
; ActiveDocument (RO) = #<VLA-OBJECT IAcadDocument 01b52fac>
; Application (RO) = #<VLA-OBJECT IAcadApplication 00b3b91c>
; Caption (RO) = "AutoCAD - [Drawing.dwg]"
; FullName (RO) = "C:\\Program Files\\AutoCAD R14\\acad.exe"
; Height = 638
; Left = 264
; LocaleId (RO) = 1033
; Name (RO) = "AutoCAD"
; Path (RO) = "C:\\Program Files\\AutoCAD R14"
; Preferences (RO) = #<VLA-OBJECT IAcadPreferences 03a937cc>
; Top = 312
; Version (RO) = "14.01"
; Visible = -1
; Width = 987
T
vlax-dump-object
480
vlax-ename->vla-object
Transform entity to VLA object (VLISP Function)
(vlax-ename->vla-object entname)
entname - entity name
Returns:
VLA object
Example
_$ (setq e (car (entsel)))
<Entity name: 27e0540>
_$ (vlax-ename->vla-object e)
#<VLA-OBJECT IAcadLWPolyline 03f713a0>
vlax-erased-p
Determines whether an object was erased (VLISP Function)
(vlax-erased-p obj)
obj - VLA object
Returns:
T if the object was erased, nil otherwise
vlax-for
Iterates through a collection of objects evaluating each expression (VLISP Function)
481
vlax-get
Low-level property get function. May be used for custom ActiveX object (VLISP
Function)
vlax-get-acad-object
Retrieves the top level AutoCAD application object for the current AutoCAD
session (VLISP Function)
(vlax-get-acad-object)
Example:
_$ (setq aa (vlax-get-acad-object))
#<VLA-OBJECT IAcadApplication 00b3b91c>
vlax-get
482
vlax-invoke
Calls the specified method of an object (VLISP Function)
vlax-ldata-delete
Erases LISP data from a drawing dictionary (VLISP Function)
483
Examples:
_$ (vlax-ldata-put "dict" "key" (1))
(1)
_$ (vlax-ldata-delete "dict" "key")
T
_$ (vlax-ldata-delete "dict" "key")
nil
vlax-ldata-get
Retrieves LISP data from a drawing dictionary (VLISP Function)
vlax-ldata-list
Lists LISP data in a drawing dictionary (VLISP Function)
(vlax-ldata-list dict)
dict - VLA object or AutoCAD drawing entity object, or a string naming a global dictionary
Returns:
vlax-ldata-get
484
vlax-ldata-put
Stores LISP data in a drawing dictionary (VLISP Function)
vlax-ldata-test
Determines if data can be saved over a session boundary (VLISP Function)
(vlax-ldata-test data)
data - any LISP data to be tested
Returns:
T, if the data can be saved and restored over the session boundary
nil, if data cannot be saved and restored
485
vlax-map-collection
Applies a function to all objects in a collection (VLISP Function)
vlax-map-collection
486
vlax-method-applicable-p
Determines if an object supports a particular method (VLISP Function)
vlax-object-released-p
Determines if an object has been released (VLISP Function)
(vlax-object-released-p obj)
obj - VLA object.
Returns:
T, if object is released (no AutoCAD drawing object is attached to obj)
nil, if the object has not been released
vlax-product-key
Returns AutoCADs registry path (VLISP Function)
487
Example:
(vlax-product-key)
"Software\\Autodesk\\AutoCAD\\R14.0\\ACAD-2450999:99924631"
vlax-property-available-p
Determines if an object has a specified property (VLISP Function)
Note how supplying the optional third argument changes the result:
_$ (vlax-property-available-p myCircle "area" T)
nil
The funtion returns nil because, although the circle has an "area" property, that property
cannot be modified.
vlax-property-available-p
488
vlax-put
Low-level property set function (VLISP Function)
Example:
$ (vlax-put vlaobj "Color" 1)
nil
vlax-read-enabled-p
Determines if an object can be read (VLISP Function)
(vlax-read-enabled-p obj)
obj - VLA object
Returns:
T, if the object is readable
nil, if the object is not readable
489
vlax-reg-app
Registers an application (VLISP Function)
vlax-release-object
Releases a drawing object (VLISP Function)
(vlax-release-object obj)
obj - VLA object
After release, the drawing object is no longer accessible through obj.
Returns:
Indeterminate
vlax-reg-app
490
vlax-remove-cmd
Removes a single command or a command group (VLISP Function)
Removes a single command or the whole command group for the current AutoCAD session.
(vlax-remove-cmd global-name)
global-name - either a string or T. If global-name is T, the whole command group
VLC-AppName (for example, VLC-VLIDE) is deleted.
vlax-tmatrix
Returns a suitable representation for a 4x4 transformation matrix to be used in
VLA methods (VLISP Function)
(vlax-tmatrix list)
Returns a suitable representation (acceptable to ActiveX methods) for a 4x4 transformation matrix (namely: vla-TransformBy).
list - a list of four lists, each containing four numbers, representing transformation
matrix elements
vlax-typeinfo-available-p
Deterines whether TypeLib information is present for the specified type of object
(VLISP Function)
(vlax-typeinfo-available-p obj)
obj - VLA object
Returns:
T, if TypeLib information is available
nil, if TypeLib information is not available
491
vlax-vla-object->ename
Transforms a VLA object to an AutoLISP entity (VLISP Function)
(vlax-vla-object->ename obj)
obj - VLA object
Returns:
An AutoLISP entity name
Example:
_$ (vlax-vla-object->ename vlaobj)
<Entity name: 27e0540>
vlax-write-enabled-p
Determines if an AutoCAD drawing object can be modified (VLISP Function)
(vlax-write-enabled-p obj)
obj - VLA object or AutoLISP entity object
Returns:
T, if an AutoCAD drawing object can be modified
nil, if the object cannot be modified
vlisp-export-symbol
Assigns a native AutoLISP variable to the value it has in Visual LISP (VLISP
Function)
(vlisp-export-symbol symbol-name)
symbol-name - Visual LISP symbol or list of symbols
Returns:
The value of the exported symbol, or the last exported symbol, if a list was supplied
vlax-vla-object->ename
492
Examples:
_$ (setq dd 1)
1
_$ (VLISP-EXPORT-SYMBOL dd)
1
_$ (setq zz "str")
"str"
$ (VLISP-EXPORT-SYMBOL (dd zz))
"str"
vlisp-import-exsubrs
Registers the entry point of an ADS or ARX application within the Visual LISP
environment (VLISP Function)
vlisp-import-symbol
Assigns a Visual LISP symbol to the same value it has in native AutoLISP
(VLISP Function)
(vlisp-import-symbol symbol-name)
symbol-name - AutoLISP symbol or list of symbols
Returns:
The value of the imported symbol, or the last imported symbol in a list of symbols
Examples:
_$ (vlisp-import-symbol dd)
1
493
_$ (vlisp-import-symbol xx)
nil
_$ (vlisp-import-symbol (xx dd))
1
vlr-acdb-reactor
Constructs a database (global) reactor object (VLISP Function)
Event
:vlr-objectAppended
:vlr-objectUnAppended
:vlr-objectReAppended
:vlr-objectOpenedForModify
:vlr-objectModified
:vlr-objectErased
:vlr-objectUnErased
vlr-acdb-reactor
494
vlr-add
Enables a disabled reactor object (VLISP Function)
(vlr-add obj)
obj -a VLR object, the reactor to be enabled
Returns:
obj (the argument)
vlr-added-p
Tests to determine if a reactor object is enabled (VLISP Function)
(vlr-added-p obj)
obj - a VLR object, the reactor to be tested
Returns:
T, if the specified reactor is enabled
nil, if the reactor is disabled
vlr-beep-reaction
Produces a beep sound (VLISP Function)
(vlr-beep-reaction [args])
This is a predefined callback function that accepts a variable number of arguments,
depending on the reactor type. Can be assigned to an event handler for debugging. This
function works in the Visual LISP IDE only.
495
vlr-current-reaction-name
Returns the name (symbol) of the current event, if called from within a reactors
callback (VLISP Function)
(vlr-current-reaction-name)
Returns:
A symbol indicating the event that triggered the reactor
vlr-data
Returns application-specific data associated with a reactor (VLISP Function)
(vlr-data obj)
obj - a VLR object, the reactor object from which to extract data
vlr-data-set
Overwrites application-specific data associated with a reactor (VLISP Function)
vlr-current-reaction-name
496
vlr-editor-reactor
Constructs an Editor (global) reactor object (VLISP Function)
The reactor object is added to the drawing database, but does not become persistent.
Event
:vlr-unknownCommand
:vlr-commandWillStart
:vlr-commandEnded
:vlr-commandCancelled
:vlr-commandFailed
:vlr-lispWillStart
:vlr-lispEnded
497
Event
:vlr-lispCancelled
:vlr-beginClose
:vlr-beginDxfIn
:vlr-abortDxfIn
The drawing database has been changed, but the DXF import was not
successful.
:vlr-dxfInComplete
:vlr-beginDxfOut
:vlr-abortDxfOut
:vlr-dxfOutComplete
:vlr-beginDwgOpen
:vlr-endDwgOpen
:vlr-dwgFileOpened
A new drawing has been loaded into the AutoCAD drawing editor.
:vlr-databaseToBeDestroyed
:vlr-beginSave
:vlr-SaveComplete
:vlr-sysVarWillChange
:vlr-sysVarChanged
vlr-editor-reactor
498
List
length
:vlr-lispEnded,
:vlr-lispCancelled,
:vlr-beginClose,
:vlr-beginDxfIn,
:vlr-abortDxfIn,
:vlr-dxfInComplete,
:vlr-beginDxfOut,
:vlr-abortDxfOut,
:vlr-dxfOutComplete,
:vlr-databaseToBeDestroyed
:vlr-unknownCommand
:vlr-commandWillStart
:vlr-commandEnded
:vlr-commandCancelled
:vlr-commandFailed
:vlr-lispWillStart
:vlr-beginDwgOpen,
:vlr-endDwgOpen,
:vlr-dwgFileOpened
:vlr-beginSave
:vlr-saveComplete
:vlr-sysVarWillChange
:vlr-sysVarChanged
499
Parameters
vlr-linker-reactor
Constructs a Linker (global) reactor object (VLISP Function)
The reactor object is added to the drawing database, but does not become persistent.
Event
:vlr-rxAppLoaded
The dynamic linker has loaded a new ARX program. The program
has finished its initialization.
:vlr-rxAppUnLoaded
vlr-object-reactor
Constructs an object reactor object (VLISP Function)
The reactor object is added to the drawing database, but does not become persistent.
vlr-linker-reactor
500
501
Event
:vlr-cancelled
:vlr-copied
:vlr-erased
:vlr-unerased
:vlr-goodbye
:vlr-openedForModify
:vlr-modified
:vlr-subObjModified
:vlr-modifyUndone
:vlr-modifiedXData
:vlr-unappended
:vlr-reappended
:vlr-objectClosed
vlr-object-reactor
502
List
length
Parameters
:vlr-cancelled
:vlr-erased,
:vlr-unerased
:vlr-goodbye
:vlr-openedForModify
:vlr-modified
:vlr-modifyUndone
:vlr-modifiedXData
:vlr-unappended
:vlr-reappended
:vlr-objectClosed
:vlr-copied
:vlr-subObjModified
vlr-owner-add
Adds an object to the list of owners of an object reactor (VLISP Function)
503
vlr-owner-remove
Removes an object from the list of owners of an object reactor (VLISP Function)
vlr-owners
Returns the list of owners of an object reactor (VLISP Function)
(vlr-owners reactor)
reactor - a VLR object
vlr-pers
Makes a reactor persistent (VLISP Function)
(vlr-pers reactor)
reactor - a VLR object
Returns:
Indeterminate
vlr-pers-p
Determines whether or not a reactor is persistent (VLISP Function)
(vlr-pers-p reactor)
reactor - a VLR object
vlr-owner-remove
504
Returns:
T, if the specified reactor is persistent
nil, if the reactor is transient
vlr-pers-release
Makes a reactor transient (VLISP Function)
(vlr-pers-release reactor)
reactor - a VLR object
Returns:
Indeterminate
vlr-reaction-names
Returns a list of all callback conditions for this reactor type (VLISP Function)
(vlr-reaction-names reactor-type)
reactor-type - one of the following symbols:
:VLR-AcDb-reactor
:VLR-Editor-reactor
:VLR-Linker-reactor
:VLR-Object-reactor
Returns:
A list of symbols indicating the possible events for the specified reactor type
vlr-reaction-set
Adds or replaces a callback function in a reactor (VLISP Function)
505
vlr-reactions
Returns a list of pairs (event-name . callback_function) for the reactor (VLISP
Function)
(vlr-reactions reactor)
reactor - a VLR object
vlr-reactors
Returns a list of all reactors of a given type (VLISP Function)
(vlr-reactors reactor-type)
reactor-type - one of the following symbols:
:VLR-AcDb-reactor
:VLR-Editor-reactor
:VLR-Linker-reactor
:VLR-Object-reactor
vlr-remove
Disables a reactor (VLISP Function)
(vlr-remove reactor)
reactor - a VLR object
Returns
Indeterminate
vlr-reactions
506
vlr-remove-all
Disables all reactors of the specified type (VLISP Function)
(vlr-remove-all reactor-type)
reactor-type - one of the following symbols:
:VLR-AcDb-reactor
:VLR-Editor-reactor
:VLR-Linker-reactor
:VLR-Object-reactor
Returns
Indeterminate
vlr-trace-reaction
A pre-defined callback function that prints one or more callback arguments in
the Trace window (VLISP Function)
vlr-type
Returns a symbol representing the reactor type (VLISP Function)
(vlr-type reactor)
reactor - a VLR object
vlr-types
Returns a list of all reactor types (VLISP Function)
(vlr-types)
Returns:
507
vports
Returns a list of viewport descriptors for the current viewport configuration
(vports)
Each viewport descriptor is a list consisting of the viewport identification number and the
coordinates of the viewports lower-left and upper-right corners.
If the AutoCAD system variable TILEMODE is set to 1 (on), the returned list describes
the viewport configuration created with the AutoCAD VPORTS command. The corners
of the viewports are expressed in values between 0.0 and 1.0, with (0.0, 0.0) representing
the lower-left corner of the display screens graphics area, and (1.0, 1.0) the upper-right
corner. If TILEMODE is 0 (off), the returned list describes the viewport objects created
with the MVIEW command. The viewport object corners are expressed in paper space
coordinates. Viewport number 1 is always paper space when TILEMODE is off.
For example, given a single-viewport configuration with TILEMODE on, the vports
function might return this:
((1 (0.0 0.0) (1.0 1.0)))
Similarly, given four equal-sized viewports located in the four corners of the screen when
TILEMODE is on, the vports function might return this:
(
The current viewports descriptor is always first in the list. In the previous example, viewport number 5 is the current viewport.
wcmatch
Performs a wild-card pattern match on a string
vports
508
quoted string or a variable. The pattern can contain the wild-card pattern-matching
characters shown in the following table. Only the first 500 characters (approximately) of
the string and pattern are compared; anything beyond that is ignored.
Wild-card characters
Character
Definition
(pound)
(at)
(period)
(asterisk)
(question mark)
(tilde)
[...]
[~...]
(hyphen)
(comma)
(reverse quote)
returns T
This tests the string Name to see if it begins with the character N. You can use commas in
a pattern to enter more than one pattern condition. This example performs three comparisons:
(wcmatch "Name" "???,~*m*,N*") returns T
If any of the three pattern conditions is met, wcmatch returns T. In this case the tests are
these: Name has three characters (false); Name does not contain an m (false); and Name
begins with N (true). At least one condition was met, so this expression returns T.
The comparison is case-sensitive, so upper- and lowercase characters must match. It is
valid to use variables and values returned from AutoLISP functions for string and pattern values.
509
To test for a wild-card character in a string, you can use the single reverse-quote character
() to escape the character. Escape means that the character following the single reverse
quote is not read as a wild-card character; it is compared at its face value. For example,
to search for a comma anywhere in the string Name, enter this:
(wcmatch "Name" "*,*")
returns nil
wcmatch
510
Both the C and AutoLISP programming languages use the backslash (\) as an escape character, so you need two backslashes (\\) to produce one backslash in a string. To test for a
backslash character anywhere in Name, you enter this:
(wcmatch "Name" "*\\*")
returns nil
All characters enclosed in brackets ([ . . . ]) are read literally, so there is no need to escape
them, with the following exceptions: the tilde character (~) is read literally only when it
is not the first bracketed character (as in "[A~BC]"); otherwise it is read as the negation
character, meaning that wcmatch should match all characters except those following the
tilde (as in "[~ABC]"). The dash character () is read literally only when it is the first or
last bracketed character (as in "[ABC]" or "[ABC]") or when it follows a leading tilde
(as in "[~-ABC]"). Otherwise, the dash character () is used within brackets to specify a
range of values for a specific character. The range works only for single characters, so
"STR[138]" matches STR1, STR2, STR3, and STR8, and "[AZ]" matches any single
uppercase letter.
The closing bracket character ("]") is also read literally if it is the first bracketed character or if it follows a leading tilde (as in "[ ]ABC]" or "[~]ABC]").
while
Evaluates a test expression, and if it is not nil, evaluates other expressions;
repeats this process until the test expression evaluates to nil
511
write-char
Writes one character to the screen or to an open file
returns 67
and writes the letter C on the screen. Assuming that f is the descriptor for an open file:
(write-char 67 f)
returns 67
returns 10
but writes the character sequence CR/LF (ASCII codes 13 and 10) to the file. writechar cannot write a NUL character (ASCII code 0) to a file.
write-line
Writes a string to the screen or to an open file
"Test"
write-char
512
xdroom
Returns the amount of extended data (Xdata) space that is available for an object
(entity)
(xdroom ename)
If unsuccessful, xdroom returns nil. Because there is a limit (currently, 16 kilobytes) on
the amount of extended data that can be assigned to an entity definition, and because multiple applications can append extended data to the same entity, this function is provided
so that an application can verify that there is room for the extended data that it will
append. It can be called in conjunction with xdsize, which returns the size of an
extended data list.
Here is an example that looks up the available space for extended data of a viewport
object. Assuming that the variable vpname contains the name of a viewport object,
(xdroom vpname)
returns 16162
In this example, 16,162 bytes of the original 16,383 bytes of extended data space are
available, meaning that 221 bytes are used. You can determine the amount of available
data space by using the xdsize function.
xdsize
Returns the size (in bytes) that a list occupies when it is linked to an object
(entity) as extended data
(xdsize lst)
If unsuccessful, xdsize returns nil. The lst argument must be a valid list of extended
data that contain an application name previously registered with the use of the regapp
function. Brace fields (group code 1002) must be balanced. An invalid lst generates an
error and places the appropriate error code in the ERRNO variable. If the extended data
contains an unregistered application name, you see this error message (assuming that
CMDECHO is on):
Invalid application name in 1001 group
The lst can start with a 3 group code (the extended data sentinel), but it is not required.
Because extended data can contain information from multiple applications, the list must
have a set of enclosing parentheses.
513
Here is the same example without the 3 group code. This list is just the cdr of the first
example, but it is important that the enclosing parentheses are included:
( ("MYAPP" (1000 . "SUITOFARMOR")
(1002 . "{")
(1040 . 0.0)
(1040 . 1.0)
(1002 . "}")
)
)
xload
Loads an ADS application
xload
514
If you attempt to load an application that is already loaded, xload issues the message
Application "application" already loaded.
and returns the application name. You may want to check the currently loaded ADS applications with the ads function before using xload.
xunload
Unloads an ADS application
If the xunload operation fails, it normally causes an AutoLISP error. However, if the
onfailure argument is supplied, xunload returns the value of this argument upon failure instead of issuing an error message. This feature of xunload is similar to that in the
xload function.
515
zerop
Verifies that a number evaluates to zero
(zerop number)
Returns T if number evaluates to zero, returns nil otherwise.
(zerop 0)
(zerop 0.0)
(zerop 0.0001)
returns T
returns T
returns nil
zerop
516
517