Autolisp Español
Autolisp Español
Autolisp Español
INTRODUCION
Overview
For years, AutoLISP® has set the standard for customizing AutoCAD®. Now Visual LISP (VLISP) represents the next
generation of LISP for AutoCAD, by adding significantly more capabilities. VLISP extends the language to interface with
objects via the Microsoft ActiveX Automation interface, and enhances AutoLISP's ability to respond to events through the
implementation of reactor functions. As a development tool, VLISP provides a complete, integrated development environment
(IDE) that includes a compiler, debugger, and other tools to increase productivity when customizing AutoCAD.
Visual LISP (VLISP) is a software tool designed to expedite AutoLISP program development. The VLISP integrated
development environment (IDE) 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 standalone applications written in
AutoLISP.
In the past, developing AutoLISP programs for AutoCAD meant supplying your own text editor for writing 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 where in your program to do this, and what variables
you needed to look at. If you discovered you still didn't have enough information to determine the error, you had to go
back and change the code again by 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.
Syntax Checker recognizes erroneous AutoLISP constructs and improper arguments in calls to built-in functions.
File Compiler improves the execution speed and provides a secure and efficient delivery platform.
Source Debugger, designed specifically for AutoLISP, supports stepping through AutoLISP source code in one window
while simultaneously displaying the results of code execution in an AutoCAD drawing window.
Text file editor uses AutoLISP and DCL color coding, as well as other AutoLISP syntax support features.
1
1.2 Working with Visual LISP and AutoCAD
VLISP contains its own set of windows and menus that are distinct from the rest of AutoCAD, but VLISP does not run
independently of AutoCAD. Whenever you work in VLISP, AutoCAD must also be running. When you run AutoLISP
programs from the VLISP IDE, you will usually need to interact with the AutoCAD graphics or Command windows to
respond to program prompts.
If AutoCAD is minimized when VLISP turns control over to it, you must manually restore and activate the AutoCAD
window to continue.
VLISP will not restore the AutoCAD window for you. Instead, a Visual LISP symbol appears in the VLISP window and
remains there until you activate AutoCAD and respond to the prompts at the AutoCAD Command prompt. The "Getting
Started" chapter shows an example of this; see "Loading and Running AutoLISP Programs."
Additional AutoLISP and Visual LISP manuals are available online through the Visual LISP and AutoCAD Help menus:
The AutoLISP Reference briefly describes and provides examples of every AutoLISP function. Refer to the AutoLISP
Reference when you need to look up the syntax of a function, or determine what a function returns.
The Visual LISP Tutorial contains step-by-step instructions guiding you toward building a working Visual LISP
application.
This Visual LISP Developer's Guide assumes you have some experience with AutoCAD and have basic user-level skills with
Microsoft Windows®. Prior experience with AutoLISP is not required, but it will make your learning curve much smoother.
If you are already familiar with AutoLISP, you may want to begin the Visual LISP 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 2 through 7 of this guide before trying the tutorial.
Following are some guidelines to help you get the most out of the Visual LISP Developer's Guide:
Begin by reading chapter 1, "Getting Started." This chapter tells you how to invoke VLISP from AutoCAD, identifies what
you'll see when VLISP first starts, and describes how to load and run existing AutoLISP programs from VLISP. Chapter 1
introduces and briefly describes the windows you will be working with in the VLISP IDE. Use this chapter to orient yourself to
the VLISP environment.
If you do not already know AutoLISP, read all of chapter 8, "AutoLISP Basics," and at least browse chapters 9 and 10,
"Using AutoLISP to Communicate with AutoCAD" and "Using AutoLISP to Manipulate AutoCAD Objects," respectively.
After that, you can either work through the tutorial or read more chapters in the Visual LISP Developer's Guide.
To search for a function that meets a particular programming need, refer to appendix A, "AutoLISP Function Synopsis," in this
guide.
Chapter organization
2
5 Maintaining Visual LISP Applications Describes how to define VLISP projects and use them to simplify
working with multi-file applications. This chapter also explains compiler optimization features, and how to use them in a
project.
6 Working with ActiveX Describes how to use ActiveX objects with VLISP, and how to access other applications
through ActiveX.
7 Advanced Topics Describes how to attach reactors to AutoCAD drawings and objects.
8 AutoLISP Basics Introduces basic AutoLISP concepts, such as how to use expressions and variables, handle numbers
and strings, display output, build lists, and define functions.
9 Using AutoLISP to Communicate with AutoCAD Describes AutoLISP functions that you can use to issue
AutoCAD commands and to interact with users in the AutoCAD environment.
10 Using AutoLISP to Manipulate AutoCAD Objects Describes AutoLISP functions you can use to manipulate
AutoCAD drawing entities, selections sets, extended data, and symbol tables.
11 Designing Dialog Boxes Introduces the elements that make up dialog boxes. Explains DCL file structure and syntax,
and presents AutoLISP and DCL code that defines and displays a sample dialog box.
12 Managing Dialog Boxes Describes how to control dialog boxes with AutoLISP programs.
13 Programmable Dialog Box Reference Lists and describes all the DCL tiles and their associated attributes, and
summarizes the AutoLISP functions available tor work with programmable dialog boxes.
3 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 Developer's Guide.
Typographical conventions
4 Related Documents
In addition to the AutoLISP Reference and the Visual LISP Tutorial, several other AutoCAD publications may be required by
users building applications with Visual LISP:
AutoCAD ActiveX and VBA Reference contains information on accessing ActiveX methods, properties, and objects. If you
develop AutoLISP applications that use ActiveX automation to reference AutoCAD objects, you will need to refer to this
reference guide. It is available through the AutoCAD and Visual LISP Help menus.
AutoCAD Customization Guide contains basic information on creating customized AutoCAD applications. For example,
it includes information on creating customized menus, linetypes, and hatch patterns. The Customization Guide is available
through the AutoCAD and Visual LISP Help menus.
The DXF Reference describes drawing interchange format (DXF) and the DXF group codes that identify attributes of
AutoCAD objects. You may need to refer to the DXF Reference when working with association lists describing entity data.
The DXF Reference is available through the AutoCAD and Visual LISP Help menus.
The ObjectARX Reference contains information on using ObjectARX to develop customized AutoCAD applications.
AutoCAD reactor functionality is implemented through ObjectARX. If you develop AutoLISP applications that implement
reactor functions, you may want to refer to this manual.
The ObjectARX Reference is not included when you install AutoCAD. To obtain the manual, download the ObjectARX SDK
(Software Development Kit) from the Autodesk World Wide Web site (http://www.autodesk.com). Click on the Product Index
link and look for ObjectARX under Development Tools.
3
4
Chapter 1 -- Getting Started
Overview
This chapter introduces you to the look and feel of the Visual LISP interactive development environment (IDE), and shows you
how to run AutoLISP programs in Visual LISP.
Topics in this chapter:
<> Starting Visual LISP
<> Exploring the Visual LISP User Interface
<> Touring the Visual LISP Menus
<> Understanding the Console Window
<> Understanding the Visual LISP Text Editor
<> Loading and Running AutoLISP Programs
<> Exiting Visual LIS
5
GRAFICOCAPT. 1
EXPLORRING THE visual LIPS u
Menu You can issue VLISP commands by choosing from the various menu items. If you highlight an item on a menu, VLISP
displays a brief description of the command's function in the status bar at the bottom of the screen.
Toolbars Click toolbar buttons to issue VLISP commands quickly. There are five toolbars—
Debug, Edit, Find, Inspect, and Run—each representing a distinct functional group of VLISP commands. (In the figure shown
on this page, the toolbars are adjacent to one another, each toolbar beginning with an icon ( ). You can execute many, but not
all, menu commands from the toolbars. If you move your mouse pointer over a toolbar button and leave it there for a couple of
seconds, VLISP displays a tooltip indicating the function of the button. A more descriptive explanation appears in the status bar
at the bottom of the VLISP screen.
Console Window This is a separate, scrollable window within the main VLISP window. In the Console window, you can type
AutoLISP commands, similar to the way you do in the AutoCAD Command window. You can also issue many Visual LISP
commands from this window, instead of using the menu or toolbars. See "Understanding the Console Window" for more
information about the Console window.
Status Bar The information displayed in the status bar located at the bottom of the screen varies according to what you are
doing in VLISP.
You may also see a minimized Trace window. During startup, this window contains informational messages about the current
release of VLISP, and may contain additional information if VLISP encounters errors during startup.
VLISP opens the file in a new window—the text editor window—and displays the name of the file in the status bar. If you
make a change to the text in the editor window, or add new text, VLISP places an asterisk (*) next to the file name in the
status bar. The asterisk remains next to that file name until you either save your changes or close the file.
You can work on more than one file at a time. Each time you open a file, VLISP displays the file in a new text editor
window.
VLISP displays some output in the Console window, but several VLISP functions create their own windows in which to
display results. For example, when you trace the sequence of events during a running AutoLISP program, the Trace function
opens a window and displays program events. You cannot enter text in these output windows, but you can copy text from
them and paste the text into the editor or Console windows.
6
3.1 Other Visual LISP Windows
VLISP displays some output in the Console window, but several VLISP functions create their own windows in which to
display results. For example, when you trace the sequence of events during a running AutoLISP program, the Trace function
opens a window and displays program events. You cannot enter text in these output windows, but you can copy text from
them and paste the text into the editor or Console windows.
As an example, click in the text editor window containing the drawline.lsp file, then choose Edit from the VLISP menu.
You'll see the following list:
Note that the last items on the menu are Parentheses Matching and Extra Commands.
Now click in the title bar of the VLISP 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.
3.2.2 isual LISP Menu Summary
The following table summarizes the VLISP menu items.
The Console window is also where VLISP displays AutoLISP diagnostic messages and the results of many AutoLISP
functions. For example, output from the print and princ functions is displayed in the Console window. You can scroll through
the Console window to view previously entered text and output.
For a description of VLISP Console window features, see "Using the Console Window." The following is a brief summary of
these features:
Evaluating AutoLISP expressions and displaying the return values from those expressions.
Entering AutoLISP expressions on multiple lines by pressing CTRL+ENTER to continue on the next line.
Evaluating multiple expressions at one time.
Copying and transferring text between the Console and text editor windows. Most text editor commands are also
available in the Console window.
Retrieving previous commands entered in the Console by pressing TAB. You can press TAB repeatedly to retrieve
earlier commands. Press SHIFT+TAB to reverse the direction of command retrieval.
Performing an associative search through the input history by pressing TAB. 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.
Pressing ESC clears any text following the Console prompt.
Pressing SHIFT+ESC leaves the text you entered at the Console prompt without evaluating the text, and displays a
new Console prompt.
Right-clicking or pressing SHIFT+F10 anywhere in the Console window displays a menu of VLISP 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 will no
longer be at the prompt when you return to the VLISP window.
The VLISP text editor is much more than a writing tool, it's a central component of the VLISP programming environment. To
appreciate the versatility and value of the VLISP text editor, you need to be familiar with the AutoLISP language. If you are not
yet familiar with AutoLISP, you can learn the basics in chapter 8, "AutoLISP Basics," and find additional information in
chapter 9, "Using AutoLISP to Communicate with AutoCAD," and chapter 10, "Using AutoLISP to Manipulate AutoCAD
Objects."
Color Coding of Files The text editor identifies different parts of an AutoLISP program and assigns distinct colors to them.
This allows you to find program components easily such as function calls and variable names, and helps you find
typographical errors.
Formatting of Text The text editor can format AutoLISP code for you, making the code easier to read. You can choose from a
number of different formatting styles.
Parenthesis Matching AutoLISP code contains many parentheses, and the editor helps you detect missing parentheses by
finding the close parenthesis that goes with an open parenthesis.
Execution of AutoLISP Expressions You can test expressions and lines of code without leaving the text editor.
Multiple File Searching The text editor can search for a word or expression in several files with a single command.
Syntax Checking of AutoLISP Code The text editor can evaluate AutoLISP code and highlight syntax errors.
Details on using the VLISP text editor begin with "Using the Text Editor."
8
Once you have opened an AutoLISP program file in the VLISP text editor, you can load and run it. Loading is the process by
which functions in a program file are made available to the VLISP command interpreter. You can try this out with the
drawline.lsp sample program.
1 Make sure the text editor window containing the drawline.lsp program is active. If you are not sure whether the
window is active, click anywhere in the window to activate it.
2 Choose the Load Active Edit Window button from the Run toolbar, or choose Tools Load Text in Editor from the
VLISP menu.
VLISP responds by displaying a message in the Console window indicating it has loaded the program.
3 Run the drawline function from the Console prompt by entering the function name in parentheses, then pressing
ENTER:
_$ (drawline)
The drawline function will ask you to specify two points, and will then draw a straight line between those points. When
drawline asks for user input, VLISP turns control over to AutoCAD to prompt you for the points. What you see next depends
on whether or not the AutoCAD windows are currently displayed on your desktop. If AutoCAD is already on your desktop,
you'll see the AutoCAD windows. But if AutoCAD is currently minimized on your desktop, the windows won't automatically
be restored and displayed. Instead, VLISP remains visible and your mouse pointer changes to a VLISP symbol:
9
6.1 Running Selected Lines of Code
With VLISP, you can select lines of code in the text editor window and run only the selected code, instead of the whole
program.
1 Using the drawline.lsp program as an example, highlight the following lines of code:
(setq pt1(getpoint "\nEnter the start point for the line: ")
pt2(getpoint pt1 "\nEnter the end point for the line: "))
VLISP immediately runs the code and switches control to AutoCAD to prompt you for input.
(vl-load-com)
This function first checks whether or not the AutoLISP extensions are already loaded; if so, the function does nothing,
otherwise it loads the extensions.
If you're using the VLISP interactive development environment to develop code, chances are you'll want to use the AutoLISP
extensions at some point. It's a good practice to issue vl-load-com when you start VLISP, or to include a call to the function in
your acaddoc.lsp file, so that it loads automatically. But if you write programs that use any of the extended AutoLISP
functions, you need to call vl-load-com in those programs to ensure that the functions are available to other users running your
code
VLISP retains its state when you exit. The next time you start a VLISP session, VLISP automatically opens whichever files and
windows were open when you last exited.
10
Chapter 2 -- Developing Programs with Visual LISP
Overview
VLISP provides many tools and features that help you develop AutoLISP programs. This chapter describes the features that
help you during the coding phase of program development. These features format AutoLISP code to improve readability and
help you detect syntax errors in your code.
1. Getting Organized
To develop an AutoLISP program with VLISP you must perform the following steps:
Think about which tasks you want to accomplish with your program, and how to approach those tasks.
Design the program.
Write the code.
Format the code for readability.
Check for errors in the program.
Test and debug the program.
This chapter provides you with information to help you accomplish writing, formatting, and checking tasks. The "Debugging
Programs" chapter describes the debugging features of VLISP. The "Building Applications" and "Maintaining Visual LISP
Applications" chapters 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.
_$
VLISP saves the text you enter and any output from executing the text. You can then scroll through the Console window and
see what transpired. You can copy any text in the window and paste it at the Console prompt or in another Windows
application.
Unlike the AutoCAD Command window, where pressing SPACEBAR causes expression evaluation, text input at the VLISP
Console prompt is not processed until you press ENTER. This permits you to do the following in the Console window:
Continue an AutoLISP expression on a new line. To continue entering an expression on a new line, press CTRL+ENTER at the
point you want to continue.
Input more than one expression before pressing ENTER. VLISP evaluates each expression before returning a value to the
Console window.
If you select text in the Console window (for example, the result of a previous command or a previously entered expression),
then press ENTER. VLISP copies the selected text at the Console prompt.
The VLISP Console window and the AutoCAD Command window differ in the way they process the SPACEBAR and TAB
keys. In the VLISP Console window, a space plays no special role and serves only as a separator. In the AutoCAD Command
window, pressing the SPACEBAR outside an expression causes AutoCAD to process the text immediately, as if you had
pressed ENTER.
12
Topics in this section:
For example, assume you entered the following commands at the Console prompt:
1 Press TAB once. VLISP retrieves the last command entered and places it at the Console prompt:
2 Press TAB again. The following command displays at the Console prompt:
4 Now press SHIFT+TAB. VLISP reverses direction and retrieves the command you entered after the previous
command:
This was the last command you entered at the Console prompt.
6 Press SHIFT+TAB again. Because the previous command retrieved was the last command you entered during this
VLISP session, VLISP starts again by retrieving the first command you entered in the Console window:
Note that if you enter the same expression more than once, it appears only once as you cycle through the Console window
input history.
You can perform an associative search in the input history to retrieve a specific command that you previously entered.
1 Enter the text you want to locate. For example, enter (command at the Console prompt:
_$ (command
2 Press TAB. VLISP searches for the last text you entered that began with (command:
13
_$ (command "_.CIRCLE" origin radius)
If VLISP does not find a match, it does nothing (except possibly emit a beep). Press SHIFT+TAB to reverse the direction of
the associative search and find progressively less-recent inputs.
2.1.2 Interrupting Commands and Clearing the Console Input Area
To interrupt a command entered in the Console window, press SHIFT+ESC. For example, if you enter an invalid function call
like the following:
((_>
Pressing SHIFT+ESC interrupts the command, and VLISP displays an "input discarded" message like the following:
_$
(Note that in this example, you can also complete the command by entering the missing close parentheses.)
If you type text at the Console prompt, but do not press ENTER, then pressing ESC clears the text you typed. If you press
SHIFT+ESC, VLISP leaves the text you entered in the Console window but displays a new prompt without evaluating the text.
If you type part of a command at the Console prompt, but activate the AutoCAD window before pressing ENTER, VLISP
displays a new prompt when you next activate the VLISP window. The text you typed is visible in the Console window history,
so you can copy and paste it, but you cannot retrieve the text by pressing TAB, because it was not added to the Console history
buffer.
14
Chapter 9 -- Using Auto LISP to Communicate with AutoCAD
4.1 Overview
Auto LISP provides various functions for examining the contents of the currently loaded drawing. This chapter introduces
these functions and describes how to use them in conjunction with other functions.
There are some restrictions on the commands that you can use with the command function. See the AutoLISP Reference
definition of this function for information on these restrictions.
The following code fragment shows representative calls to command.
If AutoCAD is at the Command prompt when these functions are called, AutoCAD performs the following actions:
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. This draws an extruded circle centered at (1.0,1.0,3.0) with a radius of 4.5.
15
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.
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.
If an AutoCAD command is in progress and the predefined symbol PAUSE is encountered as an argument to command,
the command is suspended to allow direct user input (usually point selection or dragging). This is similar to the backslash
pause mechanism provided for menus.
The PAUSE symbol is defined as a string consisting of a single backslash. When you use a backslash (\) in a string, you
must precede it by another backslash (\\).
Menu input is not suspended by an AutoLISP pause. If a menu item is active when the command function pauses for input,
that input request can be satisfied by the menu. If you want the menu item to be suspended as well, you must provide a
backslash in the menu item. When valid input is found, both the command function and the menu item resume.
NOTE You can use a backslash instead of the PAUSE symbol. However, the pause mechanism might require a different
trigger value in future versions of AutoLISP, so it is recommended that you always use the PAUSE symbol rather than an
explicit backslash. Also, if the command function is invoked from a menu item, the backslash suspends the reading of the
menu item, which results in partial evaluation of the AutoLISP expression.
If you issue a transparent command while a command function is suspended, the command function remains suspended.
Therefore, users can 'ZOOM and 'PAN while at a command pause. The pause remains in effect until AutoCAD gets valid
input, and no transparent command is in progress. For example, the following code begins the CIRCLE command, sets the
center point at (5,5), and then pauses to let the user drag the circle's radius. When the user specifies the desired point (or
types in the desired radius), the function resumes, drawing a line from (5,5) to (7,5), as follows:
If PAUSE is encountered when a command is expecting input of a text string or an attribute value, AutoCAD pauses for
input only if the TEXTEVAL system variable is nonzero. Otherwise, AutoCAD does not pause for user input but uses the
value of the PAUSE symbol (a single backslash) text.
When the command function pauses for user input, the function is considered active, so the user cannot enter another
AutoLISP expression to be evaluated.
The following is an example of using the PAUSE symbol (the layer NEW_LAY and the block MY_BLOCK must exist in
the drawing prior to testing this code):
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.
WARNING! 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.
If AutoCAD is at the Command prompt when these functions are called, AutoCAD performs the following actions:
5 Performs the TRIM command by selecting the el object and by selecting the point specified by pt.
The following code fragment ensures that subsequent FILLET commands use a radius of at least 1:
See the Command Reference for a list and description of each AutoCAD system variable.
An additional function, getenv, provides AutoLISP routines with access to the currently defined operating system
environment variables.
17
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"
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 shortcut 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 display
(pull-down menus and image tile menus are not automatically displayed when they are called). In 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 the screen menu is currently enabled).
(menucmd "S=OSNAP")
In Windows, you can reference the menu group. This can be useful if there are 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 can have two submenus defined in the
***BUTTONS1 section, **DIG-BUTTONS and **TAB-BUTTONS, and switch between them with the following code.
The following code loads the ***POP0 menu into the P0 (cursor) menu area and displays it.
(menucmd "P0=POP0") Loads the ***POP0 menu into the P0 menu area
If you are sure the correct menu is loaded into a particular menu area, you do not need to load it specifically 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 shortcut 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:
This menu remains in this location until you replace it by loading another menu, as in the following:
(menucmd "P1=POP1")
18
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.
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.
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.
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. Because DIESEL accepts only strings as input, you can pass information to
the DIESEL expression through a USERS1–5 system variable that has been set to a value returned by your function.
You can also use the menucmd function to evaluate DIESEL string expressions within an AutoLISP function. The following
routine returns the current time:
For information on the use of DIESEL expressions with AutoLISP and a catalog of DIESEL functions, see the
Customization Guide. Refer also to the Customization Guide for further information on menus.
The redraw function is similar to the AutoCAD REDRAW command but provides more control over what is displayed. It
not only redraws the entire graphics area but can also specify a single object to be redrawn or undrawn (that is, blanked out).
If the object is a complex object such as an old-style polyline or a block, redraw can draw (or undraw) either the entire
object or its header. The redraw function can also highlight and unhighlight specified objects.
8
9 9.2.3 Control of Low-Level Graphics
AutoLISP provides functions that control the low-level graphics and allow direct access to the AutoCAD graphics screen
and input devices.
The grtext function displays text directly in the status or menu areas, with or without highlighting. The grdraw function
draws a vector in the current viewport with control over color and highlighting. The grvecs function draws multiple vectors.
NOTE Because these functions depend on code in AutoCAD, their operation can be expected to change from release to
release. There is no guarantee that applications calling these functions will be upward compatible. Also, they depend on
current hardware configurations. In particular, applications that call grtext are not likely to work the same on all
configurations unless the developer is very careful to use them as described (see the Customization Guide) and to avoid
19
hardware-specific features. Finally, because they are low-level functions, they do almost no error reporting and can alter the
graphics screen display unexpectedly (see the following example for a way to fix this).
The following sequence restores the default graphics window display caused by incorrect calls to grtext, grdraw, or grvecs:
(redraw)
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 getorient function, the 0 angle is always to the right: "East" or "3 o'clock." For getangle, the 0 angle is
the value of ANGBASE, which can be set to any angle. Both getangle and getorient return an angle value (a real) in radians
measured counterclockwise from a base (0 angle), for getangle equal to ANGBASE, and for getorient to the right.
For example, ANGBASE is set to 90 degrees (north), and ANGDIR is set to 1 (clockwise direction for increasing angles). The
following table shows what getangle and getorient return (in radians) for representative input values (in degrees).
Input
(degrees) getangle
getorient
0 0.0 1.5708
–90 1.5708 3.14159
180 3.14159 4.71239
90 4.71239 0.0
20
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 capabilities, lessening the
need for error-checking.
The getkword function pauses for the input of a keyword or its abbreviation. Keywords must be defined with the initget
function before the call to getkword. All user-input functions (except getstring) can accept keyword values in addition to the
values they normally return, provided that initget has been called to define the keywords.
All user-input functions allow for an optional prompt argument. It is recommended you use this argument rather than a prior
call to the prompt or princ functions. If a prompt
argument is supplied with the call to the user-input function, that prompt is reissued in the case of invalid user input. If no
prompt argument is supplied and the user enters incorrect information, the following message appears at the AutoCAD prompt
line:
Try again:
This can be confusing, because the original prompt may have scrolled out of the Command prompt area.
The AutoCAD user cannot typically respond to a user-input function by entering an AutoLISP expression. If your AutoLISP
routine makes use of the initget function, arbitrary keyboard input is permitted to certain functions that can allow an AutoLISP
statement as response to a command implemented in AutoLISP. This is discussed in "Arbitrary Keyboard Input."
The control bits and keywords established by initget apply only to the next user-input function call. They are discarded after
that call. The application doesn't have to call initget a second time to clear special conditions.
(initget (+ 1 2 4))
This sequence requests the user's 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).
b) Keyword Options
The optional string argument specifies a list of keywords recognized by the next user-input function call.
21
The initget function allows keyword abbreviations to be recognized in addition to the full keywords. The user-input
function returns a predefined keyword if the input from the user matches the spelling of a keyword (not case sensitive), or
if the user enters the abbreviation of a keyword. There are two methods for abbreviating keywords; both are discussed in
the initget topic in the AutoLISP Reference.
The following user-defined function shows a call to getreal, preceded by a call to initget, that specifies two keywords. The
application checks for these keywords and sets the input value accordingly.
This initget call inhibits null input (bits = 1) and establishes a list of two keywords, "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 keyword Pi (or simply P), getreal returns the keyword Pi. The cond function detects this and returns the
value of p in this case. The Two-pi keyword is handled similarly.
NOTE You can also use initget to enable entsel, nentsel, and nentselp to accept keyword input. For more information on
these functions, see "Object Handling" and the entsel, nentsel, and nentselp function definitions in the AutoLISP
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
d) Input Validation
22
You should protect your code from unintentional user errors. The AutoLISP user input getxxx functions do much of this
for you. However, it's dangerous to forget to check for adherence to other program requirements that the get
xxx functions do not check for. If you neglect to check input validity, the program's integrity can be seriously affected.
The following code fragment shows calls to the geometric utility functions:
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.
The following call looks for the midpoint, the endpoint, or the center of an object nearest pt1:
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.
NOTE The APERTURE system variable determines the allowable proximity of a selected point to an object when you use
Object Snap.
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.
The actual values returned by textbox will vary depending on the current text style.
23
The following example demonstrates one method of providing the textbox function with an entity definition list.
Command: dtext
Justify/Style/<Start point>: 1,1
Height <1.0000>: ENTER
Rotation angle <0>: ENTER
Text: test
Text: ENTER
Command: (textbox e)
The following figure shows the results of applying textbox to a text object with a height of 1.0. The figure also shows the
baseline and insertion point of the text.
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.)
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 that the first point list will contain negative offsets from the text insertion point.
24
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 extent 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:
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.
p4 (list
(+ (car p0)
(- (* (car t1) cosrot)(* (cadr t2) sinrot))
)
(+ (cadr p0)
(+ (* (car t1) sinrot)(* (cadr t2) cosrot))
)
)
)
(command "pline" p1 p2 p3 p4 "c")
(princ)
9.5 Conversions
The functions described in this section are utilities for converting data types and units. See "Conversion Functions" in appendix
A, "AutoLISP Function Synopsis," for a complete list of conversion functions.
The following code fragments show calls to rtos and the values returned (assuming 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)
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:
Because the angtos function takes the ANGBASE system variable into account, the following code always returns "0":
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 2p
(2 * pi). If so, subtract 2p; if the result is negative, add 2p, then use the angtos function on the result.
Store the value of ANGBASE in a temporary variable, set ANGBASE to 0, evaluate the angtos function, then set
ANGBASE to its original value.
Subtracting the result of (atof (angtos 0)) from 360 degrees (2p radians or 400 grads) also yields the rotation of
ANGBASE from 0.
The distof (distance to floating point) function is the complement of rtos. Therefore, 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.)
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.
The UNITMODE system variable also affects strings returned by angtos when it returns a string in surveyor's 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.
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 it doesn't look like the end of the string. The preceding examples of
angtof and distof demonstrate this action.
However, a more efficient method might be to include a Radian->Degrees function in your application. The following
code shows this:
After this function is defined, you can use the Radian->Degrees function throughout your application, as in
You may also need to convert from degrees to radians. The following code shows this:
) ;_ end of defun
)
28
(defun C:ASCII ( / chk out ct code dec oct hex )
(initget "Yes")
(setq chk (getkword "\nWriting to ASCII.TXT, continue? <Y>: "))
(if (or (= chk "Yes")(= chk nil)) (progn
(setq out (open "ascii.txt" "w") chk 1 code 0 ct 0)
(princ "\n \n CHAR DEC OCT HEX \n")
(princ "\n \n CHAR DEC OCT HEX \n" out)
(while chk
(setq dec (strcat " " (itoa code))
oct (base 8 code) hex (base 16 code))
(setq dec (substr dec (- (strlen dec) 2) 3))
(progn
(setq ct 0)
(princ "\n \n CHAR DEC OCT HEX \n")
)
)
)
)
(setq ct (1+ ct) code (1+ code))
)
(close out)
(setq out nil)
)
)
(princ)
The first time 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 don't have to be located at the end of the word, and a
plural form isn't required. The following are examples of valid unit name definitions:
*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.
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. Fundamental units consist of five integers and two real numbers in the
following form:
c, e, h, k, m, r1, r2
The five integers correspond to the exponents of these five constants:
Electron charge
Planck's constant
Boltzman's constant
As a group, these exponents define the dimensionality of the unit: length, mass, time, volume, and so on.
The first real number (r1) is a multiplier, and the second (r2) is an additive offset (used only for temperature conversions).
The fundamental unit definition allows for different spellings of the unit (for example, meter and metre); the case of the
unit is ignored. An example of a fundamental unit definition is as follows:
*meter(s),metre(s),m
30
-1,0,1,0,-1,4.1214856408e11,0
In this example, the constants that make one meter are as follows:
Derived Units
A derived unit is defined in terms of other units. If the line following the *unit name line begins with an equal sign (=), it
defines derived units. Valid operators in these definitions are * (multiplication), / (division), + (addition), – (subtraction),
and ^ (exponentiation). You can specify a predefined unit by naming it, and you can use abbreviations (if provided). The
items in a formula are multiplied together unless some other arithmetic operator is specified. For example, the units
database defines the dimensionless multiple and submultiple names, so you can specify a unit such as micro-inches by
entering micro inch. The following are examples of derived unit definitions.
; Units of area
*township(s)
=93239571.456 meter^2
; Electromagnetic units
*volt(s),v
=watt/ampere
In this example, a volt is defined as a watt divided by an ampere. In the acad.unt, both watts and amperes are defined in
terms of fundamental units.
User Comments
To include comments, begin the line with a semicolon. The comment continues to the end of the line.
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.
31
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 application to send
coordinates in the WCS, OCS, or DCS to AutoCAD commands, you must first convert them to the UCS by calling the
trans function.
OCS
Object coordinate system—point values returned by entget are expressed in this coordinate system, relative to the object
itself. These points are usually converted into the WCS, current UCS, or current DCS, according to the intended use of the
object. Conversely, points must be translated into an OCS before they are written to the database by means of the entmod
or entmake functions. This is also known as the entity coordinate system.
DCS
Display coordinate system—the coordinate system into which objects are transformed before they are displayed. The
origin of the DCS is the point stored in the AutoCAD system variable TARGET, and its Z axis is the viewing direction. In
other words, a viewport is always a plan view of its DCS. These coordinates can be used to determine where something
will be displayed to the AutoCAD user.
When the from and to integer codes are 2 and 3, in either order, 2 indicates the DCS for the current model space viewport
and 3 indicates the DCS for paper space (PSDCS). When the 2 code is used with an integer code other than 3 (or another
means of specifying the coordinate system), it is assumed to indicate the DCS of the current space, whether paper space or
model space. The other argument is also assumed to indicate a coordinate system in the current space.
PSDCS
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 User's 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:
32
If the current UCS is rotated 90 degrees counterclockwise around the World Z axis, the call to trans returns a point (2.0,–
1.0,3.0). However, if you swap the to and from values, the result differs as shown in the following code:
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 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 may not be worthwhile unless your program is doing a lot of transformations.
If the call to findfile is successful, the variable refname is set to a fully qualified path name string, as follows:
"/home/work/ref/refc.dwg"
When specifying a path name, you must precede the backslash (\) with another backslash so the path name will be
recognized by AutoLISP. Alternatively, you can use the slash character (/) as a directory separator.
The getfiled function displays a dialog box containing a list of available files of a specified extension type in the specified
directory. This gives AutoLISP routines access to the AutoCAD Get File dialog box.
A call to getfiled takes four arguments that determine the appearance and functionality of the dialog box. The application
must specify the following string values, each of which can be nil: a title, placed at the top of the dialog box; a default file
name, displayed in the edit box at the bottom of the dialog box; and an extension type, which determines the initial files
provided for selection in the list box. The final argument is an integer value that specifies how the dialog box interacts
with selected files.
This simple routine uses getfiled to let you view your directory structure and select a file:
(defun C:DDIR ( )
(setq dfil (getfiled "Directory Listing" "" "" 2))
(princ (strcat "\nVariable 'dfil' set to selected file " dfil ))
(princ)
)
This is a useful utility command. The dfil variable 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 You cannot use !dfil in a dialog box. It is valid only at the command line.
For more information, see "getfiled" in the AutoLISP Reference.
You can create a Help file that provides information about your applications or about procedures you use in your business.
The following user-defined command displays the morehelp.hlp Help file as follows:
(defun C:MYHELP ( )
(help "morehelp.hlp")
(princ)
See the 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.hlp to the user-defined MYCMD command:
(defun C:MYCMD ( )
.
. Command definition
.
)
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.")
)
34
(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:
)
To reset the calibration to the values retrieved by the preceding routine, you can use the C:TABSET routine, as follows:
(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 3×3 transformation matrix that is meant to transform a 2D
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:
The calculation of a point is similar to the 3D case. AutoCAD transforms the point by using the following formulas:
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').
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 isn't normalized.
AutoCAD normalizes the direction vector before it returns it. Also, it ensures 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.
35