tailoring AutoCAD - CADalog

28 downloads 1031 Views 2MB Size Report
Dec 1, 2002 ... Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at ...
tailoring AutoCAD by

u p f r o n t . e z i n e ○



















Tailoring AutoCAD





























r a l p h

g r a b o w s k i

p u b l i s h i n g , ○





















chapter 1



























l t d . ○











introduction to customization









i

Copyright & Payment Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. To support the work of the author, you can make a payment of: On CD in Acrobat PDF format: US$24.95 (incl. shipping). Allow 1-2 weeks to arrive. By email in PkZIP/Acrobat PDF format: US$19.95. Allow for a 5MB download. Print copy: US$29.95 (incl. shipping). Allow 4-6 weeks to arrive. The CD and print copy are normally delivered by mail, with shipping cost included. Delivery by FedEx for CD or print copy: add US$18 - CDN$25 - £10. Check or Money Order • US funds drawn on a bank with its address in the USA (US$19.95 - $24.95 - $29.95). • Canadian funds drawn on a bank with a Canadian address (CDN$27.95 - $34.95 - $42.95 incl. GST). • British funds drawn on a bank located in Great Britain (£12.99 - £15.99 - £18.99). Mail your payment to: "Tailoring AutoCAD" 34486 Donlyn Avenue Abbotsford BC V2S 4W7 Canada PayPal • To the account of [email protected] at www.paypal.com. You can copy and paste the following URL into your browser: https://www.paypal.com/affil/pal=ralphg%40xyzpress.com. PayPal accepts funds in US, Euro, Yen, and Canadian currencies. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○



































































































































































































































i i



v1.0

1 december 2002

table of contents t a i l o r i n g

1: introduction to customizing

A u t o C A D

. . .1

The Many Ways of Customization . . .3 Which Customization? . . .4 Shortcut Tips . . .4 Placing Arcs

. . .4

Placing Text

. . .4

Replacing Text

. . .4

Update for AutoCAD 2000

. . .4

Which Font? . . .5 Plot Optimization

. . .5

Template Drawings

. . .5

Fast Custom Drawing Sheets . . .5 Collapsing Multilines . . .6 Changing Layers Quick Trim

. . .6

. . .6

Aerial View . . .6





















Tailoring AutoCAD



















































chapter 1





































introduction to customization









• iii

2: customizing the environment

. . .7

Starting AutoCAD . . .10 Using Command-line Switches . . .10 /b Switch

. . .12

/c Switch

. . .12

/nologo Switch

. . .12

/p Switch

. . .12

/r Switch

. . .12

/s Switch

. . .13

/t Switch

. . .13

/v Switch

. . .13

Changing Window and Layout Elements . . .14 Colors . . .14 UCS Icon . . .15

Command Line Font . . .16 Keyboard Shortcuts . . .16 Toolbars and Command Line . . .16 Menus and Tablet . . .17

Setting and Restoring Profiles . . .18 Support File Paths . . .19 Search Path Options . . .20 Support File & Working Support File Search Paths Device Driver File Search Path Project Files Search Path

. . .20

. . .20

. . .20

Menu, Help, and Miscellaneous File Names

. . .21

Text Editor, Dictionary, and Font File Names

. . .21

Print File, Spooler, and Prolog Section Names

. . .21

Printer and Plot Support Files . . .21 Search Path for ObjectARX Applications Automatic Save File Location Data Sources Location

. . .21

. . .21

Drawing Template File Location Log File Location

. . .21

. . .21

. . .21

Temporary Drawing File Location

. . .22

Temporary External Reference File Location Texture Maps Search Path



iv















v1.0















. . .22

. . .22























































































1 december 2002

Drafting and Selection Preferences . . .23 AutoSnap Settings . . .23 Grips Settings . . .23

3: command aliases

. . .25

Shortcut Keys . . .27 Defining Shortcut Keys . . .28

The .pgp File: Aliases . . .29 Alias Format . . .29 Alias Rules . . .29 Aliases Defined by Autodesk . . .29

Creating a New Alias . . .31

4: toolbar macros

. . .33

Customizing Toolbars . . .35 Rearranging Toolbars . . .35 Dragging Toolbars . . .35 Toggling Toolbars . . .38

Changing Toolbar Buttons . . .39 Changing Button Size . . .41 Drawing Icons . . .42

Writing Toolbar Macros . . .44 Simple Macros . . .45 Advanced Macros . . .46

Toolbar Macros Are No Panacea . . .46

Customizing the Toolbar — R11, R12, LT R1 and R2 . . .47 Looking Inside a Toolbar Macro . . .48 Title Bar

. . .48

AutoCAD LT Command . . .48 Image - Character Next & Previous

. . .49

. . .49

Delete, Cancel, & OK

. . .49

Customizing the INI File . . .50 Additional Toolbar Definitions . . .51 Dialog Box or Text Editor? . . .51





















Tailoring AutoCAD



















































chapter 1





































introduction to customization











v

LT R1 & 2’s SetEnv Command . . .52 Customizing Macros Directly . . .52 Editing the Macro Directly . . .52

Multiple Command Toolbar Macros . . .53 Conserving with Aliases . . .53

5: linetypes

. . .55

Commands Affecting Linetypes . . .55 System Variables that Affect Linetypes . . .57 The Special Case of Polylines . . .57

Customizing Linetypes . . .57 Testing the New Linetype . . .59

Creating Linetypes with a Text Editor . . .60 The Linetype Format . . .60 Line1: Header . . .60 Line 2: Data . . .60

Complex (2D) Linetypes . . .61 Text . . .61 Text Style . . .61 Text Scale Factor . . .61 Text Rotation Angle . . .61 Text Orientation . . .61 Text Offset Distance . . .62 Embedding a Shape . . .62 3D Linetypes . . .62 A Parallel Linetype . . .63 Alternatives to the Parallel Linetype . . .65

6: menu macros

. . .67

Loading (and Unloading) Menu Files . . .69 Loading Menu Groups . . .69 Loading Menu Bar Items . . .70 Menu File Types . . .70



vi















v1.0





































































































1 december 2002

My First Menu . . .71 A Single-Command Menu . . .71 Section Labels

. . .75

Menu Metacharacters . . .76 Shortcut Menu Aliases . . .78

My Second Menu . . .79 Loading .mnu a Second Time . . .79 Adding More Menu Macros . . .79 Adding Options to Commands . . .80 Using Coordinates in Macros . . .80

Making Macros “Official” . . .82 Cancelling a Previous Command: ^C . . .82 Adding Keyboard Shortcuts: & . . .82 Separating Macros Visually: -- . . .83 Adding Submenus: -> . . .83 Right-Justified Text: \t . . .84 Grayed-out Item: ~ . . .84 Adding a Checkmark: !. . . .84

Waiting for User Input: \ . . .85 Providing Input to the User: ^H . . .85

Writing Really Long Macros: + . . .86 Repeating a Command . . .86

Toolbars, Accelerator Keys, Image Tiles, Tablet Overlays, and the Screen Menu . . .87 Toolbar Customization . . .87 Custom Shortcut Keys . . .87 Image Tiles . . .87 Tablet Menus . . .87 Screen Menu . . .87

7: hatch patterns

. . .89

Where Do Hatch Patterns Come From? . . .91 Associative and Non-associative Patterns . . .91

Creating Custom Hatch Patterns . . .92 Hatch Command . . .92 BHatch Command . . .93





















Tailoring AutoCAD



















































chapter 1





































introduction to customization









• vii

Understanding the acad.pat File . . .94 Comment and Header Lines . . .94 The Hatch Data . . .94 Tips on Creating Pattern Codes . . .95 Adding Custom Patterns to the Palette . . .97 Stage 1: Creating a Slide from a Hatch Pattern . . .97 Stage 2: Updating the acad.slb File . . .98

. . .99

8: shapes & fonts

. . .101

About Shape Files . . .103 The Shape File Format . . .103 Header Fields . . .103 Definition Lines . . .104

Vector Codes . . .104 Instruction Codes . . .105 0/000: End of Shape

. . .105

1/001: Draw Mode

. . .105

2/002: Move Mode

. . .105

3/003: Reduced Scale

. . .106

4/004: Enlarged Scale

. . .106

5/005: Save (Push)

. . .106

6/006: Recall (Pop)

. . .106

7/007: Subshape

. . .106

8/008: X,y Distance

. . .107

9/009: X,y Distances . . .107 10/00A: Octant Arc

. . .107

11/ 00B: Fractional Arc 12/00C: Bulge Arc 13/00D: Polyarc

. . .108

. . .108

. . .109

14/00E: Flag Vertical Text Flag

. . .109

9: script files . . .111 What are Scripts? . . .111 Script Files . . .111 Drawbacks to Scripts . . .113 Strictly Command-Line Oriented . . .113





viii













v1.0





































































































1 december 2002

Script Commands and Modifiers . . .115 Script . . .115 RScript . . .115 Resume . . .115 Delay . . .115 Special Characters . . .115 (space) . . .115 ; (semicolon) . . .116 ' (apostrophe) . . .116 * (asterisk) . . .116 Backspace . . .116 Esc . . .116

10: diesel expressions . . .117 The History of Diesel . . .117 What Diesel Does . . .119 Brief Listing of Diesel Functions . . .119 Math Functions . . .119 Logical Functions . . .119 Conversion Functions . . .119 String Functions . . .120 System Functions . . .120

Jumping Into Diesel . . .121 Diesel Error Messages . . .121 $?

. . .121

$(func)??

. . .121

$(func,??) $(++)

. . .121

. . .121

Debugging Diesel . . .122

Diesel Programming Tips . . .122





















Tailoring AutoCAD



















































chapter 1





































introduction to customization









• ix

Diesel in Menus . . .123 [ . . .123 $(if, . . .123 $(getvar,dimaso) . . .123 ,!. . . .123 ) . . .123 /vAssociative Dimensions . . .124 ] . . .124 '_dimaso . . .124 $M= . . .124 $(-,1, . . .124 $(getvar,dimaso) . . .124 ) . . .124

Reusing Toggle Code . . .125

Diesel in AutoLISP . . .126 Via the setvar Function . . .126 Concatenate Two Diesel Strings . . .126 Via the MenuCmd Function . . .126

11: autolisp programming . . .127 The History of AutoLISP . . .127

The AutoLISP Programming Language . . .130 Simple AutoLISP: Adding Two Numbers . . .130

AutoLISP in Commands . . .132 Remembering the Result: SetQ . . .132

AutoLISP Functions . . .134 Math Functions . . .134 Geometric Functions . . .135 Conditional Functions . . .136 String and Conversion Functions . . .136 External Command Functions . . .137 Accessing System Variables . . .138

GetXXX Functions . . .139 Selection Set Functions . . .140 Object Manipulation Functions . . .140 Advanced AutoLISP Functions . . .140



x















v1.0





































































































1 december 2002

Writing a Simple AutoLISP Program . . .141 Why Write a Program? . . .141 The Id Command . . .141

The Plan of Attack . . .141 Obtaining the Coordinates . . .141

Placing the Text . . .143 Putting Them Together . . .144

An Alternative to LISP Programming . . .144 Writing a Simple AutoLISP Program, Cont’d . . .145 Sprucing Up the Code . . .145 Conquering Feature Bloat . . .145 Wishlist Item #1: Naming the Program . . .146 Wishlist Item #2: Saving the Program . . .146 Wishlist Item #3: Automatically Loading the Program . . .147 Wishlist #4: Using Car and Cdr . . .147

Saving Data to a File . . .151 The Three Steps . . .151 Step 1: Open the File . . .151 Step 2: Write Data to the File . . .152 Step 3: Close the File . . .152

Putting It Together . . .152 Wishlist #5: Layers . . .153 Wishlist #6: Text Style . . .153

Tips in Using AutoLISP . . .154 Tip #1. Use an ASCII Text Editor. . . .154 Tip #2: Loading LSP Code into AutoCAD . . .154 Tip #3: Toggling System Variables . . .154 Tip #4: Be Neat and Tidy. . . .155 Tip #5: Suppress That nil . . .155 Tip #6: Read-Write-Append File . . .155 Tip # 7: Quotation Marks as Quotation Marks . . .155 Tip # 8: Keep Variables to Six Characters . . .156 Tip #9: Tabs and Quotation Marks . . .156





















Tailoring AutoCAD



















































chapter 1





































introduction to customization









• xi

Feedback I welcome your feedback for correcting and improving the text. Send your email to [email protected] . Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at www.upfrontezine.com/ebooks.





xii













v1.0





































































































1 december 2002

one

introduction to customizing t a i l o r i n g

A u t o C A D

i

f, like me, you’re a messy sketcher, then you appreciate how computer software makes your work neater. For too many drafters, that’s all AutoCAD amounts to: a neater drafting machine. The real power behind CAD (computer-aided design), however, is its ability to be customized to the way you work. Customize is jargon for letting CAD do some of the drafting for you. This ranges from placing a linetype specific to your discipline, to generating a 3D staircase to fit between two floors, and more. The benefit? You get your work done is less time, or, if you are a free-lancer, you get more work done in the same time. The drawback to customizing is that it takes bits of time. First, you need to take a bit of time to learn how to customize AutoCAD — that’s what this book is all about. Then, you need a bit more time to create the customization. Time isn’t something most professionals have a lot of. I sometimes find myself doing a repetitive editing function under the false belief that it takes longer to write (and debug) a macro than it would automating the task. So, I have this rule-of-thumb: Write a macro when the same action is repeated more than three times. There lies the responsibility of Autodesk to make automation easier for the end-user. Still, the time you invest in automation makes you a more productive AutoCAD user, even in the short run.





















Tailoring AutoCAD



















































chapter 1





































introduction to customization











1

Table of Contents - Chapter 1 The Many Ways of Customization . . .3 Which Customization? . . .4 Shortcut Tips . . .4 Placing Arcs

. . .4

Placing Text

. . .4

Replacing Text

. . .4

Update for AutoCAD 2000

. . .4

Which Font? . . .5 Plot Optimization

. . .5

Template Drawings

. . .5

Fast Custom Drawing Sheets . . .5 Collapsing Multilines . . .6 Changing Layers Quick Trim

. . .6

. . .6

Aerial View . . .6



















































































































Copyright Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○

2















v1.0





































































































1 december 2002

The Many Ways of Customization By my count, there are more than two dozen ways to customize AutoCAD (some of these may vary, depending on the version of AutoCAD you are working with): ADI ADS

Autodesk Device Interface and plotting formats (replaced by HDI in AutoCAD 2000).

AutoCAD Development System (no longer available as of AutoCAD 2000). ARX AutoCAD Runtime Extension (also known as ObjectARx) for C++ programming. ASI AutoCAD SQL (structured query language) Interface for database programming. DCL Dialog Control Language for customizable dialog boxes. DDE Dynamic Data Exchange for linking with other software. DIESEL Direct Interpretively Evaluated String Expression Language (see Chapter 10). DWG DraWinG; create custom symbols and user-defined objects. DWT DraWing Template; preset drawing elements (see Chapter 2). DXB Drawing Interchange Binary. DXF Drawing Interchange Format. DXFIX Drawing translation (no longer available as of AutoCAD 2000). HLP, AHP Customizable help (no longer available as of AutoCAD 2000). INI Toolbar macros and INItialization files (no longer available as of AutoCAD 2000). LIN Customizable LINetypes (see Chapter 6). LSP AutoLISP (see Chapter 11). MNU Customizable menu and tablet, popdown, cursor, and icon menus (see Chapter 5). OLE Object linking and embedding with other software. PAT Customizable hatch PATterns (see Chapter 7). PGP ProGram Parameter files. RPF Raster Pattern Files. SCR Script files (see Chapter 9). SHP,SHX SHaPes and customizable text fonts (see Chapter 8). SLD, SLB SLiDes and Slide LiBraries. VBA Visual Basic for Applications. VLISP Visual LISP.

Plus a host of miscellaneous support and data files that can be edited: DCC DFS FMP MNL MSG MLN UNT

dialog color configuration (no longer available as of AutoCAD R14). MvSetup command’s DeFaultS. Font MaPping. MeNu utiLities. message (no longer available as of AutoCAD R14). MultiLiNe style. UNiT conversion factors.

... and more. You find many of these files in AutoCAD’s \support folder. Some customizations are designed for end-users, such as toolbar macros, menus, and AutoLISP routines, all of which we look at in this book. Others are meant for professional programmers, like ASI and ObjectARx, which we ignore. In between the two levels, there are other customization possibilities, such as hatch patterns and DIESEL programming, that some enthusiastic users enjoy tinkering with. We look at these as well.





















Tailoring AutoCAD



















































chapter 1





































introduction to customization











3

Which Customization? That said, you need to make two decisions along the way. As you work with AutoCAD, make a mental or written record of your work. In particular, chronicle repetitive drafting tasks because these are prime candidates for customization. As one of Autodesk’s founders emphasized, “You should never have to draw the same line twice.” The second decision is to pick which of AutoCAD’s many customization possibilities to apply to the repetitive task. Some solutions are obvious, such as writing a .pat file for a custom hatch pattern. Others are less obvious: to draw that 3D staircase, do you use a script file (perhaps not), a DIESEL macro (no), an AutoLISP routine (yes), an ObjectARx application (nope, at least not in this context), or a menu macro (maybe)? For this reason, you need to become familiar with most of AutoCAD’s customization possibilities — even if you never use some of them. That way you craft the solution with the best tool. You also know when to hand over the job to a professional programmer, yet have some intelligent oversight of their work. A third solution is to find out about the thousands of third-party solutions available from the Autodesk Web site, other locations on the Internet, and CDs. The bulk of these are AutoLISP routines written by amateur programmers solving their own problems with AutoCAD. By knowing AutoLISP, you can modify the routine to your needs, which is a lot easier than writing it from scratch.

Shortcut Tips Sometimes working more efficiently doesn’t involve customizing, but having a greater understanding of AutoCAD’s details. To get you started on the road to greater productivity, here are some time-saving tips that don’t involve customizing: Placing Arcs AutoCAD provides you with eleven different ways to draw an arc. Sometimes, placing an arc becomes an exercise in frustration, particularly when an angle is involved. The easier alternative is to draw a circle, then use the Trim or Break commands to convert the circle to an arc. Placing Text When you need to place bits of text all around the drawing, use the DT DTeext command. This versatile command sets text in the drawing wherever you place the cursor. Caution: When you are finished placing text, do not press Esc (or Ctrl+C in older versions of AutoCAD) because you will loose all entered text. Instead, press Enter twice to terminate the DT DTeext command. Replacing Text When you need to add similar text in a number of drawings, it is easier to place the same block of text in each drawing. Then use the DdEdit command to change wording of the text. Editing text is easier than placing new text, since all parameters have already been set, such as text style, heights, justification, and so on. Update for AutoCAD 2000 A bug in early versions of AutoCAD 2000 caused the plot size to swell (and plot time to increase) when TrueType fonts were used in the drawing. To fix this problem, either substitute .shx fonts for TrueType fonts, or update AutoCAD 2000 with the available bug patch.



4















v1.0





































































































1 december 2002

Which Font? (R12 and R13 only.) While AutoCAD Release 12, 13, and LT let you use PostScript fonts in drawings, these display very slowly compared to AutoCAD’s own .shx fonts. In addition, the Plot command often has difficulty finding the PostScript font definitions, and you end up with Courier font being substituted. For those two reasons, I recommend using .shx equivalents to PostScript fonts, which are available from third-party developers, or can be converted to .shx with FontASM. If you are using Release 13, then employ TrueType fonts, which are faster than PostScript (though slower than .shx ) and aren’t “lost” during plotting. (Recent releases of AutoCAD.) Although Autodesk promotes the use of TrueType fonts in drawings, you can still use PostScript fonts through an under-documented work-around: Use the Convert command to convert PostScript .psf font files to AutoCAD’s .shx font format. Although the font is not longer in .psf format, you can take advantage of the variety of PostScript fonts available. Plot Optimization (R14 and earlier.) The Plot command’s dialog box lets you select from seven levels of plot optimization. While any is faster than level 0 (no optimization), don’t assume that a higher number always results in a faster plot. In particular, levels 5 and 6 (eliminating overlapping vectors) really slow down a pen plotter. For monochrome plotters, the plot slows down when you go beyond level 1 (endpoint swap). Template Drawings (R13 and later.) To help you get started faster on new drawings, AutoCAD includes template drawings with system variables preset for the related standard. (Prior to R14, template drawings were known as prototype drawings.) Some of the .dwt template drawings found in AutoCAD’s \template folder are: ANSI E Title Block.dwt Architectural Title Block.dwt Generic 24in x 36in Title Block.dwt ISO A1 Title Block.dwt JIS A1 Title Block.dwt

US mechanical US architectural D-size Generic D-size drawing with title block ISO (International metric) drawing standards JIS (Japan) drawing standards

In older versions of AutoCAD, the templates are found in \common\support or \support folders: AcadIso.Dwg Jis_Arch.Dwg Jis_Mech.Dwg Us_Arch.Dwg Us_Mech.Dwg

ISO-DIN (European) prototype drawing JIS (Japan) architectural JIS mechanical US architectural US mechanical

Fast Custom Drawing Sheets The MvSetup command helps you in creating a customized drawing board, title block, and multiple view setup. izard to start a new drawing, but the MvSetup command remains the As of Release 14, you can use the Setup W Wizard more powerful tool.





















Tailoring AutoCAD



















































chapter 1





































introduction to customization











5

Collapsing Multilines (R13 and later.) To speed up the display of a drawing containing multilines, set the CMlScale system variable to 0. That collapses the multiline to a single line, which displays faster. Before plotting, set CMlStyle back to 1. Changing Layers Quicker than the Layer commands, simply click on the down arrow next to the layer name on the toolbar. That action displays a list box of layer names in the drawing. Click on the name of the layer you want to switch to. For keyboard-ists, use the CLayer command, which bypasses all of the Layer command’s options. Quick Trim To precisely trim back a pair of intersecting lines, use the Fillet command with radius set to zero. Aerial View (Undocumented in Release 13 for DOS.) The AV command, which displays an Aerial View window, just like in the Windows version. The Aerial View window lets you zoom and pan at near-instant speed.

Feedback I welcome your feedback for correcting and improving the text. Send your email to [email protected] . Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at www.upfrontezine.com/ebooks.



6















v1.0





































































































1 december 2002

two

customizing the environment t a i l o r i n g

A u t o C A D

a

utoCAD allows you to change the way it looks and works. The first few of these chapters concentrate on changing the look of AutoCAD; later chapters on changing the way it works.





















tailoring AutoCAD



















































chapter 2





































customizing the environment











7

Table of Contents - Chapter 2 Starting AutoCAD . . .10 Using Command-line Switches . . .10 /b Switch

. . .12

/c Switch

. . .12

/nologo Switch

. . .12

/p Switch

. . .12

/r Switch

. . .12

/s Switch

. . .13

/t Switch

. . .13

/v Switch

. . .13

Changing Window and Layout Elements . . .14 Colors . . .14 UCS Icon . . .15

Command Line Font . . .16 Keyboard Shortcuts . . .16 Toolbars and Command Line . . .16 Menus and Tablet . . .17

Setting and Restoring Profiles . . .18 Support File Paths . . .19 Search Path Options . . .20 Support File & Working Support File Search Paths Device Driver File Search Path Project Files Search Path

. . .20

. . .20

. . .20

Menu, Help, and Miscellaneous File Names

. . .21

Text Editor, Dictionary, and Font File Names

. . .21

Print File, Spooler, and Prolog Section Names

. . .21

Printer and Plot Support Files . . .21



















































































































Copyright Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○

8















v1.0





































































































1 december 2002

Search Path for ObjectARX Applications Automatic Save File Location Data Sources Location

. . .21

. . .21

Drawing Template File Location Log File Location

. . .21

. . .21

. . .21

Temporary Drawing File Location

. . .22

Temporary External Reference File Location Texture Maps Search Path

. . .22

. . .22

Drafting and Selection Preferences . . .23 AutoSnap Settings . . .23 Grips Settings . . .23





















tailoring AutoCAD



















































chapter 2





































customizing the environment











9

Starting AutoCAD When you start AutoCAD, you probably do it in one of three ways: • Double-clicking the icon you found on your computer’s desktop. utoCAD | A utoCAD • Clicking the Start button on the taskbar, and then selecting Programs | A AutoCAD AutoCAD utoCAD. • Double-clicking a .dwg filename in the Explorer (or File Manager). It was common knowledge in the days of the DOS operating system that there were additional options for starting AutoCAD. With Windows hiding much of what goes on behind its graphical user interface, command-line switches are no longer in common use. Command-line switches are useful for changing the way AutoCAD operates. The switches tell AutoCAD what to do when it starts: Switch

Comment

/b /c /nologo /p /r /s /t /v

Runs a .scr script file. See Chapter 9. Specifies the .cfg hardware configuration to use. Suppresses display of the startup logo. Specifies the .arg user profile to use. Resets the .cfg configuration file to default values. Specifies the path to a folder for support files. Specifies the .dwt template file. Specifies the named view to display.

TIP Command-line switches override settings in the Options dialog box and the values set by environment variables.

Using Command-line Switches To use command switches, you edit AutoCAD’s command line. Here’s how: 1. On the desktop, right-click the AutoCAD icon. Notice the shortcut menu.

2. From the shortcut menu, select Properties roperties. Notice the Properties dialog box.





10













v1.0





































































































1 december 2002

3. In the Properties dialog box, select the Shortcut tab.

In the Target text box, notice that the command-line text reads something like the following: "C:\CAD\AutoCAD 2002\acad.exe"

The path (C:\CAD\AutoCAD 2002\) may be slightly different for your system; that does not matter. The quotation marks are necessary when the command line contains spaces. 4. Edit the text in the Target box. For example, to change the path to the \support and \dwgs folders, you would enter the following (I’ve shown the changes in boldface, and the switch in cyan): "c:\cad\autocad 2002\acad.exe /s c:\support;c:\dwgs"

/s Notice that a space is required after the switch (/s /s), and that a semicolon ( ; ) is needed when the switch specifies more than one path. Here is another example: the following command-line starts AutoCAD with a script file called script.scr: "c:\cad\autocad 2002\acad.exe /b c:\autocad 2002\support\script.scr"

5. When done editing the target, click OK to close the dialog box. 6. Anytime you complete a customization, you must test that it works. Double-click the icon, and AutoCAD should start as you instructed with the switch. If it doesn’t work correctly, the most likely reason is that you made a spelling mistake. Repeat the steps listed above until it does work correctly. TIP You can have several shortcut icons on your computer’s desktop, each with a different set of command-line parameters. To make copies of icons, drag an icon while holding down the Ctrl key. To rename the icon, right-click and select Rename.





















tailoring AutoCAD



















































chapter 2













































customizing the environment • 11

/b Switch

The /b switch specifies the name of a .scr script file to run immediately after AutoCAD starts. See Chapter 9 to learn how to write a script file. Example usage: "c:\cad\autocad 2002\acad.exe /b c:\autocad 2002\script.scr"

/c Switch

The /c switch specifies the path to a .cfg hardware configuration file. The switch can point to a specific .cfg file or to a folder. If a folder, then the filename in the folder must be acad2002.cfg (or equivalent for the release of AutoCAD you are using). Example usage: "c:\cad\autocad 2002\acad.exe /c c:\autocad 2002\support\myconfig.scr"

Usually, AutoCAD is started without the /c switch; instead, it uses the AcadCfgW and AcadCfg environment variables to search for a .cfg file. If these variables are not set, AutoCAD searches the folder in which acad.exe is located. If the acad2002.cfg file does not exist, AutoCAD creates one using default values. See /r switch. /nologo Switch

The /nologo switch starts AutoCAD without its logo. Example usage: "c:\cad\autocad 2002\acad.exe /nologo"

Some people find the logo irritating because it covers up other windows for a few seconds. In AutoCAD 2002, the logo looks like this.

/p Switch

rofiles The /p switch specifies a named profile to use with AutoCAD. Profiles are created with the Options | P Profiles dialog box, and are discussed later in this chapter. Example usage: "c:\cad\autocad 2002\acad.exe" /p "my profile"

/r Switch

The /r switch restores the acad2002.cfg configuration file to its default values. The existing configuration file is renamed acad2002.bak. This switch is useful when AutoCAD’s hardware configuration gets mucked up. Example usage: "c:\cad\autocad 2002\acad.exe /r"





12













v1.0





































































































1 december 2002

/s Switch

The /s switch points to the folder(s) holding support files, such as menu, font, and linetype files. You can specify as many as 15 support folders. Separate each folder name with a semicolon ( ; ). Example usage: "c:\cad\autocad 2002\acad.exe /s c:\autocad 2002\support\;c:\alisp"

iles Usually, AutoCAD starts without the /s switch; instead, it reads the folder(s) specified by the Options | F Files P ath dialog box. AutoCAD also consults the path specified by the environmental variables in the AutoExec.Bat file. /t Switch

The /t switch specifies the drawing file to use as a template on which to base new drawings. When a template is not specified, AutoCAD uses the acad.dwg file as its template. Example usage: "c:\cad\autocad 2002\acad.exe /t c:\autocad 2002\template\Architectural Title Block.dwg"

/v Switch

The /v switch specifies a named view to display when AutoCAD opens. When a view is not specified, AutoCAD opens the drawing with the view last saved. Example usage: "c:\cad\autocad 2002\acad.exe /v titleblock"

TIP The /s and /t switches are useful for customizing AutoCAD to the needs of different clients.





















tailoring AutoCAD



















































chapter 2













































customizing the environment • 13

Changing Window and Layout Elements AutoCAD’s default colors and fonts are, for the most part, pretty good. Nevertheless, it allows you to change some aspects of its user interface, while other aspects are controlled by the Windows operating system. To have Windows make changes, right-click the desktop, and select Properties roperties. The Appearance tab handles fonts and colors, dvanced | General| Display controls the overall size of fonts and user interface elements. while the Settings | A Advanced Here is how to make changes in AutoCAD itself: Colors A change in AutoCAD you may want to make right away is the background color of the drawing area: from black to white. Black was the traditional color in the days when CAD ran on the DOS operating systems; some users continue to prefer black because colors look more vibrant against it. To change the colors of the AutoCAD window, follow these steps: 1. From the menu bar, select Tools | Options Options. Notice the Options dialog box. 2. In the Options dialog box, select the Display tab. 3. In the Display tab, click the Colors button. Notice that the Color Options dialog box has two parts: on the left for the model tab, and on the right for all layout tabs.

You can change the color of these user interface elements: • • • • •

Model T ab Background sets the background color of the drawing area in model space. Tab Model T ab P ointer sets the color of the crosshair cursor (pointer) in model space. Tab Pointer Layout T abs Background (P aper) sets the background color of the drawing area in all layouts. Tabs (Paper) Layout T abs P ointer sets the color of the crosshair cursor (but not the pointer cursor) in model space. Tabs Pointer AutoT racking V ector Color sets the color of tracking vectors, the temporary construction lines that appear utoTracking Vector while drawing, showing geometric relationships. • Command Line Background sets the background color of the ‘Command:’ prompt area. • Command Line T Teext sets the color of text in the ‘Command:’ prompt area.





14













v1.0





































































































1 december 2002

UCS Icon

The color and size of the UCS (user-defined coordinate system) icon is changed with the UCSicon command’s roperties Properties roperties, or enter the command at Properties option. From the menu bar, select View | Display | UCS Icon | P the prompt, as follows: Command: ucsicon Enter an option [ON/OFF/All/Noorigin/ORigin/Properties] : p





















tailoring AutoCAD



















































chapter 2













































customizing the environment • 15

Some of the changes you can make to the UCS icon are illustrated by the figure:

• • • •

Color, separately for model and layout (paper space) modes. Line thickness. Arrowhead type. 2D or 3D style.

TIP The UCS icon is meant to aid your view orientation during 3D design. If your drafting is primarily 2D, there is no need to display the icon. Turn it off witih the UCSicon command’s OFF option.

Command Line Font AutoCAD normally uses the Courier font for text in the command prompt area. To change the size and type of font, from the menu bar select Tools | Options | Display Display, and then click Fonts onts.

Select a font, style, and size. Click Apply & Close Close. Keyboard Shortcuts You can create keyboard shortcuts for executing commands. For example, you can assign commands to function keys. See Chapter 3 for details. Toolbars and Command Line You can change the position and number of toolbars. Additionally, you can change the icons on toolbar buttons, as well as the command(s) executed when a button is selected. See Chapter 4 for details.





16













v1.0





































































































1 december 2002

Menus and Tablet You can change the content of the drop-down menu, as well as the rarely sued screen and tablet menus. See Chapter 5 for details.





















tailoring AutoCAD



















































chapter 2













































customizing the environment • 17

Setting and Restoring Profiles After you make changes to the Options dialog box, you can save them in an .arg file. By carrying around this file with you (perhaps on a USB memory stick), you can instantly customize AutoCAD on other computers to your preferred settings. Here’s how to save and restore the settings: 1. From the menu bar, select Tools | Options Options. In the Options dialog box, select Profiles rofiles.

2. Click Add to List dd P rofile dialog box, name the profile and provide a description. List. In the A Add Profile

Click Apply & Close Close. 3. To use a profile, select its name from under the list of Available profiles rent profiles, and then click Set Cur Current rent. 4. To export a profile, select Export Export, provide a filename, and then click Save Save. To import the profile, click Import Import, select a filename, and then click Open Open.





18













v1.0





































































































1 december 2002

Support File Paths After it is freshly installed on your computer, AutoCAD uses a number of folders in which to store support files, such as fonts, on-line help, and hatch patterns. The default settings for AutoCAD 2002 are shown at left. You may want to change the file paths for several reasons: • Your firms has clients with different standards for fonts, layer sets, and so on. • You are a third-party developer, and need to have paths pointing to different files. Here is how to change file paths: 1. From the menu bar, select Tools | Options Options. In the Options dialog box, select Files iles. 2. Select a path heading, such as Support F ile Search File Path ath. To open it, click the + icon. 3. Select a path, such as \AutoCAD 2002\fonts. Notice the buttons that become available: Browse displays the Browse for F older dialog box, Folder which lets you select a drive and folder, including those on the network.

Add adds a new path to the group. Remove removes — without warning — the selected path from the group. Move Up moves the selected path up in the list. AutoCAD searches for support files first in the topmost path. ○



















tailoring AutoCAD



















































chapter 2













































customizing the environment • 19

Move Down moves the selected path down the list. Set Cur rent sets the selected item as the current (working). Current TIP

Use the Profiles feature to save and switch between different AutoCAD settings.

Search Path Options Here is an overview of the many paths that AutoCAD searches for setting options:

Support File & Working Support File Search Paths

Specifies the path to the folders in which AutoCAD searches for support files. AutoCAD also searches the path(s) defined by the Path environment variable in the autoexec.bat file executed when Windows starts up. Device Driver File Search Path

Specifies the path to folders in which AutoCAD searches for device drivers. Device drivers are programs that interface between AutoCAD and hardware, including the graphics board, mouse, digitizing tablet, plotters, and printers. Project Files Search Path

Specifies project names, which contain search paths for externally-reference drawings; also stored in system variable rojectName. ProjectName





20













v1.0





































































































1 december 2002

Menu, Help, and Miscellaneous File Names

Specifies the names and paths for menu and help files, as well as the default URL (uniform resource locator, a.k.a. Web address). The URL is used by the Browse command. Also specifies the path to the .cfg configuration file, which stores information about the hardware used with AutoCAD. (Note that this value cannot be changed here; it can only be changed by the /c command-line switch.) ver Also, the list of client license servers (as stored in system variable AcadSer cadServer ver; also read-only). Text Editor, Dictionary, and Font File Names

Specifies the name of the text editor used by the MT MTeext command (stored in system variable MT MTeextEd xtEd). The filename of the main dictionary used for checking spelling (stored in system variable DctMain DctMain). The filename of the custom dictionary file, which holds words you add to the dictionary with the Spell command (stored in system variable DctCust DctCust). The path to an alternative font file to use when: (1) AutoCAD can’t locate the needed fonts; and (2) an alternate font was not specified in the acad.fmp font mapping file. The path to the font mapping file, acad.fmp (stored in system variable FontMap ontMap). Print File, Spooler, and Prolog Section Names

Specifies the name of .plt temporary plot files used with R14 (or earlier) plotting scripts. The name of the application to use for external plot spooling in this format: spooler.bat %s

Also specifies the path to the .ps PostScript prolog file. Printer and Plot Support Files

Specifies the path for printer support files, print spool files, and .pc3 printer configuration files, .pmp printer description files, and .stb and .ctb named and color-dependent plot style tables. Search Path for ObjectARX Applications

Specifies the path for ObjectARX application files; separate multiple paths with a semicolon. Path must be written, curiously enough, in URL format, such as: file://C:\CAD\AutoCAD 2002\Sample

Automatic Save File Location

ileP ath Specifies the path for storing automatic backup files (stored in system variable SaveF SaveFileP ilePath ath). Data Sources Location

Specifies the path to database source files, used by the database-related commands in AutoCAD. Caution: The change you make to this setting takes effect only after you close and restart AutoCAD. Drawing Template File Location

Specifies the path to the .dwt template drawings. Log File Location

ath Specifies the path to the .log log file created by the LogfileOn command (stored in system variable LogfileP ogfilePath ath). ○



















tailoring AutoCAD



















































chapter 2













































customizing the environment • 21

Temporary Drawing File Location

Specifies the path to the folder in which AutoCAD stores its temporary files, which are deleted when AutoCAD is refix exited properly (stored in system variable TempP empPrefix refix). If AutoCAD crashes, these temporary files are often left behind, and can be safely erased. Temporary External Reference File Location

oadP ath Specifies the path for temporally storing externally-referenced files (stored in system variable XL XLoadP oadPath ath). Texture Maps Search Path

Specifies the path in which texture maps are stored for rendering.





22













v1.0





































































































1 december 2002

Drafting and Selection Preferences ting and Selection tabs of the Options dialog box allow you to customize the look of autosnaps and grips. The Draf Drafting AutoSnap Settings For AutoSnap, you have the option of changing: • Toggle (turn on and off) the display of the marker, magnet, tootip, and aperture box. • Color of the marker. • Size of the AutoSnap marker, and of the aperture box.

Grips Settings For grips, you have the option of changing: • Size of the pickbox and the grip size. • Color of unselected and selected grips.





















tailoring AutoCAD



















































chapter 2













































customizing the environment • 23

Feedback I welcome your feedback for correcting and improving the text. Send your email to [email protected] . Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at www.upfrontezine.com/ebooks.





24













v1.0





































































































1 december 2002

three

command aliases t a i l o r i n g

A u t o C A D

t

he best-known way to run commands in Windows programs is from their menus and toolbars. But power users know that the keyboard is the fastest method for entering commands. Once you memorize them, shortcuts Tab, Ctrl+V that copy to the Clipboard, switch to another application, and then paste — — such as Ctrl+C, AltAlt-T let you work at top speed. AutoCAD has two facilities for creating your own shortcut keystrokes: Shif Alt Shiftt/Alt Alt-key combinations to any Ctrl/Shif • The Options dialog box’s Keyboard tab assigns function keys and Ctrl command. • The acad.pgp file lets you define aliases, which are one- and two-letter command mnemonics, such as L for the Line command, and AA for the Area command.

This chapter includes tutorials for employing both facilities in your drafting work.





















tailoring AutoCAD































































chapter 3

























command aliases











25

Table of Contents - Chapter 3 Shortcut Keys . . .27 Defining Shortcut Keys . . .28

The .pgp File: Aliases . . .29 Alias Format . . .29 Alias Rules . . .29 Aliases Defined by Autodesk . . .29

Creating a New Alias . . .31



















































































































Copyright Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○



26













v1.0





































































































1 december 2002

Shortcut Keys AutoCAD predefines a number of shortcut keys. Shortcut keys let you carry out a command by simply pressing the assigned key on the keyboard. For some users, this is faster than selecting the command from the menu, toolbar, or typing it whole at the keyboard. AutoCAD permits you to assign shortcut keys to: eys are those keys marked with the F prefix, such as F1 and F2 F2. • Function kkeys eys operate by holding down the Ctrl key, and then pressing a function, number, or alphabet key, • Control kkeys CTRL+B. such as CTRL+F2 and CTRL+B ted function kkeys eys operate by holding down the Shif • Shif Shifted Shiftt key, and then pressing a function key. eys operate by holding down both the Ctrl and Shif • Control + Shif Shiftt kkeys Shiftt keys, and then pressing a function, number, or alphabet key. eys operate by holding down both the Ctrl and Alt keys, and then pressing a number • Control + Alternate kkeys or alphabet key. eys operate by holding down the Ctrl and Alt and Shif • Control + Alternate + Shif Shiftt kkeys Shiftt keys, and then pressing a number or alphabet key. Out-of-the-box, AutoCAD defines a number of shortcut keys, as shown below. You can, of course, add and change definitions, ultimately assigning commands to as many as 188 key combinations. (Don’t worry, you won’t run out of commands to assign: AutoCAD has over 300 commands!) Only commands can be assigned, not macros (multiple commands), nor the options of commands. For exindow command-and-option. ample, you can assign the Zoom command, but not the Zoom W Window





















tailoring AutoCAD































































chapter 3

























command aliases











27

TIP

You cannot redefine these keys reserved by Windows: F1 Display help. F10 Access the menu bar. CTRL+F4 Close the current window. CTRL+F6 Change focus to the next window.

Defining Shortcut Keys t+F Here are the steps to define shortcut keys. In this tutorial, you assign the Find command to Ctrl+Shif Ctrl+Shift+F t+F: 1. From the menu bar, select Tools | Customize | K eyboard Keyboard eyboard. Notice that the Customize dialog box displays the Keyboard tab.

All of AutoCAD’s commands are categorized in three ways: • Sorted by menu order. From the Categor Categoryy list, select a menu name, such as File Menu Menu. oolbar • Sorted by toolbar order. From the Categor Categoryy list, select a toolbar name, such as Draw T Toolbar oolbar. • All commands in alphabetical order. From the Categor Categoryy list, select AutoCAD Commands Commands. 2. From the Categories list, select the Edit Menu command category. 3. From the Commands list, select Find ind, the command you wish to assign to a keystroke. 4. Click in the Press new shortcut kkey ey bo t+F boxx, and then press the key combination: Ctrl+Shif Ctrl+Shift+F t+F. 5. Click Assign t+F appears in Cur rent K eys list. Assign. Notice that Ctrl+Shif Ctrl+Shift+F Current Keys 6. Click Close to dismiss the dialog box. 7. Test the keystroke shortcut by holding down the Ctrl and Shif Shiftt keys, and then pressing F. AutoCAD should ind and R eplace dialog box. execute the Find command by displaying the F Find Replace ○



28













v1.0





































































































1 december 2002

The .pgp File: Aliases In addition to keystroke shortcuts, AutoCAD also allows you to define one- and two-letter command shortcuts, called aliases. An alias typically is an abbreviation of a command name, such as L for the Line command, and OS for OSnap (object snap). Like keyboard shortcuts, aliases work only with command names; they cannot include options. Alias Format The format for defining a command alias is simple: alias, *fullCommandName

Notice that the alias is followed by a comma, a space, an asterisk, and then the complete command name, such as: L, *LINE

Alias Rules Autodesk makes the following suggestions for creating command aliases: • An alias should reduce a command by at least two characters. • Commands with a control key equivalent, status bar button, or function key do not require an alias. Examples include the New command (already assigned to Ctrl+N Ctrl+N), Snap (already on the status line), and Help (already assigned to function key F1 F1). • Try to assign the first character of the command. If it is already taken by another command, assign the first two characters, and so on. For example, C is assigned to the Circle command, so CO is assigned to the Copy command. • For consistency, add suffixes for related aliases. For example, H is assigned to the Hatch command, so assign HE for HatchEdit HatchEdit. • Remember to use the hyphen for command-line commands. For example, -LA for the -Layer command. Aliases Defined by Autodesk

The following 247 commands are assigned to aliases by Autodesk in the acad.pgp file. You may, of course, change any of these that you wish:

-AR, ARO, ASE, ASQ, ATE, -ATE, ATT, -ATT, ATTE, AV,

3 3A, 3DO, 3F, 3P,

*3DARRAY *3DORBIT *3DFACE *3DPOLY

A A, AA, AAD, ADC, AEX, AL, ALI, AP, AR,







*ARC *AREA *DBCONNECT *ADCENTER *DBCONNECT *ALIGN *DBCONNECT *APPLOAD *ARRAY















tailoring AutoCAD





*-ARRAY *DBCONNECT *DBCONNECT *DBCONNECT *ATTEDIT *-ATTEDIT *ATTDEF *-ATTDEF *-ATTEDIT *DSVIEWER

C C, -CH, CH, CHA, CO, COL, COLOUR, CP,

D

B B, -B, BH, BO, -BO, BR,

















*CIRCLE *CHANGE *PROPERTIES *CHAMFER *COPY *COLOR *COLOR *COPY





D, DAL, DAN, DBA, DBC, DCE,

*BLOCK *-BLOCK *BHATCH *BOUNDARY *-BOUNDARY *BREAK







































chapter 3

*DIMSTYLE *DIMALIGNED *DIMANGULAR *DIMBASELINE *DBCONNECT *DIMCENTER

























command aliases











29

DCO, *DIMCONTINUE DDA, *DIMDISASSOCIATE DDATTDEF, *ATTDEF DDATTEXT, *ATTEXT DDCHPROP, *PROPERTIES DDCOLOR, *COLOR DDI, *DIMDIAMETER

G

DDLMODES, *LAYER DDLTYPE, *LINETYPE DDMODIFY, *PROPERTIES DDOSNAP, *OSNAP DDUCS, *UCS DED, *DIMEDIT DI, *DIST

H, -H, HE, HI,

G, -G, GR,

*DIVIDE *DIMLINEAR *DONUT *DIMORDINATE *DIMOVERRIDE *DRAWORDER *DIMRADIUS *DIMREASSOCIATE *DSETTINGS *DIMSTYLE *DTEXT *DVIEW

*ERASE *DDEDIT *ELLIPSE *EXTEND *QUIT *EXPORT *EXTRUDE

30

*FILLET *FILTER ○











v1.0











P, *PAN -P, *-PAN PA, *PASTESPEC PARTIALOPEN, *-PARTIALOPEN PE, *PEDIT PL, *PLINE PO, *POINT POL, *POLYGON PR, *OPTIONS PRCLOSE, *PROPERTIESCLOSE PRE, *PREVIEW PRINT, *PLOT PROPS, *PROPERTIES PS, *PSPACE PTW, *PUBLISHTOWEB PU, *PURGE -PU, *-PURGE

L, *LINE LA, *LAYER -LA, *-LAYER LE, *QLEADER LEAD, *LEADER LEN, *LENGTHEN LI, *LIST LINEWEIGHT, *LWEIGHT LO, *-LAYOUT LS, *LIST LT, *LINETYPE -LT, *-LINETYPE LTS, *LTSCALE LTYPE, *LINETYPE -LTYPE, *-LINETYPE LW, *LWEIGHT

R

M

S, SAVEURL, SC, SCR, SE, SEC, SET, SHA, SL, SN,

M, MA, ME, MI, ML, MO, MS, MT, MV,

F



P

L

E



*BHATCH *HATCH *HATCHEDIT *HIDE

I, *INSERT -I, *-INSERT IAD, *IMAGEADJUST IAT, *IMAGEATTACH ICL, *IMAGECLIP IM, *IMAGE -IM, *-IMAGE IMP, *IMPORT IN, *INTERSECT INF, *INTERFERE INSERTURL, *INSERT IO, *INSERTOBJ

DIMBASE, *DIMBASELINE DIMCONT, *DIMCONTINUE DIMDIA, *DIMDIAMETER DIMED, *DIMEDIT DIMLIN, *DIMLINEAR DIMORD, *DIMORDINATE DIMOVER, *DIMOVERRIDE DIMRAD, *DIMRADIUS DIMSTY, *DIMSTYLE DIMTED,*DIMTEDIT

F, FI,

O, *OFFSET OP, *OPTIONS OPENURL, *OPEN ORBIT, *3DORBIT OS, *OSNAP -OS, *-OSNAP

I

DIMALI, *DIMALIGNED DIMANG, *DIMANGULAR

E, ED, EL, EX, EXIT, EXP, EXT,

*GROUP *-GROUP *DDGRIPS

H

DIM

DIV, DLI, DO, DOR, DOV, DR, DRA, DRE, DS, DST, DT, DV,

O



















R, RA, RE, REA, REC, REG, REN, -REN, REV, RM, RO, RPR, RR,

S

*MOVE *MATCHPROP *MEASURE *MIRROR *MLINE *PROPERTIES *MSPACE *MTEXT *MVIEW ○

















*REDRAW *REDRAWALL *REGEN *REGENALL *RECTANGLE *REGION *RENAME *-RENAME *REVOLVE *DDRMODES *ROTATE *RPREF *RENDER



























*STRETCH *SAVE *SCALE *SCRIPT *DSETTINGS *SECTION *SETVAR *SHADE *SLICE *SNAP





























1 december 2002

SO, SP, SPE, SPL, ST, SU,

*SOLID *SPELL *SPLINEDIT *SPLINE *STYLE *SUBTRACT

U

X

UC, UCP, UN, -UN, UNI,

T

*DDUCS *DDUCSP *UNITS *-UNITS *UNION

X, XA, XB, -XB, XC, XL, XR, -XR,

V

T, -T, TA, TH, TI, TM, TO, TOL, TOR, TR,

*MTEXT *-MTEXT *TABLET *THICKNESS *TILEMODE *TILEMODE *TOOLBAR *TOLERANCE *TORUS *TRIM

V, -V, VP, -VP,

*VIEW *-VIEW *DDVPOINT *VPOINT

*EXPLODE *XATTACH *XBIND *-XBIND *XCLIP *XLINE *XREF *-XREF

Z Z,

*ZOOM

W W, -W, WE,

*WBLOCK *-WBLOCK *WEDGE

Creating a New Alias To create a new alias, or to edit existing aliases, follow these steps. For this tutorial, you add the LIN alias for the DimLinear command. 1. Using a text editor, such as Notepad, open the acad.pgp file, which is found in AutoCAD’s \support folder.





















tailoring AutoCAD































































chapter 3

























command aliases











31

2. Scroll down to the alias section, until you reach the dimensioning commands. 3. Press Enter to make room for another line of text. 4. Enter the following text: lin,* dimlinear

5. From the menu bar, select Edit | Save Save. 6. Switch back to AutoCAD, and then start the Reinit command, as follows: Command: reinit

Notice the Re-initialization dialog box. This reloads the .pgp file into AutoCAD so that the new alias becomes active.

7. Select the PGP F ile option, and then click OK File OK. AutoCAD reloads the acad.pgp file. 8. Test your change by entering “lin” at the ‘Command:’ prompt. AutoCAD should start the DimLinear command: Command: lin DIMLINEAR Specify first extension line origin or :

Notice that AutoCAD reports the full name of the command in uppercase letters, as in DIMLINEAR.

Feedback I welcome your feedback for correcting and improving the text. Send your email to [email protected] . Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at www.upfrontezine.com/ebooks.





32













v1.0





































































































1 december 2002

four

toolbar macros t a i l o r i n g

A u t o C A D

t

he easiest part of AutoCAD to customize, in my opinion, are the toolbars, which were first added to AutoCAD with the Windows version of Release 11. (Yes, there was a version of R11 for Windows, called the “AutoCAD Windows Extension,” or AWE for short, which was meant by Autodesk to be more of an experiment than a working release.) With Release 13, Autodesk significantly changed how toolbars operate, which is why this chapter includes instructions for customizing toolbars for AutoCAD before and after Release 13. Toolbar buttons give you single-click access to almost any command or group of commands. Instead of huntuct ing through AutoCAD’s maze of menus (is the Hatch command under Draw or Constr Construct uct?) or trying to recall the exact syntax of a typed command (was that Viewpoint or Vpoint) Vpoint), toolbars let you collect your most-used commands in convenient strips. Toolbars buttons operate by executing one or more commands and options, called macros. Figuring in the time it takes to write and debug the macro, my rule-of-thumb is to write a macro any time the same action is repeated more than three times.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 33

Table of Contents - Chapter 4 Customizing Toolbars . . .35 Rearranging Toolbars . . .35 Dragging Toolbars . . .35 Toggling Toolbars . . .38

Changing Toolbar Buttons . . .39 Changing Button Size . . .41 Drawing Icons . . .42

Writing Toolbar Macros . . .44 Simple Macros . . .45 Advanced Macros . . .46

Toolbar Macros Are No Panacea . . .46

Customizing the Toolbar — R11, R12, LT R1 and R2 . . .47 Looking Inside a Toolbar Macro . . .48 Title Bar

. . .48

AutoCAD LT Command . . .48 Image - Character Next & Previous

. . .49

. . .49

Delete, Cancel, & OK

. . .49

Customizing the INI File . . .50 Additional Toolbar Definitions . . .51 Dialog Box or Text Editor? . . .51

LT R1 & 2’s SetEnv Command . . .52 Customizing Macros Directly . . .52 Editing the Macro Directly . . .52

Multiple Command Toolbar Macros . . .53 Conserving with Aliases . . .53



















































































































Copyright Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○



34













v1.0





































































































1 december 2002

Customizing Toolbars There are two approaches to customizing toolbars. One is to simply rearrange the icons, perhaps creating a toolbar containing oft-used commands, or containing commands not found on the four toolbars AutoCAD displays by roperties default — Draw Draw, Edit Edit, Standard Standard, and Object P Properties roperties. The second approach is to delve into all aspects of toolbar customizing: writing macros that activate when their button is clicked, creating new icons for the buttons, and modifying the help text. In this chapter, we look at both approaches. (The first half of this chapter is for you if you are using AutoCAD Release 13 - 2000; the second half describes AutoCAD Release 11 - 12.) Rearranging Toolbars When you start a fresh copy of AutoCAD, it has four toolbars that are docked along the edges of the drawing area. “Docked” means the toolbars are attached to the edges of the drawing area. When you move or change the size of the AutoCAD window, the toolbars move along. Toolbars don’t have to be docked. They can also float. When toolbars float, they are independent of the AutoCAD window. Move or resize the AutoCAD window, and floating toolbars remain where they are. If you have a dualmonitor setup, it can be useful to have toolbars, the text window, the Properties window, and so on, on the second monitor. That maximizes the first monitor for the drawing area. Dragging Toolbars

Look closely at the end of each toolbar, and notice the double-line (shown enlarged in the figure below). These are called drag handles. By dragging the toolbar by its handle, you can move the toolbar around AutoCAD.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 35

You can relocate toolbars to other edges of the drawing area, or make the toolbars float. To move a toolbar: 1. Drag it away from the edge of the drawing area. Notice the thin, gray, rectangular outline, called the dock indicator, shown in the figure above. If you were to release the mouse button at this point, the toolbar would jump back to its docked position. 2. Drag the toolbar further, and notice that the rectangular outline changes to a thicker line. This is called the float indicator.

3. When you let go of the mouse button now, the toolbar floats. 4. With the toolbar floating, you can move the toolbar by dragging it by its title bar.

5. Additionally, you can resize the toolbar by grabbing at any of its edges. Notice the two-headed cursor; it indicates that you can resize the toolbar, making it more square or more rectangular.





36













v1.0





































































































1 december 2002

6. To dock the toolbar again, drag it by its title bar back against one edge of the drawing area. TIP Although not a toolbar, the command-prompt area can also be resized and be made to float. To resize, grab the dividing line between the prompt area and the drawing area, and drag up or down. The number of prompt lines changes from the default setting of 3.

To float, drag the prompt area at its lower right corner, as shown below. If necessary, hold down the Ctrl key to prevent docking.

Once floating, you can move the prompt window by its title bar, and resize it by its edges — just like a toolbar.

To dock, drag the prompt area back into place.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 37

Toggling Toolbars

Toolbars can be turned off and on: 1. Right-click any toolbar. Notice the shortcut menu that lists the names of all the toolbars. The check mark means the toolbar is turned on.

2. To turn on a toolbar, select its name from the shortcut menu. Notice that the toolbar appears, and the menu disappears. To turn on other toolbars, repeat steps 1 and 2. 3. To turn off a toolbar, repeat steps 1 and 2, but select a toolbar name with a check mark. When a toolbar is floating, you turn it off by clicking the x in the upper right corner.

TIP To turn on (or off) all toolbars at once, use the undocumented -Toolbar command, as follows: Command: -toolbar Enter toolbar name or [ALL]: all Enter an option [Show/Hide]: s This command also turns on and off individual toolbars, which can be of use in a macro or AutoLISP routine.





38













v1.0





































































































1 december 2002

Changing Toolbar Buttons You can create a new toolbar with the buttons (commands) to your liking. Here is how to create such a toolbar: 1. Right-click any toolbar. From the context menu, select Customize Customize. (If no toolbar is visible, from the menu oolbars select Tools | Customize | T Toolbars oolbars.) 2. In the Toolbars tab, click New to create a new toolbar. Notice the New T oolbar dialog box. Toolbar

3. In the New T oolbar dialog box, enter a name for your toolbar, such as “My Toolbar.” Toolbar Click OK OK.

It’s easy to miss, but AutoCAD creates a new, empty toolbar. It’s just a tiny thing, and you may have to hunt around the screen to find it. 4. Now it’s time to populate the empty toolbar with buttons. In the Customize dialog box, select the ComFile mands tab. Notice that AutoCAD’s commands are presented in two ways: categorized by function (F ile, Edit Edit, and so on), and alphabetical (scroll down to find All Commands Commands).





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 39

5. From the Command list, drag command names into the new toolbar. As you do, notice the buttons appearing. The I-beam cursor helps you position the button in the toolbar.

6. To remove a button from the toolbar, simply drag it out of the toolbar. AutoCAD asks, “Are you sure you want to delete the button from the toolbar?” Answer in the affirmative, Yes. TIP While the Customize dialog box is open, all toolbars are customizable — not just the one you created. This means you can add and remove buttons from the other toolbars, such as Draw, Standard, and so on.

7. When done, click Close to dismiss the Customize dialog box. Your new toolbar acts just like the any other toolbar in AutoCAD. There is no need to “save” the new toolbar; it is saved automatically by AutoCAD, and will appear the next time you start AutoCAD.





40













v1.0





































































































1 december 2002

Changing Button Size

The buttons on toolbars are 16 pixels in size. In some cases, that may be too small if your eyesight isn’t as strong as that of user-interface designers. You can make the buttons 50% larger, as follows: 1. Open the Customize dialog box, and select the Toolbars tab. 2. Select Large Buttons Buttons. Notice that the buttons immediately grow larger.

3. If you like the size, click Close to dismiss the dialog box. If you don’t, uncheck the Large buttons option, and close the dialog box.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 41

Drawing Icons

You may have noticed that some command-buttons lack icons, as shown below. AutoCAD has a built-in icon editor that lets you modify existing icons and create new ones.

1. Bring back the Customize dialog box by right-clicking the toolbar and selecting Customize Customize. (The only purpose for this dialog box is to enter toolbar-customization mode; we don’t actually use the dialog box in this tutorial.) 2. Right-click the blank button, and select Edit Button Image Image.

Notice the Button Editor Editor.

The Button Editor provides a number of tools and functions: • The four tools along the top are for drawing freehand, lines, ellipses (and circles), and erasing (changes colors back to neutral gray). There is, unfortunately, no floodfill tool. • The small square on the left shows you a preview of the icon in real-size. • The colored squares on the right are the 16 standard Windows colors for drawing icons. You are limited to 16 colors to ensure the icons look correct with any depth of color display. • The large gray square in the center is where you draw the icon. ○



42













v1.0





































































































1 december 2002

Grid toggles the display of grid lines to assist your drawing; I recommend turning on the gird. Clear erases the drawing from the button. Open opens a .bmp file, which must be 16x16 pixels in size. Undo undoes the last drawing step; it is a single undo, and there is no redo. Save As saves the icon as a .bmp (Windows bitmap) file. Save saves the icon to the toolbar. Close closes the button editor.

• • • • • • •

3. Draw the icon.

4. When satisfied with your artistic endeavor, click Save Save, and then click Close Close. Notice that the toolbar’s formerly blank button is now adorned with your artwork.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 43

Writing Toolbar Macros In addition to creating custom toolbars and icons, you can also change the command(s) that lie behind each button. When you click a toolbar button, AutoCAD executes the macro (collection of commands) assigned to the button. In this tutorial, you assign a macro to the button with the custom icon created earlier. 1. Bring back the Customize dialog box by right-clicking the toolbar and selecting Customize Customize. 2. Select a button on any toolbar. Notice that the Customize dialog box switches to the Button P roperties tab. Properties

roperties tab has several areas that correspond to AutoCAD’s user interface: The Button P Properties • Name is the text displayed by the button’s tooltip. This is a brief description of the button’s function. • Description is the text displayed on the status line. This is a longer description of the button’s function. • Macro associated with this button is the collection of commands executed by clicking the button. The figure above shows quite a complex macro; most macros consist simply of the command’s name, such as: ^C^C_open

Button Image is an enlarged view of the button’s icon. Edit brings up the Icon Editor Editor, described earlier, so that you can edit the icon. Apply applies the changes you made to the button. Reset changes the button’s properties back to when you first began.

• • • •





44













v1.0





































































































1 december 2002

3. And below the Edit button is a collection of icons, which you can borrow for use with the button. Select an icon, and then click Apply to see the icon on the button. Simple Macros

A simple macro consists an AutoCAD command, prefixed by some unusual-looking characters: ^C^C_open

The characters have the following meaning: ^C is a control character. It imitates pressing Esc on the keyboard, which cancels the command currently in progress. The carat ( ^ ) alerts AutoCAD that this is a control character, and not a command. What does C have to do with the Esc key? In versions of AutoCAD older than Release 13, you pressed Ctrl+C to cancel a command; the C was short for “cancel.” (Going back even further in history, Ctrl+C comes from ASCII code 003, which meant ETX — end-transmission — in the days of telegraphs and teletypes. More than a hundred years later, these ASCII codes are still used today, because early computers used teletype terminals to communicate with humans, and some things never change. This leads to some clashes: ever since Release 13, Ctrl+C means “copy to Clipboard” but continues to mean “cancel” in macros only, for compatibility reasons. TIP

1

AutoCAD recognizes these control characters in toolbar macros: ^A Toggles group mode, like pressing Ctrl+A1. ^B Toggles snap mode between on and off, like Ctrl+B. ^C Cancels current command, like pressing Esc. ^D Changes coordinate display mode, like Ctrl+D. ^E Switches to next isometric plane, like Ctrl+E. ^G Toggles grid display, like Ctrl+G. ^H Backspaces, like Ctrl+H. ^I Same as pressing Tab. ^M Same as pressing Enter. $M= Allows use of Diesel expressions; see chapter 10. ^O Toggles ortho mode, like Ctrl+O. ^P Toggles MenuEcho system variable. ^V Switches to next viewport, like Ctrl+V. ^U Toggle polar mode, like Ctrl+U1. ^W Toggle object snap tracking, like Ctrl+W1. ^X Deletes, like Del1. ^Z Suppresses automatic Enter at the end of a macro.

Not documented by Autodesk.

^C^C Most macros start with two ^C because some AutoCAD commands are two levels deep. I PEdit, are three levels deep. recommend three of ’em — ^C^C^C — because some commands, like PEdit When the command is transparent (starts with the ' apostrophe), then you don’t prefix the macro with the Cancel character. _ The underscore is an AutoCAD convention internationalizing the command. Prefixing command and option names with the underscore ensures the English-language version of the command always works, whether used with German, Japanese, or Spanish versions of AutoCAD. open is the command name. In macros, you type AutoCAD commands and their options exactly the way you would type them on the keyboard at the ‘Command:’ prompt. That means you can, for instance, use aliases instead of the full command name; this is discouraged, however, because aliases can be changed, leading to a non-operational macro. ○



















tailoring AutoCAD























































































chapter 4 toolbar macros









• 45

Nothing is needed at the end of the macro to terminate it. AutoCAD automatically does the “pressing Enter Enter” for you. If you need to suppress the automatic Enter for some reason, hang a ^Z at the end of the macro, like this: ^C^Copen^z

Advanced Macros

You may string together more than one command in a toolbar macro. In addition, you can include Diesel expressions and AutoLISP routines (see chapters 10 and 11 for details). For example, Autodesk wrote the following macro for the RefSet button: $M=$(if,$(eq,$(getvar,refeditname),""), ^C^C^P(ai_refedit_alert); ^P,$(if,$(and,$(=,$(getvar, tilemode),0),$(=,$(getvar,cvport),1)),^C^C_refset;,^C^C_refset _add;))^Z

Yikes! Ugly, isn’t it? I’ve parsed the code in colors to make so that you can see the structure: Red Cyan Black

Macro control characters. AutoCAD commands, AutoLISP functions, and system variables. Diesel expressions. $M= $(if, $(eq, $(getvar,refeditname), ""), ^C^C^P(ai_refedit_alert);^P, $(if, $(and, $(=, $(getvar,tilemode), 0), $(=, $(getvar,cvport), 1) ), ^C^C_refset;,^C^C_refset _add; ) ) ^Z

Start of Diesel expression: If equal value of RefEditName system variable to empty then execute the (ai_refedit_alert) AutoLISP function. Otherwise, if and equal value of system variable TileMode 0 (model space) and value of system variable CvPort 1 (no viewports) then execute RefSet command or RefSet Add command. Suppress Enter at end of Diesel expression.

Toolbar Macros Are No Panacea Toolbar macros are best suited for quick’n dirty programming. There are drawbacks, however, to using toolbar and toolbox macros. The length of the macro is limited to a maximum of 79 or 255 characters, depending on the version of AutoCAD. The variety of options for writing creative macros is limited compared with AutoCAD’s programming languages. Despite these drawbacks, the toolbar is the fastest and most convenient way to minimize keystrokes and mouse clicks in AutoCAD.





46













v1.0





































































































1 december 2002

Customizing the Toolbar — R11, R12, LT R1 and R2 This tutorial is for the toolbar (yes, there was just one) found in the Windows versions of Release 11, Release 12, and the first two releases of LT. Before looking at how early releases of AutoCAD let you customize the toolbar buttons, let’s try using them: 1. Start AutoCAD for Windows, either Release 11, 12, or LT R1 or R2. 2. When AutoCAD appears, there are three rows above the drawing area. From top to bottom, these are (1) the title bar; (2) the menu bar; and (3) the toolbar. The toolbar replaces the status line of DOS-based AutoCAD. From left to right, it displays: Color Layer Layer name O, S, P Coordinates

Changes the current color. Displays the layer dialogue box. Selects a layer. Toggles orthographic, snap, and paper space modes. Toggles coordinate display between on, relative, and off.

The remaining toolbar buttons are the focus of this chapter. Many have been pre-programmed by Autodesk to perform specific functions, but you may change the meaning of any of them. These older releases of AutoCAD support a maximum of 26 buttons on the toolbar. The number of buttons visible depends, however, on your monitor’s resolution, the size of the AutoCAD window, and the size of the button themselves. The figure above displays 17 buttons. 3. Move the cursor over any toolbar button, and then press the mouse’s left button. For example, when you click on the first button (looks like a six-pane window), AutoCAD moves the position of the toolbox. Each time you click, AutoCAD executes the Toolbo oolboxx command, which moves the toolbox from docked to one side, to floating, to invisible. ○



















tailoring AutoCAD























































































chapter 4 toolbar macros









• 47

Looking Inside a Toolbar Macro Now that you’ve seen how the toolbar works, dive right in to looking at how AutoCAD customizes that row of buttons on the toolbar. 1. If you haven’t already, start AutoCAD for Windows. 2. Move the cursor up to the toolbar, then over any of the square buttons to the right of the coordinate display (see figure on previous page). 3. Click the mouse’s right mouse button. 4. The right-click action brings up a dialog box named Toolbar Button Customization Customization. This single dialog box controls every aspect of the toolbar (well, almost: later, I’ll show you how to bypass the dialog box). Take a look at the dialog box in detail: Title Bar

At the top, the dialog box’s title bar lists the button number being customized. The figure shows looking at the dialog box for Button 1.

AutoCAD LT Command

At the bottom of the dialog box is the macro attached to the toolbar button. When you click the toolbar button, AutoCAD executes the macro string typed here: \3\3_TOOLBOX

The macro consists of three control characters, and one AutoCAD command. They have the following meaning: \3 This is called a control character. It imitates pressing Ctrl C on the keyboard, which cancels the command Ctrl+C currently in progress. The number “3” comes from C being the third letter of the alphabet. The backslash ( \ ) alerts AutoCAD that this is a control character, and not a command. TIP

1

AutoCAD recognizes these control characters: \2 Toggles snap mode between on and off, like pressing Ctrl+B. \3 Cancels current command, like Ctrl+C. \4 Changes coordinate display mode, like Ctrl+D. \5 Switches to next isometric plane, like Ctrl+E. \7 Toggles grid display, like Ctrl+G. \8 Backspaces, like Ctrl+H1. \15 Toggles ortho mode, like Ctrl+O1. \22 Switches to next viewport, like Ctrl+V1. \n Starts a new line of text. \t Tab; has same effect as space1. \nnn Allows use of ASCII character nnn1. \\ Allows use of the \ character.

These control characters were not documented by Autodesk.

\3\3 Most macros start with two \3 since many AutoCAD commands are two levels deep. I recommend starting macros with \3\3\3 because some commands, like PEdit PEdit, are three levels deep. If the command is transparent (starts with the ' apostrophe), then you don’t prefix the macro with the Cancel character. ○



48













v1.0





































































































1 december 2002

_ The underscore is an AutoCAD convention that “internationalizes” the command. Whether you are using German, Spanish, or Japanese versions of AutoCAD, prefixing the command name with the underscore ensures the English-language version of the macro will always work. TOOLB OX Finally, we arrive at the command name! In macros, you type AutoCAD commands and their TOOLBO options exactly the way you would type them on the keyboard at the ‘Command:’ prompt. OX. The space is the equivalent of (Space) It is barely visible in the figure, but there is a space after TOOLB TOOLBO pressing the Enter or Spacebar key. AutoCAD automatically adds the space because every command is executed by pressing the Enter key. To suppress the automatic space, add a semicolon ( ; ). Image - Character

You have the choice of labelling the toolbar button with an “image” or a “character.” The image is one of 81 icons that you can select from the Select Image list (and previewed in the center of the dialog box). The character is simply a letter of the alphabet from A through Z. If you don’t select an icon, AutoCAD uses the first character of the macro. In this example, that would be the \ backslash. Next & Previous

xt and Previous buttons is a convenient way to edit the macros associated with the next (or Clicking the Ne Next previous) buttons on the toolbar. Delete, Cancel, & OK

The Delete button erases the macro from the button. You can leave the button blank or type in a new macro. The Cancel button cancels any changes you made to the button, and dismisses the dialog box. Clicking the OK button saves the changes to file acad.ini (aclt.ini if you are working with AutoCAD LT), and then dismisses the dialog box. TIP How to add a pause to toolbar macro, thanks to Richard L. Woodcock. The backslash ( \ ) forces the macro to pause for user input in example macro: ^C^C-layer;m;\c;\;L;\;s;\; The macro initiates the -Layer command (command-line version), selects the Make option, pauses for user input for the layer name to be assigned, selects the Color option, pauses for user input for the color name or number to be assigned, selects the Ltype option, pauses for user input for the linetype name to be assigned, selects the Set option, pauses for user input for the name of the layer to be set current, and completes the command.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 49

Customizing the INI File AutoCAD stores its toolbar macros in the acad.ini initialization file (aclt.ini if you are working with AutoCAD LT). You’ll find the file in the same folder as the AutoCAD executable (acad.exe or aclt.exe). The .ini files are commonly used by older Windows applications to store program settings between sessions; even Windows uses several .ini files for its purposes. Since .ini files are in ASCII format, you can use the Notepad text editor to look at them.

The figure shows the first part of aclt.ini from AutoCAD LT. Each .ini file looks slightly different, depending on the settings in effect. The file is often divided into sections. Section titles are in square brackets, such as [AutoCAD LT General]. Toolbar definitions look like this example: ToolBar1=\3\3_TOOLBOX ^88^

Let’s pick apart this mishmash, bit by bit, to see what it means. When AutoCAD starts, it reads the .ini file. Toolbar1= means this is Whatever is behind the equals sign in Toolbar1= is stuck onto the first toolbar button. (T the first toolbar button. The second toolbar button is defined by Toolbar2= oolbar2=, and so on.) C twice. That ensures From the previous section, we know that \3\3 are two Cancels in row like pressing Ctrl Ctrl+C that any command in progress is cancelled before executing the macro. OX is the command that toggles the display of the toolbox. Recall that the underscore ( _ ) _TOOLBO The _TOOLB internationalizes any English-language AutoCAD command. The command can be typed in UPPERCASE or lowercase — it doesn’t matter. There is a space after the command, which AutoCAD automatically appends to the macro: this acts like pressing the Enter key at the end of a command.





50













v1.0





































































































1 december 2002

At first glance, the suffix ^88^ seems mysterious. It turns out to be an awkward method of specifying the icon displayed by the toolbar button. Number 88 happens to be the 88th bitmap stored by AutoCAD LT . The ^^ carets (^^ ^^) tell AutoCAD that the 88 refers to the icon, and is not part of the macro. How do you know which icon number correspond with which icon number? Not very easily, I’m afraid. Recall that the Toolbar Button Customization dialog box presented a list of 91 icons. Those images were listed in alphabetical order and, by no coincidence, also in numerical order. The toolbox icon is the 88th icon in the list. Thus, if you want to a specific icon image, you’ll need to count along the list to determine its number. Additional Toolbar Definitions

Let's look at a couple of other toolbar definitions: ToolBar9='_DDLMODES ^56^

Here, button #9 starts with an apostrophe ( ' ), which makes transparent the DdLModes command (display layer dialog box). By clicking this button during another command, you can display the Layer Control dialog box. The icon image is the 56th one. ToolBar13=

This 13th button is undefined since there is nothing behind the equal ( = ) sign. When you click the 13th button, nothing happens. As well, the button itself is blank. Dialog Box or Text Editor?

You’ve seen toolbar macros from two approaches. In the previous section, you saw how to write macros with the Toolbar Customization dialog box within AutoCAD. In this section, you saw how to change macros via the Acad.Ini (or AcLt.Ini) file with the Notepad text editor. Which approach is better? The dialog box is better when creating one or two macros on-the-fly. Accessing the .ini file directly is better when customizing all 26 toolbar buttons at once or with a program external to AutoCAD.





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 51

LT R1 & 2’s SetEnv Command AutoCAD LT has an advantage over full-strength AutoCAD with a unique command: SetEnv lets you directly create and manipulate values in the .ini file. The command is under-documented, meaning Autodesk doesn’t really explain what it does. Let’s jump right in, and try it out. 1. When you type SetEnv SetEnv, LT prompts you for the variable name: Command: setenv Variable name: toolbarsize

2. Enter ToolBarSize to specify the parameter in aclt.ini that determines the size of the toolbar icons. It’s not well known, but you can change the size of the icons displayed by AutoCAD LT. 3. After you enter the name of the variable, such as toolbarsize, LT prompts you for the new value: Value : 24

If the variable exists, LT returns the value in angle brackets, such as . By default, the value of ToolBarSize is 16, measured in pixels. You can reduce the value down to 6 to display more buttons but very tiny icons. Or you can increase the value up to 32 to display very large but fewer buttons. 4. Type the new value and press Enter Enter. AutoCAD records the new value in its .ini file. Note that the new icon size do not come into effect until AutoCAD starts again. Customizing Macros Directly

Another trick is to directly customize buttons of the toolbar. The process works using SetEnv like this: Command: setenv Variable name: toolbar13 Value: ^C^C_bmake^9^

Here we assign the BMak BMakee command (short for block make; displays the Block Definition dialog box) to toolbar button #13 and use icon #9, the Block icon. In the AcLt.Ini file, this appears as: ToolBar13=^C^C_bmake^9^

Editing the Macro Directly

When you want to change the macro, SetEnv helpfully displays the current setting, as follows: Command: setenv Variable name: toolbar13 Value : ^C^C_block^9^

Despite the SetEnv command’s unique availability in LT, I have found it has numerous drawbacks, which Autodesk failed to address in LT Release 2: • SetEnv cannot cope with spaces. The first space you type ends the command, and returns you to the ‘Command:’ prompt. • SetEnv cannot access .ini items beyond in the first section, [AutoCAD LT General]. It cannot access .ini items in later sections, such as [AutoCAD LT ToolBox]. • SetEnv cannot check the syntax. When you type an incorrect variable name, such as ToolBat39=junk, SetEnv faithfully records it at the end of the [AutoCAD LT General] section. ○



52













v1.0





































































































1 december 2002

Multiple Command Toolbar Macros We have seen three approaches to customizing toolbar macros for the early releases of AutoCAD for Windows. Admittedly, some of those you’ve been exposed here are esoteric, but may be useful in certain situations. Let’s now move on to writing a complex macro. Until now, we worked with single-command macros. A toolbar macro can have any number of commands and options, with this limitation: a maximum of 79 characters in AutoCAD R11 and R12, or 255 characters in AutoCAD LT Release 1 and 2. With these limitations in mind, here is a three-command macro that I wrote when I needed to plot a large number of drawings. A client provided me with several hundred small drawings that she needed plotted on a laser printer. I found that loading each drawing with the File | Open command became tedious quickly. Then I remembered that AutoCAD for Windows supports drag’n drop. That meant I could select a drawing filename in the Windows File Manager, and then drag the filename into the AutoCAD window. The drag’n drop approach doesn’t actually open the file; instead, AutoCAD inserts the file as a block. Since I only needed AutoCAD for plotting, I didn’t care that it was a block, nor did I need to explode it. The Insert command, which is activated by the drag’n drop, imposes itself on you, however: it wants to know the insertion point, x- and y-scales, and rotation angle – the usual stuff that gets in the way. That, too, became too tedious. At that point, I wrote the following toolbar macro: 0,0 1 1 0 zoom e plot

This macro automates the following steps: 0,0 110

Inserts the block at the origin (0,0). Notice that macros can start in the middle of a command. Specifies the x- and y-scales of 1.0 and a rotation angle of 0 degrees. Since these are the default values, I could have written the macro with spaces, but spaces make macros harder to read and debug. zoom e Performs a zoom extents so that I see the entire drawing. plot Starts the Plot command. A single mouse click executes all three commands (representing 22 keystrokes or six menu picks) faster than I could ever hope to type at the keyboard, or select them from the menus. I would have liked to have continued the macro to automate the rest of the plot, but AutoCAD cannot do that in dialog boxes. I could have reverted to the command-line version of the -Plot command, but I needed to do a windowed plot by picking two points on the screen. Conserving with Aliases

Here is another macro. This one places a D-size (24" x 36") drawing border some 0.1 units wide using the PLine command: \3\3_pline 0,0 width 0.1 0.1 36,0 36,24 0,24 close _zoom e

If you run up against the 79- (or 255-) character limits, you can conserve characters with aliases. By employing aliases, the above macro is shortened by 15 characters to: \3\3 _L 0,0 w 0.1 0.1 36,0 36,24 0,24 c _z e





















tailoring AutoCAD























































































chapter 4 toolbar macros









• 53

Feedback I welcome your feedback for correcting and improving the text. Send your email to [email protected] . Visit the Tailoring AutoCAD e-book Web site at www.upfrontezine.com/tailor. For other CAD e-books, visit the eBooks.onLine Web site at www.upfrontezine.com/ebooks.





54













v1.0





































































































1 december 2002

five

menu macros

t a i l o r i n g

A u t o C A D

t

o customize the menu bar, you work with AutoCAD’s .mnu (menu) files. In a curious twist, the .mnu file controls far more than just the contents of the menu bar. It also defines all toolbars, “accelerator” keys (keyboard shortcuts), image tiles (an old form of dialog box), tablet overlays (used with digitizing tablets), and the rarely seen screen menu. In this chapter, you learn how to customize the menu bar only. Because, as it turns out, AutoCAD provides a much easier customizing environment for toolbars and accelerator keys (see chapters 4 and 3, respectively). As for the image tiles, tablet overlays, and screen menu, you’ll find the answer to why I ignore them on the last page of this chapter.





















tailoring AutoCAD





































































chapter 5



















menu macros











55

Table of Contents - Chapter 5 Loading (and Unloading) Menu Files . . .57 Loading Menu Groups . . .57 Loading Menu Bar Items . . .58 Menu File Types . . .58

My First Menu . . .59 A Single-Command Menu . . .59 Section Labels

. . .63

Menu Metacharacters . . .64 Shortcut Menu Aliases . . .66

My Second Menu . . .67 Loading .mnu a Second Time . . .67 Adding More Menu Macros . . .67 Adding Options to Commands . . .68 Using Coordinates in Macros . . .68

Making Macros “Official” . . .70 Cancelling a Previous Command: ^C . . .70 Adding Keyboard Shortcuts: & . . .70 Separating Macros Visually: -- . . .71 Adding Submenus: -> . . .71 Right-Justified Text: \t . . .72 Grayed-out Item: ~ . . .72 Adding a Checkmark: !. . . .72

Waiting for User Input: \ . . .73 Providing Input to the User: ^H . . .73

Writing Really Long Macros: + . . .74 Repeating a Command . . .74

Toolbars, Accelerator Keys, Image Tiles, Tablet Overlays, and the Screen Menu . . .75 Toolbar Customization . . .75 Custom Shortcut Keys . . .75 Image Tiles . . .75 Tablet Menus . . .75 Screen Menu . . .75



















































































































Copyright Information This book is covered by copyright. As the owner of the copyright, upFront.eZine Publishing, Ltd. does not give you permission to make electronic or print copies. You may not claim authorship or ownership of the text or figures herein. Copyright © 2002 by upFront.eZine Publishing, Ltd. All rights reserved worldwide. ○



56













v1.0





































































































1 december 2002

Loading (and Unloading) Menu Files When you look at the menu bar, you see a number of labels, such as File ile, Edit Edit, and Tools ools. Each of these is called a partial menu (a.k.a. menu group). AutoCAD has a clever system for loading and unloading partial menus will, ile | Exit with one exception: you cannot remove portions of partial menus defined by Windows, such as the F File item. oad command. The related MenuUnload command is To load and unload partial menus, you use the MenuL MenuLoad identical, and the purpose for its existence is not clear to me. Both commands display the same dialog box, with these two tabs:

The Menu Groups tab loads and unloads partial menus; the Menu Bar tab determines the display order of menu titles. Notice the correlation of items under Menu Bar (at the far right) with the menu bar displayed by AutoCAD:

TIP

AutoCAD remembers a maximum of 24 partial menus.

Loading Menu Groups The Menu Groups tab loads menu and partial menu files: • Click the Browse button to locate .mnu, .mns, and .mnc files. • The Replace All option should only be used if you are sure you want to erase the existing menu system and replace it with a new one. The Menu Groups list shows the menu groups loaded into your AutoCAD session. The figure above lists: • ACAD is the standard menu provided with AutoCAD. • ACCOV is a promotional menu for CAD Overlay; shows up as the Image item on the menu bar. UEBEAM is a third-party menu item. • BL BLUEBEAM To remove a menu group, select it and click the Unload button. You can always reload the menu group with the Browse button. ○



















tailoring AutoCAD





































































chapter 5



















menu macros











57

Loading Menu Bar Items The Menu Bar tab lets you control which partial menus appear on the menu bar. Under Menus Menus, you see all titles associated with a specific menu group. For example, the ACCOV menu group contains the Image menu title. In the list under Menu Bar Bar, you see the title that appear on the menu bar currently. You probably see titles such as File ile, Edit Edit, and so on. To add and remove titles to and from the menu bar, click the Insert and Remove buttons. If the Insert button is grayed out, it means that all the titles of a menu group are already on the menu bar. TIP To load an entire menu system at once, use the Menu command. It prompts you to select an .mnu, .mnc or .mns file.

Menu File Types

AutoCAD uses a number of files for its menu system, some of which you can access, while others are hands-off because they are generated by AutoCAD: File type

Meaning

User Accessible MNU MNL Hands Off MNC MNR MNS MNT

Primary menu file. Contains the AutoLISP functions used by the menu. Compiled menu file defines the menu’s functions and appearance. Menu resource file contains the menu’s bitmaps. Source menu file generated by AutoCAD. Menu resource file generated when the .mnr file is unavailable.

You write new menus with a text editor, such as Notepad, and then save the file with the .mnu extension. When you load the menu into AutoCAD, AutoCAD compiles the file. A compiled menu loads and displays faster.





58













v1.0





































































































1 december 2002

My First Menu Writing a menu is simple — or it can be complex. To view a complex menu, open acad.mnu in a word processor. You typically create a custom menu to easily make available commands and functions that you (or someone else) has written. We’ll work our way through the steps of creating a single-command menu. Later, we add features. A Single-Command Menu Menus are written with a text editor, such as Notepad.

1. Open Notepad, and enter the following lines of text: ***MENUGROUP=MyFirstMenu ***POP ID_mnuTailoring [Tailoring] [Rectangle]rectang;

This is pretty much the minimum needed for placing a command on AutoCAD’s menu bar. The characters shown in boldface are macro syntax (required parts of the menu so that AutoCAD understands what’s going on). The regular text is your stuff, which you are free to change. Let’s take a look at what those lines of text mean. The following figure illustrates the connection between the menu file and AutoCAD’s menu bar:

In the figure above, the text shown in black appears on the menu bar, while the text in periwinkle color is hidden from view. Getting into the details, here’s what it means: ***MENUGROUP=MyFirstMenu

The ***MenuGroup tag identifies the menu by name. This helps distinguish your menu from others written by Autodesk and third-party developers. You can give it any name you like; we’ll use “MyFirstMenu.”





















tailoring AutoCAD





































































chapter 5



















menu macros











59

***POP

The ***POP section label specifies that the macros following the title (as noted next) should be placed on the menu bar. Contrary to Autodesk documentation, you don’t need a number behind ***POP, unless you create more than one pop-down menu. When you leave out ***POP, the macros won’t show up — anywhere. (In older releases of AutoCAD, the macros would show up on the screen menu.) If you want the macro to operate elsewhere, use a different section label, such as ***BUTTONS1 for mouse buttons. ID_mnuTailoring [Tailoring]

This gives a name to the menu title — the word that appears on the menu bar. The “Tailoring” text following ID_mnu identifies the menu item, while the text in the square brackets — in this case, the word [Tailoring] — appears on the menu bar. [Rectangle]rectang;

And now, finally, the command! (Again, the [Rectangle] text in square brackets appears in the menu.) This macro executes the Rectang command. The semi-colon ( ; ) terminates the macro, just like pressing Enter at the keyboard. 2. Save the macro in an .mnu file: • From the menu bar, select File | Save As As. Notice the Save As dialog box. • In the Save As dialog box, select the \AutoCAD\Support folder. • Specify the file name of mymacro.mnu. • Click Save.

3. Switch over to AutoCAD, and load your new menu file: • From the menu bar, select Tools | Customize | Menus (or, at the ‘Command:’ prompt, enter menuload menuload.) Notice the Menu Customization dialog box. If necessary, click the Menu Groups tab. ile dialog box. • Click Browse Browse. Notice the Select Menu F File • From the Files of type drop list, select Menu Template (*.mnu). (If necessary, change Look in to \AutoCAD\Support.) • Select mymacro.mnu, and then click Open Open.





60













v1.0





































































































1 december 2002

• Back in the Menu Customization dialog box, click Load oad.

Notice that AutoCAD warns you needlessly:

(The warning is needless because your menu was not previously loaded; it can’t be overwritten.) Click Yes es. In the command prompt area, AutoCAD reports, “Menu loaded successfully. MENUGROUP: MyFirstMenu.” 4. Your new menu is loaded into AutoCAD, but it has not yet been “applied.” If you were to click Close Close, it would not appear anywhere. Here’s how to make it appear: • In the Menu Customization dialog box, click the Menu Bar tab. irstMenu • In the Menu Group droplist, select MyF MyFirstMenu irstMenu. Notice that Tailoring appears under the Menu list.





















tailoring AutoCAD





































































chapter 5



















menu macros











61

• Click Insert Insert. Notice that Tailoring now appears under the Menu Bar list. Look at the menu bar: you should also see Tailoring there, probably located before File ile.

• Click Close Close. 5. Finally, it is time to test the new menu: • On the menu bar, click Tailoring ailoring. Notice that the Rectangle item appears below. • Select Rectangle ectangle. In the command prompt area, notice that AutoCAD starts the Rectang command.

Congratulations! You’ve written your first custom menu file. Before continuing with more customization, I’ll list some of the macro conventions, including section labels, metacharacters, and shortcut aliases.





62













v1.0





































































































1 december 2002

Section Labels Section labels segregate the menu file into major sections and associated subsections. An AutoCAD menu file can have any, all, or none of these sections:









Section Label

Meaning

***MENUGROUP=name ***BUTTONSn ***BUTTONS1 ***BUTTONS2 ***BUTTONS3 ***BUTTONS4 ***AUXn ***AUX1 ***AUX2 ***AUX3 ***AUX4 ***POPn ***POP0 ***POP1-499 ***POP500-999 ***TOOLBARS **name ***IMAGE ***SCREEN ***TABLETn **TABLET1 **TABLET2 **TABLET3 **TABLET4 ***HELPSTRINGS ***ACCELERATORS

Menu’s group name. Pointing device buttons: Buttons. Shift+button. Ctrl+button. Shift+Ctrl+button. Additional pointing device button: Button. Shift+button. Ctrl+button. Shift+Ctrl+button. Pull-down menus: Default object-snap shortcut menu. Menu bar items. Shortcut menu items. Toolbars section: Toolbar name. Image menus (palettes). Screen menu. Tablet menu areas: Top area. Left area. Right area. Bottom area. Help text displayed on the status bar. Accelerator keys.













tailoring AutoCAD





































































chapter 5



















menu macros











63

Menu Metacharacters AutoCAD menus use special characters to indicate actions equivalent to pressing keys on the keyboard. (These special characters are sometimes called metacharacters.) For example, after you enter a command at the keyboard, you press Enter Enter; in a menu, you use the semicolon ( ; ) to represent the Enter key. Similarly, the carat ( ^ ) is represents the Ctrl key; there is no metacharacter for the Alt key. Here is a list of menu metacharacters acceptable to AutoCAD:





64







Character

Meaning

Menu Controls $ =* $I= $M=$(

Loads menu sections. Returns to top-level menu. Displays an image menu. Starts a DIESEL macro.

$Pn= $Pn=$Pn=*

Swaps menu items at position n. Removes menu item n. Restores menu item n (after swapping or removing).







v1.0





































































































1 december 2002

Pn.i=?

Returns the disabled and marked status of menu item n in a string: "~" Item is disabled. "!." Item has check mark. "" Item is neither disabled or check-marked.

Command Prefixes ’ Indicates transparent command. _ Translates AutoCAD commands and options as English. *^C^C Repeats the macro until you press the Esc key. ^C^C^C Cancels the current command before starting macro. [ ] Provides a label for the macro. Command Postfixes ; Equivalent to pressing Enter or the spacebar; you can also use ^M. space Equivalent to pressing the spacebar; can be used within macros to separate commands from options, but ; is preferred. \ Wait for input from user (cannot be used in the ***Accelerators section). + Macro continues on the next line (when the last character). Labels [--] [->label] [Erase] [Erase &Last]^C^C^C_erase l;;

Notice how AutoCAD generates the submenu:

When you have additional parent menu items beyond the submenu, you indicate the end of the submenu with the [ height 96)

If

greater than floor-to-ceiling distance 8 feet; Then use 14 steps. Else use 13 steps.

(setq sets 14) (setq steps 13)

)

String and Conversion Functions You can manipulate strings (one or more characters) in AutoLISP but to a lesser extent than numbers. For example, you can find the length of a string as follows: Command: (strlen "AutoCAD World") 13

en (short for STRing LENgth) function tells you that “AutoCAD World” has 13 characters in it, countThe StrL StrLen ing the space. Notice how “AutoCAD World” is surrounded by quote marks. That tells AutoLISP you are workutoCAD W orld) ing with a string, not a variable. If you type (strlen A AutoCAD World) orld), AutoLISP tries to find the length of the strings held by variables Autocad and World. For example: Command: (setq autocad "A software package") "A software package" Command: (setq world "The planet earth") "The planet earth" Command: (strlen autocad world) 34

Other string functions change all characters to upper or lower case, returns part of a string, finds a pattern in a string, and join two strings together, as follows: Command: (strcat autocad " used all over " world) "A software package used all over The planet earth"

That’s how you create reports, such as 13 “steps drawn drawn”” by mixing text and variables. Related to string functions are the conversion functions because some of them convert to and from strings. For example, earlier we showed how to convert 45 degrees to radians. That’s fine for decimal degrees, like 45.3711 degrees. But how do you convert 45 degrees, 37 minutes and 11 seconds, which AutoCAD represents as 45d37'11"?









136 •







v1.0





































































































1 december 2002

That’s where a conversion function like Angtof (short for ANGle TO Floating-point) comes in. It converts an angle string to a real number radians: Command: (angtof "45d37'11\"" 1) 0.796214

Here we’ve supplied Angtof with the angle in degrees-minutes-seconds format. Notice how the seconds indicator (") is handled: \". That’s so it doesn't get confused with the closing quote mark (") that indicates the end of the string. However, AutoLISP isn’t smart enough to know that, so we tell it by means of the mode number, 1 in this case. This (and some other functions) use the following as mode numbers: Mode

Meaning

Example

0 1 2 3 4

Decimal degrees Degrees-minutes-seconds Grad Radian Surveyor units

45.3711 45d 37' 11" 100.1234 0.3964 N 45d37'11" E

Notice the similarity between the mode numbers and the values of system variable AUnits Units. The coincidence is not accident. When you don’t know ahead of time the current setting of units, you make use of this fact by specifying the mode number as a variable, as follows: Command: (angtof "45d37'11\"" (getvar "aunits")) 0.796214

ar (short for GET VARiable), the AutoLISP function that gets the value of a system variable. We Here we use GetV GetVar used Getvar to get AUnits Units, which holds the state of angular display as set by the Units command. Other conversion functions convert one unit of measurement into another (via the Cvunit function and the acad.unt file), an integer number into a string, a character into its ASCII value (for example, letter A into ASCII 65), and translates (i.e. moves) a point from one coordinate system to another. External Command Functions “Powerful” often equates to “complicated,” yet one of AutoLISP’s most powerful functions is its simplest to understand: the Command function. As its name suggests, Command executes AutoCAD commands from within AutoLISP. Think about it: this means that it is trivial to get AutoLISP to draw a circle, place text, zoom a viewport, whatever. Anything you type at the ‘Command:’ prompt is available with the Command function. Let’s see how the Command function works by drawing a circle. First, though, let’s recall how the Circle command works: Command: circle 3P/2P/TTR/: 2,2 Diameter: D Diameter: 1.5

In the Command function, you mimic what you type at the ‘Command:’ prompt like this: Command: (command "circle" "2,2" "D" "1.5")





















tailoring AutoCAD































































































chapter 11 autolisp programming • 137

Notice how all the typed text is in quotation marks. After you type that in, AutoCAD responds by drawing the circle: circle 3P/2P/TTR/: 2,2 Diameter: D Diameter: 1.5 Command: nil

(Don’t worry about that ‘nil’ at the end; that’s just AutoLISP’s way to letting you know it is finished with its work. Later in this chapter, you learn how to prevent nil from appearing.) Let’s look at one of the more complex commands to use with the Command function, Text xt. When we use the Text command, AutoCAD presents these prompts: Command: text Justify/Style: 5,10 Height : 1.5 Rotation angle : (Press Enter.) Text: Tailoring AutoCAD

Converted to AutoLISP-ese, this becomes: Command: (command "text" "5,10" "1.5" "" "Tailoring AutoCAD")

And AutoCAD responds with: text Justify/Style: 5,10 Height : 1.5 Rotation angle : Text: Tailoring AutoCAD Command: nil

and draws the text. For the ‘Rotation angle:’ prompt, we simply pressed the Enter key. Notice how that was dealt with in the AutoLISP function: "" — a pair of empty quotation marks. You use the same thing for commands that automatically repeat themselves, such as the Line command: Command: (command "line" "1,2" "3,4" "")

When you don't include that final "", then you leave AutoCAD hanging with a ‘To point:’ prompt and your AutoLISP routine fails. By now it should be clear to you that you have to really know the prompt sequence of AutoCAD’s more than 300 commands to work effectively with the Command function. The easiest way to get a handle on those is to purchase one of the “quick reference” books on the market, which list commands in alphabetical order, along with the complete prompt sequence. And, as we see in a minute, check that the quick reference book has a listing of all system variables, their default value, and the range of permissible values. But the Command function has a failing. Earlier, I said, “Anything you type at the ‘Command:’ prompt is available with the Command function.’ I place the emphasis on the word type. The Command function breaks down completely when it comes to dialog boxes. That’s right: any command that uses a dialog box won’t work with the Command function — nor, for that matter, with the toolbar macros we looked at a couple of chapters ago. It is for this reason that AutoCAD includes command line versions of almost every (but not all) command. Accessing System Variables

While you could use the Command function to access system variables, AutoLISP has a pair of more direct ar and SetV ar ar gets the value of a system variable, while SetV ar changes (sets) the value. functions: GetV GetVar SetVar ar. GetV GetVar SetVar rame determines whether the frame of a spline polyline is displayed; by For example, system variable SplF SplFrame rame is 0: the frame is not displayed, as confirmed by GetV ar default, the value of SplF SplFrame GetVar ar: Command: (getvar "splframe") 0









138 •







v1.0





































































































1 december 2002

rame to 1 with SetV ar as follows: To display the frame, change the value of SplF SplFrame SetVar Command: (setvar "splframe" 1) 1

rame is 0. Zero is the default value However, we have made a crass assumption here: that the initial value of SplF SplFrame but not necessarily the value at the time that you run the AutoLISP routine. How do we know what the value of SplF rame is before we change it? We'll answer that question later in this chapter. Stay tuned. SplFrame GetXXX Functions It’s one thing to execute a command to draw a new object, such as the new circle and text we drew above with the Command function. It is trickier working with objects that already exist, such as moving that circle and editing the text. That’s where the a group of functions known collectively as Getxxx come into play. These get data from the screen. Some of the more useful ones include: GetPoint GetAngle GetString GetReal

returns returns returns returns

the the the the

x,y,z-coordinates of a picked point. angle in radians. text the user types in. value of a real number typed in by the user.

Here’s how to use some of these with the Text command from above. Let’s redo the code so that AutoLISP prompts us for everything first, then executes the Text command: Command: (setq TxtStr (getstring T "What do you want to write? ")) What do you want to write? Tailoring AutoCAD "Tailoring AutoCAD"

Notice that extra "T"; that’s a workaround that lets GetString accept a string of text with spaces. When you leave out the T, then GetString only accepts text up to the first space: you would end up with just “Tailoring” and no “AutoCAD.” The SetQ function stores the phrase “Tailoring AutoCAD” in the variable TxtStr TxtStr. Command: (setq TxtHt (getreal "How big do you want the letters? ")) How big do you want the letters? 2 2.0

eal converts the 2 (an integer) to a real number, 2.0. Notice how GetR GetReal Command: (setq TxtAng (getangle "Tilt the text by how much? ")) Tilt the text by how much? 30 0.523599

Notice how GetAngle converts the 30 (a decimal degree) into radians, 0.523599. Command: (setq TxtIns (getpoint "Where do you want the text to start? ")) Where do you want the text to start? (27.8068 4.9825 0.0)

oint returns the x, y, and z values of the coordinate, even though z is zero. Finally, we execute the Notice how GetP GetPoint Text command with the four variables: Command: (command "text" TxtIns TxtHt TxtAng TxtStr) text Justify/Style: Height : 2.000000000000000 Rotation angle : 0.523598775598299 Text: Tailoring AutoCAD Command: nil

There! We've just customized the Text command to our liking. Not only did we change the prompts that the user sees, but we change the order of the prompts.





















tailoring AutoCAD































































































chapter 11 autolisp programming • 139

Selection Set Functions To work with more than one object at a time, AutoLISP has a group of functions for creating a selection set. These all begin with SS, as in: SsAdd SsDel SsLength SsMemb

adds an object to the selection set. deletes an object from the selection set. reports the number of objects in the selection set. checks if an object is part of the selection set.

AutoCAD’s Select command can only deal with one selection set at a time; the AutoLISP SSxxx commands can work with up to 128 different selection sets. Object Manipulation Functions The really powerful AutoLISP functions are the ones that go right in and manipulate the drawing database. Unlike the Command function, which is powerful but simple, the object manipulation functions are powerful and complicated. Here’s a summary of what some of these are: EntMake EntGet EntMod EntDel TblObjName

creates a new object. gets the data that describes an object in the drawing. changes the object. erases an object from the database. gets the name of an object in a symbol table.

The Ent prefix is short for entity, the old name for AutoCAD objects. The “symbol table” refers to the part of the drawing database that stores the names of layers, text styles, and other named objects in the drawing. To create and manipulate objects, these AutoLISP functions work with a variant on the DXF format, known as “dotted pairs.” For example, to work with a layer named RightOfWay, you employ the following format: "2 . RightOfWay"

Once again, the quotation marks indicate the start and end of the data, while the dot in the middle separates the ay is the name of the layer. You can see that to work two values: 2 is the DXF code for layer names, and RightOfW RightOfWay with these object manipulating functions, you need a good grasp of the DXF format. Advanced AutoLISP Functions There is a whole host of AutoLISP functions that you may never use in your AutoCAD programming career. For example, Autodesk has written 41 AutoLISP functions for controlling the ASE (AutoCAD Structured query language Extension) link between objects in the AutoCAD drawing and records in an external database file. These functions are not hard to spot: they all start with “Ase_”, as in Ase_LsUnite and Ase_DoCmp Ase_DoCmp. Another set of AutoLISP functions — 21 of ’em — are strictly for loading and displaying dialog boxes, such as Load_Dialogue and New_Dialogue New_Dialogue. Another five functions are for memory management, whose use is so rarified that Autodesk recommends never using them.









140 •







v1.0





































































































1 december 2002

Writing a Simple AutoLISP Program In this part of the chapter, we learn the first steps in writing an AutoLISP routine of our own. Why Write a Program? If you are like many CAD users, you are so busy creating drawings that you have no time to learn how to program. No doubt, you may be wondering, “Why bother learning a programming language?” In some ways, it’s like being in school all over again. Sitting in the classroom seems like a waste of time, sometimes. But the things you learn now make life easier later. Learning some AutoLISP programming now means you’ll feel really good whipping off a few lines of code and letting AutoLISP perform a tedious task for you. The nice thing about AutoLISP is that you can program it on the fly. And you can use it for really simple but tedious tasks. Here’s the example we’ll use for this tutorial: The Id Command

AutoCAD has the Id command. When you pick a point on the screen, it tells you the 3D x,y,z- coordinates of the point. Problem is, Id reports the value in the command prompt area, like this: Command: id Point:(Pick a point.) X = 8.9227 Y = 6.5907 Z = 0.0000

Wouldn’t it be great if you could change Id to place the coordinates in the drawing, next to the pick point? That would let you label x,y-coordinates and z-elevations easily all over a site plan. With AutoLISP, you can. The Plan of Attack Before we write any AutoLISP code, we need to figure out how we’re going to get those x,y,z- coordinates off the command prompt area and into the drawing. We’ve just recognized the two parts to solving the problem: Part 1. Obtain the coordinates from the drawing, probably by picking a point. Part 2. Place the coordinates as text in the drawing. Obtaining the Coordinates

AutoLISP provides several ways to get the coordinates of a picked point. Browsing through the Customization Guide, we find we could: • Use the Id command with the Command function, as in (command "ID") "ID"). oint system variable with the GetV ar function, as in (getvar "lastpoint") • Use the LastP LastPoint GetVar "lastpoint"). oint function, as in (getpoint "P ick a point: ") • Use the GetP GetPoint "Pick It would be a useful lesson to use each of the three and see what happens. By experimenting, you make mistakes, then learn from the mistakes. 1. Start AutoCAD, load a drawing, and switch to the Text window with F2 F2. At the ‘Command:’ prompt, type: Command: (command "ID")

You are executing an AutoCAD command from within an AutoLISP routine. The Command function lets ID you use any AutoCAD command in AutoLISP. The AutoCAD command is in quotation marks "ID ID" because the command is a string (programmer talk for “text”). Just like before, AutoCAD prompts you for the point. ○



















tailoring AutoCAD































































































chapter 11 autolisp programming • 141

2. This time use an object snap to snap to a geometric feature, like the end of a line: Point: end of (Pick a point.) X = 8.9227 Y = 6.5907 Z = 0.0000

That’s great! You’ve typed in a tiny AutoLISP routine. Now, AutoCAD stores the x,y,z- coordinates of the oint last-picked point in system variable LastP LastPoint oint. 3. Before we can place the coordinates as text in the drawing, we have to store the coordinates in a variable. Recall from earlier tutorials that the SetQ function lets us store a value in a variable. Let’s make use of this now. Type at the ‘Command:’ prompt: Command: (setq xyz (getvar "LastPoint")) (8.9227 6.5907 0.0000)

Xyz is the name of the variable we are using to store the x,y,z-coordinates. GetV ar is the name of the GetVar LastP oint AutoLISP that retrieves the value stored in a system variable. And "LastP LastPoint oint" is the name of the system variable; once again, it is surrounded by quotation marks because it is a string. After typing the AutoLISP function, AutoCAD returns the value it has stored in variable Xyz Xyz: (8.9227 6.5907 0.0000). Note how the coordinates are surrounded by parenthesis. This is called a list and is the list format that LISP is famous for (LISP is short for “list processing”). The spaces separate the numbers, which are the x, y, and z-coordinates, respectively: x = 8.9227 y = 6.5907 z = 0.0000

AutoCAD always stores these values in the order of x, y, and z. You will never find the z- coordinate first or the x-coordinate last. 4. So, we’ve now solved the first problem in one manner. We obtained the coordinates off the drawing and oint stored them in a variable. We did mention a third AutoLISP function we could use, GetP GetPoint oint. Programmers oint because it is more efficient than the Id-LastP oint combo we used above. Type the following prefer GetP GetPoint Id-LastPoint to see that it works exactly the same: Command: (setq xyz (getpoint "Point: ")) Point: (Pick a point.) (8.9227 6.5907 0.0000)

oint As before, we use the SetQ function to store the value of the coordinates in variable Xyz. The GetP GetPoint oint: " is called a prompt and tells the user what function waits for you to pick a point on the screen. The "P "Point: the program is expecting the user to do. In this case, we mimicked the prompt of the ID command. 5. But we could just as easily have written anything, like: Command: (setq xyz (getpoint "Press the mouse button: ")) Press the mouse button: (Pick a point.) (8.9227 6.5907 0.0000)

6. Or, we could have no prompt at all, as follows: Command: (setq xyz (getpoint)) (Pick a point.) (8.9227 6.5907 0.0000)

That’s right. No prompt. Just a silent AutoCAD waiting patiently for the right thing to happen ... and the user puzzled at why nothing is happening. A lack of communication, you might say. That’s why prompts are important. ○







142 •







v1.0





































































































1 december 2002

We’ve now seen several approaches that solve the first problem in several different ways. With the x,y,zcoordinates safely stored in a variable, let’s tackle the second problem Placing the Text To place text in the drawing, there is just one solution: the command function in conjunction with the Text command. I suppose the MT MTeext command might work, but we are placing one line of text, and the Text command is excellent for that. The Text command is trickier than the Id command. It has four prompts that our AutoLISP routine must answer: • Start point: a pair of numbers, x,y-coordinates. • Height: a number that makes the text legible. • Rotation angle: a number, probably 0. • Text: a string, the x,y,z-coordinates. This is where I find a quick reference book handy that lists all the options of every AutoCAD command. Let’s see if we can now construct the AutoLISP function for placing the coordinates as text: (command is the Command function. "te xt" is the AutoCAD Text command being executed. "text" xyz variable stores the starting point for the text. 200 is the height of the text. Change this number to something convenient for your drawings. 0 is the rotation angle of the text. xyz — we’re lucky: the Text command accepts numbers stored in variables as text. ) and remember: one closing parenthesis for every opening parenthesis. Let's try this out at the ‘Command:’ prompt: Command: (command "text" xyz 200 0 xyz) text Justify/Style/: Height : 200 Rotation angle : 0 Text: 2958.348773815669,5740.821183398367 Command: nil

AutoCAD runs through the Text command, inserting the responses for its prompts, then placing the coordinates as text. We’ve solved the second part of the problem.





















tailoring AutoCAD































































































chapter 11 autolisp programming • 143

Putting Them Together Let’s put together the two solutions to our problem: (setq xyz (getpoint "Pick point: ")) (command "text" xyz 200 0 xyz)

There we have it: a full-fledged AutoLISP program. Well, not quite. It’s a pain to retype those two lines each time you want to label a point. In the next part of this chapter, we find out how to save the code to a .lsp file on disk. We’ll also dress up the code, including suppressing that "nil" that gets output at the end of the routine.

An Alternative to LISP Programming Just because this tutorial is about AutoLISP doesn’t mean that it is always the best approach. Here’s a wacky work-around to labeling points that uses no programming at all: 1. Use the Id command and pick a point: Command: id Point: (Pick a point.) X = 8.9227 Y = 6.5907 Z = 0.0000

2. Switch to the text screen by pressing function key F2 F2. 3. Highlight the text: Press the mouse button and drag the cursor over the "X = 8.9227 Y = 6.5907 Z = 0.0000" coordinates. 4. Click the right mouse button. AutoCAD displays the cursor menu. 5. Select Copy from the cursor menu. AutoCAD copies the coordinate text to the Windows clipboard. 6. Press F2 to switch back to AutoCAD drawing window. 7. Press Ctrl+V Ctrl+V. AutoCAD pastes the text into the drawing using the current text style. AutoCAD always pastes stuff in the upper-left corner of the drawing screen. You can use the Move command to shift the text into position.









144 •







v1.0





































































































1 december 2002

Writing a Simple AutoLISP Program, Cont’d In the last tutorial, we learned the first steps in writing an AutoLISP routine of our own. We created a two-line AutoLISP program that looks like this: (setq xyz (getpoint "Pick point: ")) (command "text" xyz 200 0 xyz)

When you pick a point on the screen, the program labels the point with its x,y,z-coordinates. A quick reminder on how to use it: 1. Type the AutoLISP code in at the ‘Command:’ prompt exactly as shown. All those spaces, parentheses, and quote marks are important; upper and lower case characters are not important. 2. When AutoCAD prompts, “Pick point: “, pick a point on the drawing: Pick point: (Pick a point.)

3. Notice that AutoCAD writes the x,y,z-coordinates at the point you picked. You may need to zoom window or extents to see the text. Sprucing Up the Code There we have it: a full-fledged AutoLISP program. Well, not quite. What we have is the algorithm — the core of every computer program that performs the actual work. What is lacking is most of the user interface — the part that makes it easier for the user to employ the program. All we have for a user interface is part of the first line that prompts, “Pick point: “. There’s a lot of user interface problems with our little program. How many can you think of? Here’s a list of problems I've come up with: • It’s a pain to retype those two lines each time you want to label a point — we need to give the program a name ... • ... and we need to save it on disk so that we don’t need to retype the code with each new AutoCAD session... • ... and if we use this AutoLISP program a lot, then we should have a way of having it load automatically. • The x,y,z-coordinates are printed to eight decimal places, which, for most users, that’s way too many. • You may want to control the layer that the text is placed on. • You may want a specific text style. • Certainly, you would like some control over the size and orientation of the text. • Here’s an orthogonal idea: store the x,y,z-coordinates to a file on disk — just in case you ever want to reuse the data. Conquering Feature Bloat “Okay,” you may be thinking, “I can agree that these are all desirable improvements. Go right ahead, Mr. Grabowski, and show how to add them in.” But, wait a minute! When you’re not familiar with AutoLISP, you may not realize how a user interface adds a tremendous amount of code, which mean more bugs and more debugging. If you are familiar with programming, then you know how quickly a simple program fills up with feature-bloat. While all those added features sound desirable, they may make the program less desirable. Can you image how irritated you’d get if you had to answer the questions about decimal places, text font, text size, text orientation, layer name, filename — each time you wanted to label a single point? Take a second look at the wishlist to check off what is important and cross off what you could live without.





















tailoring AutoCAD































































































chapter 11 autolisp programming • 145

Wishlist Item #1: Naming the Program

To give the program a name, I surround all of the code with the (defun) function, as follows: (defun c:label ( / xyz) (setq xyz (getpoint "Pick point: ")) (command "text" xyz 200 0 xyz) )

Let’s take a look at what I added, piece by piece: (defun defines the name of the function. In AutoLISP, the terms function, program, and routine are used interchangeably. c:label is the name of the function. I decided to call this program Label. I could give it any name that does not conflict with the name of a built-in AutoLISP function or any other user-defined function. The c: prefix make this AutoLISP routine appear like an AutoCAD command. To run the Label program, all I need do is type “label” at the ‘Command:’ prompt, as follows: Command: label Pick point: (Pick a point.)

When the c: prefix is missing, then I run the program like an AutoLISP function with the parentheses, as follows: Command: (label) Pick point: (Pick a point.)

TIP The c: prefix turns an AutoLISP function into an AutoCAD command. You can use other prefixes for your own purposes, such as to identify subroutines you created, such as: (defun rhg:label)

( / xyz ) declares the names of input and local variables; the slash separates the two. An input variable is for feeding data to the AutoLISP routine; the names of input variables appear before the slash. A local variable is used only within the program; the names of local variables appear after the slash. In my example program, xyz is the name of the variable that is used strictly within the program. If variables are not declared local, they become global. The value of a global variable is accessed by any AutoLISP function loaded into AutoCAD. The benefit to declaring variables as local is that AutoCAD automatically frees up the memory used by the variable when the AutoLISP program ends; the drawback is that the value is lost, making debugging harder. For this reason, otherwise-local variables are kept global until the program is debugged. ) closing parenthesis balances the opening parenthesis at the beginning of the program. I indented the code in the middle to make it stand out from the defun line and the closing parenthesis. This is standard among programmers; the indents make it easier to read code. You can use a pair of spaces or the tab key since AutoLISP doesn’t care. Wishlist Item #2: Saving the Program

By saving the program to a file on disk, I avoid retyping the code with each new AutoCAD session. I do this, as follows: 1. Start a text editor (the NotePad supplied with Windows is good).









146 •







v1.0





































































































1 december 2002

2. Type the code shown: (defun c:label ( / xyz) (setq xyz (getpoint "Pick point: ")) (command "text" xyz 200 0 xyz) )

3. Save the file with the name label.lsp in AutoCAD’s folder named \support. Wishlist Item #3: Automatically Loading the Program

To load the program into AutoCAD, I type the following: Command: (load "label")

If AutoCAD cannot find the AutoLISP program, then I have to specify the path. Assuming I saved label.lsp in the folder \acad13\win\support I would type: Command: (load "\\acad13\\win\\support\\label")

I now use the point labelling routine, as follows: Command: label Pick point: (Pick a point.)

AutoCAD provides a way to automatically load AutoLISP programs. When AutoCAD starts up, it looks for a file called acad.lsp. AutoCAD automatically loads the names of AutoLISP programs listed in the file. To add label.lsp is easy. Open the acad.lsp file with a text editor (if the file does not exist, then start a new file called acad.lsp and store it in the \support folder). Add the name of the program: (load "label.lsp")

Save the acad.lsp file. Start AutoCAD and it should automatically load label. Wishlist #4: Using Car and Cdr

The x,y,z-coordinates are printed to eight decimal places — that’s too many. There are two solutions. One is to ask the user the number of decimal places, as shown by the following code fragment: Command: (setq uprec (getint "Label precision: ")) Label precision: 1 1

rec — the precision specified by the user via the Units command Or steal the value stored in system variable LUP UPrec — under the (not necessarily true) assumption that the user want consistent units. The code to do this is as follows: (setq uprec (getvar "LUPREC"))

That was the easy part. The tough part is applying the precision to the x,y,z-coordinates, which takes three steps: (1) pick apart the coordinate triplet; (2) apply the precision factor; and (3) join the coordinates together again. Here's how: 1. Open label.lsp in NotePad or any other text editor. Remove / xyz from the code. This makes the variable “global,” so that I can check its value at AutoCAD’'s ‘Command:’ prompt. The code should look like this: (defun c:label ( ) (setq xyz (getpoint "Pick point: ")) (command "text" xyz 200 0 xyz) )





















tailoring AutoCAD































































































chapter 11 autolisp programming • 147

Save and load label.lsp into AutoCAD. 2. Run label.lsp, picking any point on the screen. If you don’t see the coordinates printed on the screen, use the Zoom Extents command. 3. At the ‘Command:’ prompt, type the following: Command: !xyz (6.10049 8.14595 10.0)

The exclamation mark forces AutoCAD to print the value of variable XYZ XYZ, which holds the x,y,z- coordinates. Your results will differ, depending on where you picked. 4. LISP has several functions for picking apart a list. Here I’ll use the car and cdr functions, and combinations thereof. The car function extracts the first item (the x-coordinate) in the list. Try it now: Command: (car xyz) 6.10049

5. The cdr function is the compliment to car car. It removes the first item from the list and gives you what’s left: Command: (cdr xyz) (8.14595 10.0)

6. In addition to car and cdr cdr, LISP allows me to combine the “a” and “d” in several ways to extract other items in the list. To extract the y-coordinate, use cadr cadr, as follows: Command: (cadr xyz) 8.14595

7. And to extract the z-coordinate, use caddr caddr, as follows: Command: (caddr xyz) 8.14595

8. I now have a way to extract the x-coordinate, the y-coordinate, and the z-coordinate from variable XYZ XYZ. I’ll store them in their own variables, as follows: Command: (setq ptx (car xyz) 1> pty (cadr xyz) 1> ptz (caddr xyz) 1> )

I am using PtX to store the x-coordinate, PtY for the y-coordinate, and so on. In addition, I am using a form of LISP shorthand that allows me apply the SetQ function to several variables. Recall the reason for AutoCAD’s 1> prompt: it reminds me that a closing parenthesis is missing. 9. Now that the three coordinates are separated, I can finally reduce the number of decimal places. There are a couple of ways to do this, but I’ll use the RtoS function because it does two things at once: (1) changes the number of decimal places to any number between 0 and 8; and (2) converts the real number into a string. Why? You'll see later. For now, here is the RtoS function at work: Command: (rtos ptx 2 uprec) "6.1"









148 •







v1.0





































































































1 december 2002

The RtoS function uses three parameters: PtX 2

Name of the variable holding the real number. Type of conversion, decimal in this case. The number 2 is based on system variable LUnits, which defines five modes of units:

Mode

Units

1 2 3 4 5 UPrec

Scientific Decimal Engineering Architectural Fractional

Name of the variable holding the precision (the code for that is at the beginning of this section). This varies, depending on the type of units. For example, a value of 2 for decimal means “two decimal places”; a 2 for architectural means “quarter-inch.”

rec is 1, the RtoS function in the code fragment above reduces Assuming, then, that the precision in UP UPrec 6.10049 to 6.1. 10. 0. I truncate and preserve the values of x, y, and z, as follows: Command: (setq ptx (rtos ptx 2 uprec) 1> pty (rtos pty 2 uprec) 1> ptz (rtos ptz 2 uprec) 1> )

Notice that I can set a variable equal to itself: the first PtX holds the new value of the x-coordinate after PtX. Reusing a variable name like this helps conserve memory. RtoS gets finished processing the second PtX 11. With the coordinates truncated, I now have to string (pardon the pun) them together with the StrCat function, short for string concatenation. Try it now: Command: (strcat ptx pty ptz) "6.18.110.0"

12. Oops! Not quite the look I was hoping for. Since LISP can’t know when I want spaces, it doesn’t provide any. I have to insert them. StrCat is one of the most useful LISP functions, since it lets me create a string that contains text and variables, like this: Command (setq xyz (strcat ptx ", " pty ", " ptz)) "6.1, 8.1, 10.0"

That’s more like it. 13. Back to the text editor. Add in the code I developed here, shown in boldface: (defun c:label ( / xyz xyz1 uprec ptx pty ptz) (setq uprec (getint "Label precision: ")) (setq xyz (getpoint "Pick point: ")) (setq ptx (car xyz) pty (cadr xyz) ptz (caddr xyz) ) (setq ptx (rtos ptx 2 uprec) pty (rtos pty 2 uprec) ptz (rtos ptz 2 uprec) ) ○



















tailoring AutoCAD































































































chapter 11 autolisp programming • 149

(setq xyz1 (strcat ptx ", " pty ", " ptz)) (command "text" xyz 200 0 xyz1)

)

Notice that I made all the variables local. Notice, too, the change to variable Xyz in the last couple of lines: I don’t want the text placed at the rounded-off coordinates, so I use Xyz1 as the variable holding the text string. 14. Finally, I should add comments to my code to remind me what it does when I look at the code several months from now. The semicolon ( ; ) indicates the start of a comment: ; Label.Lsp labels a picked point with its x,y,z-coordinates. ; by Ralph Grabowski, 25 February, 1996. (defun c:label ( / xyz xyz1 uprec ptx pty ptz) ; Ask user for the number of decimal places: (setq uprec (getint "Label precision: ")) ; Ask the user to pick a point in the drawing: (setq xyz (getpoint "Pick point: ")) ; Separate 3D point into individual x,y,z-values: (setq ptx (car xyz) pty (cadr xyz) ptz (caddr xyz) ) ; Truncate values: (setq ptx (rtos ptx 2 uprec) pty (rtos pty 2 uprec) ptz (rtos ptz 2 uprec) ) ; Recombine individual values into a 3D point: (setq xyz1 (strcat ptx ", " pty ", " ptz)) ; Place text: (command "text" xyz 200 0 xyz1) )

15. Save the file as label.lsp, and then load the AutoLISP routine into AutoCAD with: Command: (load "label") "C:LABEL"

16. Run the routine: Command: label Label precision: 1 Pick point: (Pick a point.) text Justify/Style/: Height : 200 Rotation angle : 0 Text: 5012.3, 773.2, 0.0 Command: nil









150 •







v1.0





































































































1 december 2002

Saving Data to a File In the last tutorial, we began to worry about user interface enhancements. What started out as two lines of code has now bulged out into 23 lines of code. In this tutorial, we add the ability to save data to a file and learn how to fight feature bloat. A reader wrote, “The LISP file comes in very handy with some of the programs I use but I would like to be able to save the data collected on the x,y,z- coordinates in a text file.” "a"), (write-line) (write-line), and (close) Thank you for the feedback. Saving the data to file is easily done with the (open "a") functions. Let’s take a look at how to do this. Dealing with files in AutoLISP is simpler than for most programming languages because AutoLISP has very weak file access functions. All it can do is read and write ASCII files in sequential order; AutoLISP cannot deal with binary file nor can it access data in random order. While AutoCAD users have often asked for those abilities, Autodesk has chosen not to add them. The Three Steps There are three steps in writing data to a file: • Open the file. • Write the data to the file. • Close the file. Step 1: Open the File

AutoLISP has the open function for opening a file. This function lets you open a file for one of three purposes: (1) read data from the file; (2) write data to the file; and (3) append data to the file. You have to choose one of these at a time; AutoLISP cannot do all three at once. In all three cases, AutoLISP takes care of creating the file if it does not already exist. Reading data is easy enough to understand but what's the difference between “writing” and “appending” data? • When I open a file to write write, all existing data in that file is erased and the new data is added. • When I open a file to append append, the new data is added to the end of the existing data. For our purpose, we want to keep adding data to the file, so choose append mode. The AutoLISP code looks like this: (setq FIL (open "xyzdata.txt" "a"))

Here you are setting something (setq) to a variable named FIL FIL. What is it? In pretty much all programming languages, we don’t deal with the filename directly but instead deal with a file descriptor. This is a name (some sequence of letters and numbers) to which the operating system assigns the filename. Now that you have the file descriptor stored in variable FIL FIL, you work with FIL FIL, not the filename, which I have decided to call xyzdata.txt. The final "a" tells AutoLISP we want to open xyzdata.txt for appending data. It is important that the "a" be lowercase; this is the only occasion where AutoLISP is case-sensitive. The options for the open function are:









Option

Meaning

"a" "w" "r"

Append data to end of file. Write data to file, after erasing existing data. Read data from file.













tailoring AutoCAD































































































chapter 11 autolisp programming • 151

Step 2: Write Data to the File

To write the data to the file, use the write-line function. This function writes a line of data to the file. (A related function, the write function, writes a single character to the file.) The code looks like this: (write-line xyz1 fil)

You cannot, however, just write the raw data to the file because it would look like a lot of numbers with dots mixed in: 8.15483.27520.0000

Most software is able to read data that has commas separating numbers, like this: 8.1548, 3.2752, 0.0000

That includes spreadsheets, database programs, and even some word processing software. I tell these programs that when they read the data, they should consider the comma to be a separator, and not a comma. In that way, the spreadsheet program places every number in its own cell. With each number in its own cell, I can manipulate the data. For this reason, we need code that formats the data. Fortunately, we’ve already done that. In the previous section, we used the StrCat function along with the cdr cdr, cadr cadr, and caddr functions to separate the x, y, and z components of the coordinate triplet. So we can reuse the code, which looks like this: (setq ptx (car xyz) pty (cadr xyz) ptz (caddr xyz) ) (setq xyz1 (strcat ptx ", " pty ", " ptz))

Step 3: Close the File

Finally, for good housekeeping purposes, close the file. AutoCAD automatically closes the file for you if you forget, but good programmers cleans up after themselves. Closing the file is as simple as: (close fil)

Putting It Together Add the code for opening, formatting, writing, and closing to the lable.lsp program: (defun c:label ( / xyz xyz1 uprec ptx pty ptz) (setq uprec (getint "Label precision: ")) (setq xyz (getpoint "Pick point: ")) (setq ptx (car xyz) pty (cadr xyz) ptz (caddr xyz) ) ; Format the x,y,z coordinates: (setq ptx (rtos ptx 2 uprec) pty (rtos pty 2 uprec) ptz (rtos ptz 2 uprec) ) ; Add commas between the three coordinates: (setq xyz1 (strcat ptx ", " pty ", " ptz)) ; Write coordinates to the drawing: (command "text" xyz 200 0 xyz1)









152 •







v1.0





































































































1 december 2002

; Open the data file for appending: (setq fil (open "xyzdata.txt" "a")) ; Write the line of data to the file: (write-line xyz1 fil) ; Close the file: (close fil) )

Using a text editor, such as Notepad, make those additions to your copy of lable.lsp. Load it into AutoCAD with the Load function: Command: (load "label")

And run the program by typing Label at the ‘Command:’ prompt: Command: label Label precision: 4 Pick point: (Pick a point.)

As you pick points on the screen, the routine labels the picked points but also writes the 3D point data to file. After a while, this is what the data file looks something like this: 8.1548, 7.0856, 6.4295, 5.5303, 5.4331,

3.2752, 4.4883, 5.6528, 6.7688, 8.3215,

0.0000 0.0000 0.0000 0.0000 0.0000

Wishlist #5: Layers

Let’s take a moment to go back and revisit our wish list. One wishlist item was to control the layer that text is placed on. There are two ways to approach this wishlist item: • The no-code method is to set the layer before starting the AutoLISP function. • The AutoLISP code version is to ask the user for the name of the layer, then use the system variable CLA YER to set it (much easier than using the Layer command), as follows: CLAYER (setq lname (getstring "Label layer: ")) (setvar "CLAYER" lname)

Add those two line before the line with the ‘Pick point’ prompt. Wishlist #6: Text Style

To specify the text style, there are the same two methods as with setting the layer name. The no-code method is to simply set the text style before starting the routine. Otherwise, you can write AutoLISP code similar to the following: (setq tsname (getstring "Label text style: ")) (setvar "TEXTSTYLE" tsname)

Once again, add those two line before the line with the ‘Pick point’ prompt. By now, you might be noticing that our program is starting to look big. That’s called “feature bloat” and explains why ten years ago AutoCAD used to fit on a single 360KB floppy disk, but now takes up megabytes of disk space. More features, especially in the area of user interface, makes software grow far beyond the size of its basic algorithm.





















tailoring AutoCAD































































































chapter 11 autolisp programming • 153

Tips in Using AutoLISP Here are some tips for helping out when you write your own AutoLISP functions. You may want to save clip this for reference. Tip #1. Use an ASCII Text Editor. AutoLISP code must be written in plain ASCII text — no special characters of the sort that all word processors add in. If you were to write AutoLISP code with, say, Word, then save as a .doc file (the default), AutoCAD would refuse to load the AutoLISP file, even when the file extension is .lsp. In an increasingly WYSIWYG world, it is becoming harder to find a true ASCII text editor. There is one pure ASCII text editor supplied free by Microsoft with Windows called Notepad, which you’ll find in the \windows folder. Do not use Write or WordPad supplied with Windows. While both of these have an option to save in ASCII, you’re bound to forget sometimes and end up frustrated. Almost any other word processor has an option to save text in plain ASCII, but not by default. Word processors have a number of different terms for what I mean by “pure ASCII format”. Word calls it “Text Only”; WordPerfect calls it “DOS Text”; WordPad calls it “Text Document”; and Atlantis calls it “Text Files.” Tip #2: Loading LSP Code into AutoCAD To load the AutoLISP code into AutoCAD, you use the load command, which is not to be confused with the Load command (which is for loading a .shx compiled shape files). load is for loading AutoLISP code. Clear? Here’s an example where points.lsp is the name of the AutoLISP routine: Command: (load "points")

You don’t need to type the .lsp extension. When AutoCAD cannot find the points.lsp, you’ll need to specify the folder name by using either a forward slash or double backslashes — your choice: Command: (load "\\autocad\\points")

After you’ve typed this a few times, you’ll find this gets tedious. To solve the problem, write a one-line AutoLISP routine that reduces the keystrokes, like this: Command: (defun c:x () (load "points"))

Now anytime you need to load the points.lsp routine, you just type x and press Enter Enter, as follows: Command: x

Under Windows, you can use the above shortcut method, or you can drag the .lsp file from the File Manager into AutoCAD. Note that the code moves one way: from the text editor to AutoCAD; the code never moves from AutoCAD back to the text editor. Tip #3: Toggling System Variables One of the problems in programming is: How to change a value when you don't know what the value is? In AutoCAD, you come across this problem with system variables, many of which are toggles. A toggle system variable has a value of 0 or 1, indicating that the value is either off (0) or on (1). For example, system variable SplF rame is by default 0: when turned off, splined polylines do not display their frame. SplFrame rame is going to be zero just because that’s its No computer programmer ever assumes that the value of SplF SplFrame default value. In the case of toggle system variables, there two solutions: • Use the if function to see if the value is 0 or 1. • Subtract 1, and take the absolute value. ○







154 •







v1.0





































































































1 december 2002

Tip #4: Be Neat and Tidy. Remember, your mother told you to always pick up your things. This advice applies to the problem of the settings of system variables. When your AutoLISP routine changes values of system variables, it must always set them back to the way they were before the routine began running. Many programmers write a set of generic functions that save the current settings at the beginning of the routine. After carrying out changes, restore the saved values at the end of the routine. Here's a code fragment that shows this: (setq splvar (getvar "splframe")) ... (setvar "splframe" splvar)

Tip #5: Suppress That nil Any time you run an AutoLISP routine, there is that pesky "nil" appearing as the very last thing displayed. There is an actual reason for nil appearing, but the reason isn’t good enough for leaving it there. Here’s how to prevent that nil from appearing: end your routine with a (princ) all by itself. Tip #6: Read-Write-Append File In (almost) all cases, AutoLISP doesn’t care if you use UPPERCASE or lowercase for writing the code. For legibility, there are some conventions, such as AutoLISP function names in all lowercase, your function names in Mixed Case, and AutoCAD variables and command names in all UPPERCASE. As I said, AutoLISP doesn’t care, and converts everything into uppercase in any case. It also strips out all comments, excess white space, tabs, and return characters. The exception is text in quote marks, such as prompts, is left as is. There are two exception where AutoLISP does care: when you are working with file functions and escape codes. The open function uses the arguments "r" "r", "w" "w", and "a" to read to, write from, and append to a file, respectively. Those three characters must be lowercase. Escape codes used in text strings must also remain lowercase. For example, \e is the escape character (equivalent to ASCII 27) and \t is the tab character. Note that they use backslashes; it is for this reason that you cannot use the backslash for separating folders names back in Tip #2. AutoLISP would think you were typing an escape code. Tip # 7: Quotation Marks as Quotation Marks As we have seen, AutoLISP uses quotation marks " and " for strings. Thus, you cannot use a quotation mark as for displaying quotation marks and inches, such as displaying 25 inches as 25". The workaround is to use the escape codes mentioned above in Tip #6, specifically the octal code equivalent for the ASCII character for the quotation mark. Sound complicated? It is. But all you need to know is 042. Here’s how it works. First, assign the strings to variables, as follows: (setq disttxt "The length is ") (setq distval 25) (setq qumark "\042")

Notice how I assigned octal 042 to variable qumark. The backslash tells AutoLISP the numbers following are in octal. Octal, by the way, is half of hexadecimal: 0 1 2 3 4 5 6 7 10 11 12 ... 16 17 20 ...





















tailoring AutoCAD































































































chapter 11 autolisp programming • 155

Then concatenate the three strings together with the strcat function: (strcat distxt distval qumark)

To produce the prompt: The length is 25"

Tip # 8: Keep Variables to Six Characters To write the most efficient code, keep the variable names to a length of six characters or fewer. You may have notice that the variables I used above were all six characters or fewer. When you go above the six-character length, AutoLISP uses twice the space to hold the variable name. Tip #9: Tabs and Quotation Marks Vijay Katkar is writing code for a dialog box with a list box. He told me, “I want to display strings in it — just like the dialog box displayed by the Layer command. I am able to concatenate the values and print the strings but there is no vertical alignment, since the strings are of different lengths. I tried using the tab metacharacter (\t) in the string but it prints the literal '\t' in the list box. Is there any way I can get around this problem?” I recall a similar problem: How to display quotation marks or the inches symbol within a text string? For example, I have a line of AutoLISP code that I want to print out as: The diameter is 2.54"

Normally, I cannot use the quotation ( " ) character in a string. AutoLISP uses the quotation as its string delimiter to mark the beginning and ending of the string. In the following line of code: (prompt "The diameter is 2.54"")

AutoLISP sees the first quotation mark as the start of the string, the second quotation as the end of the string, and the third quotation mark as an error. The solution is the \nnn metacharacter. This lets me insert any ASCII character, including special characters, such as tab, escape, and quotation marks. The workaround here is to use the ASCII code for the quotation mark, \042, like this: (prompt "The diameter is 2.54\042")

Similarly, Vijay needs to use the \009 metacharacter to space the text in his dialog box. And, in fact, that worked: “According to what you had told me, I used the same and it worked.”









156 •







v1.0





































































































1 december 2002