AutoCAD Platform Customization: AutoLISP
()
About this ebook
AutoLISP is the key to unlocking the secrets of a more streamlined experience using industry leading software programs like AutoCAD, Civil 3D, Plant 3D, and more.
AutoCAD Platform Customization: AutoLISP provides real-world examples that show you how to do everything from modifying graphical objects and reading and setting system variables to communicating with external programs. It also features a resources appendix and downloadable datasets and customization examples—tools that ensure swift and easy adoption.
- Find out how to remove unused buttons from the ribbon to gain screen space
- Discover how to create macros for frequently performed actions, or add your company's logo to the bottom of every drawing
- Learn to perform more involved customizations, like communicating with a database to validate and update information entered in drawing layers
- Ideal for CAD administrators, senior drafters, savvy users, and other professionals and students
Through detailed discussions and tutorials that include real-world examples, this book gives you the power to enhance your program's experience and output.
Related to AutoCAD Platform Customization
Related ebooks
Mastering AutoCAD Civil 3D 2013 Rating: 0 out of 5 stars0 ratingsGoogle SketchUp 8 For Dummies Rating: 4 out of 5 stars4/5Exploring Autodesk Revit MEP 2016 Rating: 4 out of 5 stars4/5Autodesk Revit 2024 Black Book Rating: 5 out of 5 stars5/5Mastering AutoCAD Civil 3D 2015: Autodesk Official Press Rating: 0 out of 5 stars0 ratingsArchiCAD 19 – The Definitive Guide Rating: 3 out of 5 stars3/5Mastering AutoCAD 2021 and AutoCAD LT 2021 Rating: 4 out of 5 stars4/5Exploring Autodesk Revit 2018 for Architecture, 14th Edition Rating: 5 out of 5 stars5/5Autodesk Revit 2023 Black Book Rating: 5 out of 5 stars5/5Autodesk CFD 2023 Black Book Rating: 0 out of 5 stars0 ratingsAutoCAD 2023 : Beginners And Intermediate user Guide Rating: 0 out of 5 stars0 ratingsFreeCAD Basics Tutorial Rating: 3 out of 5 stars3/5Beginning AutoCAD® 2024 Exercise Workbook Rating: 0 out of 5 stars0 ratingsRevit 2020 for Architecture: No Experience Required Rating: 0 out of 5 stars0 ratingsAutodesk Revit 2020 Black Book Rating: 0 out of 5 stars0 ratingsSketchUp For Dummies Rating: 4 out of 5 stars4/5AutoCAD 2010 Tutorial Series: Drawing a Floor Plan Rating: 5 out of 5 stars5/5Mastering Autodesk Revit 2020 Rating: 0 out of 5 stars0 ratings3D Printing For Dummies Rating: 4 out of 5 stars4/5AutoCAD 2018 For Architectural Design Rating: 5 out of 5 stars5/5Exploring Autodesk Navisworks 2016 Rating: 0 out of 5 stars0 ratingsAutoCAD® 3D Modeling: Exercise Workbook Rating: 0 out of 5 stars0 ratingsAutodesk Inventor 2015 Tutorial Rating: 4 out of 5 stars4/5AutoCAD LT 2017 for Designers, 12th Edition Rating: 0 out of 5 stars0 ratingsAutoCAD Electrical 2016 for Electrical Control Designers Rating: 0 out of 5 stars0 ratingsAutodesk® Revit Basics Training Manual Rating: 5 out of 5 stars5/5The Ultimate Guide To Auto Cad 2022 3D Modeling For 3d Drawing And Modeling Rating: 0 out of 5 stars0 ratingsAutodesk Revit 2021 Black Book Rating: 5 out of 5 stars5/5Exploring Autodesk Revit 2018 for MEP, 5th Edition Rating: 1 out of 5 stars1/5LibreCAD Basics Tutorial Rating: 0 out of 5 stars0 ratings
Computers For You
How to Create Cpn Numbers the Right way: A Step by Step Guide to Creating cpn Numbers Legally Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsThe Invisible Rainbow: A History of Electricity and Life Rating: 5 out of 5 stars5/5Uncanny Valley: A Memoir Rating: 4 out of 5 stars4/5The Innovators: How a Group of Hackers, Geniuses, and Geeks Created the Digital Revolution Rating: 4 out of 5 stars4/5Deep Search: How to Explore the Internet More Effectively Rating: 5 out of 5 stars5/5Elon Musk Rating: 4 out of 5 stars4/5Standard Deviations: Flawed Assumptions, Tortured Data, and Other Ways to Lie with Statistics Rating: 4 out of 5 stars4/5Mastering ChatGPT: 21 Prompts Templates for Effortless Writing Rating: 4 out of 5 stars4/5Slenderman: Online Obsession, Mental Illness, and the Violent Crime of Two Midwestern Girls Rating: 4 out of 5 stars4/5Alan Turing: The Enigma: The Book That Inspired the Film The Imitation Game - Updated Edition Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5The ChatGPT Millionaire Handbook: Make Money Online With the Power of AI Technology Rating: 4 out of 5 stars4/5CompTIA Security+ Get Certified Get Ahead: SY0-701 Study Guide Rating: 5 out of 5 stars5/5ChatGPT 4 $10,000 per Month #1 Beginners Guide to Make Money Online Generated by Artificial Intelligence Rating: 0 out of 5 stars0 ratingsEverybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5The Professional Voiceover Handbook: Voiceover training, #1 Rating: 5 out of 5 stars5/5101 Awesome Builds: Minecraft® Secrets from the World's Greatest Crafters Rating: 4 out of 5 stars4/5Procreate for Beginners: Introduction to Procreate for Drawing and Illustrating on the iPad Rating: 5 out of 5 stars5/5The Data Warehouse Toolkit: The Definitive Guide to Dimensional Modeling Rating: 0 out of 5 stars0 ratingsLearning the Chess Openings Rating: 5 out of 5 stars5/5CompTIA IT Fundamentals (ITF+) Study Guide: Exam FC0-U61 Rating: 0 out of 5 stars0 ratingsPeople Skills for Analytical Thinkers Rating: 5 out of 5 stars5/5
Reviews for AutoCAD Platform Customization
0 ratings0 reviews
Book preview
AutoCAD Platform Customization - Lee Ambrosius
Senior Acquisitions Editor: Willem Knibbe
Development Editor: Mary Ellen Schutz
Technical Editor: Craig Black
Production Editor: Dassi Zeidel
Copy Editor: Liz Welch
Editorial Manager: Pete Gaughan
Vice President and Executive Group Publisher: Richard Swadley
Associate Publisher: Chris Webb
Book Designers: Maureen Forys, Happenstance Type-O-Rama; Judy Fung
Proofreader: Candace Cunningham
Indexer: Ted Laux
Project Coordinator, Cover: Patrick Redmond
Cover Designer: Wiley
Cover Image: © Smileyjoanne/iStockphoto.com
Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-1-118-90055-0 (ebk.)
ISBN: 978-1-118-90696-5 (ebk.)
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make. Further, readers should be aware that Internet Web sites listed in this work may have changed or disappeared between when this work was written and when it is read.
For general information on our other products and services or to obtain technical support, please contact our Customer Care Department within the U.S. at (877) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
TRADEMARKS: Wiley, the Wiley logo, and the Sybex logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the United States and other countries, and may not be used without written permission. AutoCAD and AutoLISP are registered trademarks of Autodesk, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
Dear Reader,
Thank you for choosing AutoCAD Platform Customization: AutoLISP. This book is part of a family of premium-quality Sybex books, all of which are written by outstanding authors who combine practical experience with a gift for teaching.
Sybex was founded in 1976. More than 30 years later, we're still committed to producing consistently exceptional books. With each of our titles, we're working hard to set a new standard for the industry. From the paper we print on, to the authors we work with, our goal is to bring you the best books available.
I hope you see all that reflected in these pages. I'd be very interested to hear your comments and get your feedback on how we're doing. Feel free to let me know what you think about this or any other Sybex book by sending me an email at [email protected]. If you think you've found a technical error in this book, please visit http://sybex.custhelp.com. Customer feedback is critical to our efforts at Sybex.
Best regards,
Chris Webb
Associate Publisher
Sybex, an Imprint of Wiley
To my wife, who is also my best friend: It is hard to imagine that I would be writing this book if it were not for you. It was you, all those years ago, who encouraged me to step outside of my comfort zone and share what I knew with others. Thank you for the push I needed and for coming along on this journey with me.
Acknowledgments
I have to give a very special thanks to all the great folks at Sybex for working on and helping to get this project off the ground after a few years of talking about it, especially Willem Knibbe. The next two people I would like to thank are Mary Ellen Schutz and Dassi Zeidel, the development and production editors on this book; you two made sure I stayed on track and delivered a high-quality book. I also want to thank Liz Welch (copyeditor), Candace Cunningham (proofreader), and Ted Laux (indexer) for the work you all did on this book.
Thanks to all the folks at Autodesk, who put in the long hours and are dedicated to the work they do on the Autodesk® AutoCAD® product. Last but not least, to a great friend of mine, Craig Black. I have known Craig for nearly 20 years. I first met him while attending an AutoLISP® session at the local Autodesk Training Center, where he was an instructor. Craig is a great AutoLISP programmer and it was a joy to have him as the technical editor on this book. Being a technical editor is never the easiest job, but it is one of the most important and I appreciate what you have done to make this book better.
About the Author
Lee Ambrosius first started working with AutoCAD R12 for DOS in 1994. As a drafter, he quickly discovered that every project included lots of repetition. Lee, not being one to settle for this is just the way things are,
set out on a path that would redefine his career. This new path would lead him into the wondrous world of customization and programming—which you might catch him referring to as the rabbit hole.
In 1996, Lee began learning the core concepts of customizing the AutoCAD user interface and AutoLISP. The introduction of VBA in AutoCAD R14 would once again redefine how Lee approached programming solutions for AutoCAD. VBA made it much easier to communicate with external databases and other applications that supported VBA, and transformed the way information could be moved between project-management and manufacturing systems.
Not being content with VBA, in 1999 Lee attended his first Autodesk University and began to learn ObjectARX®. Autodesk University made a lasting impression on him. In 2001, he started helping as a lab assistant. He began presenting on customizing and programming AutoCAD at the event in 2004. Along the way he learned how to use the AutoCAD Managed .NET API.
In 2005, Lee decided cubicle life was no longer for him, so he ventured off into the CAD industry as an independent consultant and programmer for his own company, named HyperPics, LLC. After he spent two years as a consultant, Autodesk invited him to work on the AutoCAD team; he has been on the AutoCAD team since 2007. For most of his career at Autodesk, Lee has worked primarily on the customization and end-user documentation. Recently, he has been working on the AutoLISP, VBA, ObjectARX, .NET, and JavaScript programming documentation.
In addition to working on the AutoCAD documentation, Lee has been involved with the AutoCAD and AutoCAD LT Bible, AutoCAD for Dummies, AutoCAD & AutoCAD LT All-in-One Desk Reference for Dummies, AutoCAD 3D Modeling Workbook for Dummies, and Mastering AutoCAD for Mac books on different editions as a technical writer or author. He has also written white papers on customization for Autodesk and a variety of articles for AUGIWorld, published by AUGI®, on customization and programming.
Introduction
Welcome to AutoCAD Platform Customization: AutoLISP! Have you ever thought to yourself, Why doesn't the Autodesk® AutoCAD® program include every feature I need? Why isn't it streamlined for the type of work I perform? If so, you are not alone. AutoCAD at its core is a drafting platform that can be shaped and molded to more efficiently complete the tasks you perform on a daily basis and to enhance your company's workflows with the use of programming. Take a deep breath. I did just mention programming, but programming isn't something to fear. At first, just the idea of programming makes many people want to run in the opposite direction—myself included. The productivity gains are what propelled me forward. Programming isn't all that different from anything else you've tried doing for the first time.
In many ways, learning to program is much like learning a foreign language. For many new to AutoLISP®, the starting place is often a basic understanding of syntax and the command function. The command function allows you to leverage your knowledge of AutoCAD commands by being able to pass specific values to a command or pausing a command for a value. After you are comfortable with the syntax of AutoLISP and the command function, you can begin to learn additional functions that allow for the development of more robust and complex programs.
About This Book
AutoCAD Platform Customization: AutoLISP provides you with an understanding of the AutoLISP programming language and how it can help improve your productivity. This book is designed to be more than just an introduction to AutoLISP—a resource that can be used time and again when developing AutoLISP programs. As you page through this book, you will notice that it contains sample code and exercises that are based on real-world solutions.
This book is the second in a series of three that focuses on customizing and programming AutoCAD. The three-book series as a whole is known as AutoCAD Platform Customization: User Interface, AutoLISP, VBA, and Beyond, which will be available as a printed book in late 2014/early 2015. Book 1 in the series, AutoCAD Platform Customization: User Interface and Beyond, was published in early 2014 and focused on CAD standards and general customization of AutoCAD; book 3, AutoCAD Platform Customization: VBA, will be available in fall/winter 2014 and covers the VBA programming platform inside AutoCAD.
Is This Book for You?
AutoCAD Platform Customization: AutoLISP covers many aspects of AutoLISP programming for AutoCAD on Windows and Mac OS. If any of the following are true, this book will be useful to you:
You want to develop and load custom programs using the AutoLISP programming language for use in the AutoCAD drawing environment.
You want to automate the creation and manipulation of drawing objects.
You want to automate repetitive tasks.
You want to help manage and enforce CAD standards for your company.
AutoLISP in AutoCAD
AutoLISP is the most popular and is the original supported programming language for the AutoCAD program. The reason for its popularity with new (and even veteran) programmers is that it is a natural extension of the AutoCAD program. There is no additional software to purchase, and AutoLISP can leverage the commands that Autodesk and third-party developers expose at the Command prompt. For example, with a few simple lines of code you can set a layer as current and insert a title block with a specific insertion point, scale, and rotation. The block is then inserted on the layer you specified. To perform the same tasks manually, the end user would have to set a layer as current, choose the block they want to insert, and specify the properties of the block, which, in the case of a title block, are almost always the same.
The AutoLISP programming language can be used to accomplish the following:
Create custom functions that can be executed from the AutoCAD Command prompt
Create and manipulate graphical objects in a drawing, such as lines, circles, and arcs
Create and manipulate nongraphical objects in a drawing, such as layers, dimension styles, and named views
Perform mathematical and geometric calculations
Request input from or display messages to the user at the Command prompt
Interact with files and directories in the operating system
Read from and write to external files
Connect to applications that support ActiveX and COM
Display dialog boxes and get input from the end user
AutoLISP code can be entered directly at the Command prompt or loaded using a LSP file. Once an AutoLISP program has been loaded, you can execute the custom functions from the Command prompt. Functions executed from the Command prompt can be similar to standard AutoCAD commands, but the programmer determines the prompts that should be displayed. It is also possible to use AutoLISP code with a command macro that is activated from the AutoCAD user interface or a tool on a tool palette.
What to Expect
This book is organized to help you learn AutoLISP fundamentals and how to manage and implement custom AutoLISP programs. Additional resources and files containing the example code found throughout this book can be found on the companion web page, www.sybex.com/go/autocadcustomization.
Chapter 1: Quick Start for New AutoLISP Programmers In this chapter, you'll get an introduction to the AutoLISP programming language. I begin by showing you how to enter AutoLISP expressions at the Command prompt and execute standard AutoCAD commands. After that, you are eased into some basic programming concepts that allow you to perform conditional tests and repeat expressions. The chapter wraps up with creating and loading an AutoLISP file into the AutoCAD program.
Chapter 2: Understanding AutoLISP In this chapter, you'll learn the fundamentals of the AutoLISP programming language. AutoLISP fundamentals include a look at the syntax and structure of an expression, how to use a function, and how to work with variables. Beyond just syntax and variables, you learn to use AutoCAD commands and group multiple AutoLISP expressions into custom functions.
Chapter 3: Calculating and Working with Values In this chapter, you'll learn to work with mathematical and string-manipulation functions. Math functions allow you to perform basic and advanced calculations based on object values or a value that the user might provide, whereas string-manipulation functions allow you to work with text-based values. Both numeric and textual values are used when creating or manipulating objects, adding annotations to a drawing, or displaying a message to the end user. Based on how the values are used, numeric values can be converted to strings and strings can be converted to numeric values.
Chapter 4: Working with Lists In this chapter, you'll learn to work with the list data type. Lists are used throughout AutoLISP to provide 2D or 3D coordinate values and to define an object stored in a drawing.
Chapter 5: Requesting Input and Using Conditional and Looping Expressions In this chapter, you'll learn to request input from the user, use conditional statements, and repeat expressions. Requesting input allows you to get values from the user and then use those values to determine the end result of the program. Conditional statements enable a program to make choices based on known conditions in a drawing or input from a user. After you understand conditional statements, you will learn to use them in conjunction with looping expressions to execute a set of expressions until a condition is met.
Chapter 6: Creating and Modifying Graphical Objects In this chapter, you'll learn how to create, modify, and attach extended data to graphical objects using AutoCAD commands and AutoLISP functions. Graphical objects represent the drawing objects, such as a line, an arc, or a circle, that are displayed in model space or on a named layout. When modifying objects, you can choose to step through all the objects in a drawing or let the user select the objects to be modified. Extended data allows you to store information with an object that can be used to identify the objects your program creates or link objects to external database records.
Chapter 7: Creating and Modifying Nongraphical Objects In this chapter, you'll learn how to create and modify nongraphical objects using AutoCAD commands and AutoLISP functions. Nongraphical objects are used to control the appearance of graphical objects and store settings that affect the behavior of features in the AutoCAD program. Drawings support two different types of nongraphical objects: symbol-table objects and dictionaries.
Chapter 8: Working with the Operating System and External Files In this chapter, you will learn how to work with settings and files stored outside of the AutoCAD program. Settings can be stored in the Windows Registry and Plist files on Mac OS, and they can be used to affect the behavior of the AutoCAD program or persist values for your custom programs between AutoCAD sessions. Files and folders stored in the operating system can be accessed and manipulated from the AutoCAD program, which allows you to set up project folders or populate project information in the title block of a drawing from an external file.
Chapter 9: Catching and Handling Errors In this chapter, you will learn how to catch and handle errors that are caused by an AutoLISP function and keep an AutoLISP program from terminating early. AutoLISP provides functions that allow you to trace a function, see arguments as they are passed, catch an error and determine how it should be handled, and group functions together so all the actions performed can be rolled back as a single operation.
Chapter 10: Authoring, Managing, and Loading AutoLISP Programs In this chapter, you will learn how to store AutoLISP code statements in a file, load and manage AutoLISP files, and deploy custom programs with plug-in bundles. Storing AutoLISP code in a file allows for its reuse in multiple drawings. When you load an AutoLISP file, all of the functions defined in the file are made available while the drawing remains open. Based on how you load or deploy an AutoLISP file, you might need to let the AutoCAD program know where your AutoLISP files are stored.
Chapter 11: Using the Visual LISP Editor (Windows only In this chapter, you will learn how to use the Visual LISP® Editor. The editor provides tools for writing, formatting, validating, and debugging code in an AutoLISP file. Using the Visual LISP Editor, you can group AutoLISP files into project files, which make them easy to manage and compile. Compiling an AutoLISP file secures the source code contained in the file so that it can't be altered by others.
Chapter 12: Working with ActiveX/COM Libraries (Windows only In this chapter, you will learn how to use ActiveX/COM libraries with AutoLISP. ActiveX provides access to additional functions, which allow for the creation and manipulation of drawing objects and AutoCAD application settings that aren't easily accessible with standard AutoLISP functions. External applications, such as Microsoft Word and Excel, can also be accessed from the AutoCAD program when using ActiveX.
Chapter 13: Implementing Dialog Boxes (Windows only In this chapter, you will learn how to create and use dialog boxes with an AutoLISP program. Dialog boxes provide an alternative method of requesting input from the user and are implemented using Dialog Control Language (DCL).
Companion Website
An online counterpart to this book, the companion web page contains the sample files required to complete the exercises found in this book in addition to the sample code and project files used to demonstrate some of the programming concepts explained in this book. In addition to the sample files and code, the web page contains resources that are not mentioned in this book. The companion web page can be found at www.sybex.com/go/autocadcustomization.
Other Information
This book assumes that you know the basics of your operating system—Windows or Mac OS X—and AutoCAD 2009 or later. When appropriate, I indicate when a feature does not apply to a specific operating system or release of AutoCAD. Most of the images in this book were taken using AutoCAD 2014 in Windows 8 and AutoCAD 2014 in Mac OS X 10.7.
Since AutoCAD LT® doesn't support AutoLISP, none of the content in this book applies to that software package.
Styles and Conventions of This Book
This book uses a number of styles and character formats—bold, italic, monotype face, all uppercase or lowercase letters, and others—to help you distinguish from the text you read, sample code you can try, text that you need to enter at the AutoCAD Command prompt, or the name of an object class or method in one of the programming languages.
As you read through this book, keep the following conventions in mind:
User-interface selections are represented by one of the following methods:
Click the Application button arrow Options.
On the ribbon, click the Manage tab arrow Customization arrow User Interface.
On the menu bar, click Tools arrow Customize arrow Interface.
In the drawing window, right-click and click Options.
Keyboard input is shown in bold (for example, type cui and press Enter).
Prompts that are displayed at the AutoCAD Command prompt are displayed as monospace font (for example, Specify a start point:).
AutoCAD command and AutoLISP function names are displayed in all lowercase letters with a monospace font (for example, line or command).
Example code and code statements that appear within a paragraph are displayed in monospace font. Code samples might look like one of the following:
(command ._circle
PAUSE 3)
The alert method can be used to display an error message to the user.
; Draw a rectangle
Contacting the Author
I hope that you enjoy AutoCAD Platform Customization: AutoLISP and that it changes the way you think about completing your day-to-day work. If you have any feedback or ideas that could improve this book, you can contact me using the following address:
Lee Ambrosius:[email protected]
On my blog and website you'll find additional articles on customization and samples that I have written over the years. You'll find these resources here:
Beyond the UI:http://hyperpics.blogs.com
HyperPics:www.hyperpics.com
If you encounter any problems with this publication, please report them to the publisher. Visit the book's website, www.sybex.com/go/autocadcustomization, and click the Errata link to open a form and submit the problem you found.
Chapter 1
Quick Start for New AutoLISP Programmers
The AutoLISP® language and programming in general are two subjects that I have enjoyed for over 15 years now, but the same subjects make some people cringe and want to run in the opposite direction. I am not going to claim AutoLISP is easy to learn, but it can be learned by anyone, whether or not they have a programming background. When I first set out to learn AutoLISP, I didn't have any programming experience, but I wanted the benefits that AutoLISP could offer.
I understand if you have some hesitation at the thought of learning AutoLISP, but you don't need to feel that way—I will help you. This chapter will ease you into some core programming concepts and the AutoLISP programming language by exposing you to a variety of functions that are available.
To complete the exercises in this chapter and be able to create and edit LSP files, you must have the following:
For Windows users: Autodesk® AutoCAD® 2006 or later and the Notepad program
For Mac OS users: Autodesk® AutoCAD® 2011 or later and the TextEdit program
NOTE
Although I mention AutoCAD 2006 or later, everything covered in this chapter should work without any problems going all the way back to AutoCAD® 2000 and even possibly earlier releases.
Working with AutoLISP Expressions
AutoLISP is a natural extension of AutoCAD, as it can be used seamlessly from the AutoCAD Command prompt. You can enter AutoLISP when no commands are active or when AutoCAD prompts you for a value. The programming statements used in AutoLISP are known as expressions. You can type expressions at the Command prompt as long as they start with an opening parenthesis [(] or an exclamation point (!). Follow those symbols with the functions you wish to execute and the arguments that provide data or further instruction.
Each AutoLISP expression that starts with an opening parenthesis must also end with a closing parenthesis. AutoLISP expressions must contain the same number of opening and closing parentheses—this is sometimes referred to as balancing parentheses. You can enter the opening and closing parentheses on separate lines, though.
Use these steps to gain a basic understanding of entering AutoLISP expressions at the AutoCAD Command prompt:
Launch AutoCAD, if it is not already running.
At the AutoCAD Command prompt, type ( and press Enter.
AutoCAD responds with the prompt (_>, which is the program's way of letting you know that AutoLISP has taken control.
Press Esc to return to the standard AutoCAD Command prompt.
At the AutoCAD Command prompt, type (+ 3 2) and press Enter.
The AutoLISP expression is evaluated and returns a value of 5, which is the result of adding 3 and 2 together. The + (plus sign) is the function of the AutoLISP expression; 3 and 2 are the arguments (in this case, data) that are passed to the function. The AutoLISP function you want to use must be the first item after the opening parenthesis.
Type (* 3.5 2) and press Enter.
The value 7.0 is returned as a result of multiplying 3.5 by 2.
Type (setq rad (/ 0.375 2)) and press Enter.
The value 0.1875 is returned as a result of dividing 0.375 by 2, but the same value is also assigned to the user-defined variable named rad with the setq function. AutoLISP expressions can be nested one inside of another, and they are evaluated from the innermost to the outermost expression. In this example, the expression (/ 0.375 2) is evaluated first and returns 0.1875. The next expression, (setq rad 0.1875), is evaluated and it also returns 0.1875.
Type circle and press Enter.
The AutoCAD circle command is started.
At the Specify center point for circle or [3P/2P/Ttr (tan tan radius)]: prompt, type (list 0 5) and press Enter.
The (list 0 5) expression returns a value of (0 5), which is a list of two values that presents the 2D coordinate of 0,5. The center of the circle is started at 0,5,0.
At the Specify radius of circle or [Diameter]: prompt, type !rad and press Enter.
AutoLISP evaluates the rad user-defined variable and returns its value to be used for the circle's radius. The radius of the circle should be set to 0.1875.
In the drawing area, select the new circle.
On Windows, right-click in the drawing area and choose Properties. If you are using AutoCAD on Mac OS, secondary-click (two-finger tap or right-click) in the drawing area and choose Properties.
In the Properties palette (Windows) or Properties Inspector (Mac OS)—see Figure 1.1—you should notice that the Center properties are set to 0,5,0 (X=0.0, Y=5.0, and Z=0.0) and the Radius property is set to 0.1875.
...Figure 1.1 Result of using AutoLISP expressions with the circle command
icon In this exercise, you did the following:
Entered AutoLISP expressions at the AutoCAD Command prompt and stored values in a user-defined variable (see Chapter 2, Understanding AutoLISP,
for more information)
Used functions to perform basic math calculations (see Chapter 3, Calculating and Working with Values,
for more information)
Created a list that represented a 2D coordinate (see Chapter 4, Working with Lists,
for more information)
Working with Commands and Input
In addition to calculating values with AutoLISP and passing those values to a command, you can execute a command as part of an AutoLISP expression using the command function. Input can also be requested and passed to a command or saved to a user-defined variable.
The following steps demonstrate how to create a layer named Circles with an AutoCAD Color Index (ACI) of 30 using the -layer command. You'll then draw a circle on the new layer with a user-specified center point and radius.
At the AutoCAD Command prompt, type (command -layer
m
Circles
c
30
) and press Enter.
The -layer command is started. The Make (m) option of the command is used to create the layer named Circles. After the Circles layer is created (or if it already exists), the Make option makes that layer current. The Color (c) option is then used to set the color of the Circles layer to ACI 30.
Type (command circle
PAUSE PAUSE) and press Enter.
The circle command is started and the Specify center point for circle or [3P/2P/Ttr (tan tan radius)]: prompt is displayed. AutoCAD displays this prompt because the predefined PAUSE variable is used as the response to the command's prompt for a value.
At the Specify center point for circle or [3P/2P/Ttr (tan tan radius)]: prompt, pick a point in the drawing area.
At the Specify radius of circle or [Diameter]: prompt, type 0.1875 and press Enter.
This command draws a circle with a radius of 0.1875 and places it on the Circles layer.
At the Command prompt, type the following and press Enter: (setq cenPt (getpoint \nSpecify a center point:
)).
The getpoint function requests a point in the drawing area and can display an optional custom prompt to the user.
At the Specify a center point: prompt, specify a point in the drawing area.
The point you specified is assigned to the cenPt user-defined variable.
At the Command prompt, type (setq rad (getreal \nEnter radius:
)) and press Enter.
The getreal function requests a numeric value.
At the Enter radius: prompt, type 0.25 and press Enter.
The value of 0.25 is assigned to the rad user-defined variable.
Type (command circle
cenPt rad) and press Enter.
AutoCAD starts the circle command and draws a new circle based on the values assigned to the cenPt (center point) and rad (radius) user-defined variables.
Now that you've entered some short expressions, let's look at creating long expressions—expressions that can span multiple lines. Using the following steps, you will also see how to give feedback to the user based on values they provided in the form of the center point and radius of the circle.
Type (prompt (strcat \nNew circle:
and press Enter.
The prompt function allows you to return messages and values to the user, and the strcat function is used to combine multiple string values into a single string. This AutoLISP expression starts on this line and spans to the next line because no closing parentheses were provided. When an AutoLISP expression is not completed, the AutoCAD prompt displays the number of closing parentheses required to complete the current AutoLISP expression. For example, ((_> indicates you need to enter two closing parentheses to get back to the standard AutoCAD Command prompt.
Type \nCenter Point
(vl-princ-to-string cenpt) and press Enter.
The vl-princ-to-string function allows you to display the current value assigned to a user-defined variable as a string. Here the vl-princ-to-string function converts the list that represents the center point of the circle to a string.
Type \nRadius:
(rtos rad) and press Enter.
The rtos function converts a numeric value of the radius to a string.
Type ) and press Enter.
This closing parenthesis ends the strcat expression that we started in Step 1.
Type ) and press Enter.
This closing parenthesis ends the prompt expression that we started in Step 1. The message returned by the prompt function should look similar to the following:
New circle:
Center Point: (21.9627 6.18679 0.0)
Radius: 0.2500nil
In these exercises, you did the following:
Used standard AutoCAD commands to create a layer and draw a circle (see Chapter 2 for more information)
Requested input from the user and displayed information back to the user (see Chapter 5, Requesting Input and Using Conditional and Looping Expressions,
for more information)
Converted values from one type of data to another (see Chapters 3 and 4 for more information)
Conditionalizing and Repeating Expressions
Complex programs often contain branches (different sets of expressions that are used to handle different conditions or choices by the user), and they might loop (execute a set of expressions multiple times). Conditional expressions allow your programs to use a programming concept known as branching. Branching gives your programs the ability to execute different expressions based on the input a user provides or the current value of a system variable. When modifying large sets of data or even prompting a user for input, you can use looping expressions to repeat a set of expressions while a condition is met.
This exercise demonstrates some of the conditional and looping expressions that are available in AutoLISP:
At the AutoCAD Command prompt, type (if (= (tblsearch layer
Circles
) nil) and press Enter.
The if function is used to test whether a condition is true or false. If the = comparison operator returns T, then the first expression is evaluated; otherwise, the second expression is. The tblsearch function is used to check to see if a layer, linetype, or some other nongraphical object already exists in a drawing.
Type (command -layer
m
Circles
c
30
) and press Enter.
This command creates the new Circles layer if it doesn't exist in the drawing.
Type (prompt \nLayer already exists.
) and press Enter.
Type )and press Enter.
The closing parenthesis ends the if function. Either the Circles layer is created or the message Layer already exists. is displayed. Entering the four expressions again results in the displaying of the message.
Type (setq cnt 0) and press Enter.
The setq function defines a user-defined variable named cnt and assigns it the value of 0.
Type (command circle
(list 0 0) 1) and press Enter.
This command draws a circle at 0,0 with a radius of 1 on the Circles
layer.
TIP
If the new circle is not visible on the screen, pan and/or zoom to make it visible.
Type (repeat 7 and press Enter.
The repeat function is used to repeat a set of AutoLISP expressions a specific number of times.
Type (setq cnt (1+ cnt)) and press Enter.
The 1+ function increments the current value of cnt by 1 each time the expression is evaluated.
Type (command circle
(list 0 0) (* (getvar circlerad
) 1.5)) and press Enter.
Once you enter the expressions within the repeat loop and add the final closing parenthesis to complete the expression, AutoCAD draws a new circle at 0,0 with a radius that is 1.5 times larger than the previous circle that was drawn. The previous radius used to create a circle with the circle command is stored in the circlerad system variable. The getvar function returns the current value of a system variable.
Type (command change
(entlast)
p
c
cnt
) and press Enter.
The change command modifies the color of the recently drawn circle, or more specifically the last object in the drawing. The entlast function returns the last object added to the drawing.
Type )and press Enter.
The closing parenthesis ends the repeat function. Seven concentric circles, as shown in Figure 1.2, are drawn around the circle that was drawn outside of the repeat loop. Each circle drawn inside the repeat loop is assigned a different color, and the radius of each circle is 1.5 times larger than the next inner circle.
...Figure 1.2 Drawing concentric circles with AutoLISP
In the previous exercise, you did the following:
Used comparison operators and conditional functions to evaluate different expressions based on the results of a test condition (see Chapter 5 for more information)
Used math-based functions to calculate the radius of a circle and to increment a counter used in a looping expression (see Chapter 3 for more information)
Checked to see if a layer existed in the drawing (see Chapter 7, Creating and Modifying Nongraphical Objects,
for more information)
Repeated a set of AutoLISP expressions until a condition was met (see Chapter 5 for more information)
Grouping Expressions
Entering individual expressions can be helpful when you are first learning AutoLISP or when you are developing a new program, but it isn't ideal for you to do each time you want to execute a set of AutoLISP expressions. The AutoLISP programming language allows you to define a custom function that can be executed at the Command prompt or from a command macro assigned to a user-interface element, such as a ribbon or toolbar button.
The following steps demonstrate how to define a custom function named RectangularRevCloud that can be entered at the AutoCAD Command prompt:
At the AutoCAD Command prompt, type the following and press Enter:
(defun c:RectangularRevCloud ( / arclength)
The defun function is used to define a function. The function defined is named RectangularRevCloud and contains one local variable named arclength. Local variables are accessible only to the function in which they are defined.
Type the following and press Enter:
(if (= (tblsearch layer
RevCloud
) nil)
(command -layer
m
RevCloud
c
1
)
)
The expressions test to see if a layer named RevCloud exists, and if it doesn't, the layer is created and assigned the color red (1).
Type the following and press Enter:
(command rectang
PAUSE PAUSE)
The rectang command is used to draw a rectangle based on the two points the user provides.
Type the following and press Enter:
(if (> (setq arclength (abs (getvar dimscale
))) 1)
(setq arclength (* arclength 2))
(setq arclength 1.0)
)
The > operator and the if function determine whether the value of the dimscale system variable is greater than 1. If so, the value is used to set the arc length for the revision cloud that will be created from the rectangle. If the value of dimscale is less than 1, then the value of 1 is used. The calculated maximum arc length value is assigned to the user-defined variable named arclength.
Type the following and press Enter:
(command revcloud
a
(/ arclength 2) arclength o
(entlast) )
(princ)
)
The revcloud command converts the rectangle that was drawn with the rectang command to a revision cloud. The princ function keeps the last expression in the function definition from returning a value and allowing the function to exit quietly.
The final closing parenthesis closes the defun function.
Type the following and press Enter:
(defun c:RRC ( / )(c:RectangularRevCloud))
The RRC custom function acts as an alias to the RectangulatRevCloud function and makes it easier to start the function from the Command prompt.
Type RectangularRevCloud and press Enter.
At the Specify first corner point or [Chamfer/Elevation/Fillet/Thickness/Width]: prompt, specify the first corner of the rectangle.
At the Specify other corner point or [Area/Dimensions/Rotation]: prompt, specify the opposite corner of the rectangle.
The rectangle is drawn on the layer RevCloud
and converted to a revision cloud using the Object (o) option of the revcloud command; see Figure 1.3.
Figure 1.3 Converting a rectangle to a revision cloud
Type RRC and press Enter. Specify the two corners of the rectangle. RRC is simply a shortcut to the new RectangularRevCloud function.
In the previous exercise, you did the following:
Grouped a set of AutoLISP expressions into a custom function to make it easier to execute the expressions (see Chapter 2 for more information)
Accessed the value of a system variable (see Chapter 2 for more information)
Storing and Loading AutoLISP Expressions
AutoLISP expressions entered at the AutoCAD Command prompt are accessible from that drawing and only while that drawing remains open. You can store AutoLISP expressions in an LSP file that, once saved, can then be loaded into and executed from any drawing file that is opened in AutoCAD. The following exercise explains how to create and load an LSP file named acp_qs.lsp.
If you are on Windows:
Do one of the following:
On Windows XP or Windows 7, click Start arrow [All] Programs arrow Accessories arrow Notepad.
On Windows 8, on the Start Screen, type note and then select Notepad from the Search bar.
In Notepad, click File arrow Save As.
In the Save As dialog box, browse to the Documents (or My Documents) folder or the MyCustomFiles folder that you created for the exercises and examples in this book.
In the File Name text box, type acp_qs.lsp.
Click the Save As Type drop-down list and select All Files (*.*).
Click the Encoding drop-down list and select ANSI. Click Save.
In the text editor area, type the following expressions. Replace the square brackets and the text inside them with the current date and your name.
; Created [Today's date] by [Your name
] – Quick Start Examples
; Zoom shortcuts
(defun c:ZE ( / ) (command ._zoom
e
))
(defun c:ZW ( / ) (command ._zoom
w
))
; Repeat Purge command 3 times to remove nested objects
; and remove zero lines and empty objects
(defun c:P3 ( / )
(repeat 3
(command ._-purge
_all
*
_n
)
)
(command ._-purge
_z
)
(command ._-purge
_e
)
)
; List which objects are in a selection set
(defun c:ListObjects ( / selectedObjects count ent)
(prompt \nSelect objects to list:
)
(setq selectedObjects (ssget)
count 0
)
(if (/= selectedObjects nil)
(progn
(while