You are on page 1of 27

IntroductiontoMacroWriting

Kate Morrical Autodesk, Inc.

CP214-1

Do you want to customize your AutoCAD or AutoCAD LT software, but don't have the time to learn a programming language? In that case, macros may be just what you need. I'll show you how to combine commands and options into repeatable macros that perform complex operations and can be launched with a single click on an interface element like a toolbar or a ribbon panel. If you want to maximize your productivity while minimizing effort, this class is for you.

About the Speaker:


Kate joined Autodesk in 2008 as the Technical Marketing Manager for AutoCAD LT. She started using AutoCAD in 1999 with Release 14, and has been blogging about LT since April 2007. Prior to joining Autodesk, Kate was a structural engineer and CAD manager for the Washington, DC, office of Robert Silman Associates, PLLC, where she provided technical support for 20 users of AutoCAD, AutoCAD LT, and Revit Structure. She has a B.S. in Civil Engineering from Case Western Reserve University. kate.morrical@autodesk.com

IntroductiontoMacroWriting

Introduction
Firstofall,IdjustliketosaythatImnotaprogrammer.Imguessingmostofyouarenteither.There couldbeallsortsofreasonsforthistoobusy(whoisnt?),programminglanguagesdontworkwith theprogram(AutoCADLT)butyouandIhavejustneverlearnedhowtowriteprograms. Thatdoesntmeanwerecontentwiththeoutoftheboxconfiguration,though.No,wewanttosetup ourprogramsjustthewaywewantit,andtobeabletoquicklyrepeatcommandsandcommand sequencesweuseonaregularbasis. Fortunately,plentyofcustomizationcapabilitiesarebuiltrightintoAutoCADandAutoCADLT,andyou dontneedtobeacodingexperttousethem.Infact,allyouneedisalittleknowledgeofthecommand lineandtheCUIeditor. Togiveyouanideaofwhatsavailable,heresascreenshotoftheAutoCADLTHelpfile.Atthebottom oftheTableofContents,theresanentiresectioncalledCustomizationGuide. Canyoubelievehowmanytopicsareinthere?The AutoCADHelpfilelooksjustthesame,exceptithasa fewmorelinksforexternalprogramminglanguageslike LISPandARX. Havingsomanycustomizationoptionsmeansthatthey cantallpossiblyfitintoa90minuteclass.SoImgoing tohighlightsomeofmyfavorites,andgiveyousome moreresourcesattheendtolearnabouttherest. OneofthoseresourcesistheAppendix,whichincludes allthemacrosreferencedinthehandout,aswellasa bunchmoreIfoundontheAutodeskdiscussiongroups.

IntroductiontoMacroWriting

WhatsIn
ThisclassisfocusedonthemacrowritingaspectsofthebuiltincustomizationopportunitiesinAutoCAD andAutoCADLT.Specifically: WritingMacros UsingDIESELinMacros UsingMacrosinCUIelements UsingMacrosinToolPalettes TheActionRecorder

Ofthesetopics,theonlyonethatdoesntapplytoAutoCADLTistheActionRecorder.Everythingelse translatesperfectlybetweenbothprogramsandforthatmatter,betweenallAutoCADbased programs,includingverticalslikeAutoCADArchitectureorAutoCADMEP.

WhatsOut
AsyousawfromtheHelpfilecontents,therearealsoalotofcustomizationtopicsthatwedonthave timetocover,including(butnotlimitedto): Templates Commandaliases Linetypes Hatchpatterns Scripts Dynamicblocks

WhileallthesecanbeimportantandeffectivetoolsforcustomizingyoursetupandCADstandards, theyrenotinthesamecategoryasmacrosandtheCUI.(Besides,Ihadtodrawthelinesomewhere.) ThisclassalsoexcludesLISP,VBA,.NET,andanyotherexternalprogramminglanguages.Thereare plentyofotherresourcesforlearninghowtoprogram(includingmanyexcellentclasseshereatAU2009 andonAUOnline).Thisclasswillteachyouhowtocustomizewithoutprogramming.

NotesonHandoutFormatting
Thishandoutinvolvesalotofcommandlineinput,soitsimportanttounderstandwhenacertainlineis anAutoCADprompt,textornumbers,orinputlikeEnteroraleftmouseclick. Herearetheformattingconventionsthatwillbeusedinthishandout: AutoCAD-generated command-line text USER-GENERATED TEXT OR NUMBERS Enter, left-click, or other special characters

IntroductiontoMacroWriting

WritingMacros
Themajorityofthisclassisaboutunderstandingthesyntaxandrulesforwritingmacros.Onceyouve learnedhowtocreatemacros,youcanusetheminallsortsofplaces:pulldownmenus,ribbonpanels, toolbars,andtoolpalettes.

WhatIsaMacro?
Amacroisatextstringthatcombinescommandsandoptionsforrepeateduse.Itsawayoftaking commandlineinputandstoringitforlateruse,sothatoneclickofthemousecanaccomplishadrawing taskthatwouldotherwisetakeaseriesofactionsbyauser.Amacrocanbeassimpleascallinga commandandprovidingasingleinput,oracomplexseriesofcommandsandoptions.

Example:DrawaCircle
Fornow,letsstartwithsomethingsimple.Letssayyouwanttodrawacirclewitharadiusof1unit. Hereswhatthatwouldlooklikeatthecommandline: Command: CIRCLE (enter) Specify center point for circle or [3P/2P/Ttr (tan tan radius)]: (left-click) Specify radius of circle or [Diameter]: 1 (enter) Now,letsconvertthatstringofcommandsintoamacro,onestepatatime. circle ; Entersthecommandname. AmacrocantpressENTERforyou,soyouneedtouseasemicoloninstead.Thisonestarts theCIRCLEcommand.Theeffectofcircle;isthesameasifyoudtypedcircleatthe commandlineandpressedENTER. Pausesforuserinput.Inthiscase,thefirstpromptoftheCIRCLEcommandisforacenter point.Sothemacrowillwaittoallowyoutospecifyyourowncenterpointeachtimeyou runthemacro. Providesinputforthenextprompt.Here,thatstheradius.Everytimeyourunthismacro, thecirclecreatedwillhavearadiusof1unit. Anothersemicolon,thistimetoacceptthevalueof1andendthecommand.Thisoneisnt technicallynecessary.AutoCADcanseethatthisistheendofthemacro,andautomatically finishesthecommandforyou.Istillliketoputthemin,though,sothatIcanseeexactly whatshappening.

Putitalltogether,anditlookslikethis: circle;\1; 4

IntroductiontoMacroWriting

Butthisisntquitefinishedyet.Whatiftherewasanothercommandrunningwhenyoustartedthe circlecommand?Youdgetanerrormessage,right?Soletscancelanyrunningcommandsfirst. ^C^Ccircle;\1; Thisactuallyrunscanceltwice,justincaseyouhappentobedoingsomethingthatwouldrequire morethanonesteptogetoutof.Mostcommandsthesedayswouldonlyneedone^C toexit,butits stillconsideredgoodpracticetohavetwojustincase. Andonemorewhatif:WhatifsomeonetriedtousethismacroinanonEnglishversionofAutoCADor AutoCADLT?TheFrenchversion,forexample,hasitsownwordforcircle.Soletsforcethemacroto usetheEnglishcommanddefinitionbyputtinganunderscoreinfrontofthecommandname.Ifyou knowthatyourmacrowillonlybeusedinEnglish,youcanleavethisout,butitseasytoaddand ensuresthatanyonearoundtheworldcanalsousethismacro. ^C^C_circle;\1;

SpecialCharactersinMacros
Themacroaboveusesthreespecialcharacters:underscore(_),semicolon(;),andbackslash(\). Thesearecharactersthattellthemacrotoperformcertainnoncommandactions.Inadditiontothese three,thereareseveralotherspecialcharactersthatcanbeusedinmacros.Afulllistcanbefoundin theHelpfile,butherearesomeofthemostimportant: Character ; Description IssuesENTER

[blankspace] Entersaspace;ablankspacebetweencommandsequencesinamacroisequivalentto pressingtheSPACEBAR \ Pausesforuserinput _ * ^ TranslatesAutoCADcommandsandoptionsthatfollow Runsthecommandlineversionofacommand Repeatsthemacrountiltheusercancelsit EquivalenttopressingCTRLonthekeyboard.Youcancombinethecaretwithanother charactertoconstructmacrosthatdosuchthingsasturnthegridonandoff(^G)or cancelacommand(^C) IntroducesaDIESELexpression. Usesthecoordinatesofthelastpointspecified.

$ @

Thebehaviorsdescribedaboveonlyapplywhenthecharactersareusedinmacros.Ifyoutypedthese charactersatthecommandline,outsideamacro,eithertheywouldntwork,theydgiveyouanerror,or theydhaveadifferentbehaviorthantheywouldinamacro.

IntroductiontoMacroWriting

Soifyouwantedtousetheabovemacrotocreatemultiplecirclesatatime,justaddanasterisktothe beginning: *^C^C_circle;\1; Note:Spacesinmacroshavethesameeffectassemicolons.Thisisimportant,becausestrayspacesina macrocanhaveunexpectedeffects.Ialwaysrecommendusingsemicolonsinmacrosinsteadof spacestheyresomucheasiertocount! Noneofthemacrosinthishandouthavespaces.Someof themdorunontomorethanoneline,though,soifyourecopyingandpastingthem,watchoutfor wordwrap.

BasicMacros
Togetstartedwritingamacro,youneedtochoosethecommandyouwanttorunandfigureoutwhat happensatthecommandlinewhenyourunit.Ifyoureacommandlinefan,thisisprobablyalready secondnaturetoyou.Ifyouprefertoolbarsormenus,though,allyouneedtodoisrunyoursequencea fewtimesandpayattentiontowhatsgoingonatthecommandlinewhileyoudoit. Heresanotherbasicexample.

Example:RotatebyFixedAngle
Maybeyouoftenneedtorotateobjectsbyafixedangle. Ifyoudidthisbytypingatthecommandline,youdseethis: Command: ROTATE (enter) Current positive angle in UCS: ANGDIR=counterclockwise ANGBASE=0 Select objects: (left-click) 1 found Select objects: (enter) Specify base point: (left-click) Specify rotation angle or [Copy/Reference] <0>: 180 (enter) Sototranslatethisintoamacro,justputallthepiecestogether,rememberingtomakeuseofthe specialcharacters. ^C^C _rotate; \ ; \ 180; Cancelanyrunningcommands. StarttheROTATEcommand. Pauseforuserinput,soyoucanselecttheobjecttorotate. Endtheselectobjectsmode. Pauseforuserinput,soyoucanselectthebasepoint. Specifyarotationangleof180degrees,andendthecommand. 6

IntroductiontoMacroWriting

Putitalltogether: ^C^C_rotate;\;\180; Obviouslythisisstillaprettysimpleexample.ButtheprinciplescanbeappliedtoallkindsofAutoCAD andAutoCADLTcommands,andtweakedtoapplybesttowhatyouredoing.

Example:CopyandRotate
Letsexpandonthatrotatemacroforaminute.YouprobablyknowthattheROTATEcommandhasa copyoptionincludednow,whichenablesyoutorotateacopyofanobjectwhileleavingtheoriginal intact.Butwhatifyouwanttocopytheobjectfirst,andthenrotateit?Trythismacro: ^C^C_copy;\;\\_rotate;L;;@;\ ^C^C _copy; \ ; \\ Cancelsanyrunningcommands. StartstheCOPYcommand. Pausesforuserinput,soyoucanselecttheobjecttocopy. Endstheselectobjectsmode. Pausesforuserinput,soyoucanselectthebasepointandthesecondpoint.(Even thoughCOPYusuallyletsyoumakemultiplecopies,forsomereasonhereitdefaultstoa singlecopy.Itworks,though.) StartstheROTATEcommand. Selectsthelastobjectcreatedastheobjecttorotateandendstheselectionmode.(If weusedPhere,forprevious,therotatecommandwouldselecttheoriginalobject, notthecopy.) Usesthecoordinatesofthelastpointspecified.Inthiscase,thatstheendpointofthe copy. Pausesforuserinput,soyoucanspecifytherotationangle.

_rotate; L;;

@;

Example:ArcwithDonut
Heresonemoremacrothatmakesuseofthe@function.Itcreatesaleaderlikeobjectconsistingofa 3pointarcandasoliddonutontheend. ^C^C_arc;\\\donut;0;0.5;@;

IntroductiontoMacroWriting

Thethreepausesaretheresoyoucanspecifythethreepartsofthearc.Thedonuthasthesameinside andoutsidediameterseverytime(0and0.5units),anditsautomaticallyplacedattheendofthe newlycreatedarc.

MacrosforDialogBasedCommands
Creatingmacrosbasedonmostcommandsisverystraightforwardalltheoptionsyouhaveareright thereinthecommandline.Butyoucantuseamacrotoselectanoptioninadialogbox,because macrosarecompletelytextbased.Soifyouwanttouseamacrotocreatehatches,insertblocks,orrun plots,youhavetousethecommandlineversionstodoit. Gettingadialogbasedcommandonthecommandlineisassimpleasprefixingthecommandnamewith ahyphen(-).Forexample,-hatch or -insert. Whenusingtextbasedversionsofdialogboxes,youhavetopayattentiontotheorderinwhichoptions andsettingsarepresented.Inadialogbox,youcanpickanybuttonorboxatanytime,butthatsnot necessarilythecasewithcommandlinecommands.

Example:CreateaHatch
Heresanexampleofthecommandlinesyntaxyoumightusetocreateahatch: Command: -HATCH(enter) Current hatch pattern: ANSI31 Specify internal point or [Properties/Select objects/draW boundary/remove Boundaries/Advanced/DRaw order/Origin/ANnotative]: P(enter) Enter a pattern name or [?/Solid/User defined] <ANSI31>: ANSI37(enter) Specify a scale for the pattern <1.0000>: 4(enter) Specify an angle for the pattern <0>: 45(enter) Current hatch pattern: ANSI37 Specify internal point or [Properties/Select objects/draW boundary/remove Boundaries/Advanced/DRaw order/Origin/ANnotative]: S(enter) Select objects: (left-click) 1 found Select objects: (enter) Current hatch pattern: ANSI37 Specify internal point or [Properties/Select objects/draW boundary/remove Boundaries/Advanced/DRaw order/Origin/ANnotative]: (enter) ThissequencesetsthepropertiesofthehatchtobetheANSI37patternwithascaleof4andanangleof 45,andusesapredrawnobjectasthehatchboundary.Noticethatonceweenteredtheproperties section,wehadtospecifypattern,thenscale,thenangle.Itsoneexampleofhowsequencemattersin amacrowhereitwouldntinadialogbox.

IntroductiontoMacroWriting

Youllnoticethatwecouldhavespecifiedaninternalpoint,ordrawntheboundaryfromscratch.Other boundaryoptions,likeretentionandislanddetection,wouldbeavailablethroughtheadvancedoption. Wecouldalsohavesetthedraworder,origin,andannotativepropertiesofthehatchwiththismacro. Replacingalltheenterswithsemicolonsandtheleftclickswithbackslashesresultsinthefollowing macro: ^C^C-hatch;P;ANSI37;4;45;S;\;; HatchescanalsobeinsertedfromToolPalettes(seesectionlaterinthishandout).

Example:InsertaBlock
LikeHATCH,usingINSERTatthecommandlinemeansthatsomeofyouroptionsarepresentedina specificorder. Command: -INSERT (enter) Enter block name or [?]: SAMPLE (enter) Units: Inches Conversion: 1.0000 Specify insertion point or [Basepoint/Scale/Rotate]: S (enter) Specify scale factor for XYZ axes <1>: 12 (enter) Specify insertion point or [Basepoint/Scale/Rotate]: R (enter) Specify rotation angle <0.0000>: 90 (enter) Specify insertion point or [Basepoint/Scale/Rotate]: (left-click) Inthiscase,theblockisspecifiedtohaveascalefactorof12andarotationof90degrees.Replacing entersandleftclickswithsemicolonsandbackslashesgivesusthis: ^C^C-insert;sample;S;12;R;90;\ Youcanalsoreplaceanyofthenumbersherewithbackslashesforuserinput. Sometimesyouwantblockstobeexplodedoninsertion,sotheircontentscanbeeditedimmediately.(I usedtodothisfortypicaldetailfiles,whichneededanewsheetnameandnumberwiththesame titleeverytime.) Theeasiestwaytoaccomplishthisistoprecedetheblocknamewithanasterisk. Command: -INSERT (enter) Enter block name or [?]: *SAMPLE Specify insertion point for block: (left-click) Specify scale factor for XYZ axes: 12 (enter) Specify rotation angle <0>: 90(enter) Noticethattheorderofthepromptshereisalittledifferentusingthismethod.Youdontneedtoenter RorSforrotationandscale,becauseyourepromptedforthembydefault.Hereswhatthemacrolooks likewithalltheentersandleftclicksreplaced: 9

IntroductiontoMacroWriting

^C^C-insert;*sample;\12;90; Asideeffecttothismethodisthattheblockdefinitionisntaddedtothedrawingifitsnotalready there.Thiscaneitherbeagoodthingorabadthing,dependingonyourworkflow.Anothersideeffectis thatyoucantseeapreviewoftheblockbeforeyouinsertit.So,ifseeingwheretoplacetheblockis moreimportantthankeepingthedefinitionoutofthedrawing,youcanusethefollowingmacro.Ituses EXPLODEwiththelastselectionoptiontoexplodethemostrecentlycreatedobjectinthiscase,the newlyinsertedblock. ^C^C-insert;sample;S;12;R;90;\explode;L; Youmightalsowantthebestofbothworlds,whereyoucanseetheblockasyouplaceitbutstillkeep theblockdefinitionoutofthedrawing.Inthatcase,tackthePURGEcommandontotheendofthe macro. Command: -PURGE (enter) Enter type of unused objects to purge [Blocks/Dimstyles/LAyers/LTypes/MAterials/MUltileaderstyles/Plotstyles /SHapes/textSTyles/Mlinestyles/Tablestyles/Visualstyles/Regapps/Zerolength geometry/Empty text objects/All]: B (enter) Enter name(s) to purge <*>: SAMPLE (enter) Verify each name to be purged? [Yes/No] <Y>: N (enter) Deleting block "sample". 1 block deleted. Theresultingmacrowouldlooklikethis: ^C^C-insert;sample;S;12;R;90;\explode;L;-purge;B;sample;N; Thisonlyworksifnoothercopiesoftheblockexistinthedrawingwhenyourunthemacro,because youcantpurgeobjectsinuse. Note:Whenusingamacrotoinsertablock,theblockyoureinsertingeitherhastoalreadyexistinyour drawing,orafilewiththatnamemustbeinyoursupportfilesearchpaths.Youcangetaroundthisby includingtheentirepathtotheblockfileinthemacro,butIvefounditlesscumbersometokeepthe macrosshortandcontroltheblocklocationwiththesupportfilepaths.

10

IntroductiontoMacroWriting

Example3:ChangeLayerSettings
Usingmacrosisagreatwaytocreatelayersinadrawingorresetlayerproperties.Herearethestepsfor creatingared,continuouslayercalledSANNOTEXT. Command: -LAYER (enter) Current layer: "0" Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/MATerial/Plot/Freeze /Thaw/LOck/Unlock/stAte/Description/rEconcile]: M (enter) Enter name for new layer (becomes the current layer) <0>: S-ANNO-TEXT (enter) Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/MATerial/Plot/Freeze /Thaw/LOck/Unlock/stAte/Description/rEconcile]: C (enter) New color [Truecolor/COlorbook] : 1 (enter) Enter name list of layer(s) for color 1 (red) <S-ANNO-TEXT>: (enter) Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/MATerial/Plot/Freeze /Thaw/LOck/Unlock/stAte/Description/rEconcile]: L (enter) Enter loaded linetype name or [?] <Continuous>: Continuous (enter) Enter name list of layer(s) for linetype "Continuous" <S-ANNO-TEXT>: (enter) Enter an option [?/Make/Set/New/Rename/ON/OFF/Color/Ltype/LWeight/MATerial/Plot/Freeze /Thaw/LOck/Unlock/stAte/Description/rEconcile]: (enter) NoticehowmanyplacesyouhavetopressEntermorethanonce.Replacingalltheenterswith semicolons(besuretocountthemall!)resultsinthis: ^C^C-layer;M;S-ANNO-TEXT;C;1;;L;Continuous;;; Thenextexampleusesalinetypethatmayormaynotexistinthedrawingalready.(Intheprevious example,itsasafebetthatcontinuousisalwaysloaded.) Togetaroundthis,themacrofirstinsertsadrawingthatcontainsnothingbutthatlinetypedefinition. Noobjects,nostylesjustthatlinetype.Itinsertsitexploded(notetheasterisk),sothattheblock definitionisntsavedinthecurrentdrawing.Thenthemacrocancontinuewiththelayersettings. ^C^C-insert;*LT_beam_removed;0,0;1;;-layer;M;S-BEAM-STELDEMO;C;1;;L;BEAM_REMOVED;;; BothoftheseexamplesusethecommandlineversionoftheLayercommandwiththeMakeoption.I likeMakehere,insteadofSetorNew,becauseMakecombinesSetandNew.

11

IntroductiontoMacroWriting

Example4:PlotaDrawing
Thisplottingmacroassumesthatyoualreadyhaveapagesetupdefinedinthedrawing. Wellcontinuetofollowthe#1ruleofmacrowritingandgothroughthecommandlinepromptsfirst: Command: -PLOT (enter) Detailed plot configuration? [Yes/No] <No>: N(enter) Enter a layout name or [?] <Layout1>: Layout1 (enter) Enter a page setup name <>: Setup1 (enter) Enter an output device name or [?] <HP Officejet 4300 series>: (enter) Write the plot to a file [Yes/No] <N>: (enter) Save changes to page setup [Yes/No]? <N>: (enter) Proceed with plot [Yes/No] <Y>: (enter) ThiswouldplotLayout1totheHPOfficejetusingthepagesetupSetup1.Replacingalltheenterswith semicolonsresultsinthefollowing: ^C^C-plot;N;Layout1;Setup1;;;;; Ifyouwantedtousethesamesetupwithadifferentplotter,youwouldputtheplotternamerightafter thesemicolonfortheSetup1call. Onceyouhavethebasicstructureofthemacrodown,youcancopyitandrefineittousedifferentpage setupnamesordifferentplotters.

RepeatingMacros
Becausemacrosarebasicallyseriesofcommands,youcantrepeatthembyjustpressingEnterorthe spacebar,orwitharightclick(ifrightclickissettoactasEnter). However,ifyourrightclickissettobringupshortcutmenus,orifyouhavethetimesensitiveright clicksturnedon(myfavorite),thenyoucanusethemtorepeatmacros.Itllbethetopoptioninthe shortcutmenu. Ifyoulaunchedthemacrofromtheribbon,though,youcantrepeatitwithoutselectingtheribbonicon again.Thisistrueforthe2009and2010familiesofAutoCADbasedproducts.

BringingMacrosThroughUpgrades
Commandoptions(andsometimescommandnames)dontalwaysstaythesamefromreleaseto release.Forexample,thevariablePEDITACCEPTwasintroducedafewversionsago,whichmeantthat oneofthepromptsinthePEDITcommandcouldbeeliminated.(Selectedobjectisnotapolyline.Do youwanttoturnitintoone?)IfyouhadanoldmacrothatranPEDIT,itmighthaveanextracharacter ortwothatcouldcausesomeunexpectedbehavior.

12

IntroductiontoMacroWriting

Somecommandsalsoactuallychangebehaviorfromreleasetorelease.Forthose,youmightneedto usethecontrolcharacter^R(forcommandversioning)tolaunchtheversionofthecommandthatwill workinamacro.YoullseebelowthattheFILLETcommandisonethatrequirescommandversioning. Evenifyoudontanticipateanychanges,itsagoodideatoreviewallyourcustomcommandswhenyou upgradetoanewreleaseofAutoCADorAutoCADLT.

UsingDIESELinMacros
Okay,Illadmitit.DIESELisaprogramminglanguage.Ifyouuseit,youretechnicallyprogramming.ButI dontclassifyitwiththeotherlanguageslikeLISPandVBAeverythingsinoneline,therearenttoo manyparenthesestoworryabout,anditstilldoesbasicallywhatyouwoulddoinaregularcommand. Thatsmystory,andImstickingtoit. DIESELstandsforDirectInterpretivelyEvaluatedStringExpressionLanguage,anditstheonly programminglanguageavailableinAutoCADLT.Itscompletelybuiltintotheprogramyoudonthave tocreateexternalfilestouseit,thewayyoudowithLISPandVBA. YoucanuseDIESELexpressionstodobasicmathcalculations,andtoretrieveorsetsystemvariables. UsingDIESELmeansthatyoucandomuchmorewithamacrothansimplecommandpromptsmight allow.

DIESELMacrocomponents
DIESELexpressionsthatareusedinCUIelementsmustalwaysbeginwiththesamecommandstring: $M= DollarsignsalsoalwaysprecedeDIESELexpressions,andtheyrealwayssurroundedbyparentheses: $(diesel expression here) ThenextthingtoknowaboutDIESELexpressionsisthattheircommandsequenceisbackwardsfrom regularcalculators.Inastandardcalculator,youwouldenter2+3toget5,or12/3toget4.Butin DIESEL,theoperatorcomesfirst. $(+,2,3) $(/,12,4) Ithelpstothinkaboutthisverbally.Iwanttoadd2and3.Iwanttodivide12by4.Ifyouvisualize theexpressionthisway,youllalwaysgettheorderright.

13

IntroductiontoMacroWriting

UsingVariablesinDIESEL
Youprobablywouldntuseeitheroftheaboveexamplesinanactualmacro.Youdjustdothemath yourselffirst,andplugintheresultwhereyouneededit.Butwhatifoneofthenumbersyouneeded wasavariablemaybethecurrentDIMSCALEofyourdrawing? ThisiswhereDIESELreallycomesinhandy.TheGETVARfunctioncanbeusedinsomereallypowerful ways,althoughwellstartwithaprettysimpleexample. $(getvar,DIMSCALE) Thisexpressionreturnsanumber,specificallythecurrentDIMSCALEofthedrawing.Onceyouhaveit, youcanuseitinanotherexpression. $M=$(*,$(getvar,DIMSCALE),0.25) Readingfromlefttoright,thisexpressionmultiplies(withtheasterisk)theDIMSCALE(thenumberfrom theGETVARexpression)by0.25(thelastnumberintheexpression). Sonowwehaveanewnumber,onethats1/4ofthecurrentDIMSCALE.Finally,wecanuseittosetthe radiusfortheFILLETcommand. ^C^C^Rfillet;R;$M=$(*,$(getvar,DIMSCALE),0.25); Againreadingfromlefttoright,thismacrocancelsanyrunningcommand(with^Rtolaunchthecorrect versionofthefilletcommand),startsFILLET,entersRtosettheradius,andlastlyplugsinourDIESEL expressiontosetthevalue. YoucoulduseDIMSCALEinanexpressiontosettheinsertionscaleofablock,orlinetypescalesfor plotting,oranynumberofthings. HerearetwomoremacrosforstartingtheTEXTandMTEXTcommandswithaspecifictextheight(they assumethatthestyleheightis0): ^C^C_dtext;\$M=$(*,$(getvar,DIMSCALE),0.125); ^C^C_mtext;\H;$M=$(*,$(getvar,DIMSCALE),0.125);\ Andofcourse,DIMSCALEisnttheonlyvariableyoucanuseanythingthatyoucansetfromthe commandline,youcancallwithGETVAR.

ConditionalExpressions
DIESELalsosupportsanIFfunction,whichishandyfortogglingbetweentwovariablesettings,orfor performinganoperationonlyifanothervaluemeetscertaincriteria.IFfunctionslooklikethis: $(if,expression,true,false)

14

IntroductiontoMacroWriting

ItsalotlikethesimilarfunctioninExcel.First,yougiveitanexpressiontoevaluate.Ifthatcomesback astrue,IFwillrunthetruepartoftheexpression.Otherwise,itllrunfalse. Heresamacroforswitchingbetweencursorsizesof5%and100%. ^C^C$M=$(if,$(=,$(getvar,cursorsize),100),cursorsize;5;;,cursorsize;10 0;;) Inthiscase,theexpressionis: $(=,$(getvar,cursorsize),100) Inotherwords,isthecursorsizealreadysetto100?Ifitis,thenitrunsthetruepart: cursorsize;5;; Andifthecursorsizeisnt100,itrunsthefalsepart: cursorsize;100;; SothevalueofCURSORSIZEisswitchedbackandfortheachtimethemacroisrun.

USERVariables
DIESELdoesnthavethesameflexibilitywithvariablenamesasLISP,butthereareseveralpresetvalues youcanuse. Therearetenvariablesthatcanbeusedtostorenumbers:fiveUSERI(forintegers)andfiveUSERR(for realnumbers,ornumberswithdecimals).Thenextmacrousestheminaprettyneatwayto automaticallyincrementthevalueofablockattributeeachtimeitsinserted. *^C^C_insert;label;\;;$M=$(getvar,USERI1);USERI1;$M=$(+,$(getvar,USERI1),1); Thefirsthalfofthismacro(uptothefirst$)justinsertstheblockthewayanyothermacrowould.But afterthat,itcallsuptheUSERI1variable,andputsthatinastheattributevalue.Whenitsdone,ituses theadditionfunctiontoadd1toUSER1,incrementingitforthenextinsertion. Thismacrowillworkbestifyouonlyhaveoneattributetofillin.YoualsoneedtoresetUSERI1toyour desiredstartingvaluebeforeeachuse.Youcoulddothisresettingwithamacro,orsimplytypeitinat thecommandline.

15

IntroductiontoMacroWriting

UsingMacrosinCUIElements
Nowthatyouhaveamacro,youneedaplacetoputit.Macroscanbeaddedtoanumberofinterface elementsusingtheCustomizeUserInterface(CUI)Editor. TheCUIisabigtopic,butthenextfewpageswillgiveyouacrashcourseinwhatyouneedtoknowto beginexperimentingwithyourownmacros.

CreatingaNewMacroBasedCommand
Macrosarecustomcommands,soyoullneedtousetheNewCommandbuttonintheCommandList paneoftheCUIEditor.

16

IntroductiontoMacroWriting

Inthenewcommandpanethatopens,youcanfillinalltheinformationaboutyourcommand. IntheNameField,giveyourcommanda descriptivename,somethingthatwillhelp yourememberwhatitdoes. TheDescriptionFieldiswhatwillshowup inthetooltip. TheExtendedHelpFilecanpointtoa separatefilecontaininginformationthat wouldshowupinanextendedtooltip(the onesthatshowupafteryouvehovered overabuttonforawhile). TheCommandDisplaynameshowsthe commandlineversionofthecommand.It isntnecessarilyhelpfulformacros,since youcantcallthemfromthecommandline. TheMacrofieldiswhereyouputyour customcommandsyntax.Thesmallbutton attheendofthelineopensabigger windowthatcanbehelpfulwhenentering longmacros. TagsarekeywordsthatcanbeusedassearchtermsintheMenuBrowser. TheElementIDisauniquetagassignedtoeachcommand.AutoCADwillautomaticallygenerateone, andifyouuseityoureguaranteedthatitwontoverlapanythingelse. Finally,intheImagessection,youcaneitheruseoneoftheincludediconsorpointthemacrotoyour ownBMPfiles. ThecriticalfieldshereforyoutofillinareName,Macro,andImages.Therestareoptional,butmaybe helpfultootherpeopleusingyourmacro.

UsingYourNewCommand
Thelaststepinusingthisnewcommandistoputitonaninterfaceelementsoyoucanaccessit.Within theCUIEditor,yourchoicesforelementsareribbonpanels,toolbars,andmenus.Creatinganyoneof thesemakesuseofthetwomaineditingfunctionsintheCUI:rightclickinganddraganddropping.

17

IntroductiontoMacroWriting

Toolbars
Toputyournewcommandonatoolbar,youhaveacoupleofchoices.Youcaneitherdraganddropit straightontoanexistingtoolbar,oryoucancreateanewtoolbaranddraganddropthecommand there. Eitherway,theprocessisverystraightforward.First,locatetheToolbarnodeinoneofyourloadedCUI files,andexpandittoseeyouravailabletoolbars.Ifyouwantanewtoolbar,justrightclickonthe ToolbarnodeandselectNewToolbar. Onceyouhavethetoolbaryouwant,simplydraganddropyourcommandfromtheCommandListpane ontothetoolbar.

Menus
Theprocedureforputtingacommandonamenuisverysimilartotheonefortoolbars,exceptthat menuscanhavemultiplelevels. Again,ifthemenuyouwanttoaddthecommandtoalreadyexists,simplydraganddropthecommand ontoit. Ifyouwantanewmenu,rightclickoneithertheMenunodeoronanexistingmenu.Fromthere,select NewMenuorNewSubmenu.NewMenuaddsanewmenuatthesamelevelastheoneonwhichyou clicked,whileNewSubmenucreatesanewmenuonelevelinfromtheoriginalmenu. Thenyoucan draganddropyourcommandintothenewmenu.

RibbonPanels
Ribbonpanelsarealittlemorecomplicatedthanmenusandtoolbars,becausetheyhavemoreicon displayoptions. Justlikemenusandtoolbars,youcandraganddropcommandsdirectlyontoanexistingRibbonpanel, orcreatenewpanelsbyrightclickingonnodesintheCUIeditor.Keepinmindthatifyoucreateanew Ribbonpanel,youalsohavetocreateanewRibbontabforit(ordragitontoanexistingtab),oritwont showup.

18

IntroductiontoMacroWriting

ThisisascreenshotofthePropertiespaneofaRibbonbuttonforthesamecommandwecreatedapage earlier.Youcanseethatalthoughmostofthefieldsarethesame,therearethreenewsections Display,Appearance,andAccesswithmoreoptions. Letsstartatthetop. DisplayNameisthetextthatisdisplayedon theribbon,ifyouwanttext.Ifitsleftblank, theCommandNameisusedasthedisplay name. UnderAppearance,youhavefourchoices forthebuttonstyle: LargeWithText(Vertical) LargeWithText(Horizontal) SmallWithText SmallWithoutText

Thesecontrolthesizeoftheiconandthe positionofthetext,ifany. Groupingonlyappliestoflyoutcommands. Finally,KeyTipisthehotkeycombination thatcanbeusedtolaunchthemacro.Theyre usedincombinationwiththeAltkeyto activateribbontabsandcommands. Yes,thatmeansitsnowpossibletorunmacrosfromthekeyboard.

SharingCUIMacros
TheeasiestwaytosharethemacrosyoucreateisbytransferringthemtoanewCUIfile,usingthe TransfertabintheCUIeditor.SimplydraganddropyourRibbonpanels/tabs,menus,andtoolbarsfrom theleftsidetotheright,andsavethenewCUIfile.Thenyoucaneithergiveittopeopletosaveontheir owncomputer,orputitinanetworkedlocation. ToloadthisnewpartialCUIfile,usetheopeniconintheCustomizetaboftheeditor. loaded,youcanmodifyyourworkspacetoturnonthenewtools. Afterits

19

IntroductiontoMacroWriting

UsingMacrosonToolPalettes
YouprobablyalreadyknowthatyoucanaddblocksandhatchestoToolPalettes.Youmayevenknow thatyoucanaddcommandstoToolPalettes.Butdidyouknowyoucanaddmacrostothosecommand tools?

CommandTools
Letssayyouwanttoaddthat1unitradiuscircletoatoolpalette.Soyoucreateacircleanddragand dropitontoaneworexistingpalette.

20

IntroductiontoMacroWriting

Tomakesurethatallofyoursettingsarecorrect,youcanrightclickonthecircleandselectProperties. Hereswhatyousee: NoticethattheNameandDescription,aswellasthe Image,areblank.Thatsbecauseitsusingthedefault commandnameanddescription.Youcanalsoseethat UseFlyoutissettoYes,andthattheCommand Stringisgrayyoucanttypethere. Butinthiscase,youdontneedalltheflyoutoptions youjustwanttousethemacrotocreateacircle.So changetheflyouttoNo,andenteryourmacrointhe CommandStringbox.YoucouldsettheGeneral propertieshereaswell,ifyouwantedtocreatethe circleonaparticularlayer,orwithaparticularcolor, linetype,etc.

Whenyoumoveawayfromthedefaultoptions,thisisalsoyourchancetoenteryourownnameforthe command,andadescriptionthatwillshowupasatooltip. Theimageinthisscreenshotwasassigned automaticallyifyoudratheruseadifferentone,right clickandselectSpecifyImage. Belowisthefinaltool:

21

IntroductiontoMacroWriting

Block&HatchTools
WhenyoudraganddropblocksorhatchesontoToolPalettes,theyautomaticallyinherittheproperties ofthesourceobject.Ifthatswhatyouwant,thenyouredone.Ifnot,youcanrightclickthenewtool andselectProperties,justlikewithcommandtools.Thedialogboxeswilllookalittledifferent,butthe effectsarethesame.

Anypropertythatcouldbesetinacommandlinemacrocanbesetthroughthetoolsproperties.Itsan easywaytomakesurethesamesettingsareusedeverytime. Youcanevenmimictheeffectof$(getvar,DIMSCALE)inatoolwiththeAuxiliaryScaleproperty.(Seethe blockpropertiesimageabove.)IfyousetthattoDimscale,eachtimeyouinserttheblockorusethe hatchitwillreadthecurrentDIMSCALE,multiplythatbytheScaleproperty,andscaleitselfaccordingly. Youllneverhavetodothemathyourselfagain.

22

IntroductiontoMacroWriting

CreatingMacroswiththeActionRecorder
TheActionRecorderistheonepartofthishandoutthatdoesntapplytoLT.(Sorry.)Butifyoure runningfullAutoCAD,itcanbeahandywaytocreateandstoreyourmacroswithouthavingtotype themoutbyhand.

Introduction
TheActionRecorderisawaytorecordmouseclicksandcommandentryautomatically.Thenyoucan playthembackasneededtorepeattheperformedstepswithminimaleffort.Actionmacrosarecreated withanACTMfileextension,andthosefilescanbeeasilysharedbetweenusers.

ThefollowingoptionsareavailableontheActionRecorderpanel: 1. Record.Startsrecordingtheseriesofactionsthatwillcreateanactionmacro. 2. InsertaMessage,InsertaBasePoint,PauseforUserInput.Amessageistextyouwanttoshow theuserduringtheactionmacroplayback.BasePointsprovideareferencelocationfor followingrelativecoordinatesintheactionmacro.PausingforUserInputreplacesthestored inputwithaplacewheretheusercanenterinformation. 3. Play.Playsbacktheselectedactionmacro. 4. Preferences.EnablestheActionRecorderPreferencesdialog. 5. ManageActionMacros.UsetheActionMacroManagertocopy,rename,modify,ordelete actionmacrofiles. 6. ActionMacrolist.Displaysalistofallavailableactionmacros. 7. ActionTree.Theseriesofactionsthatmakeupthemacro. 8. ActionItem.OnecommandorinputintheActionTree.

23

IntroductiontoMacroWriting

CreatingActionMacros
YouusetheRecordbuttonintheActionRecordertobegincreatinganactionmacro.Whileitis recordingyoucanlaunchcommands,entervaluesandselectobjectsusingfamiliarAutoCAD functionality.TheActionRecordercanrecordtypicalactionsfromthecommandlineaswellasfrom toolbars,ribbonpanels,pulldownmenus,thePropertiespalette,theLayerPropertiesManagerandTool Palettes.However,mostdialogboxesarenotrecordedintheActionRecorderunlessyouusethe commandlineequivalentofthedialogboxsetting.(See?Learninghowtowritemacrosbyhandisstill useful.)Whenyourefinishedrecording,clickStopontheActionRecorderpanel. Rememberthatthisisnotatimedexercise!Evenifyousitthereforfiveminuteswhileyoudecidewhat yournextstepshouldbe,itwontaffecthowfastthemacrowillplayback.Itllplaybackasfastasit canasfastasanordinarymacrowould.SodontletthebrightredRecordbuttonmakeyounervous.

ActionMacroFileLocations
Eachactionmacroyourecordissavedasanindividualfileandisrecordedbythelocalmachineatthe ActionsRecordingFileLocationwithanACTMextension.ThefilelocationisspecifiedintheOptions dialogbox,Filestab,underActionRecorderSettings.

SharedActionMacros
Toallowotherstouseamacroyoucreate,youmustcopythemacrofileontoeachcomputerwhereyou wanttouseit.CopyittothelocationindicatedbytheActionsRecordingFileLocationoption. Youcanalsoputactionmacrosonyournetwork,andpointthesupportpathsinAutoCADtothe appropriatelocation.

GuidelinesforUsingActionMacros
Hereareafewrecommendedpracticestoenableyoutouseactionmacrosefficiently.Youcanusethese guidelinestocreate,editandplayactionmacros. Whilerecordingamacro,onlylaunchcommandsfromribbonpanels,toolpalettes,menusor toolbars.Donotlaunchcommandsthatbringupadialogbox. Ifyouwanttorecordthesettingschangedinadialogbox,usethecommandlineequivalentof thecommandandspecifythesettingsatthecommandline.Thiswillensurethatthemacro recordsthesteps. Whenyouusethecommandlineequivalentsfordialogboxsettingsinanactionmacro,dont acceptcommandlinedefaults.Alwaystypeinavalue. Ifyoudontwantanactionmacrotobechanged,youshoulduseWindowsExplorertoplacea readonlyattributeonthefileoronthedirectoryitissharedin.

24

IntroductiontoMacroWriting

AdditionalResources
Ifyouneedmoreinformation,checkoutthesewebsites: TheAutoCADhomepage:www.autodesk.com/autocad TheAutoCADLThomepage:www.autodesk.com/autocadlt TheAutodeskDiscussionGroups:www.autodesk.com/discussion LTUnlimitedtheofficialLTblog:http://ltunlimited.typepad.com AUGI:www.augi.com

AppendixA:SummaryofHandoutMacros
Drawacirclewitharadiusof1 ^C^C_circle;\1; Drawmultiplecircleswitharadiusof1 *^C^C_circle;\1; Rotatebyafixedangle ^C^C_rotate;\;\180; CopythenRotate ^C^C_copy;\;\\_rotate;L;;@;\ ArcwithDonut ^C^C_arc;\\\donut;0;0.5;@; CreateahatchwithpatternANSI37,scaleof4,angleof45,appliedtoaselectedobject ^C^C-hatch;P;ANSI37;4;45;S;\;; Insertablockwithascaleof12andarotationof90 ^C^C-insert;sample;S;12;R;90;\ Insertanexplodedblockwithascaleof12andarotationof90 ^C^C-insert;*sample;\12;90; Insertablockwithascaleof12andarotationof90,thenexplodeit ^C^C-insert;sample;S;12;R;90;\explode;L; Insertablockwithascaleof12andarotationof90,thenexplodeandpurgeit ^C^C-insert;sample;S;12;R;90;\explode;L;-purge;B;sample;N; Createaredlayerwithacontinuouslinetype ^C^C-layer;M;S-ANNO-TEXT;C;1;;L;Continuous;;; 25

IntroductiontoMacroWriting

Loadalinetype,thencreatearedlayerthatusesthatlinetype ^C^C-insert;*LT_beam_removed;0,0;1;;-layer;M;S-BEAM-STELDEMO;C;1;;L;BEAM_REMOVED;;; Plotadrawing ^C^C-plot;N;Layout1;Setup1;;;;; Createafilletwitharadiusequalto1/4timestheDIMSCALE ^C^C^Rfillet;R;$M=$(*,$(getvar,DIMSCALE),0.25); Createtextwithaheightequalto1/8timestheDIMSCALE ^C^C_dtext;\$M=$(*,$(getvar,DIMSCALE),0.125); Createmtextwithaheightequalto1/8timestheDIMSCALE ^C^C_mtext;\H;$M=$(*,$(getvar,DIMSCALE),0.125);\ ToggleCURSORSIZEbetween5%and100% ^C^C$M=$(if,$(=,$(getvar,cursorsize),100),cursorsize;5;;,cursorsize;10 0;;) Insertablockwithasingleattribute,andincreasetheattributevalueby1everytime *^C^C_insert;label;\;;$M=$(getvar,USERI1);USERI1;$M=$(+,$(getvar,USERI1),1);

AppendixB:UserMacros(Untested)
Ihaventbeenabletotestmostofthese,butthepeoplewhopostedthemonthediscussiongroups swearbythem.Ifyouhaveanyquestionsaboutthem,thatstheplacetolook. (http://discussion.autodesk.com) Generalcleanupbeforeclosing C^C^P-layout;set;Model;-layer;s;0;;zoom;e;.-purge;a;*;no;layout;set;;zoom;e;'spell;_qsave UsedforjoininglinesintopolylinespriortosendingtoaCNCmachine ^C^C_SELECT;SI;\^C^C_EXPLODE;@;^C^C_PEDIT;@;Y;J;ALL;;^C^C^C Redefineablock ^C^C-insert;sample=sample;\;;; Lockandhideviewports ^C^C-layer;thaw;vport;;MVIEW;L;ON;ALL;;-LAYER;S;0;OFF;VPORT;; Unlockandshowviewports ^C^C-layer;thaw;vport;;MVIEW;L;OFF;ALL;;-LAYER;ON;VPORT;; 26

IntroductiontoMacroWriting

Togglebetweenrectangularandisometricsnaps(fromKevinChandler,LaneAssociates) Thismacrodemonstratestheautomaticchecking/uncheckingofapulldownmenu: Forthemenu'sNamefield: $(if,$(and,$(getvar,SNAPSTYL),1),!.)Isometric Cursor Forthemacrofield: $M=$(if,$(and,$(getvar,SNAPSTYL),1),;^C^C_SNAPSTYL;0,;^C^C_SNAPSTYL;1) TogglebetweenLayoutsandModelspace(fromErikDeyo,http://ltsideofthings.blogspot.com) ^C^Csetvar;tilemode;$M=$(!=,$(getvar,tilemode),1) SetsthenewcurrentlayertoDIM,createsalineardimension,andrestorestheoriginallayertocurrent: ^C^C_setenv;CURRENTLAYER;$M=$(getvar,CLAYER);CLAYER;Dim;_dimlinear;\\\ CLAYER;$M="$(getenv,CURRENTLAYER)"; Labelsapolylinewithitsarea: ^C^Carea;e;\_mtext;$M=$(getvar,viewctr);@;AREA=$m=$(rtos,$(/,$(getvar,area),1000000 ),2,3)m;;_move;_L;;@;\

27

You might also like