Autolisp For Absolute Beginners Your First Autolisp Program: Zoom To Origin
Autolisp For Absolute Beginners Your First Autolisp Program: Zoom To Origin
Let us learn AutoLISP in plain English. You will be guided slowly to create your own AutoLISP program
AutoLISP has been a popular customization for AutoCAD. Many people use it to extend AutoCAD
capabilities, do things that vanilla AutoCAD can’t. AutoLISP can also be useful to automate several
process that usually need you use several tools, but with AutoLISP you may only need a few clicks.
I’m not good with AutoLISP, but if you are interested to learn it with we, you can keep reading this
tutorial. If you are an AutoLISP guru, I will be happy if you correct any mistakes or if you suggest
better solution. So let us start to learn slowly, by creating simple program. You can also refer to
AfraLISP for more AutoLISP tutorial. It’s an excellent resource!
Let us use visual lisp editor instead of notepad. You can access visual lisp editor from manage tab,
applications panel.
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.
Click new or access file>new to create a new AutoLISP program.
AutoLISP Structure
Before we start, let us see the common program structure below.
(defun c:YourProgramCommand ()
WhateverYouWantAutoCADtoDo
(princ)
It means that we are defining ZO as a command. AutoCAD will run your program when you type ZO
then enter at command line.
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
The red fonts are the command we input during the zoom process. This is what we do manually:
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 what’s 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 move to AutoCAD window, and try to type ZO then [enter]. Does it work?
We will modify this program further. So save it and don’t loose it.
Using AutoLISP Variable and Asking User
Input
November 24, 2010 By Edwin Prakoso 0 Comments and 0 Reactions
We have started the AutoLISP tutorial by creating a very simple program: zoom to origin. That
program works, but it is very limited to zoom to 0,0,0 coordinate only. We will add more
functionalities so users can pick other point to zoom to. Because we will enable users to pick their
own point, zoom to origin may not appropriate name anymore. So I changed the name to Zoom to
Point (ZP). Remember to type ZP then [enter] to run it after this.
Using Variables
In programming, we use variables to save our values. In our previous sample, we haven’t use it.
Let’s say we save the coordinate to ZPT (zoom point) and save the magnification to MRAT
(magnification ratio), then our program will be like this.
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.
(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?
It works, doesn’t it? But there is one thing left. We both know that the program want us to click a
point, but there is no instruction what should we do. If we give the program to other people, they
will be confused! So let’s fix the code.
It means that AutoCAD remember the value and use your computer resource. It probably doesn’t
matter because we only have one AutoLISP program running and only has 2 variables. But when you
already have dozens of AutoLISP program running with many variables, it may affect your machine’s
performance. You may want to leave the value as global variable if you do want to use it in other
program. But if you are not, it is a good idea to set it as a local variable.
Close your drawing, and create or open a new drawing. Type ZP then [enter] to test if your program
hasn’t loaded yet. It should say: Unknown command “ZP”. Press F1 for help. If it’s not, close
AutoCAD and open it again. Do not load your program for now.
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
I have posted an AutoCAD tip how you can create your own label coordinate in AutoCAD using block
attributes. It is nice that you can create your own block, create your own block shapes, and
customize it to look anything you want to.
But there is a limitation. It will only recognize the point position from global coordinate. If you move
the UCS, it will still use global coordinate. It makes sense, because if we want to label our coordinate,
then usually we do use global coordinate. But what if you want to label the coordinate from UCS?
Because I’m currently learning AutoLISP, then I decided to take it as a challenge to create a program
to do that. You can download the file in link you’ll find below this post.
If you are following AutoLISP tutorial in CAD Notes, be patience! We will get there. Here is the code.
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 doesn’t work fine, you may want to try his
code too. Thank you to Shawki!
Labeling Coordinate with Easting and
Northing in AutoCAD
November 26, 2010 By Edwin Prakoso 8 Comments and 0 Reactions
After I provided AutoLISP program to label coordinate automatically, I had some questions if it can
show N, E, and elevation instead of just the coordinate text. So I made minor adjustment to the
code.
This automatic labeling will create three lines of texts instead of just one line of xyz coordinate.
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 you are having fun with our AutoLISP exercises. Last time, we were introduced to use
AutoLISP variables and asking users for input. This time we will learn about asking for more user
input, then using the input in mathematical equation. The calculation result will be used to draw an
object.
Our challenge now is to create a program that can draw a regular polygon by defining number of
sides and the area. Interesting isn’t it?
(+ 2 5)
Let us try it in AutoCAD command line. Type in AutoCAD the line above. Yes you can use AutoLISP
command in AutoCAD. You need to type it exactly like above.
Now let’s try another one. Type each line then press [enter].
(setq a 2)
(setq b 5)
(+ a b)
(setq c (+ a b)
Not so difficult, isn’t it? Refer to other calculation function in AfraLISP site. Now let us see the
polygon formula.
Drawing Polygon Method
How can we draw polygon by defining the area? I did some searches and find this formula.
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.
The bad news is AutoLISP doesn’t have tan function. But there is work around. Tangen is sin/cos. Tan
(pi/N) can be written as:
Besides the sequence, you should be familiar with the command. If you want to try writing the
equation by yourself, go ahead. It can be a good exercise to get familiar with mathematical function
in AutoLISP. You can find the equation below later.
The complete equation can be written. I use variable a for area and n for number of sides. I also use
apt to keep the equation value (the apothem length), and ang to keep (pi/n).
1. Number of sides is an integer. You don’t accept 2.5 as number of sides, don’t you? We can
use GETINT to ask for integer.
2. Area can have decimal numbers, so it is a real number. We can use GETREAL for this
purpose.
3. You already use GETPOINT to ask for a point right?
(GETINT)
type integer number. It should return the number you entered. Try again. This time type a decimal
number.Let’s say 3.2. What will AutoCAD say?
Command: (getint)
3.2
Requires an integer value.
Using the right user input function will also reduce probability of errors.
Now we have complete data, what we will put in our program. I strongly suggest you to try writing
the program first. You can check and compare the code later.
Below is the complete code I created. If you have problem, you can copy the code below.
; This LISP will create regular polygon by defining polygon area and number of sides
; Created by Edwin Prakoso
; Website: http://cad-notes.com
(defun c:pba (/ a n apt ptloc)
(setq n (getint "
Number of Polygon Sides: "))
(setq a (getreal "
Expected Polygon Area: "))
(setq ang (/ pi n))
(setq apt (sqrt (/ (/ a (/ (sin ang) (cos ang))) n))) ;calculating apothem for circumscribed polygon
(setq ptloc (getpoint "
Pick Location: "))
(command "_POLYGON" n ptloc "C" apt)
)
AutoLISP exercise: creating program to label
coordinate
December 6, 2010 By Edwin Prakoso 4 Comments and 0 Reactions
In this exercise, we will continue our AutoLISP tutorial. This time we are going to use lists and strings.
We have learned how to use mathematic equation in AutoLISP to calculate a value. This time we will
work with strings.
Let us see what are we going to create. We are going to create a program to place coordinate label
for a point automatically. See the program and try it first if you want.
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.
What if you don’t want to use leader, but would like to use Multileader? Simple, use this line:
Try to use it first if you want to know how mleader works, pay attention on each step what you
should do.
The program can be used, but the result is not good enough. We can’t control the text appearance,
the label will be shown similar like below.
Now after you run it once, type !p to see the p value. It should return something like this:
The value is a list. To get the x, y, and z value we can use car, cadr, and caddr.
car will pick the first value from the list. So to get x value, we can do this:
(car p)
cadr will get the second value from the list, caddr will get the third value from the list. To separate all
the values, we can write lines as below:
When we work on 2D drawings, we don’t need to use z value, so you can delete the last line. Unless
you work in 3D.
Now x and y are strings. We can add more texts to those strings. In calculating real or integer, we can
use mathematic function like + or –. But in strings, we use strcat to add more text to the variable.
x = 100, y = 50
I can create it by combining x and y like this:
Don’t 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.
(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:
To do this, we can add a loop with (while). So the complete program will be like this.
(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
)
We will cover more about loop, but now this will do. Now try it.
I’m amazed how many thing I can do with a basic knowledge of AutoLISP, and I believe many more
things can be done. I would like to know what program have you made until this point? Please share
with us!
AutoLISP Exercise: Using Block and
Conditional If
December 13, 2010 By Edwin Prakoso
This time we are going to work with AutoCAD block. We had a good time when creating label for
coordinate. Now we are going to create a similar AutoLISP program. We will create a program to
label elevation. But this time we will also use block. Using block has several advantages. We can have
more geometries without having to draw them and also can place the text to block attributes.
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.
Insert block will insert a block with the name we defined in our AutoLISP program. If it can’t 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.
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 it’s at 0 elevation. In my country, many people like to
use+ 0.00 when it’s at zero elevation. We will add an if conditional to change the value.
So now we will add one more variable. This time we will let the variable become global variable. So
AutoCAD will still recognize the variable after the application ends. And we can use it for other LISP
application.
Because we don’t want the program to ask user for scale every time they use it, then we will use
conditional IF.
The structure of conditional IF is
(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)
)
I added one more function at the bottom so users can change the scale anytime. Remember, we only
ask for scale one time, when the global scale is NIL. So we need to provide them a way to change the
scale manually later.
Change Text in Zero Elevation
As I mentioned before, we here would like to have + 0.00 than just 0 at zero level. This is simple. Just
like before, we use conditional IF.
Instead of using
We use
The code will check if Y value is zero, and replace it with + 0.00. If it’s not, it will use the original
value.
Final Code
After we added those features, then this is the complete code:
This program works nice. But the problem is the label can’t be updated automatically. Not like using
fields. We will cover how to update the value later when we cover entity selection.
AutoLISP tutorial: system variable and
conditional COND
January 24, 2011 By Edwin Prakoso 0 Comments and 0 Reactions
In the last AutoLISP tutorial, we have tried to place block and change the attribute value. We also
use conditional IF. Using AutoCAD block in AutoLISP is a great benefit. We can use our reusable
content to make AutLISP programming less complex, and we can maintain our drawing standard in
AutoCAD. This time we will try to use another conditional, using COND. We will also touch AutoCAD
system variables, one of the most important thing in AutoLISP.
The program we will make in this AutoLISP tutorial will draw grid line, and automatically place
label at the end of line.
Before you start, you need to download this file first. The zip file has 4 AutoCAD DWG files, each file
is a grid label for each direction. We will use conditional COND to choose which AutoCAD block we
should use. This AutoLISP tutorial requires you to understand what we did previously. So if you
haven’t read it or want to refresh your memory, read the AutoLISP tutorial so far above. Or if you
completely new to AutoLISP, follow this tutorial from beginning.
(cond
((condition a) (things to do when condition a is met)
((condition b) (things to do when condition b is met)
((condition c) (things to do when condition c is met)
and so on…
)
(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:
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 don’t have to define it because we already set it as
default block name.
We need to save the current ortho mode first to a temporary variable. We can get the system
variable and save it to user variable in AutoLISP using GETVAR.
The first line will get the system variable and save it to variable CurrentOrthomode. OK, if you feel
the variable name is ridiculously long, you can choose your own name :)
After our AutoLISP program ends, we can restore the system variable to the original value.
1. It will check the drawing scale. Refer to previous tutorial to see how it works.
2. It will save the current orthomode and change orthomode to 1.
3. It will ask user to place two points for the grid.
4. It will check which it should use.
5. It will draw grid line and insert the block.
6. It will restore the orthomode.
We created an AutoLISP program to create leader to label coordinate before. It will be very useful
for surveyors who use vanilla AutoCAD. But you may want to use multileader instead of leader in
your AutoLISP program. MLEADER is neat, and you can have more control and flexibility with it.
The problem is it uses multiline text, not single line text in leader. When working with multiline text,
we press [enter] when we want to add another text line. But using “” in AutoLISP to simulate
pressing enter, it will not work. When we use “” AutoCAD thinks we want to end the command. But
not adding new line.
I posted a reply in the comment section, but just in case you miss it I write it as a post. To solve this,
we need to use ANSI character to add a new line. chr 10 will add new line (or line feed) to our
variable.
I don’t know if there is other solution for this. If you know the other way, please share it here!
AutoLISP tutorial: Working with layers
April 21, 2011 By Edwin Prakoso
An AutoLISP program doesn’t have to be difficult. We can create simple LISP program and get many
benefits from it. It’s not just about speed up the drawing creation, but also to maintain our standard.
In system variable and COND conditional, we discussed how we can use block to create grids. This
will ensure the users (or you) to use the same block for every drawing. Now let’s see how to control
the other properties you need to control: layers and styles. Let’s explore the possibility to use it to
control our drawing standard.
Layers are the most important thing to manage our drawings. If you’re not familiar with layer
standard, CADD manager has a short article about the concept.
(defun c:cntext ()
(setq oldlayer (getvar "CLAYER")) ; get current layer
(setvar "CLAYER" "A-Anno") ; change layer to annotation layer
(setq textcontent (getstring "
Type Text: "))
(setq textloc (getpoint "
Text Position: "))
(command "_TEXT" textloc "" "" textcontent) ;create the text
(setvar "CLAYER" oldlayer) ;restore active layer
)
We need to check if the layer exist or not first. We can do it by using this code:
(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.
Let’s 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 doesn’t exist, then it
will give a warning.
There are several possibilities to handle this situation. We will see in the next tutorial, other
alternatives to deal with non-exist layers.
Creating layer and styles with AutoLISP
May 27, 2011 By Edwin Prakoso
We learned how we can work with layers when we create objects in our AutoLISP program. By
changing current layer or style in the program, it will make sure our objects to use specific
properties. For example, we want when we place the grid label, we place it on annotation layer. This
is a good way to be implemented with your company standard.
But what we did before is simply change it. If it doesn’t find it in name list, it simply gives a warning.
Ask the user to create it first. That’s not cool.
The more logical thing to do is, when it doesn’t find it, it creates a new one.
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 we’re going to use in AutoLISP.
-Layer is the command.
M will create new one, it will ask you for it’s name and then make it current.
This command will keep asking you to enter an option. So we press [enter] to end the
command.
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 don’t have to add code to check if it already exist.
(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
)
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)
)
Working with text styles and dimension
styles
So what about text styles and dimension styles?
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.
Let’s 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 it’s 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.
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.
(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
)
Next, we will cover how we can change the properties of layers and dimenion styles. So we can
create it with red color, specific linetype, lineweight, etc.
Modifying objects: working with selection
June 22, 2011 By Edwin Prakoso
We covered several topics on how we can draw more efficiently using AutoLISP. Now it’s time to
move on. We are going to learn how we can modify existing objects in our drawing.
The most important thing about editing objects is to select them. As we know, After we activate an
AutoCAD modification command (like move, copy, etc) AutoCAD will ask us to select object.
(defun c:mleft ()
(setq sel1 (ssget))
(command "move" sel1 "" "0,0,0" "-5,0,0")
)
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 don’t add it, AutoCAD will continue to ask
you to select object.
Sample 2: Reset properties to ByLayer
One thing that can annoy us when trying to apply CAD standard, is having the objects’ properties
overridden. Set to other than ByLayer.
You can change object properties by using CHPROP. Then you can choose which properties you want
to set to ByLayer. Try to use CHROP to understand what we’re doing below.
(defun c:rst ()
(setq sel1 (ssget))
(command "CHPROP" sel1 ""
"COLOR" "BYLAYER"
"LWEIGHT" "BYLAYER"
"LTYPE" "BYLAYER"
"")
)
Using the code above will let users to use AutoCAD default mode.
You can use these code to select object from within the program:
That code will select all objects inside rectangular window from 0,0 to 10,10.
setq sel1 (ssget "c" '(0 0) '(10 10)) to select object inside and touching rectangular window (crossing
polygon).
If you’re not familiar with the selection mode above, read using AutoCAD selection below.
For window and crossing polygon selection, we can also ask for user’s input.
For example:
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.
Filter selection with selection set
July 26, 2011 By Edwin Prakoso
This time we will extend the object selection by using selection filter. Using filter in AutoLISP is very
similar with using AutoCAD filter.
We can define which kind of object we want to select. We can define objects with specific properties
to select.
For example, we can create a program to run and select dimensions in drawing, and move it to
annotation layer. We will create this program in this tutorial.
This kind of program probably very simple, but can help you to maintain drawing standard.
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.
More about selection filter
Afralisp covers this material in more advanced topic. I won’t cover it further here, because they have
detailed explanation about it. Go ahead, read more about conditional operators of selection filter
there.
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 covered several basic AutoLISP tutorial already. You should be able to use the programs. Now it’s
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.
In CADTutor forum, you’ll find mostly the program is given to you written in code. You need to copy
the code to your clipboard (by selecting them and pressing ctrl + c).
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.
In load/unload applications dialog, browse and find your AutoLISP file you saved before. Select it and
click load.
Automatically load AutoLISP program when
AutoCAD start
If you use your LISP program repeatedly, then you will want AutoCAD automatically load it every
time it starts. So you don’t have to load it in every new AutoCAD session. To load it automatically,
add the LISP program to startup suite.
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 don’t want a LISP
program to load automatically anymore, you know where to remove it now, right?
Using AutoLISP program
So how you can use the program?
Again, if you copy it from internet, you can see on top of the program like this.
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.
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 you’ve 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?
How to load AutoLISP program
October 14, 2011 By Edwin Prakoso
Do you want to load an AutoLISP program? Here is a basic guide how to do it.
To load application
If you have an AutoLISP program, you can load it by using load application in manage tab.
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.
In opened dialog box, click application you want to remove then click remove.
Drag and drop thing to add application is cool. If you notice the add button here, yes, it’s 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
don’t know much about customization like me. There are more methods like described in AfraLISP.
Automatically execute command when
open/create new file
October 25, 2011 By Edwin Prakoso 0
Last week we covered about loading AutoLISP file. You learned how to load, and optionally put your
LISP to startup suite. Startup suite will load LISP automatically every time you start AutoCAD.
In this post, you will learn how to load AutoLISP program using acaddoc.lsp.
We also had another post about excel datalink. The problem with datalink is, it’s not updated
automatically. We have to update it manually. It means we may send or plot files that use old value.
In this post, you will also learn how to make AutoCAD automatically update datalink when we save
or plot our files. We will define our own plot and save command.
AutoCAD is normally not supplied with the user-defined startup file acaddoc.lsp; you create
(Notepad can be used) and maintain the file yourself.
The acaddoc.lsp file is intended to be associated with each document (or drawing) initialization. This
file is useful if you want to load a library of AutoLISP routines to be available every time you start a
new drawing (or open an existing drawing).
Each time a drawing opens, AutoCAD searches the library path for an acaddoc.lsp file. If it finds one,
it loads the file into memory. The acaddoc.lsp file is always loaded with each drawing regardless of
the settings for the ACADLSPASDOC and LISPINIT system variables.
Most users will have a single acaddoc.lsp file for all document-based AutoLISP routines. AutoCAD
searches for an acaddoc.lsp file in the order defined by the library path; therefore, with this feature,
you can have a different acaddoc.lsp file in each drawing directory, which would load specific
AutoLISP routines for certain types of drawings or jobs.
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")
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.
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.
(LOAD "MYLISP")
Command: plot
Unknown command “PLOT”. Press F1 for help.
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]
Defining function in acaddoc.lsp
Now let’s work with acaddoc.lsp. First we undefine PLOT, then define new command. The new plot
command should update datalink before start to plot.
We use INITDIA to load AutoCAD plot dialog. If we don’t 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, isn’t it?
Regenerating model.
Update datalink when saving file
Now we don’t have to worry when we plot files. It surely will use most updated value from excel
files. But we haven’t finished. We need to make sure datalinks in our files are updated before we
send them. We need to modify save and saveas command.
It’s very similar with plot. You can modify them as your exercise. Discuss it here if you have problem.
And what command you want to modify? What do you want it to do? Share it here, the others might
find it useful too!
Set default system variables in acaddoc.lsp
January 24, 2012 By Edwin Prakoso
In this article, we are going to focus to the last one. I found that there are many users confused why
their AutoCAD doesn’t work as usual. And they become regular questions. These are some samples
of changed system variables.
(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 you’ve 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 don’t, you will get error
when running the LISP program.