0% found this document useful (0 votes)
269 views62 pages

Autolisp For Absolute Beginners Your First Autolisp Program: Zoom To Origin

This document provides instructions for creating a simple AutoLISP program in AutoCAD that allows users to zoom to a specified point. It begins by explaining the basic structure of an AutoLISP program and then walks through creating a program called "ZP" that prompts the user to pick a point and zoom extent. It introduces concepts like defining functions, using variables to store values like the picked point coordinate, and adding comments to document the code. The full coded example is provided with comments explaining each section.

Uploaded by

nirmal suthar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
269 views62 pages

Autolisp For Absolute Beginners Your First Autolisp Program: Zoom To Origin

This document provides instructions for creating a simple AutoLISP program in AutoCAD that allows users to zoom to a specified point. It begins by explaining the basic structure of an AutoLISP program and then walks through creating a program called "ZP" that prompts the user to pick a point and zoom extent. It introduces concepts like defining functions, using variables to store values like the picked point coordinate, and adding comments to document the code. The full coded example is provided with comments explaining each section.

Uploaded by

nirmal suthar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

AutoLISP for Absolute Beginners

Let us learn AutoLISP in plain English. You will be guided slowly to create your own AutoLISP program

Your First AutoLISP Program: Zoom to Origin


November 17, 2010 By Edwin Prakoso 2 Comments and 0 Reactions

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!

Creating AutoLISP Application


An AutoLISP program can be created in notepad. It is a plain text, you only have to save it with file
extension .lsp. However, AutoCAD itself has provided a Visual LISP editor. There are many
functionalities you can use here, more useful than notepad.

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)

Define a Function (defun ())


AutoLISP will start with (defun c:ProgramCommand ()). Defun stands for define for a function. If you
find this:

(defun c:ZO ())

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.

Your First AutoLISP Program: Zoom to Origin


We are going to create our very first program. This program will zoom to the drawing origin, no
matter which part of drawing we currently see. AutoCAD tool that can do this is zoom to center.
Examine what we do when we use the command.

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. First, we type _zoom to activate the zoom tool.


2. Then AutoCAD will ask us which method you want to use. We type _c to use zoom center.
3. Then AutoCAD will ask us the center point. Because we want to zoom to origin, we type 0,0.
4. 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 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 save this program.


Load and Run Your Program
In visual LISP editor, click load active edit window.

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 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.

Visual LISP Editor


Again, you basically can use notepad, or notepad ++ to create AutoLISP program. However, Visual
LISP editor can be very handy to find errors when our application become more complex. If you want
to learn more about it, you can read visual lisp tutorial on AfraLISP, which is very good. I will not
cover about it, at least now, and focus more on how you can write the routines.

Using Variables
In programming, we use variables to save our values. In our previous sample, we haven’t use it.

(command "_ZOOM" "_C" "0,0" "2000")

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.

(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 let’s 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?

Asking for User Input


Now we are going to ask the user to define their point. Change the 0,0 coordinate to this code:

(setq ZPT (getpoint))

Now load the application again, then try to activate it again.

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.

(setq ZPT (getpoint "


Pick a point or type coordinate: ")

Load and try again. Nice… isn’t it?

Defining Local Variables


Let us move to AutoCAD. In AutoCAD command line, type !ZPT. The exclamation mark in front of the
variable name will show you  the variable value. If you haven’t run the program, it should mention
nil. Or it doesn’t have a value. If you have run it before, it will show the last coordinate you picked.

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.

Open Visual LISP editor. In defun line, modify it to this.

(defun c:ZP (/ ZPT MRAT)


Now load your program. After you run it, type !ZPT or !MRAT to see the variable value. Now they
should say nil. Now AutoCAD doesn’t 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)
)
Using AutoLISP Program to label point
coordinate
November 25, 2010 By Edwin Prakoso 8 Comments and 0 Reactions

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.

How to use the program?


1. Download the LISP file
2. Load the LISP program. There are several ways to load AutoLISP program, but this is the
easiest way. Thanks Ellen!
3. I wrote the code to run when I type LB then [enter]. You should be able to use it after you
load the program.
4. You need to click twice: the point you want to label and label location.
5. It will use leader command. So if it’s too large, too small, or you want to customize it, change
your style.
6. It is also use file UNITS settings. If you want to change the format to decimal or architecture
format, change it in UNITS settings.
7. The program will continue to ask you for points until you press [esc] or [enter]. I decide to
make it this way because mostly we want to create several labels at once. So you don’t need
to reactivate it after you have labeled one point.

If you are following AutoLISP tutorial in CAD Notes, be patience! We will get there. Here is the code.

; Automatic coordinate labeling


; Edwin Prakoso
; http://cad-notes.com
;
; Limitation
; ----------
; Will use current leader style and current units setting
(defun c:lb (/ p x y 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)))
(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 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 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.
AutoLISP Exercise : Create Regular Polygon
by Defining Area
December 1, 2010 By Edwin Prakoso 3 Comments and 0 Reactions

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?

Writing Calculation in AutoLISP


Writing calculation in AutoLISP is quite different. But should not be difficult to understand.
If we want to calculate 2+5, then we write:

(+ 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)

What we did is set variable a value to 2, b to 5, then calculate a+b.

(setq c  (+ a b)

This one means 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.

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.

Calculating Apothem Length


We need to change the formula to get the apothem like below:
Functions in Our Formula
We will use these function in our formula.
1. square root can be written as (sqrt a),
2. multiplication as (* a b),
3. division as (/ a b),
4. cosine of an angle as (cos ang),
5. sine of an angle as (sin ang).

With a, b, and ang are variables.

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:

(setq ang (/ pi N))


(/ (sin ang) (cos ang))

Pi is built in variable, so we will just use it.

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).

(setq ang (/ pi n))


(setq apt (sqrt (/ (/ a (/ (sin ang) (cos ang))) n)))

Or you can write in a single line, which looks more confusing.

(setq apt (sqrt (/ (/ a (/ (sin(/ pi n)) (cos(/ pi n)))) n)))

Asking For User Input


We already use getpoint to ask user to pick a point. Or they can type the coordinate. Now we need
three user input: number of sides, area, and center point.

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?

Let us try. In AutoCAD command line, type

(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.

Writing the Complete Code


Now we can write the complete code.
1. You need to ask the user the number of polygon sides, the expected polygon area.
2. Then you calculate the value.
3. You need to ask one more input: the polygon center.
4. Finally you can write the polygon command.

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.

After you load it, type cnlabel to activate the tool.


Using Leader tool
Let’s see how the leader tool works.
1. After we activate leader tool, we need to place first point. The first point will be the point we
label.
2. Then it will ask next point. We are going to use text location (textloc variable) as second
point.
3. It will ask for another point for the leader. If we only want one segment, we can press
[enter]. To simulate [enter] in AutoLISP, we simply use “”.
4. Next, we type the text. In AutoLISP program we can use point coordinate we get from user.
5. Leader will ask for another input for the next line. We don’t want to add next line. To finish
it, we can press [enter]. Again, we simulate it using “”.

This line below will do what is described above.

(command "_leader" p textloc "" p "")

What if you don’t want to use leader, but would like to use Multileader? Simple, use this line:

(command "_mleader" p textloc p)

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.

See how many decimal numbers it has?


Getting Value from The List
Let us try the AutoLISP program. We haven’t define p and textloc as local variables, so the value
should be still stored even after we run the program.

Now after you run it once, type !p to see the p value. It should return something like this:

(268.782 34.178 0.0)

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)

To save the value to x, we continue the line like this.

(setq x (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:

(setq x (car p))

(setq y (cadr p))

(setq z (caddr p))

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.

Converting Real to String


We already get the x and y value, but they are still in real number. If we want to add more text, like
x=…, y=… then we need to convert them to string. We can convert them to string using rtos function.
Let us add it to our code.

(setq x (rtos (car p)))

(setq y (rtos (cadr p)))

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.

Let say I want it to look like this:

x = 100, y = 50
I can create it by combining x and y like this:

(setq ptcoord (strcat “x= ” x “; ” “y= “ y))

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.

Now let’s 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)
)

Tips: Seeing Dynamic Lines from Previous


Point
One annoying thing about this program is we can’t see dynamic line when we place the second
point. Just like when we place a leader or even a simple line.

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.


More Tips: Adding a Loop to Keep the
Program Active
When we use line tool, the tool will be still active until we press [esc] or [enter]. Some other tools
also have the same behavior. The idea is we can keep using it and don’t have to reactivate it when
we still want to use it. Because when labeling coordinate we usually need to label several points, we
can make this program to behave the same.

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.

Before We Start: Preparing the Block File


Before we start, you need to download this AutoCAD file. This is the block we are going to use as
elevation label.

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.

Command We will Use


Easy enough to guess: we are going to use INSERT to insert our block. If you try to type INSERT then
[enter] in AutoCAD, it will open insert dialog box. That will not work with our AutoLISP program.
AutoLISP will only work if we give input in command line or without dialog box.
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 I’m 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 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.

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 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.

Add Ability to Change Scale


If you examine the block, you will soon know that it was created in full scale 1:1. When you need to
place it to a drawing with 1:100 scale, then you need to scale it after placing it. We don’t want that,
don’t we?

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)
)

The code in plain English


1. The first conditional will check if the globalscale is not set (the value is NIL). If it’s true it will
ask the user for input.
2. The second conditional will check if the user don’t give any input and simply press [enter].
Because the user don’t provide value, then the scale still NIL.We assume that they want to
use default scale 1:1. That’s why we provide 1/1 in the bracket. We tell user that if they
don’t give any value, it will use full scale. This is common in AutoCAD tools to offer user to
use default value.

Now the program become like this:

(defun c:cnannolevel (/ labelposition y)


(if (= cnglobalscale nil)
(setq cnglobalscale (getreal "
Set Global Scale for CN Annotation <1/1>: "))
)
(if (= cnglobalscale nil)
(setq cnglobalscale 1)
)
(setq labelposition (getpoint "
Pick Label Position: "))
(setq y (cadr labelposition))
(setq y (rtos y))
(command "_-insert" "annolevel" labelposition cnglobalscale cnglobalscale 0 y)
)
(defun c:cnannoscale ()
(setq cnglobalscale (getreal "
Set Global Scale for CN Annotation: "))
)

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

(setq y (rtos y))

We use

(if (= y 0) (setq y "%%p 0.00") (setq y (rtos y)))

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:

; 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 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.

Using Conditional COND


COND is a bit different with IF. When using IF, you can tell AutoCAD to do A when condition is met.
Or else, do B. COND will only do things when the condition is met.

The basic of using COND is:

(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…
)

Let’s 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 don’t have to define it because we already set it as
default block name.

Changing AutoCAD system variable


Another thing we need to do is change an AutoCAD system variable temporarily. We can do it in
AutoLISP using SETVAR. We want to create the grid horizontal or vertical. To achieve that, we need
to draw line with ortho mode is on.

This behavior is controlled by system variable ORTHOMODE. We need to change it to 1 to make


ortho mode active. But before we change it, it is a good thing to restore the system variable after the
program ends. We don’t want the program to change our AutoCAD behavior and we need to change
option every time we use the program.

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.

(setq CurrentOrthomode (getvar "orthomode"))


(setvar "orthomode" 1)

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 :)

The second line, we set ORTHOMODE system variable to 1.

After our AutoLISP program ends, we can restore the system variable to the original value.

(setvar "orthomode" CurrentOrthomode)


The complete AutoLISP program
Now we have everything we need. The AutoLISP program will run like this:

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.

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 don’t set error trapping in an AutoLISP program!
Adding New Line in Multiline text
March 11, 2011 By Edwin Prakoso 

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.

Let’s take an example. We add that character to our string variable:

(setq ptcoordN (strcat "N=" y))


(setq ptcoordE (strcat "E=" x))
(setq ptcoordN (strcat ptcoordN (chr 10) ptcoordE))
The first and second line will get x and y value, then add prefix. The 3rd line will combine them both.
That AutoLISP code will combine N coordinate, new line, then place E coordinate there.
The complete AutoLISP code will be:
(defun c:cnlabel (/ p x y ptcoordN ptcoordE textloc oldprec)
(setq oldprec (getvar "LUPREC"))
(setvar "LUPREC" 4)
(while ; start while loop
(setq p (getpoint "
Pick Point to Label:")) ; asking user to click point to label and save it
(setq textloc (getpoint p "
Pick Text Location:")) ;asking user to click text location
(setq x (rtos (car p)))
(setq y (rtos (cadr p)))
(setq ptcoordN (strcat "N=" y))
(setq ptcoordE (strcat "E=" x))
(setq ptcoordN (strcat ptcoordN (chr 10) ptcoordE))
(command "mleader" p textloc ptcoordN) ;ativate label command and use the input
(setvar "LUPREC" oldprec)
(princ)
)
)

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.

Working with layers

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.

Changing the current layer


We can change the current layer using setvar. We did it this previously. Current layer variable is
controlled by CLAYER.

(setvar "CLAYER" "LAYERNAME")


Sample: creating text
Now let’s try an example. We want to create a LISP program to create text, and use a default layer.
This is what we do:

1. Get current layer and save it to a variable.


2. Set current layer to a different layer. In this sample, annotation layer.
3. We ask for required data for creating text. In this sample we ask for text content and
position. You may want to consider ask for height and rotation angle. But it’s not necessary
in this sample.
4. Set the current layer to previous layer.

This is the code after we put it all together:

(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
)

Check for existing layer


It should works. But we still have a problem. What if the layer doesn’t exist? AutoCAD returns error
warning.

; error: AutoCAD variable setting rejected: “clayer” “layername”

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.
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.

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.
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.

Creating a new layer


Creating new one is easy. We use LAYER command.
Type –layer on command prompt. You will see the list of available options. Remember, you can
check the command we can use at command line first. Use – (dash) to load the command without
dialog box. That’s how we use it with AutoLISP.

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.

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 don’t 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)
)
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.

There are 7 options AutoCAD will ask you.

Let’s see this sample. You can use this line to create text styles

(command "-style" "newstyle" "arial" "" "" "" "" "")

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.

(command "-style" "newstyle" "arial" 2.5 0.85 0 "N" "N")

* 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 doesn’t 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
)

Changing the properties


You already know how to create a text style and set it’s properties, because they’re asked when you
create a new one.

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.

Saving selection to a variable


The function that allow us to do this is SSGET.

Sample 1: Move to left


This sample program will allow you to select object and move them 5 unit to left.

(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 other selection mode


Sometimes we need to select objects without asking users to give input. Or limit the method for user
to use.

Using the code above will let users to use AutoCAD default mode.

You can use these code to select object from within the program:

(setq sel1 (ssget "w" '(0 0) '(10 10)))

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 object’s created.

setq sel1 (ssget "p")) to select objects in previous selection.

setq sel1 (ssget "x")) all objects in the drawing.

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:

(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.
Filter selection with selection set
July 26, 2011 By Edwin Prakoso

In the last tutorial, we learned how to use object selection in AutoLISP.

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.

As we did before, we can select all object using this line.

(setq sel1 (ssget "x"))

The Object filter


Now we want to select all dimensions in our drawing. To filter the selection, we can use this code:

(setq sel1 (ssget "x" '((0 . "DIMENSION"))))

The complete code become:

(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.
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 use DXF codes with selection filters in AutoLISP.

See the complete dxf associative code below

DXF Group Codes


The following table gives the group code or group code range accompanied by an explanation of the
group code value. In the table, "fixed" indicates that this group code always has the same purpose.
The purpose of group codes that aren't fixed can vary depending on the context.

Entity group codes by number :

Group Code Description


-5 APP: persistent reactor chain
-4 APP: conditional operator (used only with ssget)
-3 APP: extended data (XDATA) sentinel (fixed)
-2 APP: entity name reference (fixed)
-1 APP: entity name. This changes each time a drawing is opened. It is never saved.
(fixed)
0 Text string indicating the entity type (fixed)
1 Primary text value for an entity
2 Name (attribute tag, block name, and so on)
3-4 Other textual or name values
5 Entity handle. Text string of up to 16 hexadecimal digits (fixed)
6 Linetype name (fixed)
7 Text style name (fixed)
8 Layer name (fixed)
9 DXF: variable name identifier (used only in HEADER section of the DXF file).
10 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 31-
11-18
38)
APP: 3D point (list of three reals)
20, 30 DXF: Y and Z values of the primary point
21-28, 31-
DXF: Y and Z values of other points
37
38 DXF: entity's elevation if nonzero. Exists only in output from versions prior to
AutoCAD Release 11.
39 Entity's thickness if nonzero (fixed)
40-48 Floating-point values (text height, scale factors, and so on)
48 Linetype scale. Floating-point scalar value. Default value is defined for all entity types.
49 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
50-58
applications).
60 Entity visibility. Integer value. Absence or 0 indicates visibility; 1 indicates invisibility.
62 Color number (fixed)
66 "Entities follow" flag (fixed)
67 Space--that is, model or paper space (fixed)
68 APP: identifies whether viewport is on but fully off screen; is not active or is off.
69 APP: viewport identification number.
70-78 Integer values, such as repeat counts, flag bits, or modes
90-99 32-bit integer values
100 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
102 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.
105 DIMVAR symbol table entry object handle
Extrusion direction (fixed).
210 DXF: X value of extrusion direction
APP: 3D extrusion direction vector
220, 230 DXF: Y and Z values of the extrusion direction
280-289 8-bit integer values
300-309 Arbitrary text strings
Arbitrary binary chunks with same representation and limits as 1004 group codes:
310-319
hexadecimal strings of up to 254 characters represent data chunks of up to 127 bytes.
320-329 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
330-339
drawing. Translated during INSERT and XREF operations.
340-349 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
350-359
file or drawing. Translated during INSERT and XREF operations.
360-369 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
999
and ignores the comments. You can use the 999 group to include comments in a DXF
file that you've edited.
1000 ASCII string (up to 255 bytes long) in extended data.
1001 Registered application name (ASCII string up to 31 bytes long) for extended data.
1002 Extended data control string ("{"or "}").
1003 Extended data layer name.
1004 Chunk of bytes (up to 127 bytes long) in extended data.
1005 Entity handle in extended data. Text string of up to 16 hexadecimal digits
1010 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
1011 DXF: X value (followed by 1021 and 1031 groups)
APP: 3D point
1012 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.
1013 DXF: X value (followed by 1022 and 1032 groups)
APP: 3D vector
1020, 1030 DXF: Y and Z values of a point
1021, 1031 DXF: Y and Z values of a World space position
1022, 1032 DXF: Y and Z values of a World space displacement
1023, 1033 DXF: Y and Z values of a World space direction
1040 Extended data floating-point value.
1041 Extended data distance value.
1042 Extended data scale factor.
1070 Extended data 16-bit signed integer.
1071 Extended data 32-bit signed long.
Saving, using and managing your AutoLISP
program
August 5, 2011 By Edwin Prakoso 

Andres Rodriguez – Fotolia.com

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.

Saving an AutoLISP program


You may find people giving you LISP program written in code like this.

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).

(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 don’t 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.

Loading AutoLISP Program


Now you have your LISP program. Before you can use it, you need to load it to AutoCAD. Go to
AutoCAD ribbon> manage tab> applications panel. Click load application.

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.
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 cool way to do it is by dragging the file 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.

Placing AutoLISP in AutoCAD Interface


If you’re a command line freaks, then you can stop here. However, not all of us like using command
line. You may want to have it on your ribbon (well uh, or toolbar/menu if you use classic interface).
In ribbon panel/toolbar/menu
Type CUI then press [enter] to load Customize User Interface dialog. Or click User Interface in
customization panel.

If you’re 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 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.

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.

To add application to startup suite


If you want AutoCAD to automatically load it every time you start AutoCAD, you can add it to startup
suite. To add it to startup suite is easy. You can simply drag and drop the application to startup suite
icon as shown below.
To remove application from startup suite
To remove it from startup suite, click contents button below briefcase icon.

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.

Getting started with acaddoc.lsp


What is ACADDOC.LSP?
In short, it’s also an AutoLISP file. The difference is, AutoCAD will execute it every time we create or
open a drawing file. If you want further explanation, Jimmy Bergmark explain about ACADDOC.LSP in
details below:

Instruction on the usage of AutoCAD's


acaddoc.lsp
(It works for other versions (2000 and later) of AutoCAD and verticals as well)

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")

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.

How to create acaddoc.lsp if it does not exist


In the folder where you want to save acaddoc.lsp right click and select New>Text Document. Change
the name to acaddoc.lsp. Now you should be able to double click on the file and typically edit it in
Notepad.
Or start Notepad, edit, save, ready.

Examples on location for acaddoc.lsp


C:\Program Files\AutoCAD 2008\Support
C:\Documents and Settings\<loginname>\Application Data\Autodesk\AutoCAD
2008\R17.1\enu\Support
or in Windows Vista
C:\Users\<loginname>\AppData\Roaming\Autodesk\AutoCAD 2008\R17.1\enu\Support
If you want to find folders that are searched by AutoCAD run the OPTIONS command and look at the
Files tab and at the Support File Search Path.

Load order of files in AutoCAD


Files in acad.rx
acadYEAR.lsp
acad.lsp
acadYEARdoc.lsp
acaddoc.lsp
acad.dvb
Partials to Main CUI/CUIX named MNLs
Partials to Main CUI/CUIXloaded LSPs and MNLs in the order seen in CUI
Main CUI/CUIX named MNL
Main CUI/CUIX loaded LSP and MNL in the order seen in CUI
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 program in acaddoc.lsp


You can load AutoLISP program using this line:

(LOAD "MYLISP")

This sample below will load cnlabel.lsp and zoomextend.lsp.


Loading AutoLISP command is something quite basic we can do with acaddoc.lsp. Next, we will try to
define our own command here.

Undefine and define PLOT function in


acaddoc.lsp
In the next step, we will change how AutoCAD command work. Like we discuss before, we will
change plot and save command. First, we need to undefine it.

Undefine and redefine


We can undefine AutoCAD command using UNDEFINE.
In AutoCAD command line, type UNDEFINE [enter] then PLOT [enter].
We just undefine plot command. Try to type plot in command line and see how AutoCAD will
response.

Command: plot
Unknown command “PLOT”.  Press F1 for help.

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]
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.

Our code become like this:

; 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 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.

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

 
 
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.

How do you think acaddoc.lsp can be useful?


Do you think you can make use of acaddoc.lsp? Do you prefer to load AutoLISP from startup suite or
this method?

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 

We covered about acaddoc.lsp in AutoLISP tutorial. Acaddoc.lsp will execute commands defined in


it, every time AutoCAD open a file.

What can we do with acaddoc.lsp?


Now if you know you can run commands automatically when you open a file, what would you do?

1. You can load AutoLISP file automatically.


2. You can define new command. In the tutorial, we redefine PLOT command to update
datalink before AutoCAD starts to plot.
3. You can run commands before you start working with your file.
4. You can set system variable before you start working.

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.

Common unexpected system variables


change
These are several common system variables that change regularly.
1. File dialog box is missing. You have to type file path and file name from command line. It’s
because FILEDIA system variable has changed.
2. AutoCAD default noun-verb selection becomes verb-noun selection. It’s because PICKFIRST
system variable has changed.
3. Single document interface is activated. It’s controlled by SDI system variable.
4. And more…
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.

We can force to set the variables in


acaddoc.lsp
Harold Reuvers reminds me that we can set those variables in acaddoc.lsp. I prefer to backup my
system variables and restore them when I have problem. We can’t remember all the variables, right?
However, if you have specific system variable that changes often, this is a good solution.
All you need is to create an acaddoc.lsp using notepad or visual LISP editor.

Just type these code:

(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.

What system variables do you find change


often?
Do you find system variables in your AutoCAD change often? What are they?
Adding AIA standard layers with LISP
September 20, 2012 By Edwin Prakoso 

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.

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!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy