Unlimited AutoCAD® Scripting for Everyone
dave espinosa-aguilar – City of Richland, WA
CP4717:Some processes in AutoCAD are about as exciting as washing an old pair of dirty socks. A thousand times. Every week. It is truly amazing how many users have never learned how easy and powerful basic scripting is in AutoCAD. In a nutshell, if you can type a thing in the AutoCAD command prompt, then you can script it. This class explains how scripts can automate the boring, redundant, mind-numbing, anally-retentive aspects of your daily design and wash them right out of your hair in seconds. It demonstrates advanced scripting techniques that destroy myths regarding scripting limitations, and it also introduces users to the utilities (including the free Autodesk® ScriptPro utility) which easily apply scripts to batches of drawings at a time.
About the Speaker: A consultant in the CAD and Multimedia industry for over 20 years, dave espinosa-aguilar has trained architectural and engineering firms and Information Technology departments on the general use, customization and advanced programming of design, visualization and database applications from Autodesk including AutoCAD, AutoCAD Map, MapGuide, Architectural Desktop, Land Desktop & Civil 3D, and 3D Studio MAX. dave's passion is streamlining and automating design production environments through onsite customization and programming, and he has authored the facilities management applications of several Fortune 500 companies using AutoCAD ObjectARX, VB/VBA, AutoLISP/DCL and MAXScript technologies. dave has also produced graphics applications and animations for Toxic Frog Multimedia and has co-authored several books including NRP's "Inside 3D Studio MAX" series. He has been a speaker at Autodesk University since its inception, and served on the Board of Directors for Autodesk User Group International for 6 years including the office of President in 1996. dave currently works for the City of Richland (Washington) IT department as a GIS specialist and database/application integrator.
Boredom To The Rescue!
There may have been a time in your life when using AutoCAD to do just about anything (including your wedding invitations) was incredibly exciting. But after years (maybe it was after months? after weeks perhaps?) of being immersed in drafting production work, certain tasks in AutoCAD became downright painful for you to slog through... especially those that required mind-numbing, repetitive processes. There are times when being bored out of your mind can be a powerful cue for you to consider and investigate new methods for dealing with a situation.
Or old ones... really old ones that work so well that most people who discover them can’t believe they've been right under their nose since the product was first launched back in the 1980’s. The solution is called scripting. It’s free, it’s always been there, it’s easier than learning how to edit vertices using the PEDIT command, and it is forehead-slapping simple to use. In fact, if you know how to type any commands in AutoCAD, then you already know how to script in AutoCAD. It works in AutoCAD LT! Toolbars and pulldown menus and ribbons and palettes can look very attractive when you’re doing a thing once or twice in a minute. However, they are absolute hell to use when you have to do a thing 1000 a day. Welcome to the ultimate out-of-the-box automating technology in AutoCAD: the Command prompt.
Taking Command of ... the Command Prompt!
The command prompt has been there in AutoCAD since the beginning, and there are a lot of solid reasons why it is still in there. Over the years, some folks have suggested removing the command prompt, thinking it a waste of screen realty or an outdated interface to be bypassed by sexier dialogs, tool palettes, toolbars, ribbons and the like. But anyone who’s been around a while, who’s spent a decade or more in the AutoCAD production trenches, knows that it is not only the fastest interface to any deep functionality in AutoCAD (ever notice the Top Dogs are always typists?), it is not only the most consistent interface in AutoCAD in the last two decades (I’ll bet you can draw a LINE instantly in a next new release by typing it, no matter where it gets buried in the next pulldown menu)… it is the only automatable interface to AutoCAD which does not require programming skills.
In fact, it is quite literally AutoCAD’s "stream of consciousness" interface—a direct line to your hands. What a user types, a script types: keystroke for literal keystroke. Therefore, the more you know about the way a command functions by typing it, the more your scripts can imitate your steps verbatim to accomplish the same thing. Over and over a thousand times. It is a lightening fast keyboard feeding machine, and in those cases where a thing has to be 1000 times, it can be a lifesaver.
Streams of Consciousness
For some time now, the F2 key has launched the Text Window which reports AutoCAD’s Command Prompt history. Content in the window behaves like simple ASCII text, and it can be copied and pasted easily to Windows Notepad or any other Windows program. The history includes all the AutoCAD prompts, commands and system variables, default values and settings, error messages, reports, and of course everything the user has literally typed or “typed by invoking another interface.”
By typing any process you would like to be repeated easily in one fast step, all you need to do is manually perform the process once (thru typing), capture it, copy/paste it to Notepad, edit it down to only your keystrokes, and save it to an ASCII text file with a .SCR file extension. Yes. It is literally that simple. And what kind of a mind-numbing process might compel you to verify this for yourself?
Imagine working for someone (or with someone) who actually thinks the best way to name his layers is to name them (“1”, “2”, etc.). Imagine that whenever you have to work on this person's drawings you wind up having to :
- rename his layers to more practical values
- move certain types of entities on certain layers to other more practical layers
- thaw all layers so that you can see everything
- scale all text to a particular size for correct plotting
- change LTSCALE so that linetypes appear correctly when plotted
- change certain attribute values in certain blocks (including perhaps the titleblock)
- zoom to extents (and save the drawing of course)
Let's say that you do work with this person all the time, and not only do you wind up having to change all of his drawings to a more manageable configuration every time you receive them (just to get your work in them done), but suppose this person is paying your salary or bringing in your work and refuses to reconsider his existing "standards." Suppose he expects to get any modifications made to his original drawings returned with his original standards intact!
Guess who gets to use all those new and thrilling interfaces in the latest release of AutoCAD to change all of these things over to a more workable and coherent standard, drawing by drawing?
You do.
And there you sit, wondering whatever possessed you in the first place to take on work like this. Oh that’s right: money! So you slog your way thru these 7 steps every time you open a drawing from this guy. Maybe it's not as bad as it sounds. Not for 10-20 of his drawings. But would you want to do it for a 1000 of them?
Come on. There's got to be a faster easier lazier way to accomplish this kind of work... and there is. It's called scripting, and it's the reason we use computers for this kind of thing in the first place. Crack your knuckles, open Windows Notepad, and get ready to do this process one more time, completely typed at the Command prompt… for the last time in your life.
Here's a sampling of his typical drawing. He has 5 layers in them named "1", "2", "3", "4", and "5" and he has his lines, plines and circles mixed onto all of these layers. Suppose you and your people need all his lines on a layer named "lines", all plines on a layer named "plines," and all circles on a layer named "circles." He also always has his layer "4" frozen, and the text entities on that layer are the wrong height for your plotting needs and need to be resized. His drawing has an LTSCALE value of 1 which needs to be set to 200 for dashes to appear correctly. The second attribute value of a particular block of his also needs to be changed to a value of 200, and the drawing needs to be zoomed to extents and saved so that you and your people can now get your work done on these drawings.
To do this whole process manually, per drawing, the command prompt sequence would look something like this
(the boldfaced typing indicates what your typed strokes would be):
Command: -rename
Enter object type to rename
[Block/Dimstyle/LAyer/LType/Material/multileadeRstyle/Style/Tablestyle/Ucs/VIew/
VPort]: la
Enter old layer name: 1
Enter new layer name: lines
Command: -rename
Enter object type to rename
[Block/Dimstyle/LAyer/LType/Material/multileadeRstyle/Style/Tablestyle/Ucs/VIew/
VPort]: la
Enter old layer name: 2
Enter new layer name: circles
Command: -rename
Enter object type to rename
[Block/Dimstyle/LAyer/LType/Material/multileadeRstyle/Style/Tablestyle/Ucs/VIew/
VPort]: la
Enter old layer name: 3
Enter new layer name: plines
Command: ssx
Initializing... Type "ssx" at a Command: prompt or (ssx) at any object selection prompt.
Select object <None>: <enter>
Enter filter option [Block name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: e
>Enter entity type to add <RETURN to remove>: line
Current filter: ((0 . "line"))
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: <enter>
9 found.
Command: change
Select objects: p
9 found
Select objects: <enter>
Specify change point or [Properties]: p
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: la
Enter new layer name <varies>: lines
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: <enter>
Command: ssx
Select object <None>: <enter>
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: e
>Enter entity type to add <RETURN to remove>: circle
Current filter: ((0 . "circle"))
Enter filter option [Block name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: <enter>
9 found.
Command: change
Select objects: p
9 found
Select objects: <enter>
Specify change point or [Properties]: p
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: la
Enter new layer name <varies>: circles
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: <enter>
Command: ssx
Select object <None>: <enter>
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: e
>Enter entity type to add <RETURN to remove>: lwpolyline
Current filter: ((0 . "lwpolyline"))
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: <enter>
3 found.
Command: change
Select objects: p
3 found
Select objects: <enter>
Specify change point or [Properties]: p
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: la
Enter new layer name <varies>: plines
Enter property to change
[Color/Elev/LAyer/LType/ltScale/LWeight/Thickness/TRansparency/Material/Annotati
ve]: <enter>
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]: t
Enter name list of layer(s) to thaw: *
Enter an option
[?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/TRansparency/MATerial/Plot/Fre
eze/Thaw/LOck/Unlock/stAte/Description/rEconcile]: <enter>
Command: ssx
Select object <None>: <enter>
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: e
>Enter entity type to add <RETURN to remove>: text
Current filter: ((0 . "text"))
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: la
>Enter layer name to add <RETURN to remove>: 4
Current filter: ((8 . "4") (0 . "text"))
Enter filter option [Block
name/Color/Entity/Flag/LAyer/LType/Pick/Style/Thickness/Vector]: <enter>
6 found.
Command: scaletext
Select objects: p
6 found
Select objects: <enter>
Enter a base point option for scaling
[Existing/Left/Center/Middle/Right/TL/TC/TR/ML/MC/MR/BL/BC/BR] <Existing>: <enter>
Specify new model height or [Paper height/Match object/Scale factor]
<265.3884>: 200
6 objects changed
Command: ltscale
Enter new linetype scale factor <1.0000>: 200
Regenerating model.
Command: gatte
Initializing...
Select block or attribute [Block name]: b
Enter block name: thing
Known tag names for block: VALUE2 VALUE1
Select attribute or type attribute name: value2
Block: thing Attribute tag: VALUE2
Enter new text: 200
Number of inserts in drawing = 2 Process all of them? [Yes/No] <Yes>: y
Please wait...
2 attributes changed.
Command: zoom
Specify corner of window, enter a scale factor (nX or nXP), or
[All/Center/Dynamic/Extents/Previous/Scale/Window/Object] <real time>: e
Press F2 to bring up the Text Window and all your keystrokes are recorded there. You don't have to memorize anything to know everything you did to make this all happen. Select the entire history with your mouse (prompts and all), copy them to the Windows clipboard and paste them into Notepad. Step one accomplished, on to step two.
Whittle the pasted history down to only your keystrokes. Places where you pressed ENTER in the sequence are left as a blank line. It would look something like what you see below. Note again that blank lines signify <ENTER> keystrokes. Some comments (prefixed with a semi-colon) are also added into the mix to remind us what each keystroke series is doing:
;start whittle down this crazy process
;rename layers "1" "2" and "3" to "lines" "circles" and "plines"
-rename
layer
1
lines
-rename
layer
2
circles
-rename
layer
3
plines
;put lines on layer "lines" circles on layer "circles" and plines on layer "plines"
ssx
<this line is left blank>
e
line
<this line is left blank>
change
p
<this line is left blank>
p
la
lines
<this line is left blank>
ssx
<this line is left blank>
e
circle
<this line is left blank>
change
p
<this line is left blank>
p
la
circles
<this line is left blank>
ssx
<this line is left blank>
e
lwpolyline
<this line is left blank>
change
p
<this line is left blank>
p
la
plines
;thaw all layers
-layer
t
*
<this line is left blank>
;scale text on layer "4" to a value of 200
ssx
<this line is left blank>
e
text
la
4
<this line is left blank>
scaletext
p
<this line is left blank>
<this line is left blank>
200
;change LTSCALE value
ltscale
200
;change block "thing" attribute "value2" value to 200
gatte
b
thing
value2
200
y
;zoom to extents
zoom
e
;save the drawing
qsave
<this line is left blank>
;end of the insanity
Next step, save this information to an ASCII text file called magic.scr. Make sure it is saved as an ASCII text file and with a .SCR file extension (not .TXT) so that AutoCAD can recognize the file specifically as a script file. Now when you open a drawing from this client, you can drop and drag magic.scr right into the graphics area of the drawing… and watch the automated steps scream by as if you had typed them all at 10,000 words per minute! Need to do it again on his next drawing? Same one-step drop-and-drag. And the script can be supplemented or edited as needed if your client’s crazy “standard” ever changes. This is the essential magic of scripting, and it really is this simple to automate 10, 100 or 1000 steps in any drawing. No one can type of pick buttons that fast. And why should they.
Pre-Scriptions
Now that you’ve seen the basic concept of scripting in action, it’s time to discuss the typical types of hiccups, weirdness, and problems that arise in writing scripts. Copying/Pasting from the Text Window is an easy way to not have to remember the exact sequence of commands and values you need to create a script, but sometimes the following things happen:
- you accidentally type the wrong thing and need to backtrack: no problem. undo your step and then redo it. when you copy the Text Window, make a note to yourself where the bad sequence of steps are and chop them out.
- you forget where the <ENTER> key strokes are: no problem. anything that shows blank values after a colon, simply verify the sequence manually and then make sure a blank line is in your script to represent it. Too many blank lines (or extra spaces!!) can send you unexpectedly back into the last command typed (just as if you had pressed the ENTER key too many times). Don’t beat yourself up over this. EVERYONE goes thru this tweaking process until they get their scripts working perfectly. Welcome to the world of “debugging.”
- you use aliases but the script is run on someone else’s system that use different aliases: no problem, type the full command when you write the script. use a period in front of the command if you want to guarantee the command behavior (ex: .LINE), and avoid using aliases in any script.
- a command sequence changes in a new release of AutoCAD: no problem (and welcome to the wonderful world of migration). save the original script in a release-dedicated directory, make changes to the original and save it in a new release directory. keep directory versions of your scripts safely apart from each other.
- the script doesn’t seem to be behaving: never test new scripts on production work. always test them out on junk copies in safe places. follow the script till it breaks, tweak that portion of the script till you get it right, and then after plenty of testing you can move it to production drawing use. many things can cause a script to bomb… make sure that any command you use passes its instructions to the command prompt only. disable dialogs (CMDDIA, FILEDIA, etc) before running the rest of your script (you can include SETVAR commands to do this for you in the script itself!) and be sure to restore those settings when the script is finished (that too can be done with the SETVAR command in the script itself).
Scripting is an art form. Some folks are so proficient at it that they can immediately start writing scripts without having to manually do the commands at the command prompt because they have the sequence of commands down so well. They also know the typical problems that a script runs into and how those problems get solved quickly. As with anything in AutoCAD, the best way to get better with a feature set or technology is to use it more and more.