AutoLISP For Absolute Beginners
AutoLISP For Absolute Beginners
Let us learn AutoLISP in plain English. You will be guided slowly to create your own AutoLISP program
AutoCAD will open visual lisp window. This window might not look fancy, and and the icons remind me of good old Windows 3.1 icons. However, it has many specific AutoLISP programming tools that can help us.
AutoLISP Structure
Before we start, let us see the common program structure below. (defun c:YourProgramCommand () WhateverYouWantAutoCADtoDo (princ) )
Most programmer will put the close parenthesis below, parallel to open parenthesis. This will be easier for us to find the parenthesis pair. Most programming language will not care where is the close parenthesis, as long as they can find it. So make sure it will be EASY FOR YOU to find it. Inside the parenthesis, you define whatever you want AutoCAD to do. That is the tricky part. We will do a simple exercise here, to see how it works.
Command: _zoom Specify corner of window, enter a scale factor (nX or nXP), or [All/Center/Dynamic/Extents/Previous/Scale/Window/Object] <real time>: _c Specify center point: 0,0 Enter magnification or height <1753.5398>: 2000
The red fonts are the command we input during the zoom process. This is what we do manually: 1. 2. 3. 4. First, we type _zoom to activate the zoom tool. Then AutoCAD will ask us which method you want to use. We type _c to use zoom center. Then AutoCAD will ask us the center point. Because we want to zoom to origin, we type 0,0. The last thing AutoCAD will ask is the magnification. Type the distance you want to see on your screen. I use 2000. It means AutoCAD will show 1000 to the left, and 1000 to the right. With 0,0 at the screen center. If you use imperial, you may want to change it to smaller number.
Each time we give the input, we press enter. So we type _zoom [enter] _c [enter] 0,0 [enter] 2000 [enter]. Now in your Visual LISP editor, try to type like below. Type it, do not copy and then paste it. It will not work. (defun c:ZO () (command _ZOOM _C 0,0 2000) (princ) ) You know whats written in red means right? Command will load internal AutoCAD command, then you give the parameters. Each input in quote. This time, you can use (princ) or not using it. Adding (princ) will end the program gracefully, but without it, it will also work. Now save this program.
Now move to AutoCAD window, and try to type ZO then [enter]. Does it work? Congratulations! You have just created your first program! We will modify this program further. So save it and dont loose it.
Using Variables
In programming, we use variables to save our values. In our previous sample, we havent use it. (command "_ZOOM" "_C" "0,0" "2000") Lets say we save the coordinate to ZPT (zoom point) and save the magnification to MRAT (magnification ratio), then our program will be like this. (command "_ZOOM" "_C" ZPT MRAT)
Remember, the program name and user variables have to be unique and not using AutoCAD system variables. You can use any other names that can be easily recognized.
So how to tell AutoCAD the variables value? You can assign the value to variables using setq function. To set the ZPT value and MRAT value, we add these following lines before our command. (setq ZPT '(0 0)) (setq MRAT 2000)
Now lets put it all together in our program. Now our program become like this. (defun c:ZP () (setq ZPT '(0 0)) (setq MRAT 2000) (command "_ZOOM" "_C" ZPT MRAT) (princ) ) Try to type it in your visual LISP editor and try it. Load the program, and run it. Does it work?
Now load your program. After you run it, type !ZPT or !MRAT to see the variable value. Now they should say nil. Now AutoCAD doesnt keep the variable in your computer memory after the program has finished running.
Giving Comments
Most AutoLISP program have comments. The idea is to give information when other people open the program, what it does, who create it, and you can also add some information what the codes in a line does. Comments will be ignored by AutoCAD, and will not be processed. Let us complete it so it would looks like a real program. You can give comments to your AutoLISP program using semicolon character. I added some comments like below. Now you can see how the pretty colors can easily distinguish the codes right? See what the colors mean in this AfraLISP tutorial.
If you have a problem with the code, try to copy the completed code below, and paste in your Visual LISP editor. ;Zoom to Point ;This program will quickly zoom to a specific point ;Created by: Edwin Prakoso ;website: http://cad-notes.com (defun c:ZP (/ ZPT MRAT) (setq ZPT (getpoint " Pick a point or type coordinate: ")) ;this will ask for user input (setq MRAT 2000) (command "_ZOOM" "_C" ZPT MRAT) ; this will run the zoom command (princ) )
(setq x (rtos (car p))) (setq y (rtos (cadr p))) (setq z (rtos (caddr p))) (setq ptcoord (strcat x ", " y ", " z)) (command "_LEADER" p textloc "" ptcoord "") ) ) And if you want to simply download and use it, download this file. There are two files in the zip file. 1. LB.lsp is for Labeling Coordinate (X and Y only) 2. LBZ.lsp is for Labeling Coordinate (X, Y, and Z) Enjoy the LISP, and share it to your friends! Notes: After I wrote this, I realize that Shawki abo zeed have published similar code in labeling coordinate tips. It looks it has more features. If this one doesnt work fine, you may want to try his code too. Thank you to Shawki!
You can open notepad, copy and paste the code below, then save it as lb.lsp (type it with double quote when saving in notepad). If you want to show only Easting and Northing, you can delete the marked lines. Or replace East with E or X=, and so on. I hope this is useful. ; Automatic coordinate labeling ; Edwin Prakoso ; http://cad-notes.com ; ; Limitation ; ---------; Will use current leader style and current units setting ; If you don't want to show elevation, then modify lines marked * (defun c:lb (/ p x y z ptcoord textloc) (while (setq p (getpoint " Pick Point: ")) (setq textloc (getpoint " Pick Label Location: ")) (setq x (rtos (car p))) (setq y (rtos (cadr p))) (setq z (rtos (caddr p))) ;*you may delete this line (setq x (strcat "East " x)) (setq y (strcat "North " y)) (setq z (strcat "Elev. " z)) ;*you may delete this line (command "_LEADER" p textloc "" x y z "") ;*you may delete z
) ) Want to create this program by your own? You can also adjust it to your needs.
source: Math Open Reference page. If we know the area and number of sides, we can calculate the apothem. What is apothem? See image below.
How can we draw a polygon when we know the apothem and number of sides? Using polygon tool of course. We create it using circumscribed method.
type integer number. It should return the number you entered. Try again. This time type a decimal number.Lets say 3.2. What will AutoCAD say?
Using the right user input function will also reduce probability of errors.
Program Basic
We are going to use leader tool to label it. It will require us to define two points: point to label, and where we want to place the label. We already learned how to ask for user input for a point. So you should already familiar with this code: (defun c:\cnlabel () (setq p (getpoint " Pick Point to Label: ")) ; asking user to click point to label and save it (setq textloc (getpoint " Pick Text Location")) ; asking user to click text location (command "_leader" p textloc "" p "") ; activate label tool and use the input ) In visual LISP editor, you can copy or type it (I suggest you to type it for your exercise) then click load active edit window.
I can create it by combining x and y like this: (setq ptcoord (strcat x= x ; y= y)) Dont forget to save it to a variable! I use ptcoord. You may change the text inside the double quotes. You may want to use E=, N=, el= etc. Now lets put it all together: (defun c:cnlabel () (setq p (getpoint " Pick Point to Label: ")) (setq textloc (getpoint " Pick Text Location")) (setq x (rtos (car p))) (setq y (rtos (cadr p))) (setq ptcoord (strcat "x=" x ", " "y=" y)) (command "_leader" p textloc "" ptcoord "") (princ) )
To add the dynamic line, we simply add the variable of the first point when we ask the second point. The variable is p, so now the line become: (setq textloc (getpoint p Pick Text Location)) Add it and try it again.
Save the file to your library folder. I save it to D:\acadlib. You may have different location if you want to. Now we need to set the location as AutoCAD support file search path. Open AutoCAD option. Add the folder location here.
To prevent AutoCAD to load the dialog box, we need to add (dash) in front of the command. try to type INSERT then *enter+. See what Im talking about?
We are going to use that. Insert block will insert a block with the name we defined in our AutoLISP program. If it cant find it, then it will search and load DWG name with the same name as the block. Then insert the DWG as block. That is why we define the file location in default search path. AutoCAD will load the file from that location. The rest is easy. Like in previous tutorial, we can get the elevation value from the coordinate list and insert it to the block attribute. So our basic program can be like this: (defun c:cnannolevel (/ labelposition y) (setq labelposition (getpoint " Pick Label Position: ")) (setq y (cadr labelposition)) (setq y (rtos y)) (command "_-insert" "annolevel" labelposition 1 1 0 y) )
More Consideration
If you already tried it, you can see it works nicely. But you may want to consider to allow AutoCAD users to change the block scale. We will do it later in this AutoLISP tutorial. The next thing is change the label value when its at 0 elevation. In my country, many people like to use+ 0.00 when its at zero elevation. We will add an if conditional to change the value.
(IF (statement) (things to do if true) (else, things to do if false)) I added conditional IF twice: (if (= cnglobalscale nil) (setq cnglobalscale (getreal " Set Global Scale for CN Annotation <1/1>: ")) ) (if (= cnglobalscale nil) (setq cnglobalscale 1) )
Final Code
After we added those features, then this is the complete code: ; CAD-Notes.com annotation utilities ; by: Edwin Prakoso (defun c:cnannolevel (/ labelposition y) (if (= cnglobalscale nil) ; this will check if user already has defined the drawing scale (setq cnglobalscale (getreal " Set Global Scale for CN Annotation <1/1>: ")) ) (if (= cnglobalscale nil) ; this will check if the user choose default value (setq cnglobalscale 1) ) (setq labelposition (getpoint " Pick Label Position: ")) (setq y (cadr labelposition)) (if (= y 0) (setq y "%%p 0.00") (setq y (rtos y))) ; this will change text when in zero elevation (command "_-insert" "annolevel" labelposition cnglobalscale cnglobalscale 0 y) (princ) ) (defun c:cnannoscale () ; this another function defined to enable user to change scale later (setq cnglobalscale (getreal " Set Global Scale for CN Annotation: ")) ) This program works nice. But the problem is the label cant be updated automatically. Not like using fields. We will cover how to update the value later when we cover entity selection.
) Lets see what can we do with COND in our case. (cond ((AND (= pt1x pt2x) (> pt1y pt2y)) (setq gridblockname "vgridbottom")) ;change block name when meet the condition ((AND (= pt1x pt2x) (< pt1y pt2y)) (setq gridblockname "vgridtop")) ((AND (> pt1x pt2x) (= pt1y pt2y)) (setq gridblockname "hgridleft")) ) First, we set the block name to HGRIDRIGHT. We will use this block when we draw grid line to the right. But when we draw it to bottom, we need to use block VGRIDBOTTOM. When we draw a grid to bottom, there are two conditions are met: 1. X1 and X2 are the same. 2. Y2 is larger than Y1. X1, Y1 is the first picked point, and X2, Y2 is the 2nd point picked by user. We define the three conditions in our program. For right direction, we dont have to define it because we already set it as default block name.
The complete AutoLISP code is like this: (defun c:cngrid (/ pt1) (if (= cnglobalscale nil) (c:cnannoscale) ) ; end if (setq CurrentOrthomode (getvar "orthomode")) (setvar "orthomode" 1) (setq pt1 (getpoint " Pick Grid Start Point: ")) (setq pt2 (getpoint pt1 "nPick Grid Last Point: ")) (setq pt1x (car pt1))(setq pt1y (cadr pt1)) (setq pt2x (car pt2))(setq pt2y (cadr pt2)) (setq gridblockname "hgridright") ;set default grid name (cond ((AND (= pt1x pt2x) (> pt1y pt2y)) (setq gridblockname "vgridbottom")) ;change grid name when meet the condition ((AND (= pt1x pt2x) (< pt1y pt2y)) (setq gridblockname "vgridtop")) ((AND (> pt1x pt2x) (= pt1y pt2y)) (setq gridblockname "hgridleft")) ) (setq gridnumber (getstring " Enter Grid Number: ")) (command "_line" pt1 pt2 "") (command "_-insert" gridblockname pt2 cnglobalscale cnglobalscale 0 gridnumber) (setvar "orthomode" CurrentOrthomode) (princ) ) (defun c:cnannoscale () ; this another function defined to enable user to change scale later (setq cnglobalscale (getreal " Set Global Scale for CN Annotation <1/1>: ")) (if (= cnglobalscale nil) ; this will check if the user choose default value (setq cnglobalscale 1) ) ; end if )
Error trapping
To complete this AutoLISP program, it is a good thing that you create an error trapping. We change an AutoCAD system variable: ORTHOMODE. We do set it back to original value. The problem is, when an error occur and the program ends prematurely, the system variable is not restored. The variable will not be restored when you press esc key! This is what happen in this selection issue and the missing dialog box. Many problem can happen if you dont set error trapping in an AutoLISP program!
Layers are the most important thing to manage our drawings. If youre not familiar with layer standard, CADD manager has a short article about the concept.
We need to check if the layer exist or not first. We can do it by using this code: (setq flag (tblsearch "LAYER" "A-Anno")) Then add conditional IF like this: (if flag (PUT WHAT YOU WANT AUTOCAD TO DO HERE) (ELSE DO THIS) ) We have discussed about using conditional IF in AutoLISP before. The problem is IF only allows you to run one statement. So we need to add (progn GROUP OF STATEMENTS) to run several statements.
Lets see the complete code below: (defun c:cntext () (setq flag (tblsearch "LAYER" "A-Anno")) ;looking for A-Anno layer ;then do this if exist (if flag (progn ;grouping statement (setq oldlayer (getvar "CLAYER")) (setvar "CLAYER" "A-Anno") (setq textcontent (getstring " Type Text: ")) (setq textloc (getpoint " Text Position: ")) (command "_TEXT" textloc "" "" textcontent) (setvar "CLAYER" oldlayer) ) ;end statement group ;else - and give warning if it doesn't exist (alert "No A-Anno layer. Create it first to maintain standard.") ) ; end if ) Now AutoCAD will try to find the layer first before executing our command. If it doesnt exist, then it will give a warning.
If the layer exists, then it will run our program. There are several possibilities to handle this situation. We will see in the next tutorial, other alternatives to deal with non-exist layers.
Command: -layer Current layer: 0 Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/TRansparency/MATerial/Plot/Fre eze/Thaw/LOck/Unlock/stAte/Description/rEconcile]: m Enter name for new layer (becomes the current layer) <0>: newlayer Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/TRansparency/MATerial/Plot/Fre eze/Thaw/LOck/Unlock/stAte/Description/rEconcile]: The bold text with red color is what were going to use in AutoLISP.
-Layer is the command. M will create new one, it will ask you for its name and then make it current. This command will keep asking you to enter an option. So we press [enter] to end the command.
So we can write it as a LISP program below: (command "_layer" "m" "NEWLAYER" "")
Easy, right? This will create new layer named NEWLAYER (if there is no newlayer in the list) and make it current. The good thing about it is, if there is existing layer with that name, it will accept it and set make it current. So we dont have to add code to check if it already exist. We can replace this code we made before: (defun c:cntext () (setq flag (tblsearch "LAYER" "A-Anno")) ;looking for existing ;then do this if exist (if flag (progn ;grouping statement (setq oldlayer (getvar "CLAYER")) (setvar "CLAYER" "A-Anno") (setq textcontent (getstring " Type Text: ")) (setq textloc (getpoint " Text Position: ")) (command "_TEXT" textloc "" "" textcontent) (setvar "CLAYER" oldlayer) ) ;end statement group ;else - and give warning if it doesn't exist (alert "No A-Anno layer. Create it first to maintain standard.") ) ; end if )
With much simpler code like this defun c:newla () (setq oldlayer (getvar "CLAYER")) ;get the current first (command "_layer" "m" "newtest" "") ;create and change current (setq textcontent (getstring " Type Text: ")) (setq textloc (getpoint " Text Position: ")) (command "_TEXT" textloc "" "" textcontent) (setvar "CLAYER" oldlayer) )
Text Styles
What about text styles? We can use style command. It also can create new style and use it as current. Let examine in command line how the sequence is.
Command: -STYLE Enter name of text style or [?] <Standard>: newstyle New style. Specify full font name or font filename (TTF or SHX) <txt>: arial Specify height of text or [Annotative] <0.0000>: Specify width factor <1.0000>: Specify obliquing angle <0>: Display text backwards? [Yes/No] <No>: Display text upside-down? [Yes/No] <No>: newstyle is now the current text style.
There are 7 options AutoCAD will ask you. Lets see this sample. You can use this line to create text styles
That code will create a new text style with name newstyle and using arial.ttf as its font. It ignores the other questions and accept default values only. Another example, this will create a style with height 2.5 and width factor 0.85.
* Note: if you use shx font, you need to press [enter] one more time. SHX fonts support vertical alignment, and AutoCAD will ask one more question, if you want to make it vertical.
Dimension Styles
Unfortunately when working with dimstyle, we need to use conditional IF. 1. We need to use save option in dimstyle to create a new one. 2. Or if it doesnt exist, we need to use restore to change the current dimension style. The problem is when we use save dimstyle, and AutoCAD find it already exist, it will ask one more question. It asks us to confirm if we want to redefine the existing. So we use this code: (defun c:tst () (setq flag (tblsearch "dimstyle" "newdimstyle")) ;looking for dimstyle ;then do this if exist (if flag (command "-dimstyle" "R" "NEWDIMSTYLE") (command "-dimstyle" "S" "NEWDIMSTYLE" "") ); end if )
SSGET will save your selection to sel1 variable. Then you can add it to move command. Remember, you need to add to end selection. If you dont add it, AutoCAD will continue to ask you to select object.
(defun c:rst () (setq sel1 (ssget)) (command "CHPROP" sel1 "" "COLOR" "BYLAYER" "LWEIGHT" "BYLAYER" "LTYPE" "BYLAYER" "") )
That code will select all objects inside rectangular window from 0,0 to 10,10. Other code that we can use are:
setq sel1 (ssget "c" '(0 0) '(10 10)) to select object inside and touching rectangular window (crossing polygon). setq sel1 (ssget "l")) to select last objects created. setq sel1 (ssget "p")) to select objects in previous selection. setq sel1 (ssget "x")) all objects in the drawing.
If youre not familiar with the selection mode above, read using AutoCAD selection below. For window and crossing polygon selection, we can also ask for users input.
For example:
(setq pt1 (getpoint " Pick first point: ")) (setq pt2 (getpoint " Pick other corner point: ")) (setq sel1 (ssget "c" pt1 pt2))
We will expand this selection using filter. If you have a simple example that we can use in this exercise, please let me know. I will add your code here, and you will be credited. Further readings: 1. Selection sets. Good explanation by Kenny Ramage on AfraLISP. 2. Using AutoCAD selection. Here are the list how you can select objects in AutoCAD. 3. AutoLISP function list. See all LISP function that you can use to expand your LISP program.
(defun c:dimla (/ sel1 CLAYER ) (setq sel1 (ssget "X" '((0 . "DIMENSION")))) ; SELECT ALL DIMENSION (setq OLDLAYER (getvar "CLAYER")) ;GET CURRENT LAYER (command "_layer" "m" "ANNO-DIMENSION" "") ;CREATE NEW LAYER (setvar "CLAYER" OLDLAYER) ; SET ACTIVE LAYER TO PREVIOUS (command "CHPROP" sel1 "" ; CHANGE DIMENSION LAYER TO NEW LAYER "LAYER" "ANNO-DIMENSION" "") );END PROGRAM
With that simple code, you can quickly find and move all dimensions to desired layer. Very useful, right? You can also modify it to allow user to check the selection visually before move dimensions to other layer.
DXF code
One more thing that you might want to know is the DXF code. (0 . "DIMENSION") - Using DXF code 0 allows you to define object to select by objects type. This code will only allows you to select dimensions. (8 . "ANNO-DIMENSION") - Using DXF code 8 allows you to define object to select by their layers. This code will only allows you to select objects on layer ANNO-DIMENSION. We use DXF codes with selection filters in AutoLISP. See the complete dxf associative code below
8 9 10
Layer name (fixed) DXF: variable name identifier (used only in HEADER section of the DXF file). Primary point. This is the start point of a line or text entity, center of a circle, and so on. DXF: X value of the primary point (followed by Y and Z value codes 20 and 30) APP: 3D point (list of three reals) Other points. DXF: X value of other points (followed by Y value codes 21-28 and Z value codes 3138) APP: 3D point (list of three reals) DXF: Y and Z values of the primary point DXF: Y and Z values of other points DXF: entity's elevation if nonzero. Exists only in output from versions prior to AutoCAD Release 11. Entity's thickness if nonzero (fixed) Floating-point values (text height, scale factors, and so on) Linetype scale. Floating-point scalar value. Default value is defined for all entity types. Repeated floating-point value. Multiple 49 groups may appear in one entity for variable-length tables (such as the dash lengths in the LTYPE table). A 7x group always appears before the first 49 group to specify the table length. Angles (output in degrees to DXF files and radians through AutoLISP and ARX applications). Entity visibility. Integer value. Absence or 0 indicates visibility; 1 indicates invisibility. Color number (fixed) "Entities follow" flag (fixed) Space--that is, model or paper space (fixed) APP: identifies whether viewport is on but fully off screen; is not active or is off. APP: viewport identification number. Integer values, such as repeat counts, flag bits, or modes 32-bit integer values Subclass data marker (with derived class name as a string). Required for all objects and entity classes that are derived from another concrete class to segregate data defined by different classes in the inheritance chain for the same object. This is in addition to the requirement for DXF names for each distinct concrete class derived from ARX (see "Subclass Markers"). Control string, followed by "{<arbitrary name>" or "}". Similar to the xdata 1002 group code, except that when the string begins with "{", it can be followed by an arbitrary string whose interpretation is up to the application. The only other allowable control string is "}" as a group terminator. As noted before, AutoCAD does not interpret these strings except during drawing audit operations; they are for application use.
11-18
102
DIMVAR symbol table entry object handle Extrusion direction (fixed). DXF: X value of extrusion direction APP: 3D extrusion direction vector DXF: Y and Z values of the extrusion direction 8-bit integer values Arbitrary text strings Arbitrary binary chunks with same representation and limits as 1004 group codes: hexadecimal strings of up to 254 characters represent data chunks of up to 127 bytes. Arbitrary object handles. Handle values that are taken "as is." They are not translated during INSERT and XREF operations. Soft-pointer handle. Arbitrary soft pointers to other objects within same DXF file or drawing. Translated during INSERT and XREF operations. Hard-pointer handle. Arbitrary hard pointers to other objects within same DXF file or drawing. Translated during INSERT and XREF operations. Soft-owner handle. Arbitrary soft ownership links to other objects within same DXF file or drawing. Translated during INSERT and XREF operations. Hard-owner handle. Arbitrary hard ownership links to other objects within same DXF file or drawing. Translated during INSERT and XREF operations. DXF: The 999 group code indicates that the line following it is a comment string. DXFOUT does not include such groups in a DXF output file, but DXFIN honors them and ignores the comments. You can use the 999 group to include comments in a DXF file that you've edited. ASCII string (up to 255 bytes long) in extended data. Registered application name (ASCII string up to 31 bytes long) for extended data. Extended data control string ("{"or "}"). Extended data layer name. Chunk of bytes (up to 127 bytes long) in extended data. Entity handle in extended data. Text string of up to 16 hexadecimal digits A point in extended data DXF: X value (followed by 1020 and 1030 groups) APP: 3D point A 3D world space position in extended data DXF: X value (followed by 1021 and 1031 groups) APP: 3D point A 3D world space displacement in extended data DXF: X value (followed by 1022 and 1032 groups) APP: 3D vector A 3D world space direction in extended data. DXF: X value (followed by 1022 and 1032 groups) APP: 3D vector
330-339 340-349
350-359 360-369
999
1011 1012
1013
1020, 1030 1021, 1031 1022, 1032 1023, 1033 1040 1041 1042 1070 1071
DXF: Y and Z values of a point DXF: Y and Z values of a World space position DXF: Y and Z values of a World space displacement DXF: Y and Z values of a World space direction Extended data floating-point value. Extended data distance value. Extended data scale factor. Extended data 16-bit signed integer. Extended data 32-bit signed long.
Andres Rodriguez Fotolia.com We covered several basic AutoLISP tutorial already. You should be able to use the programs. Now its time to manage them in AutoCAD. This is not only for you who want to learn AutoLISP, but also for you who want to simply use AutoLISP program. We know that we can find many AutoLISP program on internet now.
(defun c:cnlabel (/ p x y ptcoord textloc) (while ;start while (setq p (getpoint " Pick Point to Label: ")) (setq textloc (getpoint p " Pick Text Location")) (setq x (rtos (car p))) (setq y (rtos (cadr p))) (setq ptcoord (strcat "x=" x ", " "y=" y)) (command "_leader" p textloc "" ptcoord "") (princ) ) ;end while )
You can use visual lisp editor to save it as a program. Or notepad will work. But dont use Microsoft Word or other Word Processing program. Paste your code there. Save it as LISP program. If you use Visual LISP editor, then by default it will save your code as .lsp file. But if you use notepad, then you must define the .lsp extension when saving your file. Type YourProgramName.lsp (with double quote to force notepad save it as it is). Of course, change the blue text with your program name.
Save your file to a location that allow people easily access it.
hint: AutoCAD veterans use APPLOAD in command line In load/unload applications dialog, browse and find your AutoLISP file you saved before. Select it and click load.
The less cool way to do it is by clicking contents button below startup suite briefcase. Here you can add or remove LISP from startup suite. Just in case one day you dont want a LISP program to load automatically anymore, you know where to remove it now, right?
DEFUN is defining the function. In this sample, the function can be loaded by typing DIMLA in command line then press [enter]. As simple as that. What you should do next, depends on your AutoLISP program.
In ribbon panel/toolbar/menu
Type CUI then press [enter] to load Customize User Interface dialog. Or click User Interface in customization panel.
If youre not familiar how to create a command here, read this tutorial first. You have to make a command, change the command name and macro. The macro should be ^C^CDIMLA. Or whatever command you want to activate using this macro. ^C^C means you press esc twice to cancel all running command. After youve done, drag the command to ribbon panel, toolbar, or menu as you like.
In tool palettes
What about tool palettes? Can we place the command there? Sure you can. You can use palettes to activate AutoLISP command too . The process is similar with adding action recorder command in this tutorial.
What we learned
Now you know how to save a LISP code, load it to AutoCAD, and use it. You also know how to use AutoLISP command from ribbon/toolbar. And even using from tool palette. So how do you use AutoLISP? Do you load it automatically? And do you use command line or place it to ribbon?
To load application
If you have an AutoLISP program, you can load it by using load application in manage tab.
Or you can type APPLOAD then press [enter]. You will see load/unload applications dialog opened. Find your AutoLISP program then click load. Double-clicking the file will also load the application. This method will load your application in current session only. It means that when you close AutoCAD, then restart it, the application is no longer loaded. You have to load it again. If you use the application frequently, then you can consider to load it automatically in every AutoCAD session. You can do it by adding it to startup suite.
Drag and drop thing to add application is cool. If you notice the add button here, yes, its the other method to add application to startup suite. Click it, find your application and click open. There are some more advance technique, but I find this is the most convenient way for people who dont know much about customization like me. There are more methods like described in AfraLISP.
The acaddoc.lsp file can contain AutoLISP code for one or more routines, or just a series of load function calls. The latter method is preferable, because modification is easier. If you save the following code as an acaddoc.lsp file, the files mydocumentapp1.lsp, build.lsp, and counter.lsp are loaded every time a new document is opened. (load "mydocumentapp1") (load "build") (load "counter") Warning! Do not modify the reserved startup file acadYEARdoc.lsp (acad2000doc.lsp, acad2000idoc.lsp, acad2002doc.lsp, acad2004doc.lsp, acad2005doc.lsp, acad2006doc.lsp, acad2007doc.lsp, acad2008doc.lsp, acad2009doc.lsp, acad2010doc.lsp, acad2011doc.lsp). Autodesk provides the acadYEARdoc.lsp file, which contains AutoLISP-defined functions that are required by AutoCAD. This file is loaded into memory immediately before the acaddoc.lsp file is loaded. acadYEARdoc.lsp Do not modify the reserved file acadYEARdoc.lsp; it contains AutoLISP-defined functions required by AutoCAD. The file acadYEARdoc.lsp is loaded into memory immediately before acaddoc.lsp.
Partials to Enterprise CUI/CUIX named MNLs Partials to Enterprise CUI/CUIX loaded LSPs and MNLs in the order seen in CUI Enterprise CUI/CUIX named MNL Enterprise CUI/CUIX loaded LSP and MNL in the order seen in CUI acetmain.MNL Express Tools loaded LSP and MNL in the order seen in CUI Files in the startup suite in listed order seen in APPLOAD (S::STARTUP) called Script file started by acad.exe command line switch /b This applies to AutoCAD 2000, AutoCAD 2000i, AutoCAD 2002, AutoCAD 2004, AutoCAD 2005, AutoCAD 2006, AutoCAD 2007, AutoCAD 2008, AutoCAD 2009, AutoCAD 2010, AutoCAD 2011, AutoCAD 2012, AutoCAD 2013 Update related to AutoCAD 2013 SP1: AutoLISP and VBA Security Controls in AutoCAD 2013 SP1. New /nolisp Startup Switch. LISPENABLED, AUTOLOAD, AUTOLOADPATH system variable added. The acad2013.lsp and acad2013doc.lsp files will now be loaded only from their default installation folders: <install folder>\Support <install folder>\Support\<language>
Creating acaddoc.lsp
Create a new LISP file. You may use text editor or visual LISP editor to do it. Save it to a support file path. You may choose any existing path, or create your own support path. I would recommend you to do the later, and you can also save all your LISP file there.
Loading AutoLISP command is something quite basic we can do with acaddoc.lsp. Next, we will try to define our own command here.
After we undefine PLOT, AutoCAD will not recognize it anymore. Now try type .PLOT [enter]. Notice the dot before PLOT command. Plot command should work. The dot means we use AutoCAD built in command. After we finished, PLOT and .PLOT will give different result. The first one will use plot we define in acaddoc.lsp. The last one use AutoCAD built-in plot command.
You can activate PLOT command back using REDEFINE [enter] PLOT [enter]
; This line below will undefine existing PLOT command (command "undefine" "plot") ; This line below will define new PLOT command (defun c:PLOT ( ) (command "_DATALINKUPDATE" K) (initdia) (command ".plot") )
We use INITDIA to load AutoCAD plot dialog. If we dont use INITDIA before plot, then you will not see the dialog box. You will need to setup the plot using command line.
Save this AutoLISP file. Create or open a new file then activate plot. You will see after I create a new file, our code will undefine plot. Then when we use PLOT command, it updates datalink first, then activate plot. Nice, isnt it?
Regenerating model. AutoCAD menu utilities loaded.undefine Enter command name: plot Command: Command: Command: PLOT _DATALINKUPDATE Select an option [Update data link/Write data link] <Update data link>: Command: .plot
There is a debate why they changed. Most people think that it was because routines in AutoLISP or other 3rd party applications. I used to be agree with it, until I saw this problem also happens in AutoCAD LT. So it remains a mystery to me.
(SETVAR "PICKFIRST" 1)
Feel free to add more lines or change system variables and values as you preferred. If you want to learn how to use Visual LISP editor, see the basic AutoLISP tutorial.
Standard layers is one popular topic when we talk about CAD standards. There are several standard layers available like BS 1192, AIA, ISO 12567. If you asked me, I would suggest you to keep your standard layers in AutoCAD template and standards file. However, if youve never created standard the layers before, it would take times to add them in your template manually. There is a bundle of AutoLISP programs that you can download and run to build the layers. You can run it, it will create the layers and you can save your template. There are four LISPs, one linetype, and one ctb plot style. You must load demo.lin linetype, before you run AIALAYERSDEMO. If you dont, you will get error when running the LISP program. You can use AIA Monochrome.ctb as your plot style. How to load and run the AutoLISP program You will download a zip file. 1. You need to extract it first. In Windows explorer, you can select the zip file, right click then select extract all from contextual menu. Save the files in your LISP folder. 2. After you extracted the file, you can load the AutoLISP programs. 3. After you load them, you can run the AIA layers tools by typing the commands. If you use AutoCAD 2012 or later, AutoComplete should help you. 4. It might take a while until all the layers are created.
If you are planning to adopt AIA standard layers, now you have a good tool to start using it!