NP CAD Page | Articles | Russian | Download

AutoLISP by Example: Getting Started

(from D.Abbott's book "AutoCAD®: Secrets Every User Should Know")

I don't know why more users don't write programs in AutoLISP; perhaps the very notion of programming is too intimidating. And yet nothing has more potential to expand your AutoCAD efficiency than programming new commands. Of all the programming tools out there, AutoLISP is the most accessible to AutoCAD users; but do I really think every user should know how to program in AutoLISP? Yes, I do — and you'll see why as you work through this chapter.

If the prospect of programming leaves you a bit daunted, I've got good news: If you can use AutoCAD, you can program in AutoLISP. To show you how easy it is, let's write a program right now. Just follow these steps:

1. At the AutoCAD command line, type this: (defun C:OO()(setvar "osmode" 4143))<Enter>
2. Clear your osnap settings in the Object Snap tab of the Drafting Settings dialog box.
3. Type OO<Enter> at the command line..

Congratulations, you've just written an AutoLISP program. To see what it did, check the settings for running object snaps again. We'll get back to this program after I give you a little background. When you finish this chapter, you'll be thinking up and creating all kinds of useful new AutoLISP functions of your own.

Background

AutoLISP is a powerful customizing tool with which you can write useful new AutoCAD commands in minutes. Although other programming languages are often used with AutoCAD (most notably Visual Basic for Applications [VBA] and C++), AutoLISP is an especially good choice for AutoCAD users because it relies heavily on native AutoCAD commands. It may not be the most sophisticated programming language, but what do you care as long as it's easy to use? Every accomplished VBA programmer I know still uses AutoLISP for some AutoCAD-related programming.

The AutoLISP programming language first appeared in AutoCAD R2.18. Its early appearance is one of the reasons AutoCAD is the most widely used CAD program today. The existence of a programming language made it possible for savvy users to dramatically improve AutoCAD by adding new functions. Those functions often became commands in later releases, but even when they didn’t, they made AutoCAD much more useful than competing applications. Despite the appearance of other programming languages since its inception, AutoLISP is still the primary means by which users customize AutoCAD.

AutoLISP is a subset of LISP (List Processing), which goes back to the late 1950s. I’ve often seen LISP referred to as the second-oldest programming language still in use, Fortran being the oldest. In addition to its use in AutoCAD, LISP is still used widely in Artificial Intelligence programming.

Visual LISP (VLISP or VLIDE) appeared in AutoCAD 2000 as a major enhancement to AutoLISP. It adds a development environment with debugging tools and a compiler, as well as a set of new functions, including some known as reactors. Although I’ll introduce some features of the Visual LISP editor in this book, I can’t do it justice here. Once you get the AutoLISP bug, you can learn more about special Visual LISP editing features and the extensive collection of Visual LISP functions by consulting AutoCAD’s help system for more information or using your favorite search engine to find Visual LISP references.

    You can access the AutoLISP, Visual LISP, and Drawing Interchange File (DXF) documentation by choosing Help | Additional Resources | Developer Help from the AutoCAD menu.

AutoCAD Commands

Because some commands and many Express tools are written in AutoLISP, most of us use AutoLISP programs on a regular basis without knowing it. The C:\Program Files\AutoCAD 2007\Express directory contains 70 AutoLISP programs, including the following programs that are so useful you might think they’re native commands.

  • aliasedit.lsp
  • aspace.lsp
  • attout.lsp
  • breakl.lsp
  • bscale.lsp
  • burst.lsp
  • dimassoc.lsp
  • flatten.lsp
  • layoutmerge.lsp
  • lman.lsp
  • overkill.lsp
  • saveall.lsp
  • tcase.lsp
  • textmask.lsp
  • txtexp.lsp

    Finding AutoLISP Programs

    You can find other AutoLISP programs at countless websites, in books, in magazines, and on the computers of your friends and colleagues. For a great place to start, visit the Autodesk User Group International website at www.AUGI.com. Other sites come and go, so I won’t list them here, but a web search will turn up millions of AutoLISP programs on hundreds of thousands of sites. Many of them are free, because AutoLISP programmers are generous with their work. (Remember this when you become good enough to create useful programs.) Check the copyright information of any program you find, and always follow the author’s requirements. After all, an AutoLISP program is the intellectual property of its author.

    AutoLISP programs range from simple to complex, and they require a thorough knowledge of AutoCAD commands. Because you already know the AutoCAD command structure, you’re ready to start programming in AutoLISP.

    Writing AutoLISP Programs

    I call this chapter "AutoLISP by Example" because I use code examples to demonstrate key features of programming. This chapter isn’t for experienced programmers; it’s for AutoCAD users. When I first decided to try AutoLISP, the reference I consulted began with a discussion about atoms, lists, Lambda expressions, cons and Mapcar, with one-line examples that were out of context and meant nothing to me. I had a specific goal: to write a command that would automatically insert one drawing into another. I didn’t solve my problem until I looked at actual programs to see how they worked. With that experience in mind, I’m going to give you sample programs and explain how they work. All you have to do is type them in correctly, try them, and read the explanations. It’s that simple.

    MY FIRST AUTOLISP PROGRAM

      I taught introductory AutoCAD for the first time in 1989. At the outset, I knew I'd have to evaluate student work electronically to check their geometry for accuracy, so every week I loaded each student's drawing, used the DIST command and ID to check the dimensions and locations, zoomed in on the most likely problem areas, and otherwise attempted to be diligent about giving useful and timely feedback. But with 60 students submitting drawings once a week, grading took forever. Then I had a brainstorm—the one you probably had as soon as you started reading this sidebar. Why not insert my drawing directly on top of theirs, on a grade layer with a dashed linetype in a color students didn't use? That way I could eliminate a bunch of steps.
      That helped, but not enough. I decided to automate the whole process, which meant I had to learn AutoLISP in a hurry. It seemed easy enough to use DEFUN to create a new command, and to run AutoCAD commands from an AutoLISP program. But I couldn’t get my program to work. After hours of frustration, I opened all the AutoLISP programs I could find to see if any of them dealt with drawing files. And I discovered something puzzling: Whenever a program made a reference to a filename, it used a double backslash to separate folders and files in a path. Is that why I couldn’t insert a drawing? Could it be that simple?
      In a word: yes. I was hooked! Grading for three introductory classes became a breeze as I added more features to the grading commands. Students got their work back quickly, affording me more time for the real work of teaching. That’s the true appeal of AutoLISP to me — a more interesting work life.

    Program Structure

    I want you to get started writing programs, but to avoid some common pitfalls, you should understand something about the structure of AutoLISP programs. These rules for program structure apply to all AutoLISP programs. They have the same importance to programming that the rules for sentence structure have to writing:

  • Every program contains one or more AutoLISP functions, such as DEFUN, GETPOINT, + and .
  • Each function name is preceded by an opening parenthesis.
  • Every opening parenthesis must have a balancing closing parenthesis somewhere.
  • Spaces or quotation marks are used to separate components within parentheses.
  • Functions are followed by arguments to the function, if they’re necessary.

    Let's take a computational function as an example. Because the division function in AutoLISP is represented by the forward slash, the syntax for dividing two numbers is as follows: (/ 4.0 2).

    An open parenthesis is followed by the function / which is followed by at least one space, which is followed by at least two arguments separated by spaces, the numerator 4.0 and the divisor 2.followed by a closing parenthesis. This function would be translated into English as "divide 4.0 by 2." Other functions, such as (* 4.0 2), (+ 4.0 2), and (- 4.0 2) are formatted the same way. This isn't the same structure you may expect from having studied math, so don't try using (2 + 2). It won't work, because the first element after the parenthesis is an integer, not a function.

    Entering Programs in AutoCAD

    You can do all the programming you want in your mind, but until you enter your programs into AutoCAD they won't do anything. Unfortunately, there is no way to dump the contents of your head directly into AutoCAD, so you have to do some typing. There are three ways to get AutoCAD to use an AutoLISP program:

  • Type it at the command line.
  • Load a text file that contains AutoLISP code.
  • Use the load function of the Visual LISP editor.
  • Typing at the command line is generally used only for testing short lines of code. However, I often write a very short program this way when I need to do something that's so specific to the current drawing that there's no reason to save it. I did that recently to create polyline circles. I didn't think I'd need to do it again, so I just wrote a program at the command line. When I exited AutoCAD, the program ceased to exist.

    Typing at the command line is generally used only for testing short lines of code. However, I often write a very short program this way when I need to do something that's so specific to the current drawing that there's no reason to save it. I did that recently to create polyline circles. I didn't think I'd need to do it again, so I just wrote a program at the command line. When I exited AutoCAD, the program ceased to exist.

    UPPERCASE OR LOWERCASE?

      There are only a few places where case matters in AutoLISP.
    • When you place a control character, such as the new-line character, in a prompt or other quoted string, it must be in lowercase, as in "\nSelect point: ".
    • When you indicate during a file-opening procedure how you want to treat the file (read, write, or append) the letters for that must also be lowercase, as in (open "C:\\file.dwg" "r").
      Otherwise, it's your call whether to use uppercase or lowercase. Just be consistent, so you won't confuse yourself later.

    Let's get the command-line procedure out of the way first.

    Command-Line Entry

    Go back to the program introduced in the introduction to this chapter. To enter that AutoLISP program at the command line, you did this:

  • You typed (defun C: OO()(setvar "osmode" 4143))<Enter> at the command line. If you made no errors, "C:OO" appeared on the command line.
  • To test the program, you cleared your existing running osnaps.
  • To use the new command you created, you typed OO at the command line. You should have seen "4143" returned.
  • When you checked again, you should have had the following object snap settings: End, Mid, Cen, Nod, Int, Ext.
  • You just defined a new AutoCAD command with the name OO. When you type it, the setting for OSMODE, which controls your object snap settings, is changed to 4143. That happens to be the value of my standard running osnaps. I like this little command, because I often change to a single running object snap for a series of actions. When I want my old settings back, typing OO is much quicker than opening the Drafting Settings dialog box.

      AutoCAD uses system variables (sometimes referred to as setvars) to control many aspects of the program. All of AutoCAD's system variables (there are nearly 550 of them in AutoCAD 2007) can be read from AutoLISP using the GETVAR function, and many of them can be changed using the SETVAR function. OSMODE is such a setvar, for example. The more familiar you are with system variables, the more effectively you can use AutoLISP. You can view all setvars by typing _setvar<Enter>?<Enter>*<Enter> at the command prompt or looking at the alphabetically organized list in the Help system.

    There's one problem. This nifty new command is stored in RAM, so it won't be available if you open another drawing, and it will disappear if you close the current drawing. If you want to use it again, you have to save it.


    NP CAD Page | Articles | Russian | Download