the+language+and+its+developmen+ +togores%2c+reinaldo+n

222
5/28/2018 The+Language+and+Its+Developmen++Togores%2C+Reinaldo+N-slidepdf.com http://slidepdf.com/reader/full/thelanguageanditsdevelopmen-togores2creinaldon 1

Upload: feng-zhou

Post on 19-Oct-2015

160 views

Category:

Documents


12 download

TRANSCRIPT

  • AutoCAD experts Visual LISPVolume 1

    The Language and itsDevelopment Environment

    Reinaldo N. Togores

  • AutoCAD experts Visual LISP Volume 1

    The Language and its Development Environment

    Copyright 2013 by Reinaldo N. Togores

    All Rights Reserved. No part of this book may be reproduced or utilized in anyform or by any means, electronic or mechanical, including photocopying,recording, or by any information storage and retrieval system, withoutpermission in writing from the author.

    All data, information and examples provided by this book are for educationalpurposes only. All information is provided on an as-is basis. Although theauthor and publisher have made every effort to ensure that the information in thisbook was correct at press time, the author and publisher do not assume andhereby disclaim any liability to any party for any loss, damage, or disruptioncaused by errors or omissions.

    Autodesk, AutoCAD, AutoLISP, Visual LISP, DWG, the DWG logo, Revit, 3dsMax and Inventor are registered trademarks or trademarks of Autodesk, Inc.,and/or its subsidiaries and/or affiliates in the USA and other countries.Autodesk screen shots reprinted with the permission of Autodesk, Inc.

  • To Tet, with love.

  • ContentsPreface.Acknowledgements.About the Author.

    PART 1. INTRODUCTION.Chapter 1. AutoLISP/Visual LISP.

    1.1. Visual LISP.1.2. New LISP functions.1.3. Summary.

    Chapter 2. A Visual LISP Project: Step by Step2.1. Work Space and Project Structure.2.2. A custom dictionary.2.3. The calculus function.2.4. The drawing function.2.5. The user interface.2.6. Placing the labels.2.7. Updating the dictionary2.8. On error2.9. Compiling the program.2.10. Demand loading the program.2.11. Summary.

    PART 2. THE LANGUAGE AND ITS DEVELOPMENT ENVIRONMENT.Chapter 3. The Visual LISP IDE.

    3.1. The Visual LISP IDE User Interface3.2. Interactivity: The Visual LISP Console.3.3. The Programming Editor.3.4. Interaction between the Editor and the Console.3.5. Summary.

    Chapter 4. Evaluating Expressions.4.1. Data.4.2. Expressions.4.3. Symbols and assignment.4.4. Lists.4.5. Variables and data types.4.6. Manipulating the elements of a list.4.7. Lambda.4.8. Summary.

    Chapter 5. User Defined Functions.5.1. Defun.5.2. Loading and executing user functions.5.3. Global and local variables.

  • 5.4. Predicates and Conditionals.5.5 Recursion.5.6. Iteration.5.7. Summary.

    Chapter 6. ActiveX Data and Structures.6.1. Safearrays.6.2. Variants.6.3. VLA Objects.6.4. Collections.6.5. Working with methods and properties.6.6. Collections Processing.6.7. Managing exceptions.6.8. Summary.

    Chapter 7. Data Entry.7.1. Integrated error control.7.2. Default Values.7.3. Prompting for data with options.7.4. Input control through INITGET.7.5. Data coded as binary values.7.6. File search dialog box.7.7. Summary.

    Chapter 8. File Operations.8.1. Opening files.8.2. File reading.8.3. Writing files.8.4. Files and Folders.8.5. Summary.

    Chapter 9 Debugging Visual LISP Code.9.1. Finding the error's origin.9.2. The debugging session.9.3. Data inspection tools.9.4. Error Tracing.9.5. Summary.

    Index of Function Listings.Appendix 1. Contents of other Volumes.

  • PrefaceThis book is the product of eighteen years teaching Computer Aided Design toCivil and Industrial Engineering students at the University of Cantabria. Duringthis time I have published two books about Visual LISP programming forAutoCAD. Back in 2003 the book Programacin en AutoCAD con Visual LISP1which I wrote in collaboration with Professor Csar Otero was the first onedealing with this subject in Spanish. For ten years it has been the main resourcein Spanish for Visual LISP programming. I still receive messages asking mewhere to buy it. It is impossible, since it is now out of print. A couple of yearsago I undertook the task of preparing an updated version. The newfunctionalities added since 2003 to AutoCAD required a thorough revision andrewriting of the text. The new book Experto AutoCAD con Visual LISP isupdated to Release 2012. But being written in Spanish limits this kind of booksreaders. My English speaking friends have encouraged me to prepare an Englishversion which may reach a wider audience. During this time AutoCAD 2013 hasbeen released, so the English edition has been updated to cover the few changesintroduced from 2012 to 2013.

    Back in 2003 when the first book was published, AutoLISP was not "infashion". Not even with Visual LISPs new contributions. Fashion followersthen bet on the novelty represented by VBA. But fashion is not always rationallyjustified. In that book we aimed to demonstrate that the availability of otherWindows dialog box modalities was not reason enough to forgo what had beenour way of customizing AutoCAD for more than 15 years. Thats why we endedour book with a chapter devoted to Chad Wanlesss ObjectDCL, a plug-inwhich allowed the use of this kind of Graphic User Interface with AutoLISP.

    VBA, like all fashions, passed away. Its over and those who opted for it arenow hastily rewriting their applications2. But AutoLISP/Visual LISP is stillhere. And ObjectDCL, now OpenDCL, has become an open source projectwhich we can use free of charge. And once more it deserved the new bookslast chapter.

    I wish this book will guide he who uses AutoCAD in becoming a real expert.That kind of AutoCAD expert that is acquainted with, understands and canmanipulate the programs inner workings to achieve the desired output in a fastand efficient way. He who is not satisfied with what comes out of the box, butdemands more.

    Among the most significant new contributions of recent versions we have 3D

  • modeling, including surfaces associativity. To them, and other advancedtechniques, including parameterization, reactors, user graphic interfaces andcompiling applications, more than half of this new book is devoted.

    The contents have been tested for compatibility with AutoCAD 2014. Sourcecode has been tested with the Windows 32 and 64 bit versions. Although muchof the above also applies to previous versions there is no excuse not to study itusing the latest release. Autodesk offers student versions of most of its softwarecompletely free of charge. To obtain them, simply register in the AutodeskEducation Community website (students.autodesk.com) or in the AutodeskStudents Facebook page (https://www.facebook.com/Autodeskedcommunity).

    The source code for all the examples included in the book can be freelydownloaded from my Blog at http://lispexpert.blogspot.com/ where readers canpost questions and comments about the books contents. You can also visit mywebsite: http://www.togores.net/ where I have published other materials relatedto computer-aided design developed during the last twenty years both in spanishand english. I hope that you will not only learn from this book, but that you willenjoy doing it.

    Acknowledgements.

    First of all, I wish to recognize the support received from the DevelopersAssistance Services of the Autodesk Developer Network with their answers tomy many questions when preparing the chapters devoted to the new Mesh andSurface entities. Without this information it would have been difficult to attainthe goals I had set myself.

    To this I have to add the contribution of the participants to the many AutoLISPforums in the Internet, in particular Autodesks Visual LISP, AutoLISP andGeneral Customization group and the forum at www.theswamp.org. A specialmention is deserved by Owen Wengerd and the group of enthusiasts that keepalive the OpenDCL project.

    Many of the ideas developed in this book have been tested in exercisesproposed during my 18 years as a teacher in the Geographic Engineering andGraphic Expression Techniques Department at the University of Cantabria(Spain). I want to recognize the contribution of my colleagues and in particularof Professor Csar Otero, director of my doctoral thesis on ComputationalGeometry Methods Applied to the Design of Space Structures. It was during thework in this thesis that I could investigate in depth some of the procedures fortransformations in 3D space proposed in this book. From the UniversitysApplied Mathematics and Computational Sciences Department I wish to express

  • my debt with Professors Andrs Iglesias and Jaime Puig-Pey for their researchon NURBS curves and surfaces from which I have profited for the preparationof these themes.

    No doubt many are the names missing here, but I must not leave out that ofNikolas Bokisch, former Autodesk EMEA Education Program Manager, for hisinterest in our work and the help that he has always provided.

    About the Author.

    Reinaldo N. Togores has been using AutoCAD for about 25 years in his work asan Architect and Industrial Designer. For the past eighteen years he has taughtAutoLISP programming to Civil and Industrial Engineering Students at theUniversity of Cantabria, in Northern Spain. As a researcher on Computer AidedDesign topics he has worked with several research groups at the University ofCantabria and has been a member of the Autodesk Developers Network sincethe late 90s. He has authored three books about Visual LISP programming.

    1 Togores, R. and Otero, C.; Programacin en AutoCAD con Visual LISP. McGraw-HillInteramericana de Espaa, S.A.U. ISBN: 84-481-3694-2. Madrid, 2003.

    2 On August 6, 2012 Autodesk announced that due to Microsofts recent renewedinvestment in VBA, it has become possible for Autodesk to upgrade the VBA engine (inthose products that support VBA) from version 6.3 to 7.1. It will be available as aseparate download for AutoCAD and AutoCAD verticals, and as part of the standardinstallation for Autodesk Inventor as of the next release. However, while this meansVBA code will not become immediately obsolete, Autodesk does not recommend using VBAfor professional application development.

  • Part 1 Introduction

    The spirit of Lisp hacking can be expressed in two sentences.Programming should be fun. Programs should be beautiful.

    Paul Graham, in his preface to ANSI Common Lisp.

  • Chapter 1AutoLISP/Visual LISP

    LISP syntax is none other than that of mathematical functions, already familiarfrom our secondary education. We all know how to solve an expression such as(8 x ((17 + 3) / 4)). First we would add 17 + 3, obtaining a numberwhich we would then divide by 4, to finally multiply this new result by 8. Thatis, we solve the innermost parentheses passing the resulting value to theoperations represented in the containing parentheses

    The figures and the sign of the mathematical operations to be performed aregrouped within parentheses. A data sequence between parentheses is what inLISP we call a list. The solution of the previous expression consisted, as wehave seen, in the successive processing of each one of these lists. Hence thename of LISP, derived from LISt Processing. In LISP notation the operatoralways appears at the beginning of the list.

    (* 8 (/ (+ 3 17) 4)) would be the equivalent LISP expression. This typeddirectly into the AutoCAD command line (see Figure 1.1) would return 40.

    Figure 1.1. Evaluation of a LISP expression.

    Were already using LISP. As simple as that. AutoCAD Has interpreted thefunction received and has returned the result of its evaluation, which is printedon the screen. Thus we have accessed LISPs fundamental mechanism.Expressions like the one just written are the basic units of the language, whichoperates through repeated reading, evaluating and printing a result, which in theterminology of the language is known as the read-eval-print loop.

    An additional advantage, at least from the standpoint of the group of users towhich this book is addressed: other programming languages demand a series ofarrangements related to memory management. We would have to foresee thetypes of data to employ and define in advance the suitable containers for thesedata types (declaration of variables, etc.). In LISP memory is managedautomatically, and only some minimum cautions should be taken by theprogrammer regarding possible interferences between the names of variables.

  • Thus, the success of AutoLISP as a means for extending the capabilities ofAutoCAD was overwhelming. Perhaps today we are not aware that some of thetools that we consider essential were not available in the original program,being developed as AutoLISP macros and programs, primarily for the personaluse of their creators. If we review Schaefer and Brittains AutoCADProductivity Book published in 1986 1, we will find the COPYPARA menumacro whose function was to perform a parallel copy of the designated lineusing AutoLISP expressions, the same that is now advantageously performed bythe OFFSET command. Or the LTC (Line To Circle) program with which youcould draw lines tangent to two circles, unnecessary today thanks to theintroduction of the differed mode of the TANgent object snap. The books titlewas very precise regarding what AutoLISP offered to the user: a way toincrease his productivity automating any repetitive task.

    1.1. Visual LISP.

    AutoLISP had barely changed since its introduction in 1985-86. Its limitationswere obvious. Among the most important, processing speed, especially inregard to complex numerical calculations and a safer way to protect the sourcecode. A group of programmers working from Moscow in the Basis Software2company sought a solution for these limitations. The initial proposal of thisgroup was the ACOMP compiler that was included in the international releasesof AutoCAD 10, 11 and 12. The fact that it was not distributed with the releasedistributed in the United States, limited its use.

    BASIS Software introduced Vital LISP in the spring of 1995 as a standaloneproduct for AutoCAD releases 12 and 13. In addition to the compiler, thisapplication supplied a complete Development Environment. The success ofVital LISP led AutoCAD to buy it in 1997, renaming it as Visual LISP 3.Without the possibility of adding it to Release 14, already in the market, it wasoffered as a complementary program at a price substantially lower than that ofBASIS Software.

    Not being a part of AutoCAD R14s core, it required us to include a RTS(Runtime System) to be loaded along with our programs. This need was coveredin a very practical way by allowing all the applications files, both compiledLISP files (FAS) and those that must remain as plain text (DCL files, forexample) along with the RTS to be packaged as an executable ARX (AutoCADRuntime eXtension) format file similar to those developed with C++ using theObjectARX API.

  • Since AutoCAD 2000, Visual LISP is part of AutoCADs standard releases.Thus, it is no longer necessary to include an RTS with our application, whichleads to a considerable program size reduction. According to our experience, anapplication whose sources (LSP and DCL files) took about 102 Kb is, oncecompiled as ARX (Release 14) a 602 Kb file, while compiled as Visual LISPExecutable file (VLX) for AutoCAD 2000 or subsequent releases occupies only46 Kb

    What does Visual LISP offer?

    The two most pressing demands of the expert user, speed and safety are largelytaken care of. Besides programming will be easier with these new tools. Buttheres still a question to be answered: Is AutoLISP/Visual LISP theprogramming language we need? Back in 1986 there was no choice. But todayyou can create applications that manage AutoCAD with almost any modernprogramming language. To a programmer who wishes to engage in buildingapplications that extend the features of AutoCAD we would certainlyrecommend the use of languages such as C#, Visual Basic or VC++ on the .NETplatform.

    This is not the user profile to which Visual LISP is oriented. Visual LISP is theideal language for anyone who makes a living day by day using AutoCAD as atool. For those looking to increase their productivity by automating everydaytasks. For those who want something more than "what comes out of the box". Inshort, to become a real expert, what we usually deem as an AutoCAD "Power-user". Visual LISP provides them, with respect to classical AutoLISP, a numberof advantages.

    1.2. New LISP functions.

    First, Visual LISP significantly increases the number of available functions,including many which have been for quite a long time part of the Common LISPstandard4. These functions are distinguished from the primitive AutoLISPfunctions by the VL- prefix totaling about 77, including several functions forreading and writing in the Windows registry or to manage storage in files andfolders, some that can be used for a more effective treatment of run-time errorsand others which deal with LISP data treatment (symbols, strings, lists, etc.) andtype conversion.

    Visual LISP ActiveX Extensions.

  • ActiveX extensions supplied with Visual LISP include functions for themeasurement of curves, data conversion, and objects, properties, collectionsand dictionaries manipulation. These features provide a number of advantages,among which are greater execution speed and wider functionality. They alsoallow us to use data types that are not available in AutoLISP, such as arrays.These functions are distinguished, like the other new features built into VisualLISP, by their prefixes. We have them in two types:

    VLA- Functions that directly correspond to the native AutoCAD ActiveXmethods.VLAX- Functions specialized functions that are unique to Visual LISP.

    This ActiveX interface allows Visual LISP to act as a client and a server in theWindows environment, allowing AutoCAD to control or be controlled fromother applications. This way the ability to interact with other applications isenabled, something almost impossible for the old AutoLISP. VLA- and VLAX-functions are not available in AutoCAD for Mac.

    Reactors

    Other new features group, identified by the VLR- prefix, aim at implementingreactors. Reactors make it possible for a specific AutoCAD application toreceive notifications when certain actions occur, making it possible to schedulea response to that event. There are four types of reactors that correspond to thegeneral categories of events to which an application can respond:

    Editor reactors, which notify each time an AutoCAD command is called.Database Reactors, linked to specific entities or objects in a drawing'sdatabase.Object reactors that notify the program if certain actions are performed onan AutoCAD entity.Link Reactors, which notify the application when loading or unloading anARX application.

    This is a complex matter which we will address in Part 5, Chapter 21. Callbackroutines invoked from the reactors must necessarily use the new Visual LISPActiveX functions instead of the AutoLISP command function.

    The Development Environment.

    Finally we have the programming tools included in the Visual LISP IntegratedDevelopment Environment (IDE). Among the components of the IDE we find:

  • A syntax checker that recognizes erroneous expressions and inappropriatearguments within calls to primitive AutoLISP functions.A file compiler that increases the speed of execution and provides a safeand efficient platform for application delivery. The compiler is able toprocess files both isolated or grouped as projectsA source code debugger designed specifically for AutoLISP, which allowsstepping through the code in the Editor window while showing the resultsof its execution in the AutoCAD viewport.A text editor which enables color coding for AutoLISP and DCL sources,while providing assistance in syntax checking.An AutoLISP formatter which restructures the program code to improvereadability.Inspection and Watch windows which provide access to the valuesassumed by variables and expressions allowing their review andmodification. They can be used to examine AutoLISP data and AutoCADentities.A context-sensitive help providing information about AutoLISP functionsand an efficient Apropos feature for searching symbol names.A project management system that facilitates the maintenance ofapplications that span multiple archives.The possibility of packing compiled AutoLISP files in a single module,together with the corresponding DCL dialog definitions.An intelligent LISP console for immediate code evaluation that provides aseries of other features useful in the process of program development.

    1.3. Summary.

    Today the applications that manage AutoCAD drawings and can be developedin such different programming languages as Visual BASIC, Delphi, C++, C #Java and even other LISP implementations. For a programmer with experiencein any of these environments to learn Visual LISP would be useful but notessential. But in the same manner, an expert AutoCAD user, not a professionalprogrammer, but with knowledge of AutoLISP/Visual LISP need not miss, inorder to streamline his daily work, the features offered by those languages.Hopefully this will be demonstrated in the following chapters. AutoLISP /Visual LISP is also the programming interface for a large number of alternativeCAD programs, most of them based on the IntelliCAD 5 technology.

    1 Schaefer, A.T.; Brittain, J. The AutoCAD Productivity Book, Ventana Press, Piedmont,California, 1986. ISBN: 0-940087-00-6

    2 Information from http://wiki.alu.org/Success%20Stories and

  • http://en.wikipedia.org/wiki/AutoLISP. Basis Software later moved to Pennsylvania.

    3 Visual LISP was, before Autodesk bought it, the name of an AutoLISP code editordeveloped by Western Sierra Software, available as freeware on the Internet.

    4 Defined in editions 1 and 2 of Guy Steeles book Common LISP, The Language, andmore recently as an ANSI standard.

    5 For a long list of CAD programs developed from IntelliCAD see:https://members.intellicad.org/members/index.php.

  • Chapter 2A Visual LISP Project,

    Step by StepAs an introduction to both the programming language and its DevelopmentEnvironment we shall follow the process that leads from the initial statement ofthe problem to solve to its completion in the form of a new AutoCADapplication. This is the spirit that this book will maintain hereafter: addressingsuch problems as any user can find in his daily work. We hope that this book inaddition to being a learning tool will provide a library of programs to which thereader may resort, adapting them to his needs. For readers with previousexperience in AutoLISP programming we hope to give in this chapter a glimpseof the power available through the new tools. And from here on the moreimpatient readers will surely start to use immediately and with benefit tools likethe Programming Editor. The rest of the book will be a reference andindispensable guide in their daily work. Those without such experience willsurely find more questions than answers. These answers will be found in thefollowing chapters. To become a true expert always requires effort anddedication. We hope this tutorial will set the mood for this endeavor.

    A real case.

    An AutoCAD expert always looks for ways to make more efficient his work andthe work of those who depend on him. In this first approach we will addresshow to develop a very simple tool that can represent great savings in time andeffort.

    Some time ago, a friend from Colombia posed the following problem:

    I must identify the buildings on a site with a number which increases by10 each time. I would like that if I placed a number x in the first house ofa block, I could just click on this first number and by clicking on thesecond house I would have placed the previous number increased by 10,and so on. Right now what I have to do is to copy the same text on allhouses and then change them one by one, procedure which I find to bevery slow.

    This is a typical example of how a few lines of code will increase ourproductivity. Despite its simplicity, we will establish in the development of this

  • program a series of work habits essential in more complex applications.

    2.1. Work Space and Project Structure.

    The first thing we will do is to establish a folder and file structure that allowsus to organize our work. To locate the components of our programs we willcreate a folder named Visual LISP Projects. After creating this folder it shouldbe included in the AutoCAD support files search paths. This is done from theFiles tab in the Options dialog box1. Within it we will create the folders forour various projects. The one for this particular project shall be calledNUMERA. In turn, the folder NUMERA will contain two subfolders, which wewill name FAS and TEMP. The NUMERA folder is intended for the sourcecode files and the FAS and TEMP folders will contain files generated duringthe project's compilation.

    Within the Visual LISP Projects folder we will also create a folder namedUtilities, designed to contain source code files for those functions intended to beused in more than one project. Figure 2.1 shows the tree view of the proposedstructure.

    Figure 2.1. Folder structure.

    As the book progresses we will incorporate new projects, each in its ownfolder, always with the same layout: a folder for the project and within that, theFAS and TEMP folders.

    Having included the Visual LISP Projects folder in the support files searchpaths allows us to load a program from a relative path excluding its name, withan expression such as:

    (load ".//")

    The file name need not include the file extension. The system will search forfiles with the extensions .vlx (Visual LISP compiled application) .fas(Compiled AutoLISP file) or .lsp (AutoLISP source file) in that order and load

  • the first one it finds. In our projects folder we will also create a file calledacaddoc.lsp, which is a special file which, if found, AutoCAD willautomatically load for each new drawing opened. At this chapters end we willindicate what to do with it.

    Starting with AutoCAD 2014, custom applications like those that we willdevelop in this book must work under secure mode. Secure mode is enabledwhen the new system variable SECURELOAD is set to 1 or 2. When operatingunder secure mode loading of applications is restricted to files contained intrusted locations. These trusted locations are specified by the TRUSTEDPATHSsystem variable. So besides including the Visual LISP Projects folder in theSupport Files Search Paths list, it must be also included in the TrustedLocations list of the Files tab in the Options dialog box. This must also bedone for the Numera and the Utility folders and any other folders that willcontain executable code.

    Figure 2.2. Setting the Support and Trusted locations folders.

    These folders, once we have concluded development should be set to a Read-Only staus. In case we add a folder which is not Read-Only to the TrustedLocations list, a Security Concern warning box will be shown.

  • Figure 2.3. Security concern alert box.

    Project structure.

    Once organized our workspace, we shall analyze the components of our project.In general, any program that we develop:

    Will almost always have as its goal the creation, modification or checkingof drawing elements, that is to say they will have almost always a graphicoutput.The characteristics of what we will draw will be determined through aseries of calculations.To perform these calculations, we must allow the user to select parameterssuch as size, distance, etc. he considers appropriate.

    That is, data entry functions, calculation functions and graphical output functions(i.e., drawing) from the calculations made. Separate source files willcorrespond to these three parts of our project. This way of organizing our workcan be managed by creating Visual LISP projects.

    Source Code Files.

    We shall proceed to create the new source code files and set up the projectincluding them. To do so we will use the Visual LISP Integrated DevelopmentEnvironment (IDE). To access it will be necessary to type VLIDE or VLISP inthe AutoCAD command line. We can also access the Visual LISP IDE from theManage ribbon tab (Figure 2.4.) clicking on the Visual LISP Editor button inthe Applications group.

  • Figure 2.4. Access to the Visual LISP Editor.

    Once in the IDE select the New File button to create the source code file, towhich we then give a name, clicking on the Save File button. Using the SaveAs dialog box search for the previously created \Visual LISPProjects\NUMERA folder naming this new file as numera-calculus.lsp.Check before you save it that the drop-down list box at the bottom of the dialogreads Lisp source files. If not, select this option. The file is saved with a LSPextension. The same shall apply to create another file that is saved with thename of numera-input.lsp. We will create a third file, but in this case the targetfolder will be Utility. This last file will be named draw-text.lsp. This file willcontain the code needed to create text entities. It is obvious that a function usedto create text entities can be necessary in many different programs so we shoulddesign it as a generic function to be used in more than one project.

    To create a new source code file we can use the key combination CTRL+Nand to save it CTRL+S. The New File... and Save as... options are alsoavailable on the Files menu.

    In more complex applications it may be necessary to use a larger number of filesto organize your work. You do not need to create them as we have now, from thestart. We can do it as the situation demands, grouping interrelated functions.

    Create the project.

    The management of the files in which we subdivide the project would beuncomfortable if we did not count with the Visual LISP project. To create theproject, select the option New Project... from the Project menu. In the NewProject dialog box we will select the NUMERA folder, and type numera as thefile name. The .PRJ extension will be automatically assigned to this file,indicating that this is the file that stores the project properties. On saving the

  • Project Properties dialog box shown in Figure 2.5.a opens. This dialog opensshowing the Project Files section that will allow us to select the LISP sourcecode files we want to include.

    Having saved the project in the NUMERA folder, the files numera-input.lspand numera-calculus.lsp will appear in the list to the left of the dialog. Usingthe button with the > symbol we will add the desired files to the project. Thesefiles disappear from the left window appearing on the one to the right. Toinclude the file draw-text.lsp we have to search for the Utility folder, using theellipsis button on the right of the Search edit box. After selecting the folder weshall include the draw-text.lsp file in the project.

    The Project properties dialog has another section (Figure 2.5.b), BuildOptions, Which is accessed by clicking on the appropriate tab at the top of thedialog box. Here we define the parameters to use in a future compilation of theproject.

    Figure 2.5.a. Selection of project files.

  • Figure 2.5.b Selection of build options.

    As Compilation Mode we keep, for now, the Standard option. In Merge filesmode we select Single module for all, so we get a single compiled file fromthe three source code files that the project includes. In Message mode, the Fullreports option will show the errors found when compiling, the warnings andthe compiler statistics. In the Fas directory and Tmp directory edit boxes wewill use their respective ellipsis buttons to select the FAS and TEMP folderswe had previously created.

    Having made these changes, we click OK. A dialog box (see Figure 2.6) willappear in the IDE showing the names of the source code files that make up theproject. These tools are also available as Project menu options.

  • Figure 2.6. Project dialog box.

    Analysis of the problem.

    Now that the skeleton of our application is ready we must think how to solve theproblem we are dealing with. Our friend tells us that he wants to select a textthat contains a figure and thereafter place similar text entities in which thatfigure is increased by 10 each time. This tells us that we need a set of functionsfor:

    Reading a text in the drawing and checking that its value is a number.If it is a number, increasing it in the desired amount.Requesting a location for the new text.

  • Drawing in that location a text containing the new figure.

    In order to make it a more general purpose tool, it is also desirable that:

    We can type an initial figure as an alternative.Make it possible to change the increment value.That this value and the last number written shall be retained betweendrawing sessions.

    We could also store other information related to text formatting. In order not tocomplicate this tutorial we shall memorize, for the time being, only the textheight.

    2.2. A custom dictionary.

    To save data between sessions and retrieve them when we reopen the drawingwill use a DICTIONARY object. Dictionaries are objects that the user can createat will to keep non-graphical information in them. The functions we shall use tomanipulate our dictionary are extensions to the AutoLISP language that must beloaded before using them by calling the expression (vl-load-com).

    To create the custom dictionary, which we will name "VARS-NUMERA" we willprogram the user function numera-dict, whose source code is shown in Figure2.7. This function is closely linked to the calculation of new values of thenumbers and therefore we will include it in the numera-calculus.lsp file. Tostart editing this file just double-click its name in the project window. This waythe file is opened (if not already open) and set in focus. Another way to accessthe file for editing is through the context menu displayed by pressing the rightmouse button on the project window.

    Adding a comment to remind us later what this function does and how is a goodhabit. After writing this comment we select the text and click on the Commentblock button (Also Ctrl+E+C.) Doing this, the system adds three semicolons toeach line, coloring the text purple on a gray background in the editor. Theselines will not be processed on loading and compiling the program. As you typethe text in the editor window, we see that the names of LISP functions (orprimitives) are colored in blue, integer values in green and list opening andclosing parentheses in red. Syntax color coding allows us to immediately detectmany typing errors.

    Like all LISP user functions this one is defined by means of the special formdefun that is placed as the first term of the expression, after the openingparenthesis. After the defun term the function name appears, in this case

  • numera-dict followed by a parenthesized list of arguments that the function isto receive and which in this case is empty.

    Figure 2.7. Function NUMERA-DICT.

    The reason we say that defun is a special form and the way it operates will beunderstood as we advance in studying this book. After loading the necessaryVisual LISP extensions calling (vl-load-com), we find a conditionalexpression if, which according to whether or not the dictionary "VARS-NUMERA" exists, extracts its values or creates it with default values that the usercan later change. The existence of the dictionary is checked by the expression:

    (dictsearch (namedobjdict) "VARS-NUMERA")

    that, if the dictionary does not exist, returns nil which is equivalent to false.The dictionary is created only if the value returned by this expression is nil,thus avoiding the loss of previous values.

    Each value is identified by an associated key. The dictionary is created whendata is added using the vlax-ldata-put function. To retrieve that data thevlax-ldata-get function can be used.

    (vlax-ldata-put "VARS-NUMERA" "INCREM" 10) assigns 10 to"INCREM"(vlax-ldata-get "VARS-NUMERA" "INCREM") recovers the valueassociated to "INCREM"

    These functions are discussed in detail in Part 5, Chapter 23.

  • For the text height we read, using the getvar function, the current text heightwhich we obtain from the TEXTSIZE system variable.

    For checking the syntax and use of these functions, we recommend using theApropos tool. To do this, we select the function name in the Editor and pressthe Apropos button in the View toolbar. The Apropos results window appearsshowing the function name highlighted. We can then click on the Help button2.

    Testing the programmed function.

    We said earlier that LISP is an interactive programming environment. We canimmediately verify what we meant by this. It means we can proceed step by stepchecking our functions, without intermediate compilation phases. To do this, wemust first load it by clicking on the Load Source Files button in the projectwindow (see Figure 2.6). Once a function is loaded, the loading outcome isshown in the Visual Lisp Console.

    If when loading or evaluating an expression we receive an error message, wecan use several tools intended to detect and correct these errors. To thesedebugging tools, which appear as options in the Debug menu and in the toolbarwith the same name, we will dedicate an entire chapter later on. For now, incase of errors, we will carefully check if what we typed matches the codeshown. Special care should be taken with the location and number of openingand closing parentheses.

    The term form is used in the Console messages to describe the loadedexpressions (in this case the defun.). Form, used in this context means anyLISP expression in condition to be evaluated. It should not be confusedwith the Visual BASIC usage of this term meaning the dialog box used in agraphical user interface.

    In this chapter we present the code in the form of screenshots that show the waythey are presented in the Editor. The format shown is intended to facilitateparentheses checking through their vertical alignment and the introduction ofcomments that indicate to which expression each closing parentheses belongs.This can be achieved automatically using the format options offered by theVisual LISP editor. In the following chapters code listings will be presented asprinted text using a more compact format so the number of pages is notunnecessarily increased.

    The editor automatically adds the appropriate indentation for each new

  • line by pressing ENTER. If the code does not adopt a format similar tothat shown in the screenshots it indicates that an error has occurred,probably omitting a parenthesis or adding one in excess. The easiest wayto check for the closing parenthesis that corresponds to an openingparenthesis (or vice versa) is to place the cursor next to them (on theoutside) and double-click. This will highlight all the text from aparenthesis to the corresponding closing or opening one.

    Loading a function can reveal errors that are detected at compile time, but theremay be errors that only become apparent when running the program. To test thefunction we just loaded we just type the expression (numera-dict) in theConsole and press ENTER. This will create the dictionary object with defaultvalues. If an error occurs at run time the control is automatically transferred tothe Visual LISP Console which will enter a break loop. This is verified byobserving the console symbol that will show the current break loop level, forexample, $ _1_. For now it is enough to know that to get out of this loop wemust type CTRL+R.

    To check the stored values we must type in the console the expression (vlax-ldata-list "VARS-NUMERA") which returns all the stored values as anassociation list. For a specific value we can use the vlax-ldata-get function,passing the value of the associated key as argument. For now we will settle withthese initial default values. Later we will create the user interface that willallow us to change them at will.

    2.3. The calculus function.

    The functions shown in this section will be included in the numera-calculus.lsp file. The next-num function (see Figure 2.8) is used to incrementthe figure for each new text. No arguments are received here either. It limitsitself to adding the value stored in) is used to increment the figure for each newtext. No arguments are received here either. It limits itself to adding the valuestored in "NUMBER" with the value stored in "INCREM" and saving the resultingnumber as the new value for "NUMBER" in the "VARS-NUMERA" dictionary.

  • Figure 2.8. Function NEXT-NUM.

    This function will be saved in the numera-calculus.lsp file, together with theabove described numera-dict (See Figure 2.7). Each time next-num is calledthe value will be increased. Well check it by loading again the project andexecuting (next-num) from the Console (See Figure 2.9).

    Figure 2.9. Evaluation of functions in the console.

    This way we can see that whenever the (next-num) expression is evaluated itreturns a number incremented by 10. That is the figure we will use for theconsecutive numbering of our parcels.

    2.4. The drawing function.

    We will now consider the function that draws the text (see Figure 2.10), whichwe include in the draw-text.lsp file. There are three ways to create newentities in the drawing. The oldest one is through the command function. Thisfunction allows the programmer to control the command system following thesame sequence of keyboard inputs the user would type to execute any command.Another option that, as we will see further on, offers obvious advantages in

  • execution speed and reliability, is to incorporate directly into the drawingdatabase the desired entities by means of the entmake function, which receivesan association list with the parameters associated with the correspondingidentifying code from the DXF system. An even more effective third option,available only since the addition of Visual LISP, is to create graphic objectsusing the ActiveX interface methods.

    In this tutorial we will use the command function, keeping in mind thatconceiving the drawing function as a standalone utility will allow replacing itwith another which uses a more advanced technology at any time (see Part 2,Chapter 10). For this, changing the source file referenced in the project wouldbe enough. It will only be necessary that the other function receives the samearguments.

    Figure 2.10. Text drawing function.

    The drawing of the number itself is done by the expression (command"._text" The expressions appearing before and after it disable any runningobject snap that may be active at the time of executing the function (which couldresult in a wrong location for the text). Its setting, stored in the OSMODE systemvariable is read by the getvar function and assigned to the local variable old-osm, so we can restore that previous value (with the setvar function) once thetext is placed.

    That this variable has a local scope is achieved through the structure thefunction parameters list adopts. This list is divided into two parts by a slash.The name old-osm that appears to the right of that slash corresponds to thevariable that is used for storing the running object snap value when this functionis called. The object snaps are here disabled by assigning OSMODE the value 0and the value assigned to old-osm is used for restoring the previous situationonce the text has been drawn. Once the previous running object snaps have beenrestored that value is no longer necessary, and including it in the right side of theargument list causes it to cease to exist as soon as this function has concluded.

  • That such a variable has a local scope means that it will not interfere with otherpossible global variables of the same name used by other programs.

    The programmer must know thoroughly the sequence of options correspondingto the command he wishes to execute. We must be aware that some commandsuse a different version when called interactively from the command line thanwhen called from an AutoLISP program. To check the commands behavior andoptions it should be called from an expression like (command "TEXT").Regarding text, we must keep in mind that AutoCAD has two differentcommands for it, whose names are: TEXT and MTEXT. The difference is thatMTEXT is able to write text in multiple lines while TEXT is only able to do itin one line. Since in our case a single line is enough we will use TEXT.

    One factor to consider is that our program could be used with any localizedversion of AutoCAD without language being an obstacle. So the rule followedin this book will be to employ the English name preceded by an underscorecharacter, which makes it valid for any version. If you are using a non-Englishversion, you can obtain this universal name by using the getcname function. So(getcname "texto") in a Spanish localized version will return "_TEXT"which is the name we pass to the command function. The getcname functionworks for command names, but not for their parameter names. As for theparameters, it is usually enough just to run the command in AutoCAD monitoringclosely the data requested and their sequence.

    Usually, we say because the TEXT command has different behaviors if run fromthe command line or from a program. The difference is that when run from thecommand line, once a line of text is finished, the command keeps asking for newlines, while from a program it does not, stopping once it has received the text todraw. Apart from this detail, the commands behavior is similar from thecommand line or from a program. We should also take into account that TextStyle settings will also affect the arguments required by the _TEXT command.First of all we must consider if the Text Style includes a fixed text height. Inthis case the height will not be prompted for.

    Command: (command "TEXT")TEXTCurrent text style: "Standard" Text height: 2.5000 Annotative: NoSpecify start point of text or [Justify/Style]: 100,100Specify height : 5Specify rotation angle of text : 0

    As before, we should not proceed without loading and testing the new function.For that we will call from the console, once loaded anew the project, the

  • expression:

    (draw-text (getpoint "Insertion Point: ") 5.0 "TEST")

    Pressing ENTER will activate the AutoCAD graphics window asking us toselect a point. The label TEST will be drawn on that point of the screen with aheight of 5 units.

    2.5. The user interface.

    As we see, the program code so far is limited to little more than twenty lines.Communication with the user may require a fairly large amount of extra codedepending on the type of presentation to which we aspire. The possible optionswith Visual LISP are:

    The command line.Dialog boxes programmed in DCL language.Windows dialog boxes programmed in .NET and compiled as DLL.Dialog boxes generated by the OpenDCL plug-in.

    Later we will examine in detail some of these possibilities. For now we limitourselves to the simplest, using the AutoCAD command line. Even using thecommand line quite complex interaction mechanisms can be attained. In thechapter on that subject we will show more sophisticated solutions using thecommand line interface.

    In an effort to simplify this first program as much as possible, we chose tocreate two different input functions. The first one (see Figure 2.11), which wehave called C:NUMERA starts a loop repeatedly requesting the next numbersposition until the user ends it by pressing ENTER or ESC.

  • Figure 2.11. Function C:NUMERA.

    The second one (see Figure 2.12), named C:NUM-OPTIONS is used to change theparameter values stored in the dictionary. This function requires the help ofnum-read (See Figure 2.13) that extracts the value of a text label in a drawing.Those user functions whose names start with C: create new AutoCADcommands that are invoked by typing the name in the command line withoutusing parentheses as in other LISP functions. All these functions should beincluded in the numera-input.lsp file. The parentheses are necessary if youwant to invoke the function from the VLISP console. In this case you need totype (c:numera).

    2.6. Placing the labels.

    To place the numbers, after loading the program (for now we will do it from theproject window), we type NUMERA on the command line. Immediately a messagerequesting the point of the screen where you want the number will appear. This

  • message includes the number to be inserted as a label. After selecting a positionand placing the label, the figure will be increased and new locations willcontinue to be asked for until the user presses ENTER, the space bar, ESC orthe right mouse button.

    The first thing we want to highlight in the code of this function is the use, as inthe draw-text function, a variable of local scope. The name pt-ins shown onthe right side of the parameter list is a variable that is used to memorize thecoordinates of the point selected by the user. That value is not necessary oncefinished the programs execution and so it then ceases to exist.

    The call to numera-dict ensures that the dictionary exists before the valuesstored in it are extracted. The user input for the texts insertion point is managedby the getpoint function. This function will display the message Positionfor No. #: printed on the command line, where # would be the value of thenumber whose turn it is to insert. The preparation of this message involvesreading the current number stored in the dictionary in integer number format so itwill be necessary to convert it into a string data type using the itoa function sothat it can be appended using strcat to the rest of the message. The setqfunction assigns to the pt-ins variable the value of the point selected on thescreen by the user (or if typed on the command line with the X, Y or X, Y, Zformat.) The repetition is ensured by a while loop whose condition is that thept-ins variable has a value other than nil.

    Within the loop, actions take place as follows:

    The label is drawn with a call to draw-text, Passing the insertion point,the number (as a string) and the text height as arguments.The number stored in the dictionary is increased by calling (next-num).The user is prompted for a new point selection. If this point has a valueother than nil, The loop is repeated.

    2.7. Updating the dictionary.

    The C:NUM-OPTIONS function has been designed (See Figure 2.12) to modify thedictionary settings prompting the user for the new increment, text height andinitial figure values. To define a new increment the getint function is called,taking into account that we do not wish to use decimals. In the case of textheight, where it is advisable to allow the introduction of real numbers (i.e.,decimals) we will use the getdist function which makes it possible tointroduce the value by typing or by selecting two points on the screen whosespacing is equal to the new labels' desired height. Both for the increment value

  • as for the text height, pressing ENTER passes to the next option withoutchanging the stored value.

    For the initial figure there are two possibilities: typing the value or selecting anexisting label. This selection is an example of the use of keywordsaccomplished by calling in succession the initget function (to define thesupported keywords) and getkword that only admits as input these keywords(or their uppercase characters) or ENTER. These user input fuctions areexplained in detail in Chapter 7.

    C:NUM-OPTIONS uses a helper function named num-read (See Figure 2.13) thatreturns, from any selected text entity, its value as a string of characters. As in allinput functions possible user errors must be taken into account. Therefore num-read first checks if the selected object is a text calling the expression:

    (= (cdr (assoc 0 (entget nom-ent))) "TEXT").

    If not, it reports the error and prompts again for a selection. Another possibleerror is that the selected text or the typed value is not a number, which isverified by the following expression, which returns nil if the values are non-numeric:

    (distof (cdr (assoc 1 (entget nom-ent)))).

    A third abnormal condition would be that the user pressed ENTER. The latter isnot a mistake but rather the signal to move on to the next option.

  • Figure 2.12. Function C:NUM-OPTIONS.

    The decision to type the value or to select an object is managed by the condconditional that checks first if the selected keyword was "Type", in this caserequesting the value using the getint function.

    This function incorporates its own error detecting mechanism, so that we can besure it will not admit an erroneous value (the only alternative admitted isENTER, In which case no changes are made to the dictionarys content). Theother two possibilities, choosing "Select" or pressing ENTER lead to thesame result. Therefore if the conditionals first block is not executed, the nextone will always be executed, this being ensured by including the constant T

  • which represents the status of true (as opposed to nil which represents false).As before, we will load the project for testing it. After loading the project wecan change to AutoCAD (by pressing the Activate AutoCAD button from theView toolbar) And type NUMERA to run the numbering and NUM-OPTIONS tochange the parameters. After placing some text labels we can save the drawingso we can check how, on reopening it, the parameters have been stored. If noerrors occur, its time to compile our program.

    Figure 2.13. Function NUM-READ.

    2.8. On error

    While debugging is left for a subsequent chapter, it is inevitable that some errorhas crept in while typing the code. Basically, two types of errors will occur.Those that the compiler detects when loading the project and which are almostalways due to errors in the location and number of parentheses, and those thatare detected when you attempt to run the program. In the first case, on loadingthe project we will receive messages in the Console as shown in Figure 2.14.

  • Figure 2.14. Error messages when loading the project.

    Observing these messages we will see that draw-text.lsp and numera-input.lsp were loaded without problems, so we know where to look for theerror, in numera-calculus.lsp. The message Malformed list on inputusually means that one or more closing parenthesis (right) are missing. If insteadwe would have a closing parenthesis in excess we would receive the messageAdditional input right parenthesis. The search for these brackets canbe an arduous task for a novice. We have an aid in the way the editorautomatically sets the indentation of new lines. If the resulting format is not thesame as the code listings shown in the book we can suspect that we have anerror in some of our parentheses.

    Two other ways are to use the Check edit window or Format edit windowbuttons having selected the file you want to check. If there is an error, In the firstcase the erroneous lines will be highlighted in the window andin the second case, if there are parentheses errors we will receive a warningmessage offering to fix the error.

    This usually will not solve the problem, but if we select No the text file will behighlighted beginning with the function where the error is located.

    Figure 2.15. Warning about a parentheses error when formatting the code.

    Another type of error can occur when trying to run the program. We havealready discussed how to quit from the break loop in which we automaticallyenter. In situations like this we have a highly effective mechanism to identifywhere the error lies. It is the Error Trace which can be activated from theView menu. In this window you can see the sequence, ordered from bottom totop, of the functions called. The one which caused the error is in the second row

  • just below the keyword :ERROR-BREAK. To find the exact place we selectthis line and right-click to access the contextual menu where we can select theCall point source option which highlights the offending expression in oureditor. If we encounter any run-time error it would be good opportunity for afirst contact with this powerful tool.

    Figure 2.16. Error Trace window with its contextual menu.

    2.9. Compiling the program.

    After checking the correct operation of the program will proceed to compile it.This will fulfill several purposes. First, it will combine the three source codefiles into a single program file. In addition, our code will be encrypted so thatusers can not know the means we used to achieve our goals. This is essential ifwe wish to sell our work, or simply to avoid any modification of the code byinexperienced persons that may adversely affect its performance. Moreover,loading and executing the program will surely gain in speed.

    Compiling the program is as simple as selecting the Build Project FAS buttonin the project window . We should study carefully the messages presented in the window, which appears on compiling. This window containsdetailed information about the process that will be explained in detail in a laterchapter. Examining at the FAS folder we see that a new file named numera.fashas been created, which is the compiled program. In the TEMP folder a numberof files with .ob and .pdb extensions remain, representing intermediate steps ofthe compilation process.

    To load the compiled program we can use the Project windows Load Fasbutton. Once the compiled program is loaded we can use it in the same way as

  • the project whose source code we had loaded. To install this program in othercomputers just copy numera.fas to a folder that is in one of the AutoCADsupport files search paths and type in the command line the expression (load"numera"). It can also be loaded using the Load Application button from theApplications group on the ribbons Manage tab or selecting the option of thesame name from the Tools menu in the Classic Workspace.

    Figure 2.17. Load/Unload Applications dialog box.

    2.10. Demand loading the program.

    Once we have our entire program in a single file we can take advantage of thedemand load option for programs. Demand loading means that our program willnot take up memory space when not in use and will be automatically loadedwhen typing the command name, in this case NUMERA or NUM-OPTIONS.

    To accomplish this, we will resort to the acaddoc.lsp file that, as weinstructed, was created in the Visual LISP projects folder. This is a special file

  • that will be loaded automatically for each drawing3. We will include in this filean autoload expression enabling the demand loading of program files. TheAutoLISP autoload function provides access to commands without loading thefull routines in memory. It takes two arguments: the name of the program file anda list with the command names defined in it (without the C: prefix), all asstrings.

    (autoload "program-name" '("command1" "command2" ...))

    If it is a LSP file it is not necessary to indicate the extension. But in our case theprogram commands are divided into three different .LSP files. In this case youmust load the .FAS which is where on compiling all the code was grouped in asingle file. But when, as in this case it is not a LSP file we'll have to include theextension. As the file numera.fas file is in the FAS folder within the Numerafolder, it necessary to include its relative path also. Adding the followingexpression to the file acaddoc.lsp our programs NUMERA and NUM-OPTIONSwill be available for each new drawing we open:

    (autoload "./Numera/FAS/numera.fas" '("NUMERA" "NUM-OPTIONS"))

    Notice how the relative path is expressed: the Visual LISP Projects folder isthe root folder and is represented by a dot. The path delimiters are slashes("/"). In case that on opening a new drawing and typing NUMERA we wereinformed that:

    The file ./Numera/FAS/numera(.lsp/.exe/.arx) was not found in yoursearch path folders.Check the installation of the support files and try again.

    we must first ascertain that our Visual LISP Projects folder is effectivelyincluded in the AutoCAD support files search paths and that the specified pathis the correct one. And for Release 2014 that all the folders containing the codeare included in the Trusted Locations. For this application to load in AutoCAD2014 we would have to include the Visual LISP Projects/Numera/FAS folderto these Trusted Locations. In case we don't do so a Security concern alert boxwill be displayed (Figure 2.18) where we can accept or reject loading thisprogram.

  • Figure 2.18. Warning about loading the application if not in a Trusted Location.

    2.11. Summary.

    This tutorial has served to introduce us to some of the key tools of the VisualLisp Development Environment (VLISP IDE):

    The ProjectThe EditorThe Visual LISP ConsoleThe Apropos utilityThe Error Trace windowThe Compiler

    For those familiar with classical AutoLISP, using the Dictionary object as ameans of preserving the values of the program's parameters will have surelyrevealed the new possibilities that Visual LISP ActiveX extensions provide .

    Exercises.

    Although we have not really started studying the programming language thereader may try his hand at extending the functionality of the applicationdeveloped in this tutorial.

    Exercise 1.

    Redesign the drawing function so that the texts are justified with the MIDDLEoption. The reader will recall that it is enough to pass to the command functionthe additional parameters that would make this adjustment when invoking TEXTfrom the command line. As a guide the command sequence is shown as it wouldappear in the AutoCAD text screen (see Figure 2.19).

  • Figure 2.19. Sequence for the TEXT command.

    Exercise 2.

    Expand the program to include drawing a circle centered at the text insertionpoint and with a radius equal to 2 times the height of the text. The drawing of thecircle will be implemented in a new function named draw-circ to be executedafter draw-text. By supplying as arguments the coordinates of the text'sinsertion point (assigned to the local variable pt-ins) and the value of"HEIGHT" multiplied by two:

    (* (vlax-ldata-get "VARS-NUMERA" "HEIGHT") 2)

    The options for the _CIRCLE command are:

    Command: CIRCLE

    Specify center point for circle or [3P/2P/Ttr (tan tan radius)]:

    Specify radius of circle or [Diameter]:

    Excersise 3.

    The text height saved to the dictionary will be the value the TEXTSIZE systemvariable had when the dictionary was initially created. The program does notinclude an option for modifying this value. You can add this option to theC:NUM-OPTIONS function by prompting the user for a new value, in this caseusing the getreal function: We can use the same structure used for theincrement data, but in this case we must take into account that the numeric valueis a real number (see Chapter 4, section 4.5) so we must convert it to stringusing rtos.

    (setq option (getreal (strcat "\nNew text height : ")))

    1 To display this dialog box we can use the graphic windows contextual menu or type theOPTIONS command.

  • 2 In the latest releases of AutoCAD, Help files are in HTML format, and by default thefiles hosted on the Autodesk server are used. But the installed configuration onlysearches for files in the application's language. Therefore users of localized versions willnot have access to the AutoLISP reference. The only solution for them is disabling theonline help. This is done in the System tab of the Options dialog box, deselecting the"Access online content when available" checkbox.

    3 A file named acad.lsp, if found, will be loaded when the AutoCAD session starts. Thefunctions loaded from it will be available only for the first drawing. A vl-load-allexpression in an acad.lsp file will make sure that a LSP file will be loaded to everydocument opened in that session. But an autoload expression must be called oninitializing each drawing. This is the reason we are using it instead of the acad.lsp file.Setting the ACADLSPASDOC system variable to 1, the acad.lsp file will be loaded intoevery drawing, its behavior then being the same as acaddoc.lsp.

  • Part 2The Language and its

    Development EnvironmentThis part of the book includes the essential information needed to programwith Visual LISP. This information relates primarily to the operation of the

    two most frequently used tools in the Visual LISP Integrated DevelopmentEnvironment: the Console and the Editor. We will use these two tools in

    learning the programming language.

  • This is a book that addresses a wide range of readers, from those withoutexpertise in programming to those who, skilled in AutoLISP programming seekinformation about how profit in their work from the new features that VisualLISP has been adding to AutoCAD since release 2000. In this part of the bookwe intend to describe the languages fundamental principles, not the detailedsyntax of each of each of the functions used or the programming methodology. Itshould be read carefully as it certainly is a sometimes dense text, but the ideasproposed therein will serve to further understand the sometimes complexprogramming techniques that in some cases it will inevitable to propose.

    For starters, the study of this part of the book is an absolute necessity tounderstand the rest. However, it is also a recommended reading for those withexpertise in the subject, as we address here basic conceptual aspects of thelanguage whose understanding will lead to more effective programming. In anycase, we consider that the study of Chapter 6, ActiveX Data Structures isessential for even the most experienced reader using AutoLISP versions prior toAutoCAD 2000.

    On a first reading, this part of the book certainly poses issues whose immediateunderstanding is not easy. Experience acquired in the development of programsoriented to solve practical tasks proposed in the following chapters will allowdeeper second readings in which the wealth and possibilities of LISP as aprogramming language as will become increasingly evident.

    First of all, we insist on the fundamental mechanism of learning we recommend:try each one of the expressions and carefully observe its effects. This is how welearned and also how we wrote this book. It is easy to see that much of the textshows evaluation results copied directly from the console and programs writtenand formatted in the editor.

    The whole book, but especially this part, is designed to be followed on thecomputer, using the Visual LISP IDE. In Chapter 4 the Console will be used andfrom Chapter 5 on we will begin to create source code files in the ProgrammingEditor that will configure a code modules library designed for their use ineveryday programs such as those shown in the subsequent parts of this book andin the additional examples the reader can download from our website or otherAutoLISP Internet sites. Each chapter also includes a summary as a reminder ofthe concepts that the reader will have acquired in their study and, whereappropriate, self-assessment exercises are proposed.

  • Chapter 3The Visual LISP IDE

    The Visual LISP Integrated Development Environment (VLISP IDE) includestools that assist in writing, modifying and debugging the source code. Now wecan, once we have coded the program using the Programming Editor, check itsoperation step by step, viewing at all times the output returned by the evaluationof each one of the expressions and the value the variables are assuming withouthaving to include any additional expressions in the program. It also provides themeans to package and distribute applications in a single executable file thatcontains the DCL dialog interface. These operations are performed within asingle environment, allowing text editing and program debugging, plusinteraction with AutoCAD and other applications.

    Figure 3.1. Visual LISP Application Window

    3.1. The Visual LISP IDE user interface.

    Visual LISP (see Figure 3.1) has its own set of windows and menus, but cannotrun independently of AutoCAD. A working session is started by typing vlide or

  • vlisp on the command line. When activated Visual LISP shows the followingcomponents:

    The Menu Bar: VLISP commands can be issued by selecting menu options. By placing thecursor over a menu item, a brief description of the action of this commandappears in the Status bar at the bottom of the screen. Active options on amenu may vary depending on which window (for example, the Editor orthe Console) is active at the time.The Toolbars: The toolbar buttons allow launching many of the VLISP commands. Thereare five toolbars: Debug, Edit, Search, Inspect and Run representingeach of the different features available. Moving the cursor over any buttonand leaving it still for a few seconds, displays a help message (tooltip)Indicating its function. Further explanation also appears in the status bar.Console window: It is a separate window, where we can type Lisp expressions, as in theAutoCAD command line. Many VLISP commands can be launched fromthis window rather than using the menu or tool bars. The Console is thetool we will use for learning the fundamentals of the programminglanguage, as it allows us to evaluate and immediately obtain the result ofany LISP expression.The Status Bar: Is located at the bottom of the screen. The information displayed variesaccording to the task being performed.The Programming Editor: It is designed especially for use with AutoLISP code. For each source codefile a new Editor window opens with the name of that file in its title bar.The name also appears in the status bar. An asterisk (*) next to the filename in the status bar indicates that you have made changes that have notbeen saved.Other Visual LISP Windows: Some outputs are displayed in the Console window, but certain functionscreate their own windows to display theirs. Some look like the console, forexample when you search for text in files of a project or when a program iscompiled. These windows cannot be written on, but you can copy the textthat appears in them and paste it in the editor or the console.

    3.2. Interactivity: The Visual LISP Console.

    From the Console, you can run LISP expressions to check their outcome. Thiscan also be done from the AutoCAD command line but there are several

  • differences in how the two operate. For example, to display the value of avariable in LISP, we simply type the name of the variable in the Consolewindow and click ENTER. But to obtain the value of a variable in theAutoCAD command line, we must precede the variable name with anexclamation point (!).

    In the Console window messages appear in case of errors and also the valuereturned on evaluating many expressions. For example, it shows the outputs ofthe print and princ functions.

    Console Operation.

    We will use the Console to learn the basics of LISP. During this process wewill use many of the techniques outlined below.

    Evaluating expressions.

    The main function of the console is to evaluate LISP expressions. The symbol_$ indicates the Console is waiting for an expression to be evaluated. Theexpression can be typed following this symbol. The text you type into theconsole is not evaluated until you explicitly press ENTER. To continue a LISPexpression on a new line avoiding its evaluation you can use the keycombination CTRL+ENTER.

    Repeating expressions.

    The typed text and the evaluation outputs are retained by the Console window.To re-evaluate an expression we can just press TAB. This will display on thecurrent Console prompt line the last expression evaluated. Pressing ENTERwill repeat its evaluation.

    If instead of repeating the last expression we should wish to repeat a previousone we can press TAB repeatedly, which will cycle through all of theexpressions evaluated during this work session. Once the first expression isreached, the cycle restarts. With SHIFT+TAB we cycle the expressions inreverse. The TAB key can also be used to perform an associative search in theset of expressions for this session. To do this, type the text you want to locatepressing TAB later. If there is a previous expression that includes that text, itwill appear in the current Console prompt line.

    Other way to repeat a previous expression would be to select it among thosememorized by the Console window (which can be scrolled using the vertical

  • scroll bar) and pressing ENTER. This will copy the selected expression to thecurrent Console prompt line, ready to be re-evaluated.

    Discarding expressions without evaluating them.

    If we start to write an expression in the console and decide not to continue, wecan delete it by pressing ESC so it will not be saved in the session history. Butif we wish to retain the expression but without evaluating it, we can pressSHIFT+ESC. Although not evaluated, the expression is stored in the sessionhistory so you can retrieve it by pressing TAB.

    Completing words.

    In many ways the console operates just as the Editor. One such aspect is thefunctionality of the Spacebar in combination with the CTRL and SHIFT keys.Once you have started typing a word it can be completed automatically, eitherby resemblance to other terms used in previous expressions pressingCTRL+SPACE, or by a symbols table lookup by pressingCTRL+SHIFT+SPACE.

    By using the complete words by resemblance tool (CTRL+SPACE) VLISPcompletes a word only partially typed by comparing it with other words in thesame window. If the word shown is not the desired one you can continue topress this same key combination until the required word appears. If it is asymbol (function names or variables used in the program or in the Visual LISPenvironment) the word can be completed with a name that exists in the symboltable without requiring that it had been used before in the console. In this casethe combination CTRL+SHIFT+SPACE is used or you could select theComplete word button (See Figure 3.4) of the Standard toolbar.

    Figure 3.2. Search with CTRL+SHIFT+SPACE.

    This will display a contextual menu (see Figure 3.2) that includes the symbolnames found. Selecting one of the names will complete the word. If no symbolhas been found, the Apropos Options window will open. If the number of

  • possible names found is greater than 15, instead of the window shortcut menuthe Apropos results window appears. In this case the symbol could be copiedto the clipboard by selecting the corresponding option from the windowscontext menu. This functionality is also available for the Editor windows.

    Console contextual menu.

  • The most important VLISP console features are included in the menu thatappears when you right-click (or SHIFT+F10) anywhere on the Console.

    According to the text selected in the Console window and the cursors position,some commands not relevant to the situation are disabled. The features invokedby these commands will be explained in the following chapters of this book.Table 3.1 shows all of the available commands in the consoles contextualmenu, also indicating the equivalent Standard (Figure 3.4) Or View (Figure3.9) toolbar buttons and the equivalent hotkey combination

    Syntax color coding.

    Another aspect in which the console works similarly to the Editor is in the colorcoding of the different parts that make up a LISP expression. The color codedexpression is the one that will be evaluated on pressing ENTER. Onceevaluated, the color coding disappears.

    AutoLISP functions helpfile.

    If we select a function name anywhere in the Editor or the console and press theHelp button on the Tools toolbar (See Figure 3.6) VLISP shows the help entryavailable for this function. The same effect is achieved by pressing CTRL+F1.This functionality is also available in the Editor.

    The Console and AutoCAD drawings.

    There is a single console for all open AutoCAD drawings. Scrolling theConsole we will find expressions and commands that have been issued in thecontext of each of these documents. In this it differs from the command line thatonly shows those related to the current drawing. VLISP automatically changescontext on activating a different drawing. The active AutoCAD drawing isalways the active document in VLISP. The expressions you type in the Consolealways have an effect on that drawing. The VLISP window's title bar shows itsname .

    If you switch to the AutoCAD window without evaluating an expression alreadytyped in the console, that expression will be visible in it, but a new line willhave been generated on returning to the IDE and the typed expression cannot berecovered by pressing TAB. In cases like this you can highlight the expressionand press ENTER, which will automatically copy it to the current Console line.To select a LISP expression the easiest way to is double-click next to the

  • opening or closing parentheses, this way the entire expression will behighlighted.

    3.3. The Programming Editor.

    If you only need to run a few AutoLISP expressions the Console might beenough. But in writing programs of some complexity it will be essential to usethe Programming Editor as a way to save the source code into a permanent file.The Editor is along with the console, one of the key components of the VisualLISP environment.

    The Editor as well as the Console, is designed to assist in AutoLISPprogramming and has the ability to complete expressions, locate the matchingopening and closing parentheses, syntax coloring and evaluating expressionswithout leaving the Editor window.

    In contrast to the Console, pressing ENTER generates a new line in the Editor.The new line is automatically indented. The Editor is also able to format thecode according to different user selectable styles.

    In general, besides syntax color coding and automatic indentation, the Editorprovides other utilities that assist in program development. Some of theseutilities are:

    Checking the parenthesis closure.The ability to insert expression-closing comments.Commenting and uncommenting text blocks.Finding and replacing text.Syntax checking.Loading of LISP expressions to be evaluated in the Console.

    VLISP IDE allows opening any number of files. When finishing a work session,information is saved for open files which will be reopened automatically whenyou start a new session.

    Editor windows do not have their own Menu or Toolbars. When an Editorwindow is in focus, the Menu options and VLISP IDE tools that can be used inEditor operations will be enabled. Some of the options can also be run from thecontextual menu that opens on right-clicking your mouse. You can use the usualtext editor keyboard shortcuts as well as some others unique to this Editor. Inthe following sections we will explain these features as they are accessed fromthe Toolbars, the Contextual Menu and Keyboard shortcuts.

  • Toolbars.

    Visual LISP has five toolbars which can be activated or deactivated from thedialog box (see Figure 3.3) That is opened from the View>Toolbars... menuoption. These five Toolbars include the essential IDE commands.

    For the time being we will only use the Standard, Search and Tools toolbars.The commands available in the Debug and View toolbars are used in thedebugging process to which we will devote a chapter later on.

    Figure 3.3. Toolbars dialog.

    Figure 3.4 Standard toolbar.

    Standard toolbar.

    It contains the usual Windows commands like New File, Open File, Save File,

  • Print, Cut, Copy, Paste, Undo and Redo.

    Undo recovers previous editor states. You can undo an unlimited numberof operations, up to the last time you saved the Editor contents to disk.Once saved you cannot undo. In this case, if needed, the backup copy couldbe restored using the File>Revert menu option.Redo is used to cancel Undo operations, but it should be usedimmediately after it.

    Besides these most usual operations, the Editor allows dragging text from onelocation to another within the edit window. To do this, you must highlight thetext and left-clicking on any part of the selection, drag it to the new location. Inthe same way it can be copied by pressing the CTRL key before releasing theleft button. You can also save the selected text into a new file by pressingCTRL+E+Q.

    Complete word completes a partially entered word with a matchingsymbol name from the VLISP symbol table. This functionality is alsoavailable for the console.

    Search Toolbar.

    This toolbar includes commands for locating and bookmarking text in the Editorwindows.

    Find and Replace (See Figure 3.5). The search for an expression can beperformed both in the file being edited as in a project's files or in the filescontained in a given folder (and its sub-folders). The search output isdisplayed in a new window called presenting theexpressions where the searched term is used. The search tool can beconfigured so it will place bookmarks each time it finds the searched term.To enable this you should select the Mark instances checkbox. Each editorwindow has its own set of bookmarks, so this option will be effective forsuccessive searches in a single file. The bookmarks are managed using thebuttons described below.To the right of the Replace button a drop-down list box is displayed wherepreviously searched terms are saved during the work session allowing torepeat searches by pressing the Find toolbar string button next to it.Toggle bookmark places a bookmark at the cursor line. Up to 32bookmarks can be placed in an Editor window. If you have alreadybookmarked 32 positions, the next position to be bookmarked removes theoldest one.Next bookmark and Previous Bookmark cycle through the existing

  • bookmarks.Clear all bookmarks. Deletes all bookmarks in the current window.

    When you format a text that contains bookmarks, they move to the start of theblock selected for formatting. If we format all of the Editor window's content,we lose the bookmarks, remaining only one on the window's first line, fact thatwe must take into account if we use this tool.

    Tools toolbar.

    The Tools toolbar (See Figure 3.6) is enabled only if the Editor window isactive. Its commands are, from left to right:

    Load the code in the active Editor window so it can be executed.Load only the selected code block.Check the syntax of the active Editor window's content.Check only the selected code block.

    The syntax checking results are displayed in a new window that bears the titleof . If an error is detected, the affected code will be displayedand highlighted in this window. Double-clicking on the highlighted line in theBuild output window, the cursor will move to the line of code in the Editorwindow where the error was detected highlighting the text. Not only are obviousmistakes signaled but also some situations that should be handled with care asthey may be, in certain cases, a source of errors.

    Format Edit window.Format selection.

    The Visual LISP code formatter organizes the content of the Editor's activewindow to improve its appearance and readability. Although intelligentindentation organizes the program code as the text is typed, it can also beexplicitly invoked with the Tools toolbar buttons (See Figure 3.6) to rearrangethe selected blocks or the entire Editor text .

    If the formatter finds an unbalanced parenthesis, it displays a warning messageand offers to add the necessary parentheses. But rarely will these parentheses beplaced correctly, so it is better not to accept this offer and look by oneselfwhere the mistake has been made, which we should do starting from the portionof code that remains highlighted in the Editors window.

    There are different styles for the automatic formatting depending on the settingsof several environment options. The format we used in the books code listings

  • are obtained with the settings shown in Figure 3.7.

    Figure 3.5. Search Toolbar.

    Figure 3.6. Tools toolbar.

    To set these or other options select: Environment Options>Visual LISPFormat Options... in the Tools menu. The user can experiment with these

  • options until a presentation of the source code that is comfortable to work withis found. Many professionals use a format similar to this books code listings,which for us is also imposed by the need to make it more compact, although forbeginners it is often clearer to enable the Close at new line with outerindentation and Insert form-closing comment options. This comment can becustomized by inserting a prefix (e.g. end of) in the edit box provided for this.These formatting options were used in the screenshots for the tutorial in Chapter2.

    Comment block.Uncomment block.The comment marking introduced by the Comment block buttoncorresponds to the three semicolon character style (;;;) that is alignedwith the left margin with the automatic formatting option. In DCL files, adouble slash (//) is used for commenting a line .Online help for the function on which the cursor is placed.

    Formatting keyboard shortcuts and contextual menu.

    Typing CTRL+E while an editor window is active or selecting the Edit>Extracommands menu option displays the formatting menu displaying the list ofoptions shown in Figure 3.8. These options enable a series of operations relatedto the formatting of text in the editor. They have the associated shortcut keysshown, with a description of their operation, in Table 3.2.

  • Figure 3.7 Visual LISP Formatting Options.

  • Figure 3.8. Formatting menu.

    View toolbar.

    The View Toolbar (See Figure 3.9) allows us to access AutoCAD and otherspecialized tool windows in the IDE. It is also available when the focus is onthe Console. Most of the buttons on this toolbar are used during the debuggingprocess. Here we limit ourselves here to describing the use they would have inthe editing stage.

    The first button is used to access the AutoCAD graphic window.The second button (Select Window) Opens a menu where you can selectthe Visual LISP IDE window we want to set in focus. This is convenientbecause we can simultaneously open a large number of files and locatingthe one we wish to edit may not be easy.The third button sets the focus on the console.For the time being we will only use the second last button, Apropos.

  • Figure 3.9 View Toolbar.

    The Apropos button opens the Apropos results window, a tool that searchesthe system symbols table. This table contains each of the symbols read byAutoLISP in the current session. This includes both the symbols of userprograms and those implemented by the language.

    Apropos is a very effective way of checking function names and accessing theonline documentation. Specific search criteria can be defined. For example,searching for all symbols that contain a particular string and even refining thissearch so that only those that identify functions are returned. If no text ishighlighted a dialog box is displayed for typing the text to search.

    Other way to restrict the search is to establish that the search string should bethe symbol names prefix. You can also opt for a search using wildcards asdone by the wcmatch function.

    The Apropos results window (See Figure 3.10) has three buttons that call thefollowing actions:

    Returns to the Apropos options dialog box to refine the searchCopies the results of the search window content to the Trace window fromwhich you can select text and copy it for use in any Windows application.If Trace logging is enabled, the contents are also copied to the log file. Toenable logging activate the Trace window, and specify a log file name inthe file dialog box displayed by the File>Toggle Trace Log... optionfrom the File menu.Opens the on-line Help item which refers to the selected function name.

  • Figure 3.10 Apropos results.

    The contextual menu enables copying the symbol name to the clipboard, openingthe Inspect window for the selected symbol, print it in the Console, opening theSymbols service, copying it to the *obj* global variable and adding it to theWatch window so as to monitor its values at runtime. The Help option displaysthe online documentation (if any) for the selected symbol.

    Editor contextual menu.

    Right-clicking anywhere in the Editor window opens a contextual menu inwhich, according to whether or not any text is selected, a number of often usedEditor commands will be enabled. Some of these options are equivalent to thoseof the same name described for toolbars.

  • Automatic backups.

    Visual LISP backups the files opened in the Editor. This backup is done onsaving the file for the first time. The backup has the same name as the file and itsextension starts with an underscore sign (_) followed by the first two charactersof the original extension. So a backup with a ._LS extension will corres