Autolisp Español

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 35

VISUAL LISP DEVELOPER’S GUILDE

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.

Topics in this chapter:

1 AutoLISP and Visual LISP


AutoLISP is a programming language designed for extending and customizing AutoCAD functionality. It is based on the
LISP programming language, whose origins date back to the late 1950s. LISP was originally designed for use in Artificial
Intelligence (AI) applications, and is still the basis for many AI applications.
AutoCAD introduced AutoLISP as an application programming interface (API) in Release 2.1, in the mid-1980s. LISP
was chosen as the initial AutoCAD API because it was uniquely suited for the unstructured design process of AutoCAD
projects, which involved repeatedly trying different solutions to design problems.

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.

Topics in this section:

1.1 What Visual LISP Offers


During the development cycle of an AutoLISP application or routine, the AutoLISP user performs a number of operations
that are not available within the AutoCAD software. Some of these operations—like text editing—are available with other
software tools. Others, such as full AutoLISP source-level debugging, are introduced only with VLISP. In VLISP, you
perform most of the necessary operations inside a single environment. This permits text editing, program debugging, and
interaction with AutoCAD and other applications.

The following are components of the Visual LISP IDE:

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.

AutoLISP Formatter restructures programs into an easily readable format.


Comprehensive Inspect and Watch features provide convenient access to variable and expression values for data
structure browsing and modification. These features may be used to explore AutoLISP data and AutoCAD drawing
entities.
Context-sensitive Help provides information for AutoLISP functions and a powerful Apropos feature for symbol name
search.
Project Management system makes it easy to maintain multiple-file applications.

Compiled AutoLISP files are packaged into a single module.


Desktop Save and Restore capabilities preserve and reuse the windowing environment from any VLISP session.
Intelligent Console window introduces a new level of convenience and efficiency for AutoLISP users. The basic
functions of the Console correspond to the AutoCAD Text Screen functions and provide a number of interactive features,
such as history scrolling and full-input line editing.

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."

2 Using Visual LISP Documentation


The Visual LISP Developer's Guide explains how to use the VLISP IDE and how to build and run AutoLISP applications. This
guide also introduces the constructs of the AutoLISP language.
All users should check the AutoCAD Readme file for notices concerning AutoLISP and Visual LISP. The Readme file is in the
AutoCAD Help directory and contains information that became available too late to be included in this manual.
If you have developed AutoLISP applications in earlier releases of AutoCAD, it is important that you refer to the Readme file
for information on AutoLISP changes that may affect your applications.

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.

The following table summarizes the organization of this manual:

Chapter organization

Chapter Title Contents


1 Getting Started Orientation to Visual LISP
2 Developing Programs with
Visual LISP Shows you how to use the VLISP text editor to enter AutoLISP program code, format the code, and
check the code for AutoLISP syntax errors. Also shows you how to run the code you've developed from the VLISP
editor window.
3 Debugging Programs Shows you how to use VLISP to trace program execution, watch the value of variables
change during program execution, see the sequence in which expressions are evaluated, and step through program
execution one instruction at a time.
4 Building Applications Introduces the VLISP file compiler and shows how you can use the VLISP Application
Wizard to build standalone applications.

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

Text element Example


Program code examples are
displayed in 8 pt Courier font. (defun initfunc ( ) (setq *GLOBAL-WARMING* 4.0))
Text you enter is shown
in boldface At the VLISP Console prompt, enter shape
File names and directory
names are shown in
italics when referred
to in a sentence. Double-click the file name drawline.lsp.The default install directory is C:\Program Files\AutoCAD\VLISP
In definitions that include
variable text, the variable is
in italics. A FAS file named appname-init.fas, where appname is the application module name
AutoLISP and Visual LISP
variable names are in
courier type. Double-click on any occurrence of the variable name origin-yThe *LAST-VALUE* system variable
AutoLISP function names are shown in bold courier type. Use the entget function...Use vlax-import-type-library to import

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

1. Starting Visual LISP


The Visual LISP (VLISP) interactive development environment runs in a separate set of windows from the rest of AutoCAD.
You must explicitly start VLISP to work in the interactive development environment.
To start Visual LISP
1 Start AutoCAD.
2 Choose Tools AutoLISP Visual LISP Editor from the AutoCAD menu, or enter the following at the Command
prompt:
vlisp
You can use either the menu or the vlisp command to return to the VLISP IDE at any time.
Note that AutoCAD also recognizes the vlide command to start or return to Visual LISP. This command name stands for
"Visual LISP interactive development environment." AutoCAD issues the vlide command to call VLISP, and as a result you
may sometimes see "VLIDE" displayed in the AutoCAD Command window.

2. Exploring the Visual LISP User Interface

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.

Topics in this section:


Introducing the Visual LISP Text Editor
Other Visual LISP Windows

2.1 Introducing the Visual LISP Text Editor


You will spend much of your time in VLISP creating or modifying AutoLISP programs. VLISP comes with an integrated
text editor for you to use with AutoLISP code.
To see how the text editor window displays code, open a sample AutoLISP program. Begin with the drawline.lsp file
provided with VLISP.
NOTE The sample files are only included in your installation if you chose Full install, or if you chose Custom install and
selected the Samples item. If you previously installed AutoCAD and did not install the samples, rerun the install, choose
Custom, and select only the Sample item.

To view a LISP program in the VLISP text editor

1 From the VLISP menu, choose File Open File.


2 In the Open File dialog box, select the Sample\VisualLISP folder, which is in your AutoCAD install directory.
3 Double-click the drawline.lsp file.

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.

2.2 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.

3 Touring the Visual LISP Menus


You can issue VLISP commands by choosing from the various menu 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 you're editing.

Topics in this section:

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.

3.2 Touring the Visual LISP Menus


You can issue VLISP commands by choosing from the various menu 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 you're editing.

Topics in this section:

3.2.1 Variable Menu Contents

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.

Visual LISP menu items


Menu item Uses
File Create a new AutoLISP program file for editing, open an existing file, save changes to program files, build Visual
LISP application files, and print program files.
Edit 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 VLISP editor or Console windows, match parentheses in expressions, and redisplay
previous commands entered in the Console window. See the chapter titled "Developing Programs with Visual
LISP" for more information on Edit features.
Search Find and replace text strings, set bookmarks, and navigate among bookmarked text. See "Using the Text Editor" for
information on these topics.
View Find and display the value of variables and symbols in your AutoLISP code. For more information on this topic, see
chapter 3, "Debugging Programs."
Project Work with projects and compile programs. See "Managing Multiple LISP Files," and "Compiling and Linking
Programs" for information on these topics.
Debug Set and remove breakpoints in your program and step through program execution one expression at a time. You can
then check the state of variables and the results of expressions. See chapter 3, "Debugging Programs," for more
information on these features.
Tools Set VLISP options for text formatting and various environment options, such as the placement of windows and
toolbars.
7
Window Organize the windows currently displayed in your VLISP session, or activate another VLISP or AutoCAD window.
Help Display online help.

4 Understanding the Console Window


From the VLISP Console window, you can enter and run AutoLISP commands and see the results. This is similar to what you
can do in the AutoCAD Command window, but there are a few differences—some subtle—in how you accomplish the same
task in these two windows. For example, to display the current value of an AutoLISP variable in VLISP, 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 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.

5. Understanding the Visual LISP Text Editor

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."

Here are some of the major features of the text editor:

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."

6. Loading and Running AutoLISP Programs

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.

To load and run a program in a Visual LISP text editor window

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:

This symbol indicates that the VLISP window is no longer active.


If this is the case, you must manually switch to the AutoCAD window. Click the AutoCAD icon on the Windows task bar to
activate AutoCAD.
The following figure shows AutoCAD prompting for the input requested by drawline:

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.

To run selected lines of AutoLISP code in a Visual LISP editor window

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: "))

2 Press the Load Selection button on the Run toolbar.

VLISP immediately runs the code and switches control to AutoCAD to prompt you for input.

6.2 Using Extended AutoLISP Functions


VLISP provides some extensions to the AutoLISP language that are not loaded automatically when you start AutoCAD. These
functions have names that begin with vla-, vlax-, and vlr. The vla- functions implement ActiveX support in AutoLISP
(described in chapter 6, "Working with ActiveX"). The vlax- functions provide ActiveX utility and data conversion functions,
dictionary handling functions, and curve measurement functions. The vlr- functions provide support for AutoCAD reactors.
Before you can use any of these functions, you need to load the AutoLISP extensions with the following function call:

(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

7 Exiting Visual LISP


When you are finished with your VLISP session, you can close the program by either choosing Exit from the File menu or
clicking the Windows Close button. Note that AutoCAD does not completely unload VLISP but merely closes all VLISP
windows.
Upon exiting AutoCAD, if you have made any changes to the code in any VLISP text editor window and have not saved those
changes, you will be asked if you want to save your changes. You can either save all the changes you've made by choosing Yes,
or save none of the changes by choosing No.

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.

Topics in this chapter:


Getting Organized
11
Using the Console Window
Using the Text Editor
Using Console and Editor Coding Aids
Formatting Code with Visual LISP
Checking for Syntax Errors

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.

2. Using the Console Window


Most programming in VLISP takes place within the confines of the VLISP text editor, but the ability to program interactively
with AutoLISP provides some unique advantages to the development process. In the VLISP Console window you can enter
AutoLISP code and immediately see the results of executing that code.
Enter text in the Console window following the Console prompt, which looks like the following:

_$

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.

Topics in this section:

Understanding Console Behavior


Using the Console Window with Multiple Drawings
Using the Console Shortcut Menu
Logging Console Window Activity

2.1 Understanding Console Behavio


The VLISP Console window is similar in some respects to the AutoCAD Command window, but it provides many more
features. Although the Console window and the AutoCAD Command window provide similar capabilities, you don't always
use the same process to accomplish identical tasks. For example, to display the current value of an AutoLISP variable in
VLISP, 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 enter it at the AutoCAD Command
prompt.

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:

Using the Console Window History


Interrupting Commands and Clearing the Console Input Area

2.1.1 Using the Console Window History


You can retrieve text you previously entered in the Console window by pressing TAB while at the Console prompt. Each time
you press TAB, the previously entered text replaces the text at the Console prompt. You can repeatedly press TAB until you
cycle through all the text entered at the Console prompt during your VLISP session. After you've scrolled to the first entered
line, VLISP starts again by retrieving the last command entered in the Console window, and the cycle repeats. Press
SHIFT+TAB to scroll the input history in the opposite direction.

For example, assume you entered the following commands at the Console prompt:

(setq origin (getpoint "\nOrigin of inyn sign: "))


(setq radius (getdist "\nRadius of inyn sign: " origin))
(setq half-r (/ radius 2))
(setq origin-x (car origin))

(command "_.CIRCLE" origin radius)

To retrieve commands entered in the Console window

1 Press TAB once. VLISP retrieves the last command entered and places it at the Console prompt:

_$ (command "_.CIRCLE" origin radius)

2 Press TAB again. The following command displays at the Console prompt:

_$ (setq origin-x (car origin))

3 Press TAB again. VLISP displays the following command:

_$ (setq half-r (/ radius 2))

4 Now press SHIFT+TAB. VLISP reverses direction and retrieves the command you entered after the previous
command:

_$ (setq origin-x (car origin))

5 Press SHIFT+TAB again. VLISP displays the following command:

_$ (command "_.CIRCLE" origin radius)

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:

_$ (setq origin (getpoint "\nOrigin of inyn sign: "))

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.

To perform an associative search of the Console input history

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:

_$ ((setq origin-x (car origin)

((_>

Pressing SHIFT+ESC interrupts the command, and VLISP displays an "input discarded" message like the following:

((_> ; <input discarded>

_$

(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.

2.2 Using the Console Window with Multiple Drawings


There is a single Console window for all open AutoCAD drawing documents. When you scroll through the Console window,
you see commands entered in all document contexts. This differs from the AutoCAD Command window, which shows only the
commands issued against the current drawing. In other words, each AutoCAD drawing has its own Command window, but all
drawings share the same VLISP Console prompt.
VLISP automatically switches context when you change the active drawing document in AutoCAD. The active document in
AutoCAD is always the active document in VLISP. Commands entered in the VLISP Console window always apply to the
active document. The title bar of the VLISP window contains the name of the active drawing document. The following
example shows how the title bars of the AutoCAD and VLISP windows identify the same drawing document downtown.dwg:

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.

Topics in this chapter:


5
6 9.1 Query and Command Function
The query and command functions described in this section provide direct access to AutoCAD commands and drawing
services. Their behavior depends on the current state of the AutoCAD system and environment variables, and on the drawing
that is currently loaded. See "Query and Command Functions" in appendix A, "Auto LISP Function Synopsis," for a complete
list of query and command functions.
NOTE The Auto LISP examples in this chapter show code entered at the AutoCAD Command prompt, not the Visual LISP
Console window.
Topics in this section:

1.1 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 command's
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 pressing the SPACEBAR or ENTER on the keyboard.

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.

(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)

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.

Topics in this section:


1.2
7 Foreign Language Support
If you develop AutoLISP programs that can be used with a foreign language version of AutoCAD, the standard AutoCAD
commands and keywords are automatically translated if you precede each command or keyword with an underscore (_).

(command "_line" pt1 pt2 pt3 "_c")

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.

a) Foreign Language Support


If you develop AutoLISP programs that can be used with a foreign language version of AutoCAD, the standard AutoCAD
commands and keywords are automatically translated if you precede each command or keyword 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.

b) Pausing for User Inpu

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:

(command "circle" "5,5" pause "line" "5,5" "7,5" "")

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):

(setq blk "MY_BLOCK")


(setq old_lay (getvar "clayer"))
(command "layer" "set" "NEW_LAY" "")
(command "insert" blk pause "" "" pause)

(command "layer" "set" old_lay "")

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.

c) Passing Pick Points to AutoCAD Commands


Some AutoCAD commands (such as TRIM, EXTEND, and FILLET) require the user to specify a pick point as well as the
object itself. To pass such pairs of object and point data by means of the command function without the use of a PAUSE,
16
you must first store them as variables. Points can be passed as strings within the command function or can be defined
outside the function and passed as variables, as shown in the following example. This code fragment shows one method of
passing an entity name and a pick point to the command function.

(command "circle" "5,5" "2") Draws circle


(command "line" "3,5" "7,5" "") Draws line
(setq el (entlast)) Gets last entity name
(setq pt '(5 7)) Sets point pt

(command "trim" el "" pt "") Performs trim

If AutoCAD is at the Command prompt when these functions are called, AutoCAD performs the following actions:

1 Draws a circle centered at (5,5) with a radius of 2.


2 Draws a line from (3,5) to (7,5).
3 Creates a variable el that is the name of the last object added to the database. (See "Using AutoLISP to Manipulate
AutoCAD Objects" for more discussion of objects and object-handling functions.)
4 Creates a pt variable that is a point on the circle. (This point selects the portion of the circle to be trimmed.)

5 Performs the TRIM command by selecting the el object and by selecting the point specified by pt.

d) Undoing Commands Issued with the command Function


An UNDO group is explicitly created around each command used with the command function. If a user enters U (or
UNDO) after running an AutoLISP routine, only the last command will be undone. Additional entries of UNDO will step
backward through the commands used in that routine. If you want a group of commands to be considered a group (or the
entire routine), use the UNDO Begin and UNDO End options.

9.1.2 System and Environment Variables


With the getvar and setvar functions, AutoLISP applications can inspect and change the value of AutoCAD system
variables. These functions use a string to specify the variable name. The setvar function specifies a value of the type that the
system variable expects. AutoCAD system variables come in various types: integers, real values, strings, 2D points, and 3D
points. Values supplied as arguments to setvar must be of the expected type. If an invalid type is supplied, an AutoLISP
error is generated.

The following code fragment ensures that subsequent FILLET commands use a radius of at least 1:

(if (< (getvar "filletrad") 1)


(setvar "filletrad" 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.

9.1.3 Configuration Control


AutoCAD uses the acadxx.cfg file to store configuration information (the xx in the file name refers to the AutoCAD release
number). The AppData section of this file is provided for users and developers to store configuration information pertaining
to their applications. The getcfg and setcfg functions allow AutoLISP applications to inspect and change the value of
parameters in the AppData section.

9.2 Display Control


AutoLISP includes functions for controlling the AutoCAD display in both text and graphics windows. Some functions prompt
for, or depend on, input from the AutoCAD user.
The prompt, princ, prin1, and print functions are the primary text output functions. These functions were described in the
"AutoLISP Basics" chapter, under the heading, "Basic Output Functions."
See "Display Control Functions" in appendix A, "AutoLISP Function Synopsis," for a complete list of display control
functions.

Topics in this section:

9.2.1 Controlling Menu

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.

(menucmd "B1=DIG-BUTTONS") Enables the DIG-BUTTONS submenu

(menucmd "B1=TAB-BUTTONS") Enables the TAB-BUTTONS submenu

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

(menucmd "P0=*") Displays it

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:

(menucmd "P1=MORESTUFF") Loads the **MORESTUFF menu in the


P1 menu location

(menucmd "P1=*") Displays it

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.

(menucmd "P2.4=#?") If disabled returns "P2.4=~"

These function calls enable and disable that same label:

(menucmd "P2.4=") Enables the label

(menucmd "P2.4=~") Disables the label

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.

(menucmd "Gacad.ID_New=~") Disables the label

(menucmd "Gacad.ID_New=") Enables the label

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:

(defun C:CTIME ( / ctim)


(setq ctim
(menucmd "M=$(edtime,$(getvar,date),H:MMam/pm)"))
(princ (strcat "\nThe current time is " ctim ))
(princ)

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.

9.2.2 Control of Graphics and Text Windows


You can control the display of the graphics and text windows from an AutoLISP application. On single-screen AutoCAD
installations, a call to graphscr displays the graphics window, and a call to textscr displays the text window. Using these
functions is equivalent to toggling the Flip Screen function key. The function textpage is like textscr, but textpage clears the
text window before displaying the next text window (as the AutoCAD STATUS and LIST commands do).

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:

(grtext) Restores standard text

(redraw)

9.3 Getting User Input


Several functions enable an AutoLISP application to prompt the user for input of data. See "User Input Functions" in appendix
A, "AutoLISP Function Synopsis," for a complete list of user input functions.

Topics in this section:

9.3.1 The getxxx Functions


Each user-input getxxx function pauses for data entry of the indicated type and returns the value entered. The application
specifies an optional prompt to display before the function pauses. The following table lists the getxxx functions and the type
of user input requested.

Allowable input to the getxxx user-input functions

Function name Type of user input


getint An integer value on the Command line
getreal A real or integer value on the Command line
getstring A string on the Command line
getpoint A point value on the Command line or selected from the screen
getcorner A point value (the opposite corner of a box) on the Command line or selected from the screen
getdist A real or integer value (of distance) on the Command line or determined by selecting points on the screen
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 A predefined keyword or its abbreviation on the Command line
NOTE Although the getvar, getcfg, and getenv functions begin with the letters g, e, and t, they are not user-input functions.
They are discussed in "Query and Command 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 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).

Possible return values from getangle and getorient

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."

9.3.2 Control of User-Input Function Conditions


The initget function provides a level of control over the next user-input function call. The initget function establishes various
options for use by the next entsel, nentsel, nentselp, or getxxx function (except getstring, getvar, and getenv). This function
accepts two arguments, bits and string, both of which are optional. The bits argument specifies one or more control bits that
enable or disable certain input values to the following user-input function call. The string argument can specify keywords that
the following user-input function call will recognize.

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.

Topics in this section:

a) Input Options for User-Input Functions


The value of the bits argument restricts the types of user input to the following user-input function call. This reduces error-
checking. These are some of the available bit values: 1 disallows null input, 2 disallows input of 0 (zero), and 4 disallows
negative input. If these values are used with a following call 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 applies to the next user-input function call. (For a
complete listing of initget bit settings, see "initget" in the AutoLISP Reference.)

(initget (+ 1 2 4))

(getint "\nHow old are you? ")

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.

(defun C:GETNUM (/ num)


(initget 1 "Pi Two-pi")
(setq num (getreal "Pi/Two-pi/<number>: "))
(cond
((eq num "Pi") pi)
((eq num "Two-pi") (* 2.0 pi))
(T num)
)

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.

c) Arbitrary Keyboard Inpu


The initget function also allows arbitrary keyboard input to most getxxx functions. This input is passed back to the
application as a string. An application using this facility can be written to permit the user to call an AutoLISP function at a
getxxx function prompt.
These functions show a method for allowing AutoLISP response to a getxxx function call:

(defun C:ARBENTRY ( / pt1)


(initget 128) ; Sets arbitrary entry bit
(setq pt1 (getpoint "\nPoint: ")) ; Gets value from user.
(if (= 'STR (type pt1)) ; If it's a string, convert it
(setq pt1 (eval (read pt1))) ; to a symbol, try evaluating
; it as a function; otherwise,
pt1 ; just return the value.
)
)
(defun REF ( )
(setvar "LASTPOINT" (getpoint "\nReference point: "))

(getpoint "\nNext point: " (getvar "LASTPOINT"))

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

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.

9.4 Geometric Utilities


A group of functions allows applications to obtain pure geometric information and geometric data from the drawing. See
"Geometric Functions" in appendix A, "AutoLISP Function Synopsis," for a complete list of geometric utility functions.
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 pt1 '(3.0 6.0 0.0))


(setq pt2 '(5.0 2.0 0.0))
(setq base '(1.0 7.0 0.0))
(setq rads (angle pt1 pt2)) ; Angle in XY plane of current UCS
; (value is returned in radians)

(setq len (distance pt1 pt2)) ; Distance in 3D space


(setq endpt (polar base rads len))

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.

Topics in this section:

9.4.1 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.
NOTE The APERTURE system variable determines the allowable proximity of a selected point to an object when you use
Object Snap.

9.4.2 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.
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: (setq e (entget (entlast)))


((-1 . <Entity name: 1ba3568>) (0 . "TEXT") (330 . <Entity name: 1ba34f8>) (5 .
"2D") (100 . "AcDbEntity") (67 . 0) (410 . "Model") (8 . "0") (100 .
"AcDbText") (10 1.0 1.0 0.0) (40 . 1.0) (1 . "test") (50 . 0.0) (41 . 1.0) (51
. 0.0) (7 . "Standard") (71 . 0) (72 . 0) (11 0.0 0.0 0.0) (210 0.0 0.0 1.0)

(100 . "AcDbText") (73 . 0))

Command: (textbox e)

((0.0 0.0 0.0) (0.8 0.2 0.0))

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:

(defun C:TBOX ( / textent tb ll ur ul lr)


(setq textent (car (entsel "\nSelect text: ")))
(command "ucs" "Object" textent)
(setq tb (textbox (list (cons -1 textent)))
ll (car tb)
ur (cadr tb)
ul (list (car ll) (cadr ur))
lr (list (car ur) (cadr ll))
)
(command "pline" ll lr ur ul "Close")
(command "ucs" "p")
(princ)

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.

(defun C:TBOX2 ( / textent ang sinrot cosrot


t1 t2 p0 p1 p2 p3 p4)
(setq textent (entget (car (entsel "\nSelect text: "))))
(setq p0 (cdr (assoc 10 textent))
ang (cdr (assoc 50 textent))
sinrot (sin ang)
cosrot (cos ang)
t1 (car (textbox textent))
t2 (cadr (textbox textent))
p1 (list
(+ (car p0)
(- (* (car t1) cosrot)(* (cadr t1) sinrot))
)
(+ (cadr p0)

(+ (* (car t1) sinrot)(* (cadr t1) cosrot))


)
)
p2 (list
(+ (car p0)
(- (* (car t2) cosrot)(* (cadr t1) sinrot))
)
(+ (cadr p0)
(+ (* (car t2) sinrot)(* (cadr t1) cosrot))
)
)
p3 (list
(+ (car p0)
(- (* (car t2) cosrot)(* (cadr t2) sinrot))
)
(+ (cadr p0)
(+ (* (car t2) sinrot)(* (cadr t2) cosrot))
25
)
)

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.

Topics in this section:

9.5.1 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 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 ")

(setq fmtval (rtos x 1 4)) ; Mode 1 = scientific

(princ (strcat str fmtval)) ; displays Value formatted as 1.7500E+01

(setq fmtval (rtos x 2 2)) ; Mode 2 = decimal

(princ (strcat str fmtval)) ; displays Value formatted as 17.50

(setq fmtval (rtos x 3 2)) ; Mode 3 = engineering

(princ (strcat str fmtval)) ; displays Value formatted as 1'-5.50"

(setq fmtval (rtos x 4 2)) ; Mode 4 = architectural

(princ (strcat str fmtval)) ; displays Value formatted as 1'-5 1/2"

(setq fmtval (rtos x 5 2)) ; Mode 5 = fractional

(princ (strcat str fmtval)) ; 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 1'5.50"


26
Value formatted as 1'5-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 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.)

(distof "1.7500E+01" 1) ; Mode 1 = scientific


(distof "17.50" 2) ; Mode 2 = decimal
(distof "1'-5.50\"" 3) ; Mode 3 = engineering
(distof "1'-5 1/2\"" 4) ; Mode 4 = architectural
(distof "17 1/2" 5) ; Mode 5 = fractional

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)) ; Mode 0 = degrees

(princ (strcat str2 fmtval)) ; displays Angle formatted as 180

(setq fmtval (angtos ang 1 4)) ; Mode 1 = deg/min/sec

(princ (strcat str2 fmtval)) ; displays Angle formatted as 180d0'0"

(setq fmtval (angtos ang 2 4)) ; Mode 2 = grads

(princ (strcat str2 fmtval)) ; displays Angle formatted as 200.0000g

(setq fmtval (angtos ang 3 4)) ; Mode 3 = radians

(princ (strcat str2 fmtval)) ; displays Angle formatted as 3.1416r

(setq fmtval (angtos ang 4 2)) ; Mode 4 = surveyor's

(princ (strcat str2 fmtval)) ; displays Angle formatted as W

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.

(angtof "180" 0) ; Mode 0 = degrees


(angtof "180d0'0\"" 1) ; Mode 1 = deg/min/sec
27
(angtof "200.0000g" 2) ; Mode 2 = grads
(angtof "3.14159r" 3) ; Mode 3 = radians

(angtof "W" 4) ; Mode 4 = surveyor's

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.

9.5.2 Angular Conversion


If your application needs to convert angular values from radians to degrees, you can 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))) returns 90.0

However, a more efficient method might be to include a Radian->Degrees function in your application. The following
code shows this:

; Convert value in radians to degrees


(defun Radian->Degrees (nbrOfRadians)
(* 180.0 (/ nbrOfRadians pi))

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

9.5.3 ASCII Code Conversion


AutoLISP provides the ascii and chr functions that handle decimal ASCII codes. The ascii function returns the ASCII
decimal value associated with a string, and chr returns the character associated with an ASCII decimal value.
To see your system's characters with their codes in decimal, octal, and hexadecimal form, save the following AutoLISP
code to a file named ascii.lsp. Then load the file and enter the new ASCII command at the AutoCAD Command prompt.
This command prints the ASCII codes to the screen and to a file called ascii.txt. The C:ASCII function makes use of the
BASE function. You may find this conversion utility useful in other applications.

; BASE converts from a decimal integer to a string in another base.


(defun BASE ( bas int / ret yyy zot )
(defun zot ( i1 i2 / xxx )
(if (> (setq xxx (rem i2 i1)) 9)
(chr (+ 55 xxx))
(itoa xxx)
)
)
(setq ret (zot bas int) yyy (/ int bas))
(while (>= yyy bas)
(setq ret (strcat (zot bas yyy) ret))
(setq yyy (/ yyy bas))
)
(strcat (zot bas yyy) ret)

)
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))

(if (< (strlen oct) 3)(setq oct (strcat "0" oct)))


(princ (strcat "\n " (chr code) " " dec " "
oct " " hex ) )
(princ (strcat "\n " (chr code) " " dec " "
oct " " hex ) out)
(cond
((= code 255)(setq chk nil))
((= ct 20)
(setq xxx (getstring
"\n \nPress 'X' to eXit or any key to continue: "))
(if (= (strcase xxx) "X")
(setq chk nil)

(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)

9.5.4 Unit Conversion


The acad.unt file 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.

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.

Topics in this section:

a) Converting from Inches to Meters


If the current drawing units are engineering or architectural (feet and inches), the following routine converts a user-
specified distance of inches into meters:

(defun C:I2M ( / eng_len metric_len eng metric)


(princ "\nConverting inches to meters. ")
(setq eng_len
29
(getdist "\nEnter a distance in inches: "))
(setq metric_len (cvunit eng_len "inches" "meters"))
(setq eng (rtos eng_len 2 4)
metric (rtos metric_len 2 4))
(princ
(strcat "\n\t" eng " inches = " metric " meters."))
(princ)

b) The Unit Definition File


With the AutoCAD unit definition file acad.unt, you can define factors to convert data in one set of units to another set of
units. The definitions in acad.unt are in ASCII format and are used by the unit-conversion function cvunit.
You can make new units available by using a text editor to add their definitions to acad.unt. A definition consists of two
lines in the file—the unit name and the unit definition. The first line must have an asterisk (*) in the first column, followed
by the name of the unit. A unit name can have several abbreviations or alternate spellings, separated by commas. If a unit
name has singular and plural forms, you can specify these using the following format:

*[ [common] [ ( [singular.] plural) ] ]...

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:

Velocity of light in a vacuum

Electron charge

Planck's constant

Boltzman's constant

Electron rest mass

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

The definition of a township is given as 93,239,571.456 square meters.

; 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.

; This entire line is a comment.

List the acad.unt file itself for more information and examples.

9.5.5 Coordinate System Transformations


The trans function translates a point or a displacement from one coordinate system into another. It takes a point argument,
pt, that can be interpreted as either a 3D point or a 3D displacement vector, distinguished by a displacement argument
called disp. The disp argument must be nonzero if pt is to be treated as a displacement vector; otherwise, pt is treated as a
point. A from argument specifies the coordinate system in which pt is expressed, and a to argument specifies the desired
coordinate system. The following is the syntax for the trans function:

(trans pt from to [disp])

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:

Coordinate system codes

Code Coordinate system


0 World (WCS)
1 User (current UCS)
2 Display; DCS of current viewport when used with code 0 or 1, DCS of current model space viewport when used with
code 3
3 Paper space DCS, PSDCS (used only with code 2)
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) ; WCS
(setq cs_to 1) ; UCS

(trans pt cs_from cs_to 0) ; disp = 0 indicates that pt is a point

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:

(trans pt cs_to cs_from 0) ; the result is (–2.0,1.0,3.0)

Topics in this section:

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.

9.6 File Handling


AutoLISP provides functions for handling files and data I/O. See "File-Handling Functions" in appendix A, "AutoLISP
Function Synopsis," for a complete list of file-handling functions.

Topics in this section:

9.6.1 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, 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.

9.6.2 Accessing Help Files


The help function provides access to both AutoCAD Help files (.ahp) and Windows Help files (.hlp). Depending on the
Help file's extension, the help function calls the AutoCAD or the Windows Help viewer with the specified file. You can
use this function to add a Help facility to your applications. The following code fragment calls the default AutoCAD Help
file and provides information about the LINE command.
33
(help "" "line")

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
.
)

(setfunhelp c:mycmd "morehelp.hlp" "mycmd")

9.7 Device Access and Control


AutoLISP provides the grread and tablet functions for accessing data from the various input devices.
Note that the read-char and read-line file-handling functions can also read input from the keyboard input buffer. See the
AutoLISP Reference for more information on these functions.

Topics in this section:

Accessing User Input


Calibrating Tablets

9.7.1 Accessing User Input


The grread function returns raw user input, whether from the keyboard or from the pointing device (mouse or digitizer). If
the call to grread enables tracking, the function returns a digitized coordinate that can be used for things such as dragging.
NOTE There is no guarantee that applications calling grread will be upward compatible. Because it depends on the current
hardware configuration, applications that call grread are not likely to work in the same way on all configurations.

9.72. Calibrating Tablets


AutoCAD users can calibrate a digitizing tablet by using the TABLET command (see the 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 row3—are the three rows of the tablet's
transformation matrix. The fourth point, direction, is a vector that is normal to the plane in which the tablet's surface is
assumed to lie (expressed in WCS, the World Coordinate System). When the calibration is set with the TABLET
command, the tablet's 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.")
)
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:

(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)

)
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

You might also like