Page 1
AutoLISPDeveloper'sGuide>
Introduction
Foryears,AutoLISP®hassetthestandardforcustomizingAutoCAD®.NowVisualLISP®(VLISP)representsthenextgenerationofLISPforAutoCAD,byaddingsignificantlymorecapabilities.VLISPextendsthelanguagetointerfacewithobjectsviatheMicrosoftActiveX®Automationinterface,andenhancestheabilityofAutoLISPtorespondtoeventsthroughtheimplementationofreactorfunctions.Asadevelopmenttool,VLISPprovidesacomplete,integrateddevelopmentenvironment(IDE)thatincludesacompiler,debugger,andothertoolstoincreaseproductivitywhencustomizingAutoCAD.
AutoLISPandVisualLISPUsingVisualLISPDocumentationRelatedDocuments
Pleasesendusyourcommentaboutthispage
Page 2
AutoLISPDeveloper'sGuide>Introduction>
AutoLISPandVisualLISP
AutoLISPisaprogramminglanguagedesignedforextendingandcustomizingAutoCADfunctionality.ItisbasedontheLISPprogramminglanguage,whoseoriginsdatebacktothelate1950s.LISPwasoriginallydesignedforuseinArtificialIntelligence(AI)applications,andisstillthebasisformanyAIapplications.
AutoCADintroducedAutoLISPasanapplicationprogramminginterface(API)inRelease2.1,inthemid-1980s.LISPwaschosenastheinitialAutoCADAPIbecauseitwasuniquelysuitedfortheunstructureddesignprocessofAutoCADprojects,whichinvolvedrepeatedlytryingdifferentsolutionstodesignproblems.
VisualLISP(VLISP)isasoftwaretooldesignedtoexpediteAutoLISPprogramdevelopment.TheVLISPintegrateddevelopmentenvironment(IDE)providesfeaturestohelpeasethetasksofsource-codecreationandmodification,programtesting,anddebugging.Inaddition,VLISPprovidesavehiclefordeliveringstandaloneapplicationswritteninAutoLISP.
Inthepast,developingAutoLISPprogramsforAutoCADmeantsupplyingyourowntexteditorforwritingcode,thenloadingthecodeintoAutoCADandrunningit.Debuggingyourprogrammeantaddingstatementstoprintthecontentsofvariablesatstrategicpointsinyourprogram.Youhadtofigureoutwhereinyourprogramtodothis,andwhatvariablesyouneededtolookat.Ifyoudiscoveredyoustilldidn'thaveenoughinformationtodeterminetheerror,youhadtogobackandchangethecodeagainbyaddingmoredebuggingpoints.Andfinally,whenyougottheprogramtoworkcorrectly,youneededtoeithercommentoutorremovethedebuggingcodeyouadded.
WhatVisualLISPOffersWorkingwithVisualLISPandAutoCAD
Page 3
Pleasesendusyourcommentaboutthispage
Page 4
AutoLISPDeveloper'sGuide>Introduction>AutoLISPandVisualLISP>
WhatVisualLISPOffers
DuringthedevelopmentcycleofanAutoLISPapplicationorroutine,theAutoLISPuserperformsanumberofoperationsthatarenotavailablewithintheAutoCADsoftware.Someoftheseoperations—liketextediting—areavailablewithothersoftwaretools.Others,suchasfullAutoLISPsource-leveldebugging,areintroducedonlywithVLISP.InVLISP,youperformmostofthenecessaryoperationsinsideasingleenvironment.Thispermitstextediting,programdebugging,andinteractionwithAutoCADandotherapplications.
ThefollowingarecomponentsoftheVisualLISPIDE:
SyntaxCheckerrecognizeserroneousAutoLISPconstructsandimproperargumentsincallstobuilt-infunctions.
FileCompilerimprovestheexecutionspeedandprovidesasecureandefficientdeliveryplatform.
SourceDebugger,designedspecificallyforAutoLISP,supportssteppingthroughAutoLISPsourcecodeinonewindowwhilesimultaneouslydisplayingtheresultsofcodeexecutioninanAutoCADdrawingwindow.
TextFileEditorusesAutoLISPandDCLcolorcoding,aswellasotherAutoLISPsyntaxsupportfeatures.
AutoLISPFormatterrestructuresprogramsintoaneasilyreadableformat.
ComprehensiveInspectandWatchfeaturesprovideconvenientaccesstovariableandexpressionvaluesfordatastructurebrowsingandmodification.ThesefeaturesmaybeusedtoexploreAutoLISPdataandAutoCADdrawingentities.
Context-sensitiveHelpprovidesinformationforAutoLISPfunctionsandapowerfulAproposfeatureforsymbolnamesearch.
Page 5
ProjectManagementsystemmakesiteasytomaintainmultiple-fileapplications.
CompiledAutoLISPfilesarepackagedintoasinglemodule.
DesktopSaveandRestorecapabilitiespreserveandreusethewindowingenvironmentfromanyVLISPsession.
IntelligentConsolewindowintroducesanewlevelofconvenienceandefficiencyforAutoLISPusers.ThebasicfunctionsoftheConsolecorrespondtotheAutoCADTextScreenfunctionsandprovideanumberofinteractivefeatures,suchashistoryscrollingandfull-inputlineediting.
Pleasesendusyourcommentaboutthispage
Page 6
AutoLISPDeveloper'sGuide>Introduction>AutoLISPandVisualLISP>
WorkingwithVisualLISPandAutoCAD
VLISPcontainsitsownsetofwindowsandmenusthataredistinctfromtherestofAutoCAD,butVLISPdoesnotrunindependentlyofAutoCAD.WheneveryouworkinVLISP,AutoCADmustalsoberunning.WhenyourunAutoLISPprogramsfromtheVLISPIDE,youwillusuallyneedtointeractwiththeAutoCADgraphicsorCommandwindowstorespondtoprogramprompts.
IfAutoCADisminimizedwhenVLISPturnscontrolovertoit,youmustmanuallyrestoreandactivatetheAutoCADwindowtocontinue.VLISPwillnotrestoretheAutoCADwindowforyou.Instead,aVisualLISPsymbolappearsintheVLISPwindowandremainsthereuntilyouactivateAutoCADandrespondtothepromptsattheAutoCADCommandprompt.TheGettingStartedchaptershowsanexampleofthis;seeLoadingandRunningAutoLISPPrograms.
Pleasesendusyourcommentaboutthispage
Page 7
AutoLISPDeveloper'sGuide>Introduction>
UsingVisualLISPDocumentation
TheAutoLISPDeveloper'sGuideexplainshowtousetheVisualLISPIDEandhowtobuildandrunAutoLISPapplications.ThisguidealsointroducestheconstructsoftheAutoLISPlanguage.
AllusersshouldchecktheAutoCADReadmefilefornoticesconcerningAutoLISPandVisualLISP.TheReadmefileisintheAutoCADHelpdirectoryandcontainsinformationthatbecameavailabletoolatetobeincludedinthismanual.
IfyouhavedevelopedAutoLISPapplicationsinearlierreleasesofAutoCAD,itisimportantthatyourefertotheReadmefileforinformationonAutoLISPchangesthatmayaffectyourapplications.
AdditionalAutoLISPandVisualLISPmanualsareavailableonlinethroughtheVisualLISPandAutoCADHelpmenus:
TheAutoLISPReferencedescribeseveryAutoLISPfunctionandprovidesexamples.RefertotheAutoLISPReferencewhenyouneedtolookupthesyntaxofafunctionordeterminewhatafunctionreturns.
TheAutoLISPTutorialcontainsstep-by-stepinstructionsguidingyoutowardbuildingaworkingVisualLISPapplication.
ThisAutoLISPDeveloper'sGuideassumesyouhavesomeexperiencewithAutoCADandhavebasicuser-levelskillswithMicrosoft®Windows®.PriorexperiencewithAutoLISPisnotrequired.
TheAutoLISPDeveloper'sGuideisdividedintothefollowingsections:
UsingtheVisualLISPEnvironmentdescribeshowtouseVLISPtodevelopandtestAutoLISPprograms.
UsingtheAutoLISPLanguageisadetailedguidedescribingtheelementsandstructuresoftheAutoLISPlanguage.
Page 8
WorkingwithProgrammableDialogBoxesdescribeshowtodesignandimplementdialogboxesinyourAutoLISPapplications.
AppendixesincludesafunctionsynopsissummarizingAutoLISPfunctionsbycategory,informationonAutoLISPerrorcodes,andasummaryoftheenvironmentandprogramoptionsavailableinVisualLISP.
ThefollowingareafewguidelinestohelpyougetthemostoutoftheAutoLISPDeveloper'sGuide:
Beginbyreadingchapter1,GettingStarted.ThischaptertellsyouhowtoinvokeVLISPfromAutoCAD,identifieswhatyou'llseewhenVLISPfirststarts,anddescribeshowtoloadandrunexistingAutoLISPprogramsfromVLISP.Chapter1introducesandbrieflydescribesthewindowsyouwillbeworkingwithintheVLISPIDE.UsethischaptertoorientyourselftotheVLISPenvironment.
IfyoudonotalreadyknowAutoLISP,readallofchapter8,AutoLISPBasics,andatleastbrowsechapters9and10,UsingAutoLISPtoCommunicatewithAutoCADandUsingAutoLISPtoManipulateAutoCADObjects,respectively.Afterthat,youcaneitherworkthroughthetutorialorreadmorechaptersintheAutoLISPDeveloper'sGuide.
Tosearchforafunctionthatmeetsaparticularprogrammingneed,refertoAutoLISPFunctionSynopsis,inthisguide.
Thefollowingtablesummarizestheorganizationofthismanual:
Chapterorganization
Chapter Title Contents
1 GettingStarted ProvidesanorientationtoVisualLISP.
2 DevelopingProgramswithVisualLISP
ShowsyouhowtousetheVLISPtexteditortoenterAutoLISP
Page 9
programcode,formatthecode,andcheckthecodeforAutoLISPsyntaxerrors.Alsoshowsyouhowtorunthecodeyou'vedevelopedfromtheVLISPeditorwindow.
3 DebuggingPrograms
ShowsyouhowtouseVLISPtotraceprogramexecution,watchthevalueofvariableschangeduringprogramexecution,seethesequenceinwhichexpressionsareevaluated,andstepthroughprogramexecutiononeinstructionatatime.
4 BuildingApplications
IntroducestheVLISPfilecompilerandshowshowyoucanusetheVLISPApplicationWizardtobuildstandaloneapplications.
5 MaintainingVisualLISPApplications
DescribeshowtodefineVLISPprojectsandusethemtosimplifyworkingwithmulti-fileapplications.This
Page 10
chapteralsoexplainscompileroptimizationfeatures,andhowtousetheminaproject.
6 WorkingwithActiveX
DescribeshowtouseActiveXobjectswithVLISP,andhowtoaccessotherapplicationsthroughActiveX.
7 AdvancedTopics
DescribeshowtoattachreactorstoAutoCADdrawingsandobjects.
8 AutoLISPBasics
IntroducesbasicAutoLISPconcepts,suchashowtouseexpressionsandvariables,handlenumbersandstrings,displayoutput,buildlists,anddefinefunctions.
9 UsingAutoLISPtoCommunicatewithAutoCAD
DescribesAutoLISPfunctionsthatyoucanusetoissueAutoCADcommandsandtointeractwithusersintheAutoCADenvironment.
10 UsingAutoLISPto
DescribesAutoLISPfunctionsyoucanuse
Page 11
ManipulateAutoCADObjects
tomanipulateAutoCADdrawingentities,selectionsets,extendeddata,andsymboltables.
11 DesigningDialogBoxes
Introducestheelementsthatmakeupdialogboxes.ExplainsDCLfilestructureandsyntax,andpresentsAutoLISPandDCLcodethatdefinesanddisplaysasampledialogbox.
12 ManagingDialogBoxes
DescribeshowtocontroldialogboxeswithAutoLISPprograms.
13 ProgrammableDialogBoxReference
ListsanddescribesalltheDCLtilesandtheirassociatedattributes,andsummarizestheAutoLISPfunctionsavailabletorworkwithprogrammabledialogboxes.
Pleasesendusyourcommentaboutthispage
Page 12
AutoLISPDeveloper'sGuide>Introduction>
RelatedDocuments
InadditiontotheAutoLISPReferenceandtheAutoLISPTutorial,severalotherAutoCADpublicationsmayberequiredbyusersbuildingapplicationswithVisualLISP:
AutoCADActiveXandVBAReferencecontainsinformationonaccessingActiveXmethods,properties,andobjects.IfyoudevelopAutoLISPapplicationsthatuseActiveXautomationtoreferenceAutoCADobjects,youwillneedtorefertothisreference.ItisavailablethroughtheAutoCADandVisualLISPHelpmenus.
AutoCADCustomizationGuidecontainsbasicinformationoncreatingcustomizedAutoCADapplications.Forexample,itincludesinformationoncreatingcustomizedmenus,linetypes,andhatchpatterns.TheCustomizationGuideisavailablethroughtheAutoCADandVisualLISPHelpmenus.
TheDXFReferencedescribesdrawinginterchangeformat(DXFTM)andtheDXFgroupcodesthatidentifyattributesofAutoCADobjects.YoumayneedtorefertotheDXFReferencewhenworkingwithassociationlistsdescribingentitydata.TheDXFReferenceisavailablethroughtheAutoCADandVisualLISPHelpmenus.
TheObjectARXReferencecontainsinformationonusingObjectARX®
todevelopcustomizedAutoCADapplications.AutoCADreactorfunctionalityisimplementedthroughObjectARX.IfyoudevelopAutoLISPapplicationsthatimplementreactorfunctions,youmaywanttorefertothismanual.TheObjectARXReferenceisnotincludedwhenyouinstallAutoCAD.Toobtainthemanual,downloadtheObjectARXSDK(SoftwareDevelopmentKit)fromthewww.autodesk.com.
Page 13
Pleasesendusyourcommentaboutthispage
Page 14
AutoLISPDeveloper'sGuide>
UsingtheVisualLISPEnvironment
GettingStartedYoucanuseVisualLISPtoincreaseyourproductivitybycompilingprograms,steppingthroughcode,anddebugging.DevelopingProgramswithVisualLISPWithVisualLISP,youcanformatyourcodeandautomaticallydetectsyntaxerrors.DebuggingProgramsTodebugaprogram,youcantraceexecution,tracethevaluesofvariablesduringexecution,andviewthesequenceinwhichexpressionsareevaluated.BuildingApplicationsYoucancompileyourprogramfilesandcreateasingleexecutablemodulethatyoucandistributetousers.MaintainingVisualLISPApplicationsYoucanmaintainlargeprogramsbycreatingaVisualLISPprojectandoptimizingcode.WorkingwithActiveXWithVisualLISP,youcanaccesstheAutoCADobjectmodel.AdvancedTopicsYoucanusereactorsforeventnotification.
Pleasesendusyourcommentaboutthispage
Page 15
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
GettingStarted
YoucanuseVisualLISPtoincreaseyourproductivitybycompilingprograms,steppingthroughcode,anddebugging.
ThischapterintroducesyoutothelookandfeeloftheVisualLISP®interactivedevelopmentenvironment(IDE),andshowsyouhowtorunAutoLISP®programsinVisualLISP.
StartingVisualLISPExploringtheVisualLISPUserInterfaceTouringtheVisualLISPMenusUnderstandingtheConsoleWindowUnderstandingtheVisualLISPTextEditorLoadingandRunningAutoLISPProgramsExitingVisualLISP
Pleasesendusyourcommentaboutthispage
Page 16
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
StartingVisualLISP
TheVisualLISP(VLISP)interactivedevelopmentenvironmentrunsinaseparatesetofwindowsfromtherestofAutoCAD®.YoumustexplicitlystartVLISPtoworkintheinteractivedevelopmentenvironment.
TostartVisualLISP
1. StartAutoCAD.
2. ChooseTools AutoLISP VisualLISPEditorfromtheAutoCADmenu,orenterthefollowingattheCommandprompt:
vlisp
YoucanuseeitherthemenuorthevlispcommandtoreturntotheVLISPIDEatanytime.
NotethatAutoCADalsorecognizesthevlidecommandtostartorreturntoVisualLISP.Thiscommandnamestandsfor“VisualLISPinteractivedevelopmentenvironment.”AutoCADissuesthevlidecommandtocallVLISP,andasaresultyoumaysometimessee“VLIDE”displayedintheAutoCADCommandwindow.
Pleasesendusyourcommentaboutthispage
Page 17
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
ExploringtheVisualLISPUserInterface
WhenyoufirststartVisualLISP,thefollowingcomponentsaredisplayed:
Menu
YoucanissueVLISPcommandsbychoosingfromthevariousmenuitems.Ifyouhighlightanitemonamenu,VLISPdisplaysabriefdescriptionofthecommand'sfunctioninthestatusbaratthebottomofthescreen.
Toolbars
ClicktoolbarbuttonstoissueVLISPcommandsquickly.Therearefivetoolbars—Debug,Edit,Find,Inspect,andRun—eachrepresentingadistinctfunctionalgroupofVLISPcommands.Youcanexecutemany,butnotall,menucommandsfromthetoolbars.Ifyoumoveyourmousepointeroveratoolbarbuttonandleaveitthereforacoupleofseconds,VLISPdisplaysatooltipindicatingthefunctionofthebutton.AmoredescriptiveexplanationappearsinthestatusbaratthebottomoftheVLISPscreen.
ConsoleWindow
Thisisaseparate,scrollablewindowwithinthemainVLISPwindow.IntheConsolewindow,youcantypeAutoLISPcommands,similartothewayyoudointheAutoCADCommandwindow.YoucanalsoissuemanyVisualLISPcommandsfromthiswindow,insteadofusingthemenuortoolbars.SeeUnderstandingtheConsoleWindowformoreinformationontheConsolewindow.
StatusBar
TheinformationdisplayedinthestatusbarlocatedatthebottomofthescreenvariesaccordingtowhatyouaredoinginVLISP.
YoumayalsoseeaminimizedTracewindow.Duringstartup,thiswindow
Page 18
containsinformationalmessagesaboutthecurrentreleaseofVLISP,andmaycontainadditionalinformationifVLISPencounterserrorsduringstartup.
IntroducingtheVisualLISPTextEditorOtherVisualLISPWindows
Pleasesendusyourcommentaboutthispage
Page 19
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>ExploringtheVisualLISPUserInterface>
IntroducingtheVisualLISPTextEditor
YouwillspendmuchofyourtimeinVLISPcreatingormodifyingAutoLISPprograms.VLISPcomeswithanintegratedtexteditorforyoutousewithAutoLISPcode.
Toseehowthetexteditorwindowdisplayscode,openasampleAutoLISPprogram.Beginwiththedrawline.lspfileprovidedwithVLISP.
Note ThesamplefilesareonlyincludedinyourinstallationifyouchoseaFullinstallation,orifyouchoseaCustominstallationandselectedtheVisualLISPSamplesitem.IfyoupreviouslyinstalledAutoCADanddidnotinstallthesamples,reruntheinstall,chooseCustom,andselecttheVisualLISPSamplesitem.
ToviewaLISPprogramintheVLISPtexteditor
1. FromtheVLISPmenu,chooseFile OpenFile.
2. IntheOpenFiledialogbox,selecttheSample\VisualLISPfolder,whichisinyourAutoCADinstallationdirectory.
3. Double-clickthedrawline.lspfile.VLISPopensthefileinanewwindow—thetexteditorwindow—anddisplaysthenameofthefileinthestatusbar.Ifyoumakeachangetothetextintheeditorwindow,oraddnewtext,VLISPplacesanasterisk(*)nexttothefilenameinthestatusbar.Theasteriskremainsnexttothatfilenameuntilyoueithersaveyourchangesorclosethefile.Youcanworkonmorethanonefileatatime.Eachtimeyouopenafile,VLISPdisplaysthefileinanewtexteditorwindow.
Page 20
Pleasesendusyourcommentaboutthispage
Page 21
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>ExploringtheVisualLISPUserInterface>
OtherVisualLISPWindows
VLISPdisplayssomeoutputintheConsolewindow,butseveralVLISPfunctionscreatetheirownwindowsinwhichtodisplayresults.Forexample,whenyoutracethesequenceofeventsduringarunningAutoLISPprogram,theTracefunctionopensawindowanddisplaysprogramevents.Youcannotentertextintheseoutputwindows,butyoucancopytextfromthemandpastethetextintotheeditororConsolewindows.
Pleasesendusyourcommentaboutthispage
Page 22
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
TouringtheVisualLISPMenus
YoucanissueVLISPcommandsbychoosingfromthevariousmenuitems.Forexample,fromtheFilemenuyoucancreateanewAutoLISPprogramfile,selectanexistingprogramfiletoedit,andprintthefileyou'reediting.
VariableMenuContentsVisualLISPMenuSummary
Pleasesendusyourcommentaboutthispage
Page 23
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>TouringtheVisualLISPMenus>
VariableMenuContents
MenucontentsmayvarydependingonwhichVLISPwindow(forexample,texteditor,Console)isactive.Toactivateadifferentwindow,clickinthewindow'stitlebar,orinanyemptyareaofthatwindow.
Asanexample,clickinthetexteditorwindowcontainingthedrawline.lspfile,thenchooseEditfromtheVLISPmenu.You'llseethefollowinglist:
NotethatthelastitemsonthemenuareParenthesesMatchingandExtraCommands.
NowclickinthetitlebaroftheVLISPConsolewindow,thenselecttheEditmenuitemagain:
Page 24
NoticethatExtraCommandsisnolongerthelastitemonthemenu.ParenthesesMatchingisfollowedbytwonewitems,ConsoleHistoryUpandConsoleHistoryDown;theseitemsapplyonlytoaConsolewindow.
Pleasesendusyourcommentaboutthispage
Page 25
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>TouringtheVisualLISPMenus>
VisualLISPMenuSummary
ThefollowingtablesummarizestheVLISPmenuitems.
VisualLISPmenuitems
Menuitem Uses
File CreateanewAutoLISPprogramfileforediting,openanexistingfile,savechangestoprogramfiles,buildVisualLISPapplicationfiles,andprintprogramfiles.
Edit Copyandpastetext,undothelastchangeyoumadetotext(orundothelastcommandenteredintheConsolewindow),selecttextintheVLISPeditororConsolewindows,matchparenthesesinexpressions,andredisplaypreviouscommandsenteredintheConsolewindow.SeethechaptertitledDevelopingProgramswithVisualLISPformoreinformationonEditfeatures.
Search Findandreplacetextstrings,setbookmarks,andnavigateamongbookmarkedtext.SeeUsingtheTextEditorforinformationonthesetopics.
Page 26
View FindanddisplaythevalueofvariablesandsymbolsinyourAutoLISPcode.Formoreinformationonthistopic,seechapter3,DebuggingPrograms.
Project Workwithprojectsandcompileprograms.SeeManagingMultipleLISPFiles,andCompilingandLinkingProgramsforinformationonthesetopics.
Debug Setandremovebreakpointsinyourprogramandstepthroughprogramexecutiononeexpressionatatime.Youcanthencheckthestateofvariablesandtheresultsofexpressions.Seechapter3,DebuggingPrograms,formoreinformationonthesefeatures.
Tools SetVLISPoptionsfortextformattingandvariousenvironmentoptions,suchastheplacementofwindowsandtoolbars.
Window OrganizethewindowscurrentlydisplayedinyourVLISPsession,oractivateanotherVLISPorAutoCADwindow.
Help DisplayHelp.
Pleasesendusyourcommentaboutthispage
Page 27
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
UnderstandingtheConsoleWindow
FromtheVLISPConsolewindow,youcanenterandrunAutoLISPcommandsandseetheresults.ThisissimilartowhatyoucandointheAutoCADCommandwindow,butthereareafewdifferences—somesubtle—inhowyouaccomplishthesametaskinthesetwowindows.Forexample,todisplaythecurrentvalueofanAutoLISPvariableinVLISP,yousimplytypethevariablenameintheConsolewindowandpressENTER.ToviewthevalueofavariableinAutoCAD,youmustprecedethevariablenamewithanexclamationpoint(!)whenyoutypeitintheCommandwindow.
TheConsolewindowisalsowhereVLISPdisplaysAutoLISPdiagnosticmessagesandtheresultsofmanyAutoLISPfunctions.Forexample,outputfromtheprintandprincfunctionsisdisplayedintheConsolewindow.YoucanscrollthroughtheConsolewindowtoviewpreviouslyenteredtextandoutput.
ForadescriptionofVLISPConsolewindowfeatures,seeUsingtheConsoleWindow.Thefollowingisabriefsummaryofthesefeatures:
EvaluatingAutoLISPexpressionsanddisplayingthereturnvaluesfromthoseexpressions.
EnteringAutoLISPexpressionsonmultiplelinesbypressingCTRL+ENTERtocontinueonthenextline.
Evaluatingmultipleexpressionsatonetime.
CopyingandtransferringtextbetweentheConsoleandtexteditorwindows.MosttexteditorcommandsarealsoavailableintheConsolewindow.
RetrievingpreviouscommandsenteredintheConsolebypressingTAB.YoucanpressTABrepeatedlytoretrieveearliercommands.PressSHIFT+TABtoreversethedirectionofcommandretrieval.
Page 28
PerforminganassociativesearchthroughtheinputhistorybypressingTAB.Forexample,ifyoubeginanexpressionwith(+andthenpressTAB,VLISPretrievesthelastcommandyouenteredthatbeginswith(+.Toreversethedirectionofthesearch,pressSHIFT+TAB.
PressingESCclearsanytextfollowingtheConsoleprompt.
PressingSHIFT+ESCleavesthetextyouenteredattheConsolepromptwithoutevaluatingthetext,anddisplaysanewConsoleprompt.
Right-clickingorpressingSHIFT+F10anywhereintheConsolewindowdisplaysamenuofVLISPcommandsandoptions.Forexample,youcanusethisfeaturetocopyandpastetextintheConsolecommandline,searchfortext,andinitiateVLISPdebuggingfeatures.
NotethatifyoutypetextattheConsolepromptbutswitchtotheAutoCADwindowbeforepressingENTER,thetextwillnolongerbeatthepromptwhenyoureturntotheVLISPwindow.
Pleasesendusyourcommentaboutthispage
Page 29
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
UnderstandingtheVisualLISPTextEditor
TheVLISPtexteditorismuchmorethanawritingtool,it'sacentralcomponentoftheVLISPprogrammingenvironment.ToappreciatetheversatilityandvalueoftheVLISPtexteditor,youneedtobefamiliarwiththeAutoLISPlanguage.IfyouarenotyetfamiliarwithAutoLISP,youcanlearnthebasicsinchapter8,AutoLISPBasicsandfindadditionalinformationinchapter9,UsingAutoLISPtoCommunicatewithAutoCADandchapter10,UsingAutoLISPtoManipulateAutoCADObjects
Herearesomeofthemajorfeaturesofthetexteditor:
ColorCodingofFiles
ThetexteditoridentifiesdifferentpartsofanAutoLISPprogramandassignsdistinctcolorstothem.Thisallowsyoutofindprogramcomponentseasilysuchasfunctioncallsandvariablenames,andhelpsyoufindtypographicalerrors.
FormattingofText
ThetexteditorcanformatAutoLISPcodeforyou,makingthecodeeasiertoread.Youcanchoosefromanumberofdifferentformattingstyles.
ParenthesisMatching
AutoLISPcodecontainsmanyparentheses,andtheeditorhelpsyoudetectmissingparenthesesbyfindingthecloseparenthesisthatgoeswithanopenparenthesis.
ExecutionofAutoLISPExpressions
Youcantestexpressionsandlinesofcodewithoutleavingthetexteditor.
MultipleFileSearching
Thetexteditorcansearchforawordorexpressioninseveralfileswitha
Page 30
singlecommand.
SyntaxCheckingofAutoLISPCode
ThetexteditorcanevaluateAutoLISPcodeandhighlightsyntaxerrors.
DetailsonusingtheVLISPtexteditorbeginwithUsingtheTextEditor.
Pleasesendusyourcommentaboutthispage
Page 31
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
LoadingandRunningAutoLISPPrograms
OnceyouhaveopenedanAutoLISPprogramfileintheVLISPtexteditor,youcanloadandrunit.LoadingistheprocessbywhichfunctionsinaprogramfilearemadeavailabletotheVLISPcommandinterpreter.Youcantrythiswiththedrawline.lspsampleprogram.
ToloadandrunaprograminaVisualLISPtexteditorwindow
1. Makesurethetexteditorwindowcontainingthedrawline.lspprogramisactive.Ifyouarenotsurewhetherthewindowisactive,clickanywhereinthewindowtoactivateit.
2. ChoosetheLoadActiveEditWindowbuttonfromtheRuntoolbar,orchooseTools LoadTextinEditorfromtheVLISPmenu.
VLISPrespondsbydisplayingamessageintheConsolewindowindicatingithasloadedtheprogram.
3. RunthedrawlinefunctionfromtheConsolepromptbyenteringthefunctionnameinparentheses,thenpressingENTER:
_$(drawline)
Thedrawlinefunctionwillaskyoutospecifytwopoints,andwillthendrawastraightlinebetweenthosepoints.Whendrawlineasksforuserinput,VLISPturnscontrolovertoAutoCADtopromptyouforthepoints.WhatyouseenextdependsonwhetherornottheAutoCADwindowsarecurrentlydisplayedonyourdesktop.IfAutoCADisalreadyonyourdesktop,you'llseetheAutoCADwindows.ButifAutoCADiscurrentlyminimizedonyourdesktop,thewindowswon't
Page 32
automaticallyberestoredanddisplayed.Instead,VLISPremainsvisibleandyourmousepointerchangestoaVLISPsymbol.
ThissymbolindicatesthattheVLISPwindowisnolongeractive.Ifthisisthecase,youmustmanuallyswitchtotheAutoCADwindow.ClicktheAutoCADiconontheWindowstaskbartoactivateAutoCAD.
4. RespondtothepromptsbyspecifyingpointsinthegraphicswindoworontheCommandline.Afteryourespondtotheprompts,controlreturnstoVLISPandyouwillonceagainseetheVLISPwindow.WhenyouentercommandsintheVLISPConsolewindoworrunaprogramloadedfromthetexteditor,youmaybefrequentlyswitchingbackandforthbetweentheVLISPandAutoCADwindows.AsidefromusingthestandardWindowsmethodsofswitchingbetweenwindows,youcanactivatetheAutoCADwindowbychoosingWindow ActivateAutoCADfromtheVLISPmenu,orbyclickingtheActivateAutoCADbuttonontheRuntoolbar.IfyouareinAutoCADandwanttoreturntotheVLISPenvironment,youcanentervlispattheCommandprompt,orchooseTools AutoLISP VisualLISPEditorfromtheAutoCADmenu.RunningSelectedLinesofCodeUsingExtendedAutoLISPFunctions
Pleasesendusyourcommentaboutthispage
Page 33
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>LoadingandRunningAutoLISPPrograms>
RunningSelectedLinesofCode
WithVLISP,youcanselectlinesofcodeinthetexteditorwindowandrunonlytheselectedcode,insteadofthewholeprogram.
TorunselectedlinesofAutoLISPcodeinaVisualLISPeditorwindow
1. Usingthedrawline.lspprogramasanexample,highlightthefollowinglinesofcode:
(setqpt1(getpoint"\nEnterthestartpointfortheline:")
pt2(getpointpt1"\nEntertheendpointfortheline:"))
2. ChoosetheLoadSelectionbuttonontheRuntoolbar.
VLISPimmediatelyrunsthecodeandswitchescontroltoAutoCADtopromptyouforinput.
Pleasesendusyourcommentaboutthispage
Page 34
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>LoadingandRunningAutoLISPPrograms>
UsingExtendedAutoLISPFunctions
VLISPprovidessomeextensionstotheAutoLISPlanguagethatarenotloadedautomaticallywhenyoustartAutoCAD.Thesefunctionshavenamesthatbeginwithvla-,vlax-,andvlr.Thevla-functionsimplementActiveX®supportinAutoLISP(describedinWorkingwithActiveX).Thevlax-functionsprovideActiveXutilityanddataconversionfunctions,dictionaryhandlingfunctions,andcurvemeasurementfunctions.Thevlr-functionsprovidesupportforAutoCADreactors.Beforeyoucanuseanyofthesefunctions,youneedtoloadtheAutoLISPextensionswiththefollowingfunctioncall:
(vl-load-com)
ThisfunctionfirstcheckswhetherornottheAutoLISPextensionsarealreadyloaded.IftheAutoLISPextensionsareloaded,functiondoesnothing;otherwiseitloadstheextensions.
Ifyou'reusingtheVLISPinteractivedevelopmentenvironmenttodevelopcode,chancesareyou'llwanttousetheAutoLISPextensionsatsomepoint.It'sagoodpracticetoissuevl-load-comwhenyoustartVLISP,ortoincludeacalltothefunctioninyouracaddoc.lspfile,sothatitloadsautomatically.ButifyouwriteprogramsthatuseanyoftheextendedAutoLISPfunctions,youneedtocallvl-load-cominthoseprogramstoensurethatthefunctionsareavailabletootherusersrunningyourcode.
Pleasesendusyourcommentaboutthispage
Page 35
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>GettingStarted>
ExitingVisualLISP
WhenyouarefinishedwithyourVLISPsession,youcanclosetheprogrambyeitherchoosingExitfromtheFilemenuorclickingtheWindowsClosebutton.NotethatAutoCADdoesnotcompletelyunloadVLISPbutmerelyclosesallVLISPwindows.
UponexitingAutoCAD,ifyouhavemadeanychangestothecodeinanyVLISPtexteditorwindowandhavenotsavedthosechanges,youwillbeaskedifyouwanttosaveyourchanges.Youcaneithersaveallthechangesyou'vemadebychoosingYes,orsavenoneofthechangesbychoosingNo.
VLISPretainsitsstatewhenyouexit.ThenexttimeyoustartaVLISPsession,VLISPautomaticallyopenswhicheverfilesandwindowswereopenwhenyoulastexited.
Pleasesendusyourcommentaboutthispage
Page 36
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
DevelopingProgramswithVisualLISP
WithVisualLISP,youcanformatyourcodeandautomaticallydetectsyntaxerrors.
VisualLISP®providesmanytoolsandfeaturesthathelpyoudevelopAutoLISP®programs.Thischapterdescribesthefeaturesthathelpyouduringthecodingphaseofprogramdevelopment.ThesefeaturesformatAutoLISPcodetoimprovereadabilityandhelpyoudetectsyntaxerrorsinyourcode.
GettingOrganizedUsingtheConsoleWindowUsingtheTextEditorUsingConsoleandEditorCodingAidsFormattingCodewithVisualLISPCheckingforSyntaxErrors
Pleasesendusyourcommentaboutthispage
Page 37
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
GettingOrganized
TodevelopanAutoLISPprogramwithVLISPyoumustperformthefollowingsteps:
Thinkaboutwhichtasksyouwanttoaccomplishwithyourprogram,andhowtoapproachthosetasks.
Designtheprogram.
Writethecode.
Formatthecodeforreadability.
Checkforerrorsintheprogram.
Testanddebugtheprogram.
Thischapterprovidesyouwithinformationtohelpyouaccomplishwriting,formatting,andcheckingtasks.TheDebuggingProgramschapterdescribesthedebuggingfeaturesofVLISP.TheBuildingApplicationsandMaintainingVisualLISPApplicationschaptersdescribehowtopackageyourprogramsintoapplicationsthatcanberunbyotherusers,andhowtoorganizeapplicationcomponentstofacilitatefutureupdates.
Pleasesendusyourcommentaboutthispage
Page 38
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
UsingtheConsoleWindow
MostprogramminginVLISPtakesplacewithintheconfinesoftheVLISPtexteditor,buttheabilitytoprograminteractivelywithAutoLISPprovidessomeuniqueadvantagestothedevelopmentprocess.IntheVLISPConsolewindowyoucanenterAutoLISPcodeandimmediatelyseetheresultsofexecutingthatcode.
EntertextintheConsolewindowfollowingtheConsoleprompt,whichlookslikethefollowing:
_$
VLISPsavesthetextyouenterandanyoutputfromexecutingthetext.YoucanthenscrollthroughtheConsolewindowandseewhattranspired.YoucancopyanytextinthewindowandpasteitattheConsolepromptorinanotherWindowsapplication.
UnderstandingConsoleBehaviorUsingtheConsoleWindowwithMultipleDrawingsUsingtheConsoleShortcutMenuLoggingConsoleWindowActivity
Pleasesendusyourcommentaboutthispage
Page 39
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>
UnderstandingConsoleBehavior
TheVLISPConsolewindowissimilarinsomerespectstotheAutoCAD®
Commandwindow,butitprovidesmanymorefeatures.AlthoughtheConsolewindowandtheAutoCADCommandwindowprovidesimilarcapabilities,youdon'talwaysusethesameprocesstoaccomplishidenticaltasks.Forexample,todisplaythecurrentvalueofanAutoLISPvariableinVLISP,yousimplytypethevariablenameintheConsolewindowandpressENTER.ToviewthevalueofavariableinAutoCAD,youmustprecedethevariablenamewithanexclamationpoint(!)whenyouenteritattheAutoCADCommandprompt.
UnliketheAutoCADCommandwindow,wherepressingSPACEBARcausesexpressionevaluation,textinputattheVLISPConsolepromptisnotprocesseduntilyoupressENTER.ThispermitsyoutodothefollowingintheConsolewindow:
ContinueanAutoLISPexpressiononanewline.Tocontinueenteringanexpressiononanewline,pressCTRL+ENTERatthepointyouwanttocontinue.
InputmorethanoneexpressionbeforepressingENTER.VLISPevaluateseachexpressionbeforereturningavaluetotheConsolewindow.
IfyouselecttextintheConsolewindow(forexample,theresultofapreviouscommandorapreviouslyenteredexpression),thenpressENTER.VLISPcopiestheselectedtextattheConsoleprompt.
TheVLISPConsolewindowandtheAutoCADCommandwindowdifferinthewaytheyprocesstheSPACEBARandTABkeys.IntheVLISPConsolewindow,aspaceplaysnospecialroleandservesonlyasaseparator.IntheAutoCADCommandwindow,pressingtheSPACEBARoutsideanexpressioncausesAutoCADtoprocessthetextimmediately,asifyouhadpressedENTER.
Page 40
UsingtheConsoleWindowHistoryInterruptingCommandsandClearingtheConsoleInputArea
Pleasesendusyourcommentaboutthispage
Page 41
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>UnderstandingConsoleBehavior>
UsingtheConsoleWindowHistory
YoucanretrievetextyoupreviouslyenteredintheConsolewindowbypressingTABwhileattheConsoleprompt.EachtimeyoupressTAB,thepreviouslyenteredtextreplacesthetextattheConsoleprompt.YoucanrepeatedlypressTABuntilyoucyclethroughallthetextenteredattheConsolepromptduringyourVLISPsession.Afteryou'vescrolledtothefirstenteredline,VLISPstartsagainbyretrievingthelastcommandenteredintheConsolewindow,andthecyclerepeats.PressSHIFT+TABtoscrolltheinputhistoryintheoppositedirection.
Forexample,assumeyouenteredthefollowingcommandsattheConsoleprompt:
(setqorigin(getpoint"\nOriginofinynsign:"))
(setqradius(getdist"\nRadiusofinynsign:"origin))
(setqhalf-r(/radius2))
(setqorigin-x(carorigin))
(command"_.CIRCLE"originradius)
ToretrievecommandsenteredintheConsolewindow
1. PressTABonce.VLISPretrievesthelastcommandenteredandplacesitattheConsoleprompt:
_$(command"_.CIRCLE"originradius)
2. PressTABagain.ThefollowingcommanddisplaysattheConsoleprompt:
_$(setqorigin-x(carorigin))
Page 42
3. PressTABagain.VLISPdisplaysthefollowingcommand:
_$(setqhalf-r(/radius2))
4. NowpressSHIFT+TAB.VLISPreversesdirectionandretrievesthecommandyouenteredafterthepreviouscommand:
_$(setqorigin-x(carorigin))
5. PressSHIFT+TABagain.VLISPdisplaysthefollowingcommand:
_$(command"_.CIRCLE"originradius)
ThiswasthelastcommandyouenteredattheConsoleprompt.
6. PressSHIFT+TABagain.BecausethepreviouscommandretrievedwasthelastcommandyouenteredduringthisVLISPsession,VLISPstartsagainbyretrievingthefirstcommandyouenteredintheConsolewindow:
_$(setqorigin(getpoint"\nOriginofinynsign:"))
Notethatifyouenterthesameexpressionmorethanonce,itappearsonlyonceasyoucyclethroughtheConsolewindowinputhistory.Youcanperformanassociativesearchintheinputhistorytoretrieveaspecificcommandthatyoupreviouslyentered.
ToperformanassociativesearchoftheConsoleinputhistory
1. Enterthetextyouwanttolocate.Forexample,enter(commandattheConsoleprompt:
_$(command
2. PressTAB.VLISPsearchesforthelasttextyouenteredthatbeganwith(command:
_$(command"_.CIRCLE"originradius)
IfVLISPdoesnotfindamatch,itdoesnothing(exceptpossiblyemitabeep).PressSHIFT+TABtoreversethedirectionoftheassociativesearchandfindprogressivelyless-recentinputs.
Page 43
Pleasesendusyourcommentaboutthispage
Page 44
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>UnderstandingConsoleBehavior>
InterruptingCommandsandClearingtheConsoleInputArea
TointerruptacommandenteredintheConsolewindow,pressSHIFT+ESC.Forexample,ifyouenteraninvalidfunctioncalllikethefollowing:
_$((setqorigin-x(carorigin)((_>
PressingSHIFT+ESCinterruptsthecommand,andVLISPdisplaysan“inputdiscarded”messagelikethefollowing:
((_>;<inputdiscarded>
_$
(Notethatinthisexample,youcanalsocompletethecommandbyenteringthemissingcloseparentheses.)
IfyoutypetextattheConsoleprompt,butdonotpressENTER,thenpressingESCclearsthetextyoutyped.IfyoupressSHIFT+ESC,VLISPleavesthetextyouenteredintheConsolewindowbutdisplaysanewpromptwithoutevaluatingthetext.
IfyoutypepartofacommandattheConsoleprompt,butactivatetheAutoCADwindowbeforepressingENTER,VLISPdisplaysanewpromptwhenyounextactivatetheVLISPwindow.ThetextyoutypedisvisibleintheConsolewindowhistory,soyoucancopyandpasteit,butyoucannotretrievethetextbypressingTAB,becauseitwasnotaddedtotheConsolehistorybuffer.
Pleasesendusyourcommentaboutthispage
Page 45
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>
UsingtheConsoleWindowwithMultipleDrawings
ThereisasingleConsolewindowforallopenAutoCADdrawingdocuments.WhenyouscrollthroughtheConsolewindow,youseecommandsenteredinalldocumentcontexts.ThisdiffersfromtheAutoCADCommandwindow,whichshowsonlythecommandsissuedagainstthecurrentdrawing.Inotherwords,eachAutoCADdrawinghasitsownCommandwindow,butalldrawingssharethesameVLISPConsoleprompt.
VLISPautomaticallyswitchescontextwhenyouchangetheactivedrawingdocumentinAutoCAD.TheactivedocumentinAutoCADisalwaystheactivedocumentinVLISP.CommandsenteredintheVLISPConsolewindowalwaysapplytotheactivedocument.ThetitlebaroftheVLISPwindowcontainsthenameoftheactivedrawingdocument.
Pleasesendusyourcommentaboutthispage
Page 46
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>
UsingtheConsoleShortcutMenu
ThemostimportantfunctionsneededwhenworkingwiththeVLISPConsolewindowarecombinedintoashortcutmenuforfastaccess.Right-clickanywhereintheConsolewindoworpressSHIFT+F10todisplaytheshortcutmenu.
DependingonwhetherthereistextselectedintheConsolewindowanddependingonthecursorposition,somecommandsmaynotbeappropriateatthemomentandcannotbeactivatedfromtheshortcutmenu.ThefollowingtablesummarizesthecommandsthatmaybeavailablefromtheConsolewindowshortcutmenu.
Consolewindowshortcutmenucommands
Command Action
Cut RemovestheselectedtextfromtheConsolewindowandmovesittotheWindowsClipboard
Copy CopiestheselectedtexttotheClipboard
Paste PastestheClipboardcontentstothecursorlocation
ClearConsolewindow
EmptiestheConsolewindow
Find FindsspecifiedtextintheConsolewindow
Inspect OpenstheInspectdialogbox
Page 47
AddWatch OpenstheWatchwindow
Aproposwindow OpenstheAproposwindow
SymbolService OpenstheSymbolServicedialogbox
Undo Reversesthelastoperation
Redo ReversestheeffectsofthepreviousUndo
AutoCADMode TransfersallinputtotheAutoCADcommandlineforevaluation
ToggleConsoleLog CopiesConsolewindowoutputtothelogfile
NotealsothatyoucancutandpastetextbetweentheVLISPConsolewindowandtheAutoCADCommandwindow.
Pleasesendusyourcommentaboutthispage
Page 48
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheConsoleWindow>
LoggingConsoleWindowActivity
YoucankeeparecordofallConsolewindowactivitybyloggingtheactivityinafile.Later,youcanviewthefileandreviewtheactivitythatoccurredintheConsolewindow.
TocontrolConsoleloggingactivity
1. CreatealogfilebychoosingFile ToggleConsoleLogfromtheVLISPmenu.NotethattheConsolewindowmustbeactivefortheToggleConsoleLogoptiontobeavailable.
2. Chooseadirectoryforthelogfileandspecifyafilenameforthelog.Ifthefilealreadyexists,VLISPdisplaysanalertboxthatasksifyouwanttoappendthecurrentlogtotheexistingfile.IfyouchooseYes,VLISPappendsfutureConsolewindowinformationtotheexistingcontentsofthefile.IfyouchooseNo,VLISPoverwritesthefile.
3. Toclosethelogfileandquittheloggingprocess,chooseToggleConsoleLogfromtheFilemenuagain.
ThestateofConsolewindowloggingisindicatedintheConsolewindow'stitlebar.Ifloggingisineffect,VLISPdisplaysthenameofthelogfileinthetitlebar.Ifloggingisoff,nofilenameappearsinthetitlebar.
IfyoudonotclosethelogfilebeforeexitingVLISP,itclosesthelogfileautomaticallyuponexit.Afteralogfileisclosed,youcanviewitscontentswithanytexteditor,suchastheVLISPtexteditor.
Pleasesendusyourcommentaboutthispage
Page 49
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
UsingtheTextEditor
IfyoujustneedtorunafewsimpleAutoLISPexpressions,enteringtheexpressionsintheVLISPSystemConsolemaysuffice.Foranythingmorethanthat,however,youwillneedtousetheVLISPtexteditorandsaveyourAutoLISPcodeinafile.
ThetexteditorisabasiccomponentofVLISP.Itiseasytouseand,ifyouhavesomeexperienceusingWindows,youcanbeginusingitafteraquickreviewofthischapter.
TheVLISPtexteditorhasanumberoffeaturesdesignedtosupportAutoLISPprogramming,suchasselectingofcompleteAutoLISPexpressions,matchingofbalancedparentheses,syntaxcoloring,andexecutingAutoLISPexpressionswithoutleavingtheeditorwindow.Mosttexteditorcommandscanbecalledfromthemenubar,andsomeofthemostfrequentlyusedcommandsarealsoavailablefromtoolbarpushbuttons.
EditingaFileUsingtheTextEditorShortcutMenuUsingKeyboardShortcutsintheTextEditorMovingandCopyingTextSearchingforTextBookmarkingText
Pleasesendusyourcommentaboutthispage
Page 50
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
EditingaFile
ToopenanewfileintheVLISPtexteditor,chooseFile NewFilefromthemenubar.Anemptyeditorwindowappearsonthescreen,andyoucanbeginenteringtext.
Tostartanewline,pressENTER.Thetexteditordoesnotwrapyourtextwhenitreachestheendofthevisibletexteditorwindow,soeverythingyoutypegoesonthesamelineuntilyoupressENTER.
Youcanindentlinesoftextmanually,butVLISPautomaticallyformatscodeforyouasyouenternewlinesofcode.YoucanalsocopytextfromanotherfileandhaveVLISPformattheblockoftextyouadd.SeeFormattingCodewithVisualLISPfordetailsonusingtheVLISPcodeformattingfeatures.
UndoingYourLastChangeCreatingAutomaticBackupFilesRestoringfromaBackupFileEditinganExistingFile
Pleasesendusyourcommentaboutthispage
Page 51
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>EditingaFile>
UndoingYourLastChange
YoucanreverseyourlasteditactionbychoosingEdit UndofromtheVLISPmenubar.Youcanundoavirtuallyunlimitednumberofchanges,backtothepointatwhichyoulastsavedthefile.
ToreversetheeffectsoftheUndocommand,chooseEdit Redofromthemenu.RedoonlyworksifyouissueitimmediatelyafterUndo.
Pleasesendusyourcommentaboutthispage
Page 52
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>EditingaFile>
CreatingAutomaticBackupFiles
VLISPsupportstheautomaticcreationofbackupcopiesoffilesloadedbythetexteditor.Theactualbackupcreationoccurswhenyousavethefileforthefirsttime.Backupfileshavethesamenameasyouroriginalfile,exceptthefileextensionbeginswithanunderscore(_)andisfollowedbythefirsttwocharactersoftheoriginalextension.Forexample,thebackupfilefordrawline.lspwouldbedrawline._ls.
AutomaticcreationofbackupfilesisanoptionyoucansetbychoosingToolsEnvironmentOptions GeneralOptions.ChoosetheEditoroptionlabeledBackuptheFileEditedonFirstSavetoturnonautomaticbackup.Bydefault,thisoptionisalreadyselectedwhenyoufirstinstallVLISP.
Pleasesendusyourcommentaboutthispage
Page 53
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>EditingaFile>
RestoringfromaBackupFile
Ifabackupfileexists,youcanrestorethefileyouareeditingtoitsoriginalcontent,reversingallthechangesyoumade.FromtheFilemenu,chooseReverttorestorethefile.Ifthereisnobackupfileforthetextintheeditorwindow,VLISPdisplaysanerrormessage.
Pleasesendusyourcommentaboutthispage
Page 54
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>EditingaFile>
EditinganExistingFile
ChooseFile OpenfromtheVLISPmenutoopenanexistingfile.VLISPopensanewtexteditorwindowforthefileyouselect.Youcanopenanynumberoffilesandworkonthemsimultaneously.VLISPplaceseachfileinitsowneditorwindow.
Note IfyouselecttextinanyVLISPwindowbeforechoosingFile Open,theselectedtextisplacedintheFilenamefieldoftheOpendialogbox.
WhenyouexitVLISP,itnoteswhichfilesareopenandsavesthisinformationforyournextVLISPsession.ThenexttimeyoustartVLISP,itautomaticallyopensthefilesforyou.
Pleasesendusyourcommentaboutthispage
Page 55
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
UsingtheTextEditorShortcutMenu
Right-clickingyourmouseinanactiveVLISPtexteditorwindowbringsupashortcutmenuforquickaccesstofrequentlyusedcommands.Dependingonwhetherthereistexthighlightedintheeditorwindowanddependingonthepositionofthecursor,somecommandsontheshortcutmenumaybeinactive.Thefollowingtablesummarizestheeditorshortcutcommands:
Texteditorwindowshortcutmenucommands
Command Action
Cut MovestheselectedtexttotheClipboard
Copy CopiestheselectedtexttotheClipboard
Paste PastestheClipboardcontentstothecursorposition
Find Findsthespecifiedtextinoneormoreeditorwindows
GotoLastEdited Movesthecursortothepositionyoulastedited
ToggleBreakpoint Setsabreakpointatthecursorposition,orremovesabreakpointifoneissetcurrentlyatthatposition
Inspect OpenstheInspectdialogbox
AddWatch OpenstheWatchwindow
Page 56
Aproposwindow OpenstheAproposwindow
SymbolService OpenstheSymbolServicedialogbox
Undo Reversesthelastoperation
Redo ReversestheeffectsofthepreviousUndo
Pleasesendusyourcommentaboutthispage
Page 57
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
UsingKeyboardShortcutsintheTextEditor
TheVLISPtexteditorprovidesnumerouskeyboardshortcutsyoucanuseinsteadofmenuselectionsandmouseclicks.
CorrectingTextSelectingTextNavigationShortcutsIndentingShortcuts
Pleasesendusyourcommentaboutthispage
Page 58
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>UsingKeyboardShortcutsintheTextEditor>
CorrectingText
Youcandeletewordsorlinesusingthefollowingshortcuts:
Textcorrectionshortcutkeys
To Press
Eraseawordtotheleftofthecursor CTRL+BACKSPACE
Eraseawordtotherightofthecursor SHIFT+BACKSPACE
Deletecharactersfromthecursorpositiontotheendofthecurrentline
CTRL+EthenpressE
Youcanalsocanusetheoverstrikemodetoinserttext.OverstrikemodeistoggledonandoffbypressingINSERT.Wheninoverstrikemode,eachcharacteryoutypereplacesexistingtext.Thecursorchangesshapefromverticaltohorizontalwheninoverstrikemode.
Pleasesendusyourcommentaboutthispage
Page 59
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>UsingKeyboardShortcutsintheTextEditor>
SelectingText
Thesimplestmethodtoselecttextistodouble-clickyourleftmousebutton.Theamountoftextselecteddependsonthelocationofyourcursor.
Ifthecursorimmediatelyprecedesanopenparenthesis,VLISPselectsallthefollowingtextuptothematchingcloseparenthesis.
Ifthecursorimmediatelyfollowsacloseparenthesis,VLISPselectsallprecedingtextuptothematchingopenparenthesis.
Ifthecursorimmediatelyprecedesorfollowsaword,oriswithinaword,VLISPselectsthatword.
Toselectspecifictext,pressandholdtheSHIFTkeywhilepressingthearrowkeysonthekeyboard.Otherkeyboardmethodsoftextselectionarelistedinthefollowingtable:
Textselectionshortcutkeys
To Press
Expandtheselectiontothenextline
SHIFT+DOWNARROW
Expandtheselectiontothepreviousline
SHIFT+UPARROW
Expandtheselectiontotheendoftheline
SHIFT+END
Page 60
Expandtheselectiontothebeginningoftheline
SHIFT+HOME
Expandtheselectiondownonewindow,orabandonselectionofthenextwindow,ifitiscurrentlyselected
SHIFT+PAGEDOWN
Expandtheselectionuponewindow,orabandonselectionofthepreviouswindow,ifitiscurrentlyselected
SHIFT+PAGEUP
Expandtheselectiontothenextword,orabandonselectionofthenextword,ifitiscurrentlyselected
CTRL+SHIFT+RIGHTARROW
Expandtheselectiontothepreviousword,orabandonselectionofthepreviousword,ifitiscurrentlyselected
CTRL+SHIFT+LEFTARROW
Expandtheselectionuptothematchingleftparenthesis
CTRL+SHIFT+[
Expandtheselectionuptothematchingrightparenthesis
CTRL+SHIFT+]
Movethecursortotheothersideoftheselection
ALT+ENTER
Page 61
Pleasesendusyourcommentaboutthispage
Page 62
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>UsingKeyboardShortcutsintheTextEditor>
NavigationShortcuts
Inadditiontousingthecursorarrowkeys,youcanusethefollowingVLISPeditorshortcutstonavigatethroughyourtext:
Navigationshortcutkeys
Tomove Press
Onewordtotheleft CTRL+LEFTARROW
Onewordtotheright CTRL+RIGHTARROW
Totheendofaline END
Tothebeginningofaline HOME
Downonewindow PAGEDOWN
Uponewindow PAGEUP
Totheendofadocument CTRL+END
Tothestartofadocument CTRL+HOME
Tothematchingleftparenthesis CTRL+[
Tothematchingrightparenthesis CTRL+]
Page 63
Pleasesendusyourcommentaboutthispage
Page 64
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>UsingKeyboardShortcutsintheTextEditor>
IndentingShortcuts
MostindentingofprogramcodeisbesthandledbytheVLISPautomaticcodeformattingandSmartIndentfeatures,andbycustomizingtheformatter'soptions(seeFormattingCodewithVisualLISP).Buttherearesomethingsyoumaywanttodobyyourself.
Toindentselectedlinesofcode,pressTABorpressCTRL+E,andthenchooseIndentBlock.VLISPinsertsaTABcharacteratthebeginningofeachlineyouselected.YoucancontroltheindentamountoftheTABcharacterbychoosingTools WindowAttributes ConfigureCurrentandsettingtheTabWidthvalue.Youcanalsousethefollowingkeyboardshortcutstoadjusttheindentationoftext.
Codeindentationshortcuts
To Do
AdjusttheindentofthecurrentselectiontotheprecedingAutoLISPtext.
PressSHIFT+TAB
CleartrailingSPACEandTABcharacters,insertanewline,andindentatthelevelofthepreviousnon-emptyline.
PressSHIFT+ENTER
InsertanewlinewithoutclearingtrailingSPACEandTABcharactersofthecurrentline.
PressCTRL+ENTER
Page 65
Pleasesendusyourcommentaboutthispage
Page 66
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
MovingandCopyingText
InadditiontousingthestandardWindowsCut,Copy,andPastefunctions,theVLISPtexteditorallowsyoutodragtextfromonelocationtoanotherwithintheeditwindow.
Tomovetextbydragging
1. Selectthetextyouwanttomove.
2. Pointanywhereinsidetheselectedarea,andpressandholdtheleftmousebutton.
3. Dragthetexttothenewlocation.
4. Releasethemousebutton.
Tocopythetextinsteadofmovingit,followthesamesteps,butpressCTRLbeforereleasingthemousebuttoninstep4.
Youcanalsotakeselectedtextandcopyitintoanewfile.Withthetextselected,pressCTRL+Etodisplayalistofoptions,andchooseSaveBlockAs.VLISPrepliesbydisplayingadialogboxforyoutospecifywhereyouwanttosavethetext.
VLISPusestheWindowsClipboardforallcutandcopyoperations.Therefore,youcanexchangetextwithanyotherWindowsapplicationthatsupportsthesefunctions.ThisalsomeansyoucancopyandpastetextbetweenthetexteditorandtheVLISPConsolewindow.
Rememberthatimmediatelyaftermovingorcopyingtext,youcanchangeyourmindandreversetheaction,usingtheUndofunction.
Page 67
Pleasesendusyourcommentaboutthispage
Page 68
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
SearchingforText
TheVLISPtexteditorhasextensivetext-searchingcapabilities.FromtheSearchmenu,chooseFindtobeginasearch,orchoosetheFindtoolbarbutton.VLISPdisplaystheFinddialogbox.
IntheFindWhatdataentryfield,typethecharacterstringyouwanttolocate.IfthereistextselectedwhenyouentertheFindcommand,thistextisautomaticallyplacedintheFindWhatfield.
ChooseFindtostartthesearch.Whensearchingthroughasinglefile,pressF3tosearchforthenextoccurrenceofyoursearchstring.ChooseCanceltoendthesearch.
Whensearchingthroughmultiplefiles(seethenexttopic,ChoosingSearchOptions),VLISPdisplaysthematchesitfoundinanoutputwindow.Double-clickonanyhighlightedlinesintheFindOutputwindowtoopentheassociatedLISPfileinaVLISPeditorwindow.
ChoosingSearchOptionsRepeatinganEarlierSearchReplacingText
Pleasesendusyourcommentaboutthispage
Page 69
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>SearchingforText>
ChoosingSearchOptions
UndertheSearchheading,indicatetheextentofthesearchyouwantVLISPtoconduct.Youcanchooseoneofthefollowing:
CurrentSelection
Searchesonlythetexthighlightedintheeditorwindow.
CurrentFile
Searchesthroughtheentirefileintheactiveeditorwindow.
FindinProject
Withthisoptionselected,VLISPpromptsyoutospecifythenameoftheVLISPprojectyouwanttosearch.Itwillsearchallthefilesinthisprojectanddisplayallmatchesinanewoutputwindow.SeeFindingaStringinProjectSourceFilesformoreinformationonthisoption.
FindinFiles
Ifyouselectthisoption,VLISPallowsyoutospecifyaWindowsdirectory(folder)tosearchforthetext.Optionally,youcaninstructVLISPtosearchallsubdirectoriesofthatdirectoryaswell.VLISPwillsearchthroughallthefilesanddisplayallmatchesinanewoutputwindow.
Whensearchingfortextwithinthecurrentfile,theDirectionsettingdetermineswhereVLISPlooksnextforthesearchtext.ChooseDowntosearchforward(towardtheendofthefile)fromthecursorposition.ChooseUptosearchbackward(towardthebeginningofthefile)fromthecursorposition.
TheFinddialogboxalsoincludesthefollowingoptions:
MatchWholeWordOnly
Ifselected,VLISPwillonlymatchcompletewords.Forexample,ifthe
Page 70
searchtermisentandVLISPencountersthewordenterinthetext,VLISPdoesnotconsiderthisamatch.However,iftheMatchWholeWordOnlyoptionisnotselected,VLISPconsiderstheentwithinentertobeamatch.
MatchCase
Ifselected,VLISPonlymatchestextsetinthesamecase.Inthisinstance,Entandentarenotconsideredamatch.IfMatchCaseisnotselected,Entandentareconsideredamatch.
MarkInstances
Ifyouselectthisoption,thepositionofthelocatedtextwillbeaddedtothebookmarkring(seeBookmarkingText).Thisletsyoureturnquicklytothiscodepositionlater.Searchesthatfindalloccurrencesofastringaddeachpositiontothebookmarkring.
Pleasesendusyourcommentaboutthispage
Page 71
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>SearchingforText>
RepeatinganEarlierSearch
VLISPsaveseachsearchstringyouenterinapull-downlistonthetoolbar.
Torepeatasearchyoumadeearlier,clickthepull-downarrowandselectasearchtermfromthetoolbarlist.PresstheFindToolbarStringbuttontoconductthesearch.
Pleasesendusyourcommentaboutthispage
Page 72
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>SearchingforText>
ReplacingText
TheSearchmenucontainsaReplacefunctionthatisusedtoreplacethesearchtextwithatextstringthatyouspecify.
TheReplacedialogboxissimilartotheFinddialogbox,butwithfeweroptions.ItcontainsanadditionalReplaceWithentryfield,inwhichyouspecifythetextyouwantVLISPtosubstituteforthesearchtext.SpecifythesearchtextintheFindWhatfield.
YoucantakethefollowingactionsfromtheReplacedialogbox:
PressFindNexttofindthenextoccurrenceofthesearchstring.
PressReplacetoreplacethefoundtextwiththereplacementstring.Ifyoudon'twanttoreplacethisoccurrenceofthetext,pressFindNexttosearchforthenextoccurrenceofthetext,orCanceltoendthesearch.
PressReplaceAlltoreplacealloccurrencesofthesearchstringwiththereplacementstring.
PressCanceltoendtheReplacefunction.
Pleasesendusyourcommentaboutthispage
Page 73
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingtheTextEditor>
BookmarkingText
ThebookmarkfeaturehelpsyounavigatethroughVLISPtexteditorwindowsbylettingyoumarkupto32positions(bookmarks)ineachwindow.Once32bookmarksareset,addinganewbookmarkresultsintheoldestbookmarkbeingremoved.
Eachtexteditorwindowmaintainsitsownsetofbookmarks,andthebookmarknavigationtoolsletyouwalkthroughthemarkswithineachwindowindependentlyoftheotherwindows.Asetofbookmarkswithinawindowisknownasabookmarkring.Youcanstepeitherforwardorbackwardthroughthering,andeventuallyreturntothestartingpoint.
Wheneveryousteptoabookmark,VLISPautomaticallyplacesamarkeratthelocationyouaresteppingfrom.Ineffect,themarkerfortheplaceyouarejumpingtoismovedtotheplaceyoujumpedfrom.Thismakesiteasytoreturntoyouroriginallocationjustbysteppingbackintheoppositedirection,orbycyclingthroughallthebookmarksuntilyougetbacktothestartingpoint.
Toaddabookmark
1. Movethecursortothelocationyouwanttomark.
2. PresstheToggleBookmarkbuttononthetoolbar,orpressALT+.(ALTplusaperiod).
BookmarksmayalsobeinsertedautomaticallywhenusingtheFindcommandtosearchfortext.SeethediscussiononsearchoptionsinSearchingforTextformoreinformationonthisfeature.
Tomovethecursorfromonebookmarktothenext
Page 74
1. MovethecursortothepreviousbookmarkintheringbychoosingSearch Bookmarks PreviousBookmark,orbypressingthePreviousBookmarktoolbaricon.YoucanalsoaccomplishthisbypressingCTRL+,(CTRLplusacomma).
2. MovethecursortothenextbookmarkintheringbychoosingSearchBookmarks NextBookmark,orbypressingtheNextBookmarktoolbaricon.YoucanalsoaccomplishthisbypressingCTRL+.(CTRLplusaperiod).
Inadditiontojumpingbetweenbookmarks,youcanalsojumpandselectthetextbetweentwobookmarks.
Tomovethecursorandselecttextbetweenbookmarks
1. PressCTRL+SHIFT+,(comma)toselectthetextbetweenthecurrentlocationandthenextbookmark.
2. PressCTRL+SHIFT+.(period)toselectthetextbetweenthecurrentlocationandthepreviousbookmark.
Removingabookmarkissimilartosettingabookmark.
Toremoveabookmark
1. Movethecursortothebookmarkedlocation.
2. PresstheToggleBookmarkbutton,orpressALT+.(ALTplusaperiod).TheToggleBookmarkcommandworksasanon/offswitch.Ifyouissuethecommandwhenabookmarkisset,ToggleBookmarkturnsitoff.Issuethesamecommandwhenthereisnobookmarkset,andToggleBookmarkinsertsabookmark.
3. Toremoveallthebookmarksintheactivewindow,presstheClearAllBookmarksbuttononthetoolbar,orchooseSearch BookmarksClearAllBookmarksfromtheVLISPmenu.
Page 75
Pleasesendusyourcommentaboutthispage
Page 76
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
UsingConsoleandEditorCodingAids
SeveralVLISPcodingaidsareusefulatboththeConsoleandtexteditorwindows.OnehighlyvisualaidistheassignmentofcolorstoAutoLISPlanguageelements.Colorcodinghelpsyoudetectsyntaxerrorsinyourcode.VLISPalsocontainsseveralfeaturestohelpyoudeterminethenamesofvariablesandfunctionsthatyouneedtorefertoinyourprogram,andshortcutstoonlineHelpforAutoLISPfunctions.
UnderstandingVisualLISPColorCodingUsingtheAproposFeatureLettingVisualLISPHelpYouCompleteWordsGettingHelpforAutoLISPFunctions
Pleasesendusyourcommentaboutthispage
Page 77
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>
UnderstandingVisualLISPColorCoding
AssoonasyouentertextintheVLISPConsoleortexteditorwindows,VLISPattemptstodetermineiftheenteredwordisabuilt-inAutoLISPfunction,anumber,astring,orsomeotherlanguageelement.VLISPassignseverytypeofelementitsowncolor.Thishelpsyoudetectmissingquotesormisspelledfunctionnames.Thedefaultcolorschemeisshowninthefollowingtable.
DefaultcolorcodingschemeforAutoLISPcode
AutoLISPlanguageelement Color
Built-infunctionsandprotectedsymbols Blue
Strings Magenta
Integers Green
Realnumbers Teal
Comments Magenta,ongraybackground
Parentheses Red
Unrecognizeditems(forexample,uservariables)
Black
YoucanchangethedefaultcolorsbychoosingTools WindowAttributes
Page 78
ConfigureCurrentfromtheVLISPmenu.SeeConfigureCurrentformoreinformationonsettingcolors.
TheVLISPtexteditorprovidescolorcodingforLISPfiles,DCLfiles,SQLfiles,andC++languagesourcefiles(seeLISP,FAS,andOtherFileTypesforalistoffiletypesrecognizedbyVLISP).VLISPusesthefilenameextensiontodetermineafile'stype,andthenselectsthecolorcodingaccordingly.YoucanchangethecolorcodingstyleassociatedwithafiletypebychoosingToolsWindowAttributes SyntaxColoringfromtheVLISPmenu.AlltextenteredintheConsolewindowistreatedasAutoLISPcode.
Pleasesendusyourcommentaboutthispage
Page 79
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>
UsingtheAproposFeature
TheAproposfeatureisatoolthatsearchestheVLISPsymboltable.ThesymboltablecontainseverysymbolreadbytheAutoLISPreader.ThisincludessymbolsinuserprogramsandsymbolsthatimplementtheAutoLISPlanguage.
YoucandefinespecificsearchcriteriaforApropostouseinsearchingthesymboltable.Forexample,youcantellApropostosearchforallsymbolnamesthatcontainaspecificcharacterstring,andyoucanfurtherrefinethatsearchtoreturnonlysymbolsthatidentifyfunctions.
ToinvokeApropos,chooseView AproposWindowfromtheVLISPmenu,orpresstheAproposbuttonontheVLISPtoolbar.IfyouselecttextpriortoinvokingApropos,VLISPimmediatelyperformsanApropossearchontheselectedtext.Ifnotextisselected,VLISPdisplaystheAproposOptionsdialogbox.
IntheinputfieldoftheAproposOptionsdialogbox,enterthetextyouwantApropostosearchfor.Thedialogboxcontainsthefollowingoptions:
MatchbyPrefix
Ifthisoptionisturnedon,Apropossearchesforamatchstartingonlyfromthefirstcharacterofthesymbolname.Iftheoptionisturnedoff,Apropostriestomatchthetextyouenteredstartingatanypositionofasymbolname.Forexample,withMatchbyPrefixoff,asearchonthewordgetreturnssymbolnamesincludinggetint,getpoint,ssget,andvla-getActive.WithMatchbyPrefixon,thesamesearchdoesnotreturnssgetandvla-getActive,becausegetappearsinthemiddleofthosesymbolnames,notatthebeginning.
Page 80
UseWCMATCH(wildcardmatch)
Ifthisoptionisturnedon,Apropostreatsasterisksaswild-cardcharacterswhensearching.Forexample,ifyouspecifyfun*asthesymbolyouwantmatched,Aproposlooksforallnamesthatcontainfun,nomatterwhatcharactersfollow.Incontrast,withUseWCMATCHturnedoff,theasteriskistreatedasastringandAproposonlymatchesnamesthatpreciselycontainfun*.
DowncaseSymbols
Ifthisoptionisturnedon,anysymbolsyoucopytotheClipboardwiththeAproposserviceareconvertedtolowercasecharacters.Ifyoupastethesymbolnameinanotherwindow,itappearsinlowercase.
FilterFlags
Thisoptionletsyouchoosesymbolswithmatchingflagsettings.VLISPdisplaysalistofcheckboxesthatcorrespondtothesymbolflagsdescribedinUnderstandingSymbolFlags.Iftheflagfilterison,onlysymbolssetwiththeselectedflagsareconsidered.
FilterValue
OpenstheFilterValuedialogbox,fromwhichyoucanselectadditionalsearchcriteria.Youcanchooseoneofthefollowing:All Nofilter.Nullvalue Onlynil-valuedsymbolsareconsideredformatching.Nonullvalue Onlysymbolsthatarenotnilareconsideredformatching.Functions Allfunctiontypes(user-defined,built-in,andsoon)areconsideredformatching.Userfunction Onlyuser-definedfunctions(USUBR)areconsidered.Built-infunction Onlybuilt-inorcompiledAutoLISPfunctions(SUBR)areconsideredformatching.Exrxsubr Onlyexternalfunctionnamesarematched.
Ifyouspecifyafiltervalueorfilterflag,themessageareaoftheAproposoptionsdialogboxindicatesyourselections.
Whenyou'vespecifiedthecriteriayouwantApropostouseinitssearch,pressOKtoconductthesearch.
Page 81
TosearchforAutoLISPsymbolsthatbeginwithset
1. ChooseView AproposWindowfromtheVLISPmenu.
2. EntersetinthetextinputfieldoftheAproposoptionsdialogbox.
3. SelecttheMatchbyPrefixoption.
4. ClearallotheroptionsintheAproposoptionsdialogbox.
5. PressOKtoconductthesearch.UsingtheResultsofanAproposSearch
Pleasesendusyourcommentaboutthispage
Page 82
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>UsingtheAproposFeature>
UsingtheResultsofanAproposSearch
Aproposdisplaysthesymbolsmatchingyoursearchcriteriainthefollowingwindow:
ThebottomoftheAproposResultswindowcontainsamessageareawithinformationabouttheresultsofthesearch.Inthecurrentexample,themessageindicatesthenumberofsymbolsAproposfoundinitssearch.
IftheAproposResultswindowisnotlargeenoughtoshowallthesymbolsfound,thewindowisdisplayedasscrollable.Ifthesearchreturnsoverathousandmatches,Aproposwillnotbeabletolistallthesymbols,eveninascrollablewindow.Themessageareaintheresultswindowwarnsyouwhenthisoccurs,asinthefollowingexamplefromasearchontheprefixVL:
Page 83
IfyoursearchresultsintoomanysymbolsforApropostodisplayintheResultswindow,youcanusetheCopytoTrace/LogfeaturetoviewthecompletelistofsymbolsintheVLISPTracewindow.
ToreturntotheAproposOptionswindowandrefineyoursearch,presstheAproposoptionsbuttonintheAproposResultswindowtoolbar.
Thetoolbaralsocontainsthefollowingbuttons:
CopytoTrace/log
CopiestheresultsoftheApropossearchtotheVLISPTracewindow.DataintheTracewindowcanbecopiedusingtheWindowsCopycommand.IfTraceloggingisactive,thecontentsarealsocopiedtothelogfile(seeUsingVisualLISPDataInspectionToolsforinformationonTracelogging).
Help
InvokesHelpfortheselectedsymbol.ThesymbolnameisusedastheHelpindexsearchvalue.
YoucanalsousetheAproposResultswindow'sshortcutmenuonselectedsymbols.Forexample,youcanselectasymbolfromthelistandinsertitintotheVLISPConsoleortexteditorwindow.
Page 84
ToinsertasymbolfromtheAproposResultswindow
1. Selectasymbolfromthelist.
2. Right-clicktodisplaytheshortcutmenu,andchooseCopytoClipboardfromthelistofoptions.
3. ClickintheVLISPwindowatthepointyouwanttoinsertthesymbolname.
4. Right-clickandselectPastefromtheshortcutmenu,orpressCTRL+Vtopastethetext.
Theotheroptionsontheshortcutmenuare:
Inspect
InvoketheVLISPInspectfeaturefortheselectedsymbol.SeeUsingInspectWindowsforinformationonusingthisfeature.
Print
PrintthesymbolnameintheConsolewindow.IfyouselectasymbolnamedisplayedintheConsolewindowandpressENTER,VLISPcopiesthesymbolnametotheConsoleprompt.
Symbol
InvoketheVLISPSymbolServicefeaturefortheselectedsymbol.SeeUsingtheSymbolServiceDialogBoxforinformationonusingthisfeature.
Copy
Copytheselectedsymbolnametothe*obj*IDEglobalvariable.
AddtoWatch
AddtheselectedsymboltotheWatchwindow.SeeUsingtheWatchWindowforinformationonusingthisfeature.
Help
InvokeonlineHelpfortheselectedsymbol.
Pleasesendusyourcommentaboutthispage
Page 85
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>
LettingVisualLISPHelpYouCompleteWords
TwoVLISPfeatures,CompleteWordbyMatchandCompleteWordbyApropos,allowyoutotypepartofawordandgethelpincompletingtherest.
CompletingaWordbyMatchingCompletingaWordbyApropos
Pleasesendusyourcommentaboutthispage
Page 86
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>LettingVisualLISPHelpYouCompleteWords>
CompletingaWordbyMatching
UsingCompleteWordbyMatch,VLISPcompletesapartiallyenteredwordbymatchingthepartyouhavetypedwithanotherwordinthesamewindow.Forexample,supposethefollowingshowsthehistoryofyourVLISPConsolewindow:
_$(setqorigin(getpoint"\nOriginofinynsign:"))
_$(setqradius(getdist"\nRadiusofinynsign:"origin))
_$(setqhalf-r(/radius2))
_$(setqorigin-x(carorigin))
_$(command"_.CIRCLE"originradius)
Inotherwords,thesearethelastfivecommandsthatyouenteredfromtheConsole.
Tocompleteawordbymatching
1. TypethefollowingattheConsoleprompt:
_$(c
2. PressCTRL+SPACEBARtoinvokeCompleteWordbyMatch.VLISPfindsthelastwordyouenteredthatbeganwiththeletter“c,”andcompletesthewordyoustartedtotype:
_$(command
3. Ifthatisnotthewordyouarelookingfor,pressCTRL+SPCAEBARagain.VLISPsearchesbackthroughtheConsolehistoryforthepreviousoccurrenceofawordbeginningwiththeletter“c”:
Page 87
_$(car
VLISPwillkeepsearchingformatchingwordseachtimeyoupressCTRL+SPACEBAR.IfyoukeeppressingCTRL+SPACEBARafterVLISPfindsthelastmatchingword,VLISPrepeatstheretrievalsequence.(NotethatyoucanalsochooseSearch CompleteWordbyMatchfromtheVLISPmenuinsteadofpressingCTRL+SPACEBARtoinvoketheMatchfeature.)IfVLISPdoesnotfindanymatchingwords,itdoesnothing.YoucanuseCompleteWordbyMatchineithertheConsolewindoworthetexteditorwindow.WhenyouinvokethefeaturefromtheConsolewindow,VLISPonlysearchestheConsoleforamatch;wheninvokedfromatexteditorwindow,VLISPonlysearchesthateditorwindowforamatch.TheCompleteWordbyMatchfeatureisnotcase-sensitive.Inthepreviousexample,youwouldhaveachievedthesameresulthadyouenteredacapitalCinsteadofalowercasec.
Pleasesendusyourcommentaboutthispage
Page 88
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>LettingVisualLISPHelpYouCompleteWords>
CompletingaWordbyApropos
WiththeCompleteWordbyAproposfeature,VLISPcompletesapartiallyenteredwordwithamatchingsymbolnamefromtheVLISPsymboltable.Todemonstratethisfeature,assumeyouhaveenteredthefollowingcommandsshowninyourVLISPConsolewindow:
_$(setqorigin(getpoint"\nOriginofinynsign:"))
_$(setqradius(getdist"\nRadiusofinynsign:"origin))
_$(setqhalf-r(/radius2))
_$(setqorigin-x(carorigin))
_$(command"_.CIRCLE"originradius)
TousetheCompleteWordbyAproposfeature
1. AttheConsoleprompt,typethefollowing:
_$(ha
2. PressCTRL+SHIFT+SPACEtoinvokeCompleteWordbyAproposonthepartiallyenteredword.VLISPlistsallsymboltableentriesthatbeginwith“ha”:
Page 89
VLISPfoundtwomatchingwordsinthesymboltable.Thehalf-rsymbolisavariableyoudefinedintheConsolewindow,andthehandentsymbolrepresentsanAutoLISPfunction.
3. Selectthesymbolyouwanttocompleteyourtyping.Ifyoudonotwanttoselectasymbol,pressESC.NotethatyoucanalsochooseSearch CompleteWordbyAproposfromtheVLISPmenuinsteadofpressingCTRL+SHIFT+SPACEtoinvokethefeature.Ifnosymbolsmatchthetextyou'veentered,VLISPdisplaystheAproposoptionsdialogbox:
ThemessageareaoftheAproposoptionsdialogboxshowsthevaluethatAproposcouldnotmatch.SeeUsingtheAproposFeatureforinformationonsettingAproposoptionsandrenewingyoursearch.
Page 90
IfVLISPfindsmorethan15matchingnamesinthesymboltable,itdisplaystheAproposResultsdialogbox.Forexample,typegetattheConsoleprompt,thenpressCTRL+SHIFT+SPACEBARtoinvoketheAproposfeature.VLISPdisplaysthefollowingdialogbox:
Youcanselectasymbolfromtheresultswindowandcopyitintoyourcodeusingashortcutmenu.Ifyouneedadditionalhelpwithcopyingthesymboltoyourprogramcode,orusingotherfeaturesoftheAproposResultswindow,seeUsingtheResultsofanAproposSearch.
Pleasesendusyourcommentaboutthispage
Page 91
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>UsingConsoleandEditorCodingAids>
GettingHelpforAutoLISPFunctions
IfyouselectafunctionnameanywhereinatexteditororConsolewindow,andthenpresstheHelpbuttonontheToolstoolbar,VLISPdisplayshelpforthefunction.ThisfeatureworksforanyfunctionrecognizedbyVLISP.YoucanalsopressCTRL+F1toviewHelpfortheselectedfunction.
Pleasesendusyourcommentaboutthispage
Page 92
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
FormattingCodewithVisualLISP
TheVLISPcodeformatterarrangesthetextofAutoLISPexpressionsinastylethatimprovestextappearanceandreadability.ThecodeformatterincludesaSmartIndentfeaturetoarrangetheindentationofprogramcodeautomatically.ThecodeformatterworksautomaticallyasyouentercodeinaVLISPtexteditorwindow.YoucanalsoexplicitlyinvoketheformattertorearrangeselectedblocksoftextoralltextinaVLISPeditorwindow.Thisisusefulforformattingtextyoucopyfromothereditors,orforreformattingyourcodeinadifferentstyle.
Toformattextinanactiveeditorwindow
1. Toformatallthecodeinthewindow,chooseTools FormatcodeinEditorfromtheVLISPmenu,orclicktheFormatEditwindowbuttonontheToolstoolbar.
2. Toformatonlypartofthecodeintheeditorwindow,selectafragmentofcodetextandchooseFormatCodeInSelectionfromtheToolsmenu,orclicktheFormatSelectionbuttonontheToolstoolbar.
Ifyouselecttexttobeformatted,theselectionmustcontainvalidAutoLISPexpressionsortheformatterwillissueanerrormessage.
Iftheformatterfindsunbalancedparenthesesinyourcode,analertboxisdisplayed.ChooseYestohaveVLISPaddparentheseswhereitthinkstheybelong;chooseNoifyouwanttofixtheparenthesesonyourown.
Note TheVLISPformattercanbalancethenumberofparenthesesbutusually
Page 93
doesnotinserttheadditionalparenthesesintherightplaces.SeeCheckingtheBalanceofParenthesesformoreinformationondetectingandcorrectingunmatchedparentheses.
TheVLISPSmartIndentfeatureworksinthebackgroundasyoutypeinthetexteditor.TheindentisevaluateduptothecurrentAutoLISPparenthesisnestinglevel.Ifthecurrentexpressionisprecededbyonlyasequenceofcompletedtop-levelAutoLISPexpressions,theindentationwillbezero.YoucanaffecttheamountofindentationbyspecifyingVisualLISPformatoptions;seethenexttwotopics.
UnderstandingVisualLISPFormattingStylesApplyingFormattingOptionsApplyingVisualLISPCommentStylesSavingandRestoringFormattingOptionsFormatterRestrictionsFormattingShortcutKeys
Pleasesendusyourcommentaboutthispage
Page 94
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
UnderstandingVisualLISPFormattingStyles
TheVLISPformatterchoosestheappropriateformattingstyleaccordingtorulesthatareexplainedinthissection.YoucaninfluencethechoiceofVLISPstylesthroughtheoptionsyousetintheFormatOptionsdialogbox.TodisplaytheFormatOptionsdialogbox,chooseTools EnvironmentOptions VisualLISPFormatOptionsfromtheVLISPmenu.
Initially,VLISPdisplaysonlyasubsetoftheformattingoptionsyoucanspecify.PresstheMoreOptionsbuttonintheFormatOptionsdialogboxtoexpandthewindowwithadditionalformattingoptions.
Thefollowingaretwomainformattingstylesets:
Asingle-lineformattingstyle—Plane
Multiple-lineformattingstyles—Wide,Narrow,Column
Thesampletextbelowdemonstratesthedifferentformattingstyles.
Sampletextinitialappearance:
(autoload"appload"
'("appload"))
Forageneralfunctioncallexpression,theformatterappliesoneofthestylesinthefollowingsections.
PlaneStyleWideStyleNarrowStyleColumnStyle
Page 95
Pleasesendusyourcommentaboutthispage
Page 96
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>UnderstandingVisualLISPFormattingStyles>
PlaneStyle
InthePlanestyle,allargumentsareplacedinthesameline,separatedbyasinglespace:
(autoload"appload"'("appload"))
ThePlanestyleisappliedtoanexpressionwhenallthefollowingconditionsaremet:
Theexpression'slastcharacterpositiondoesnotexceedthevalueoftheRightTextMarginenvironmentoption.
Theexpression'sprintinglengthislessthanthevalueoftheApproximateLineLengthenvironmentoption(thatis,lastcharacterpositionminusstartingindentationpositionislessthanthisvalue).
TheexpressiondoesnotcontainembeddedcommentswithNewlinecharacters.
Pleasesendusyourcommentaboutthispage
Page 97
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>UnderstandingVisualLISPFormattingStyles>
WideStyle
IntheWidestyle,thefirstargumentisplacedinthesamelineasthefunctionname,andotherargumentsarealignedinacolumnbelowthefirstargument.
(autoload"appload"
'("appload")
)
TheWidestyleappliestoanexpressionwhenthefollowingconditionsaremet:
ThePlanestylecannotbeapplied.
Thefirstelementisasymbol,andthefirstelement'slengthislessthantheMaximumWideStyleCarLengthenvironmentoption.
Pleasesendusyourcommentaboutthispage
Page 98
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>UnderstandingVisualLISPFormattingStyles>
NarrowStyle
IntheNarrowstyle,thefirstargumentisplacedonthenextlineafterthefunctionname,andotherargumentsarealignedinacolumnbelowthefirstargument.Thedisplacementofthefirstargument'sstartingpositionrelativetotheexpressionstartingpositioniscontrolledbythevalueoftheNarrowStyleIndentationenvironmentoption(inthefollowingexample,thisvalueisequalto2):
(autoload
"appload"
'("appload")
)
TheNarrowformattingstyleappliesforprognexpressions,andforthoseinstanceswhenthePlaneandWideformattingstylescannotbeapplied.
Pleasesendusyourcommentaboutthispage
Page 99
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>UnderstandingVisualLISPFormattingStyles>
ColumnStyle
IntheColumnstyle,allelementsarepositionedinacolumn.ThisstyleisappropriatefordisplayingquotedlistsandCOND-expressionclauses.Forexample,thefollowingtext:
'((10"{insertion}")(1"{string}")
(7"{style}"))
wouldbedisplayedas:
'((10"{insertion}")
(1"{string}")
(7"{style}")
)
Pleasesendusyourcommentaboutthispage
Page 100
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
ApplyingFormattingOptions
Inadditiontoaffectingthebasicformattingstyles,youcanchoosefromanumberofVisualLISPformatoptions.
CloseParenthesisStyleInsertForm-ClosingCommentPreserveExistingLineBreaksSplitCommentsLongListFormatStyleSettingCaseforSymbols
Pleasesendusyourcommentaboutthispage
Page 101
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
CloseParenthesisStyle
Thisstylecontrolsthepositionofthecloseparenthesisformultiple-lineformattingstyles.Youcanselectoneofthefollowingoptions:
CloseattheSameLine
Closeparenthesisonthelastlineofeachformattingexpression.
CloseattheNewLinewithInnerIndentation
Closeparenthesisonthenextlinefollowingthelastlineofeachformattingexpressionwiththeinnerindent.
CloseattheNewLinewithOuterIndentation
Closeparenthesisonthenextlinefollowingthelastlineofeachformattingexpressionwiththeouterindent.
Examples
Theinitialexpressioniswrittenas:
(cond
((/=(logandmaskflg)0)
(list(listtxton)))
)
FormattingresultwhenCloseattheSameLineoptionisselected:
(cond((/=(logandmaskflg)0)
(list(listtxton))))
FormattingresultwhenCloseattheNewLinewithInnerIndentationoptionisselected:
Page 102
(cond((/=(logandmaskflg)0)
(list(listtxton))
)
)
FormattingresultwhenCloseattheNewLinewithOuterIndentationisselected:
(cond((/=(logandmaskflg)0)
(list(listtxton))
)
)
Pleasesendusyourcommentaboutthispage
Page 103
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
InsertForm-ClosingComment
Ifyouselectthisoption,VLISPaddsacommentfollowingthecloseofanexpression.However,theoptiontakeseffectonlyiftheCloseParenthesisStyleformatsettingiseitherCloseattheNewLinewithInnerIndentationorCloseattheNewLinewithOuterIndentation.
WhentheInsertForm-ClosingCommentoptionison,theVLISPformatterinsertsacommentoftheform
;_endof<functionname>
aftereachmultiple-linefunction.Thiscommentdoesnotappearifaninline-comment,single-semicoloncomment,orpasted-commentexistsafterthefunctioncall.YoucanchangethecommenttextbyenteringadifferentcommentintheForm-ClosingCommentprefixfieldoftheFormatOptionsdialogbox.
Example
Initialtext:
(autoarxload"image"
'("gifin""pcxin""riaspect""ribackg""riedge"
"rigamut""rigrey""rithresh""tiffin"))
Formattedtext:
(autoarxload"image"
'("gifin""pcxin""riaspect"
"ribackg""riedge""rigamut"
"rigrey""rithresh""tiffin"
)
);_endofautoarxload
Page 104
Notethe_endofautoarxloadcommentinthelastlineofcode.
Pleasesendusyourcommentaboutthispage
Page 105
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
PreserveExistingLineBreaks
WhenthePreserveExistingLineBreaksoptionison,theVLISPformatterinsertsnewlineswheneveranewlineisdetectedinthetextitisformatting.Whentheoptionisoff,theformattercansqueezeamultiple-lineexpressiontothePlanestyle,ifitfitswithintherightmargin.
ThefollowingexampleshowshowthePreserveExistingLineBreaksoptionworks.
Initialtext:
(if(/=s"Functioncanceled")(princ(strcat
"\nError:"
s));singlesemicoloncmt
)
Formattingresultiftheoptionison(default):
(if(/=s"Functioncanceled")
(princ(strcat
"\nError:"
s
)
);singlesemicoloncmt
)
Formattingresultwhentheoptionisoff:
(if(/=s"Functioncanceled")
(princ(strcat"\nError:"s));singlesemicoloncmt
)
Notethatmultiple-lineprincandstrcatexpressionsarecompressedtoasingleline.
Page 106
Pleasesendusyourcommentaboutthispage
Page 107
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
SplitComments
WhentheSplitCommentsoptionison,theformattersplitslongcommentsthatextendpasttherightmargin.
Forthepreviousexample,iftheRightTextMarginsettingis60,andSingle-Semicoloncommentindentationis40,theformatterwillsplitthecommentasfollows:
(if(/=s"Functioncanceled")
(princ(strcat"\nError:"s));single
;semicoloncmt
)
Pleasesendusyourcommentaboutthispage
Page 108
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
LongListFormatStyle
Longlistsarelistsofformalargumentsindefun,lambda,orquotedlistscontainingmorethanfiveelements.TheLongListformatstyleappliestoliststhatdonotfitonasingleline(withintheRightTextMargin).
IftheLongListformatstyleoptionsdonotappearinyourFormatOptionsdialogbox,presstheMoreOptionsbuttontodisplayadditionalformattingoptions.TheavailablemodesforLongListformatarelistedbelowandillustratedwithanexamplebasedonthefollowinglistelements,andwithRightTextMarginsetto45:
'("entdel""entmake""entmod""entnext"
"entsel""entupd")
Single-Columnformatting:
'("entdel"
"entmake"
"entmod"
"entnext"
"entsel"
"entupd"
)
Two-Columnformatting:
'("entdel""entmake"
"entmod""entsel"
"entnext""entupd"
)
Multi-Columnformatting:
Page 109
'("entdel""entmake""entmod"
"entsel""entnext""entupd"
)
Fill-the-Stringformatting(placesasmanyquotedstringsononelineaspossible,uptotherightmargin):
'("entdel""entmake""entmod""entsel""entnext""entupd"
)
ThePreserveExistingLineBreaksoption,ifselected,maysupersedetheformattingindicatedbyLongListformatstyle.
Pleasesendusyourcommentaboutthispage
Page 110
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>ApplyingFormattingOptions>
SettingCaseforSymbols
Bydefault,theVLISPformatterdoesnotchangethecaseofAutoLISPsymbols.YoucansettheformattertochangethecaseofsymbolsaccordingtotheVLISPprotectionstateforsymbols.
TheProtectedoptionssubgroupcontrolsthecaseconversionofprotectedsymbols(built-insymbolsorsymbolswiththeASSIGN-PROTECTflagset).TheUnprotectedoptionssubgroupcontrolscaseconversionofunprotected(user)AutoLISPsymbols.
Casesettingsforsymbols
Setting Effect
None Doesnotchangethecase
downcase Forcesallcharactersinasymbol'snametolowercase
UPCASE Forcesallcharactersinasymbol'snametouppercase
Pleasesendusyourcommentaboutthispage
Page 111
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
ApplyingVisualLISPCommentStyles
TheVLISPformatterrecognizesfivetypesofAutoLISPcomments,andpositionseachcommentaccordingtoitstype.
VisualLISPcommentformatting
Comment Formattedappearance
;|Inline|; Thesingle-linecommentappearsafterformattingasanyotherexpression;themultiple-linecommentappearsstartingatanewline
;Single-Semicolon Startsatthecomment-columnposition,asdefinedbythe“Single-Semicoloncommentindentation”formatoption
;;Current-Column Thecommentappearsstartingonanewline,indentedatthesamelevelasthelastlineofprogramcode
;;;Headingor0-Column Appearsonanewline,withoutindentation
;_Function-Closing Appearsjustafterthepreviousexpression
Page 112
Thefollowingexampledemonstrateseachcommentstyle.
Initialtext:
(defunfoo(x)
;|inlinecomment|;
(list123);comment-columncomment
;;current-columncomment
;;;headingor0-columncomment
);_function-closingcomment
Formattedtext:
(defunfoo(x);|inlinecomment|;
(list123);comment-columncomment
;;current-columncomment
;;;headingor0-columncomment
);_function-closingcomment
Pleasesendusyourcommentaboutthispage
Page 113
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
SavingandRestoringFormattingOptions
TosaveyourformattingoptionssothattheycarryovertosubsequentVLISPsessions,chooseTools SaveSettingsfromtheVLISPmenu.Alternatively,youcansavethecurrentsettingsspecificallyfortheprogramintheactivetexteditorwindow.VLISPsavesformattersettingsinaprogramwhentheSaveFormattingOptionsinSourceFileoptionisselected.Toselectorcancelthisoption,chooseEnvironmentOptions VisualLISPFormatOptionsfromtheToolsmenu.Iftheoptionisineffect,VLISPaddsformattinginformationascommentsattheendoftheprogram,whenyouruntheformatter.
Eachformatterinvocationchecksforformattingoptionssettingsatthebottomoftheselectedtext.Iffound,thesesettingsoverridethesessionsettingslistedinTools EnvironmentOptions VisualLISPFormatOptions.
Pleasesendusyourcommentaboutthispage
Page 114
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
FormatterRestrictions
ThefollowingrestrictionsapplytotheVLISPcodeformatter:
Theformatterreliesonafixedwindowfontandaparticulartabsize.Tochangefontsettings,chooseWindowAttributes Font;tochangetabsettings,chooseWindowAttributes ConfigureCurrent.
TheformatterisavailableonlywithinVLISPtexteditorwindows.
ExistingSPACEandTABcharactersplacedoutsideofinlinecommentsandstringswillnotinfluencetheformattingresult.
Pleasesendusyourcommentaboutthispage
Page 115
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>FormattingCodewithVisualLISP>
FormattingShortcutKeys
PressCTRL+EwhileinanactiveVLISPtexteditorwindowtodisplayalistcontainingthefollowingeditoroptions.
Texteditorcodeformattingcommands
Option Effect
IndentBlock Indentstheselectedblockoftextbyaddingatabtothebeginningofeachline
Unindent Unindentstheselectedblockoftextbyremovingatab
IndenttoCurrentLevel Indentsthecurrentlinetothesamelevelasthepreviouslineofprogramcode
PrefixWith Addsatextstringtothebeginningofthecurrentline,ortoeachlineinablockofselectedlines,afterpromptingyouforthestring
AppendWith Appendsatextstringtoselectedlinesoftext,afterpromptingyouforthestring
Page 116
CommentBlock Convertsablockofcodetocomments
UncommentBlock Changesablockofcommentstoactivetext
SaveBlockAs Copiesselectedtexttoanewfile
Upcase Convertstheselectedtexttoalluppercase
Downcase Convertstheselectedtexttoalllowercase
Capitalize Capitalizesthefirstletterofeachwordintheselectedtext
Insertdate Insertsthecurrentdate(defaultformatisMM/DD/YY)
Inserttime Insertsthecurrenttime(defaultformatisHH:MM:SS)
FormatDate/Time Changesthedateandtimeformat
SortBlock Sortstheselectedblockofcodeinalphabeticalorder
InsertFile Insertsthecontentsofatextfileintothecurrenteditorwindowatthecursorposition
DeletetoEOL Eraseseverythingfromthecursorpositiontotheendofthecurrentline
DeleteBlanks Deletesallblankspacesfromthe
Page 117
cursorpositiontothefirstnon-blankcharacterintheline
Pleasesendusyourcommentaboutthispage
Page 118
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>
CheckingforSyntaxErrors
OnemainattractionofusingVLISPistheextensivedebuggingtoolsitprovides.Thesetoolsallowyoutowatchwhatyourprogramisdoingwhileitisexecuting,andtotakea“snapshot”ofyourprogramatanypoint.However,VLISPalsoprovidesanumberoffeaturesdesignedtodetectprogramerrorsbeforeyouruntheprogram.
CheckingtheBalanceofParenthesesUsingColorCodingtoDetectSyntaxErrorsUsingtheCheckCommandtoLookforSyntaxErrors
Pleasesendusyourcommentaboutthispage
Page 119
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>CheckingforSyntaxErrors>
CheckingtheBalanceofParentheses
AutoLISPusesparenthesesmorefrequentlythanmostothercomputerlanguages.OneofthemostfrequentsyntaxerrorsinAutoLISPisanunequalnumberofopenandcloseparentheses.VLISPincludesanumberoftoolstohelpyoudetectunbalancedorunmatchedparentheses.
AsnotedinToformattextinanactiveeditorwindow,theVLISPcodeformattersearchesforunbalancedparentheseswhenitformatsyourcode.Ifyouallowitto,theformatterwilladdparentheseswhereitthinkstheyaremissing.Typically,though,theVLISPformatteraddsparenthesesattheendofaprogram,nottowhereyoureallyneedthem.IfyouletVLISPaddtheparentheses,youwillprobablyhavetoremovethemlater.
Note Ifyoudonotallowtheformattertoaddthebalancingparentheses,itwon'tformatyourcodeeither.
Inanyevent,youmustcheckthestructureofyourprogramtodeterminewheretheparenthesesarereallymissing.YoucanusetheseparenthesesmatchingitemsfromtheEditmenutohelpyoufindunbalancedparentheses:
MatchForward(CTRL+])
Movestheinsertionpoint(markedbythecursor)justpastthecloseparenthesisthatmatchesanopenparenthesis.Ifthecurrentcursorpositionisjustbeforeanopenparenthesis,VLISPmatchesthatparenthesiswithitsclosingparenthesis.Ifthecursorpositionisinthemiddleofanexpression,VLISPmatchesthecurrentexpression'sopenparenthesiswithitsclosingparenthesis.
MatchBackward(CTRL+[)
Movestheinsertionpointtojustbeforetheopenparenthesisthatmatchesacloseparenthesis.
Page 120
Ifthecurrentcursorpositionisjustafteracloseparenthesis,VLISPmatchesthatparenthesiswithitsopeningparenthesis.Ifthecursorpositionisinthemiddleofanexpression,VLISPmatchesthecurrentexpression'scloseparenthesiswithitsopenparenthesis.
SelectForward(CTRL+SHIFT+]
MovestheinsertionpointastheMatchForwardcommanddoes,butalsoselectsalltextbetweenthestartandendpositions.Withthecursorpositionedrightbeforeanopenparenthesis,double-clickingalsoselectsalltextuptothematchingcloseparenthesis,butdoesnotmovetheinsertionpoint.
SelectBackward(CTRL+SHIFT+[)
MovestheinsertionpointastheMatchBackwardcommanddoes,butalsoselectsalltextbetweenthestartandendpositions.Withthecursorpositionedrightafteracloseparenthesis,double-clickingalsoselectsalltextuptothematchingopenparenthesis,butdoesnotmovetheinsertionpoint.
Forexample,lookatthefollowingcode:
1(defunyinyang(/originradiusi-radiushalf-rorigin-xorigin-y)
2(setqhalf-r(/radius2))
3(setqorigin-x(carorigin))
4(setqorigin-y(cadrorigin))
5(command"_.CIRCLE"
6origin
7radius
8(command"_.ARC"
9"_C"
10(listorigin-x(+origin-yhalf-r))
11(listorigin-x(+origin-yradius))
12origin
13)
14(command"_.ARC"
15"_C"
16(listorigin-x(-origin-yhalf-r))
17(listorigin-x(-origin-yradius))
Page 121
18origin
19)
20)
(Thelinenumbersarenotpartofthetext;theyareusedtohelpexplaintheexample.)
HereiswhathappensifyouloadthiscodeinVLISPandcontinuallyissuetheMatchForwardcommand,startingwiththeinsertionpointatthebeginningofline1.
VLISPdoesnotfindamatchingcloseparenthesis,sothecursordoesnotmove.
Movethecursortothebeginningofline2.
Cursormovestotheendofline2.
Cursormovestotheendofline3.
Cursormovestotheendofline4.
Cursorjumpstothelastrightparenthesisintheprogram.(20)
Inotherwords,thecloseparenthesisthatmatchestheopenparenthesisonline5isthelastparenthesisintheprogram.YouknowthisisanerrorbecausethelastcloseparenthesisinanAutoLISPprogramshouldmatchtheopenparenthesisoftheprogram'sdefun.Noticealsothatallthestatementsafterline5areindentedinamannerunlikeintheprecedingprogramcode.Thesetwocluesindicatesomethingisamissatthispointintheprogram.Infact,thecloseparenthesistothecommandthatbeginsonline5ismissing.
Pleasesendusyourcommentaboutthispage
Page 122
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>CheckingforSyntaxErrors>
UsingColorCodingtoDetectSyntaxErrors
TheAutoCADSample\VisualLISPdirectorycontainsafilenameddrawline-with-errors.lsp.Itissimilartothedrawline.lspprogramfileintroducedearlierinthismanual,butitcontainsacoupleoferrors.OpenthefileinVLISP,sothatyoucanseehowcolorisusedinthefile:
(defundrawline(/pt1pt2);Localvariablesdeclared
;;gettwopointsfromtheuser
(setqpt1(getpoint"\nEnterthestartpointfortheline:"))
(setqpt2(getpointpt1"\nEntertheendpointfortheline:"))
;;checktoseethatthetwopointsexist
(iff(andpt1pt2)
(command"_.line"pt1pt2"")
(princ"\nInvalidormissingpoints!")
(princ);;exitquietly
)
)
IfyouusethestandardVLISPsyntacticcolorations,systemsfunctionssuchassetq,defun,getdist,getpoint,and/aredisplayedinblue.TheitemsVLISPdoesnotrecognize,suchasuser-definedvariables,areprintedinblack.Inthisexample,ifyoulookattheunrecognizedelementsintheprogram,thewordiffmighteasilycatchyoureye.Changeittothecorrectspelling,if,andthecolorimmediatelychangestoblue.
Pleasesendusyourcommentaboutthispage
Page 123
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>CheckingforSyntaxErrors>
UsingtheCheckCommandtoLookforSyntaxErrors
YoucanperformadditionalsyntaxcheckingwiththeVLISPCheckcommand.TheCheckcommandcandetectthefollowingerrors:
Incorrectnumberofargumentssuppliedtoaknownfunction
Invalidvariablenamepassedtoafunction(forexample,aquotedsymbolwhereavariableisrequired)
Incorrectsyntaxinspecialformfunctioncalls(forexample,lambda,setq,andforeach)
SomesyntaxerrorscanonlybedeterminedatruntimeandCheckcannotdetecttheseerrors.Forexample,ifyoucallafunctionthatexpectsanintegerargumentandyousupplyastring,AutoLISPdoesnotdetectthisuntilrun-time.Asaresult,thiserrorwillnotbedetecteduntilyourunyourprogram.
ToruntheCheckcommandontextinaneditorwindow
1. Switchtotheeditorwindowcontainingthecodeyouwanttocheck.
2. Tochecktheentirefile,chooseTools CheckTextinEditorfromtheVLISPmenu.
3. Tocheckthesyntaxofaselectedpieceofcodeinsteadofthewholeprogram,chooseTools CheckSelection.
VLISPdisplayserrormessagesinanewBuildOutputwindow,ifitdetectserrors.Forexample,ifyouchangetheiffindrawline-with-errors.lsptoif
Page 124
andrunCheck,thefollowingerrormessageresults:
Themessageindicatesthataniffunctioncallcontainstoomanyarguments.FindingtheLocationoftheSyntaxErrorinYourProgram
Pleasesendusyourcommentaboutthispage
Page 125
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DevelopingProgramswithVisualLISP>CheckingforSyntaxErrors>UsingtheCheckCommandtoLookforSyntaxErrors>
FindingtheLocationoftheSyntaxErrorinYourProgram
Ifyoudouble-clickontheerrormessageintheBuildOutputwindow,VLISPactivatestheeditorwindow,placesthecursoratthebeginningofthestatementthatcausedtheerror,andhighlightstheentireexpression,asfollows:
Thiserrorresultsfromthelastprincstatementfollowingtheif.Theifstatementonlyallowstwoarguments:thestatementtoexecuteiftheexpressionistrue,andthestatementtoexecuteiftheexpressionisfalse.Thelastprincstatement,whichisusedinthisprogramtocauseaquietexit,belongsafterthecloseparenthesisthatcurrentlyfollowsit.(SeeExitingQuietlyforanexplanationofaquietexit.)IfyoumovethestatementtothecorrectlocationandrunCheckagain,thecodeshouldpassaserror-free.
Pleasesendusyourcommentaboutthispage
Page 126
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
DebuggingPrograms
Todebugaprogram,youcantraceexecution,tracethevaluesofvariablesduringexecution,andviewthesequenceinwhichexpressionsareevaluated.
Programsdonotalwaysbehaveinthewaytheywereintended.Whentheresultsyougetappeartobewrong,orcausetheprogramtofail,itcanbedifficulttodeterminewhatisgoingwrong.VisualLISP®providesmanyfeaturesthathelpyouwiththedebuggingprocess—findingandresolvingprogramproblems.
IntroducingVisualLISPDebuggingFeaturesLearningbyExampleUsingtheVisualLISPDebuggingFeaturesUsingVisualLISPDataInspectionTools
Pleasesendusyourcommentaboutthispage
Page 127
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>
IntroducingVisualLISPDebuggingFeatures
Debuggingisusuallythemosttime-consumingstageinthedevelopmentofanyprogram.Forthisreason,VLISPincludesapowerfuldebuggerthatprovidesthefollowingfeatures:
Tracingofprogramexecution
Tracingofvariablevaluesduringprogramexecution
Viewingthesequenceinwhichvariousexpressionsareevaluated
Inspectingthevaluesofparametersusedwithinfunctioncalls
Interruptingprogramexecution
Steppingthroughprogramexecutiononeinstructionatatime
Inspectingthestack
VLISPprovidesthefollowingfacilitiestoimplementthesefeatures:
BreakLoopMode
Haltsprogramexecutionatspecifiedpoints,allowingyoutolookatandmodifythevalueofobjectsduringthebreak.ExamplesofAutoLISP®objectsarevariables,symbols,functions,andexpressions.
Inspect
ProvidesdetailedinformationonanobjectinanInspectdialogbox.Iftheobjectbeinginspectediscomposedofnestedobjects(alist,forexample),theInspectfeatureallowsyoutoinspectallthecomponents,eachonelistedonitsownlinewithinthewindow.Youcanalsorecursivelyinspectanynestedobjectuntilanatomicobject(suchasanumberorasymbol)isreached.
WatchWindow
Page 128
Watchesthevaluesofvariablesduringprogramexecution.ThecontentoftheWatchwindowisupdatedautomatically.ThismeansthatifthevalueofavariableplacedintheWatchwindowischanged,thischangewillautomaticallybereflectedintheWatchwindow.
TraceStackFacility
Viewsthefunctioncallstack.ThecallstackisamechanismbywhichVLISPrecordsthesequenceoffunctionsastheyareexecutedbyyourprogram.Youcanviewthestackduringadebuggingsession(whentheprogramisinasuspendedstate,suchassteppingthroughafterabreakpoint),orafteryourprogramhascrashed.Ifviewedafteryourprogramcrashes,thefunctioncallstackshowswhatVLISPwasdoingatthemomenttheapplicationfailed.
TraceFacility
AstandardLISPfacility,logsthecallsandreturnsvaluesoftracedfunctionsintothespecialTracewindow.
Pleasesendusyourcommentaboutthispage
Page 129
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>
LearningbyExample
ThissectiontakesyouthroughaVLISPsampleprogramanddemonstratessomeVLISPdebuggingfacilitiesalongtheway.Youcanfindthesampleprogram,yinyang.lsp,intheSample\VisualLISPdirectoryunderthedefaultAutoCADinstallationpath.OpenthefileinVLISPsothatyoucantrytheexamplesinthissection.
SteppingthroughtheDebuggingExample
Pleasesendusyourcommentaboutthispage
Page 130
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>
SteppingthroughtheDebuggingExample
First,loadtheyinyang.lspfileandruntheyinyangfunctiontoseewhatitdoes.Thefunctiondrawstheyin-yangsymbol,whichisusedinmanyreligions:
Whenyouruntheprogram,VLISPpassescontroltoAutoCADandyouneedtorespondtothepromptsintheAutoCADCommandwindow.
VLISPevaluatesAutoLISPprogramsbyevaluatingtheexpressionscontainedinparentheses.TheseparentheticalexpressionsaresimilartooperatorsinotherprogramminglanguagessuchasC++andVisualBasic6.TheVLISPdebuggerusesanexpression-basedapproach,unliketheline-by-linedebuggersoflanguagessuchasC.Intheexpression-basedapproach,thedebuggercansuspendprogramexecutionimmediatelybeforeoraftertheevaluationofanyexpression.
DebuggingoptionsarecontrolledfromseveraldifferentplaceswithinVLISP,includingthetexteditor,theSystemConsole,andvariousmenus.
SettingaBreakpointtoInterruptProgramExecutionSteppingthroughtheProgramMonitoringtheEvaluationResultsofanExpressionContinuingProgramExecutionRunninginAnimateMode
Page 131
Pleasesendusyourcommentaboutthispage
Page 132
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>SteppingthroughtheDebuggingExample>
SettingaBreakpointtoInterruptProgramExecution
Beginbyenteringsomedebugginginformationinthetexteditorwindowcontainingtheyinyang.lspprogram.
Tosetabreakpointthatinterruptsprogramexecution
1. Movethecursorinfrontoftheopenparenthesisinthelineofcodethatreads:
(setqhalf-r(/radius2))
Thefollowingscreensnapshotindicatesthepositionofthisstatementwithintheprogram:
2. ClicktheToggleBreakpointbuttonintheDebugtoolbar,orchooseDebug ToggleBreakpointfromtheVLISPmenu.ToggleBreakpointswitchesbreakpointsonandoff.Whennobreakpointexists,ToggleBreakpointaddsabreak;ifabreakpointalreadyexistsatthecursorposition,ToggleBreakpointremovesit.
Page 133
3. Loadtheyinyangfunction,ifyouhavenotdonesoalready,runitfromtheVLISPConsolepromptbyenteringthefollowingcommand:
(yinyang)
AfteryoureplytothepromptstheprogramdisplaysattheAutoCADcommandline,VLISPhaltsyinyangexecutionatthebreakpointyousetanddisplaysthecodeinthetexteditorwindow:
Notehowthestatementfollowingthecursorishighlighted.
Pleasesendusyourcommentaboutthispage
Page 134
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>SteppingthroughtheDebuggingExample>
SteppingthroughtheProgram
TheStepcommandsallowyoutomovethroughaprogrambyexecutingoneormoreexpressionsatatime.
Tostepthroughaprogramfromabreakpoint
1. ClicktheStepIntobutton,orchooseDebug StepIntofromtheVLISPmenu.YoucanalsopressF8toissuetheStepIntocommand.Executionbeginsandhaltsbeforeevaluationoftheinnerparentheticalexpression,thatis,beforethespecifieddivisionoccurs.Theexpressionishighlighted,asshowninthefollowingfigure:
NowlookattheStepIndicatorbuttonontheDebugtoolbar;itisthelastbuttononthattoolbar.
TheStepIndicatorbuttonisactivewhenyouaresteppingthroughaprogram.Itindicateswhereyouareinrelationtotheexpressionatthe
Page 135
breakpoint.Thecurrentsymbolindicatesthatyouarestoppedjustbeforeanopenparenthesis.
2. ClicktheStepIntobuttonagain.Thecursormovestoapositiondirectlyaftertheevaluatedexpression,andtheStepIndicatorbuttonindicatesthis.
3. ClicktheStepIntobuttonagain.Thecursormovestotheendoftheentirestatement(theexpressionandallnestedexpressions).
4. ClicktheStepIntobuttonagainandthecursormovestoapositionjustbeforethebeginningofthestatementonthenextline:
5. Nowtakeabiggerstep.ClicktheStepOverbutton,orchooseDebugStepOverfromthemenu,orpressSHIFT+F8toissuethiscommand:
Page 136
WiththeStepOvercommand,VLISPevaluatesanentireexpression(andallnestedexpressions),thenstopsattheendoftheoverallexpression.Thecursormovestotheendoftheevaluatedexpression.
Pleasesendusyourcommentaboutthispage
Page 137
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>SteppingthroughtheDebuggingExample>
MonitoringtheEvaluationResultsofanExpression
Asyoustepthroughaprogram,youmaywanttomonitorthevaluesresultingfromtheevaluationofindividualexpressions.
Tomonitorvariablesduringprogramexecution
1. FromtheDebugmenu,chooseWatchLastEvaluation.
VLISPdisplaystheWatchwindow,whichshowsthevalueofthe*LAST-VALUE*IDEglobalvariable.VLISPalwaysstoresthevalueofthelastevaluatedexpressioninthe*LAST-VALUE*variable.
2. Inthetexteditorwindowcontainingyinyang.lsp,double-clickonanyoccurrenceofthevariablenameorigin-y.
3. ClicktheAddWatchbuttonintheWatchwindow.VLISPpassestheorigin-yvariablenametotheWatchwindowanddisplaysthecurrentvalueofthevariableinthewindow:
Page 138
IftheWatchwindowisnotalreadyopenandyouwanttoviewavariable'svalue,youcanopenthewindowbychoosingView WatchWindowfromtheVLISPmenu.IfyouclicktheWatchwindow'sAddWatchbuttonwithoutdouble-clickingonavariablenamefirst,thefollowingwindowappears:
Inthiswindow,youcanenterthenameofthevariableyouwanttoview.VLISPmayanticipateyourchoicebycopyingthenameofthevariablenearestthecursorintothewindow.Ifthisisnottheoneyouwanttoview,simplytypeoverthename.VLISPupdatesthevariablesintheWatchwindowaftereachexecutionstep.
4. ClicktheStepOverbutton(orpressSHIFT+F8)twice.IntheWatchwindow,notehowthevalueoforigin-ychanges.Itwasnilatfirst,butafterexecutionittookonthevaluecorrespondingtothepointyouclickedintheAutoCADwindow.
Page 139
Pleasesendusyourcommentaboutthispage
Page 140
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>SteppingthroughtheDebuggingExample>
ContinuingProgramExecution
Tocontinuerunningyourprogramtothenextbreakpoint,ortotheend,iftherearenomorebreakpoints,presstheContinuebuttonontheDebugtoolbar,orchooseDebug ContinuefromtheVLISPmenu.
Pleasesendusyourcommentaboutthispage
Page 141
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>LearningbyExample>SteppingthroughtheDebuggingExample>
RunninginAnimateMode
Anotherdebuggingfeature,animation,allowsyoutowatchasVLISPstepsthroughyourprogramcodeandevaluateseachexpression.InAnimatemode,it'sasifVLISPrepeatedlyentersaStepIntocommandforyou.Texteditorwindowshighlightexpressionsbeingevaluated,andtheWatchwindowcontinuouslyupdatesitsdata.
ToseehowAnimatemodeworks
1. TurnonAnimatemodebychoosingDebug AnimatefromtheVLISPmenu.
2. Enter(yinyang)attheConsoleprompttobeginexecutingtheprogram.You'llseeeachfunctionhighlightedasVLISPevaluatesthefunction.You'llbepromptedforinput,asusual.NoticehowtheWatchwindowisupdatedwheneverawatchedvariablechanges.Becauseyoupreviouslysetabreakpointintheprogram,executionwillhaltatthatbreakpoint.
3. Afteryoustopatthebreakpoint,presstheContinuebuttontoresumeexecution;VLISPresumesexecutinginAnimatemode.
YoucanalsointerruptanimationbypressingBREAK(it'sthekeynexttoSCROLL-LOCKonmostkeyboards).OnceanimationispausedyoucanaddWatchvalues,setvariablestonewvalues,andaddbreakpoints.
Toadjusttherateofanimation,chooseTools EnvironmentOptions GeneralOptions,andselecttheDiagnostictab.TheAnimationDelaysettingdefinesthepausebetweenprogramsteps,inmilliseconds.
ToturnoffAnimatemode,chooseDebug AnimatefromtheVLISPmenuagain.
Page 142
Pleasesendusyourcommentaboutthispage
Page 143
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>
UsingtheVisualLISPDebuggingFeatures
InadditiontosettingbreakpointsandrunninginAnimatemode,asdescribedintheLearningbyExamplesectionofthischapter,VLISPprovidesanumberofotheroptionsforcontrollingprogramexecution.
StopOnce
CausesVLISPtobreakunconditionallywhenitevaluatestheveryfirstLISPexpressionencountered.YouturnonthismodeofoperationbychoosingDebug BreakonErrorfromtheVLISPmenu.
BreakonError
Automaticallyactivatestheinteractivebreakloopwheneveryourprogramencountersaruntimeerror.YouturnonthismodeofoperationbychoosingDebug StopOncefromtheVLISPmenu.Notethatifthisoptionisselected,someerrorsthatresultfromfunctioncallsenteredattheAutoCADCommandpromptwillcauseVLISPtogetfocus.Thatis,theactivewindowmayswitchfromAutoCADtotheVLISPConsolewindow,whereyouwillbeinabreakloop.
BreakonFunctionEntry
SetstheDebug-on-Entryflagforafunction'snamesymbol,causingabreaktooccureverytimeyouinvokethatfunction.Atthebreak,thesourcecodeforthefunctionwillbeshowninaspecialwindow.YoucansetorcleartheDebug-on-EntryflaginteractivelywiththeSymbolServicedialogbox.SeeUsingtheSymbolServiceDialogBoxforinformationonsettingthisflag.
Top-LevelDebuggingMode
Controlstheloadingofaprogramfromafileoraneditorwindow.Iftheoptionisset,breaksoccurbeforeevaluatingeverytop-levelexpression(suchasdefun).TheTop-Leveldebuggingmodeisturnedonbyswitchingoffthe
Page 144
DoNotDebugTopLeveloption.Tofindthecheckboxforthisoption,chooseTools EnvironmentOptions GeneralOptionsfromtheVLISPmenu,thenclicktheDiagnostictab.
IfTop-LeveldebuggingandStopOncemodeareturnedon,VLISPwillenterthedebuggingmodeeverytimeyouloadafilebecauseVLISPisdebuggingdefun,setq,andotherfunctionsdefinedwithinthefileastheyareloaded.Thisisusuallynotahelpfuldebuggingtechniqueandshouldonlyberequiredinrareinstances.
StartingaDebuggingSessionUnderstandingBreakLoopsUsingBreakpoints
Pleasesendusyourcommentaboutthispage
Page 145
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>
StartingaDebuggingSession
TheeasiestwaytostartdebuggingistochooseDebug StopOncefromtheVLISPmenu.Whenthisitemisselected,theevaluationofthefirstLISPexpressionwillbeinterrupted.AfterthatyoucanresumeprogramexecutionusingvariousDebuggercommands.Anotherwaytoenterintothedebuggermodeistosetabreakpoint,asshowninSettingaBreakpointtoInterruptProgramExecution.
Whenabreakoccurs,thecorrespondingVLISPtexteditorwindowwillshowthecurrentLISPexpressionatthepointwhichthebreaktookplace.AbreakloopmarkerwillappearintheConsolewindow.UsingtheConsolewindow,youcanaccessandmanipulatetheprogramenvironmentinwhichthebreakoccurred.YoucanalsoexaminevariablesusingtheWatchwindow.
Pleasesendusyourcommentaboutthispage
Page 146
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>
UnderstandingBreakLoops
ExpressionsarethebasicstructuralunitsofAutoLISP,andVLISPworksbyrepeatedlyreading,evaluating,andprintingexpressions.InLISPterminology,thisisaread-eval-printloop.
WhenyouarerunninganAutoLISPprogramwithoutanydebugginginterventionbyVLISP,youarerunningintheTop-Levelread-eval-printloop.WhenyouevaluateanexpressionwithintheVLISPConsolewindow,andthenormalpromptisdisplayed,youarealsoworkingattheTopLevel.
Whenaprogram'sevaluationisinterruptedorsuspendedinthemiddleofexecution,VLISPpassescontroltotheConsoleandyouenterabreakloop.Thisbreakloopisaseparateread-eval-printloop,andisnestedunderneaththeoriginalread-eval-printloop.Itispossibletointerruptabreakloopandstartyetanotherread-eval-printloopbeneathit.ThenestinglevelofabreakloopwithrespecttotheTopLeveliscalledthebreaklevel.
Whenyouenterabreakloop,VLISPprefixestheConsolepromptwithanumberindicatingthelevelwhereyouarelocated.Forexample,whenyoufirstenterabreakloopinaprogram,thepromptindicatesthiswiththenumber1:
_1_$
Whileyouareinabreakloop,youcannotswitchcontroltotheAutoCADwindow.
Onexitingfromabreakloop(forexample,afterissuingtheQuitcommand),thecurrentread-eval-printloopisterminatedandthepreviouslevelloopisresumed.Ifyouchangethevalueofavariableinthebreakloop,thisvaluewillbeusedwhentheprogramresumesexecution.
ContinuableBreakLoopsNon-ContinuableBreakLoops
Page 147
Pleasesendusyourcommentaboutthispage
Page 148
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UnderstandingBreakLoops>
ContinuableBreakLoops
TherearecontinuableandnoncontinuablebreakloopsinVLISP.Youcanenterthecontinuablebreakloopattheveryfirstbreakinprogramexecutionbyanyofthefollowingmethods:
TurningontheStopOncemodeandreachinganexpressionwithdebugginginformation(thatis,anexpressionthatisloadedfromsourcecode,asopposedtofromacompiled.exefile)
ReachingafunctionmarkedforDebugonEntry
Reachingabreakpointyousetintheprogram
EnteringabreakloopbypressingthePausebutton
ProceedingwithaStepOver,StepInto,orStepOutcommandfromthepreviousbreakloopstate
Whentheprogramisinterrupted,youenterthebreakloop.ThisisapparentiftheVLISPConsolewindowisactive,becausethepromptischangedtoreflectthecurrentlevelofthebreakloop.Inthissuspendedstate,youhaveread-writeaccesstoallvariablesintheenvironmentinwhichthebreakoccurred.Forexample,ifthebreakoccurredwithinafunctioncontainingseverallocalvariabledeclarations,thosevariablesareaccessibleandyoucanchangetheirvaluesbyissuingsetqassignmentsattheConsoleprompt.
Whenstoppedatabreakpoint,youcancontrolsubsequentprogramexecutionbychoosingoneofthefollowingitemsfromtheDebugmenu,orbypressingtheequivalenttoolbarbutton:
ResettoTopLevelterminatesallcurrentlyactivebreakloopsandreturnstotheConsoletop-level(thetopread-eval-printloop).
Page 149
QuitCurrentLevelterminatesthecurrentbreakloopandreturnstoabreaklooponelevelup.Thismaybeanotherbreaklooporthetop-levelread-eval-printloop.
Continueresumesnormalprogramexecutionfromthebreakpoint.
TheStepcommandsevaluateportionsofprogramcodebeforeresumingsuspendedmode:
StepOverlooksforthecloseparenthesismatchingtheopenparenthesiswheretheprogramiscurrentlypaused,andevaluatestheexpressionsinbetween.
StepIntojumpsintoanestedexpression,ifany.Iftherearenonestedexpressions,itjumpstothenextexpressioninsequence.
StepOutsearchesfortheendofthefunctionwheretheprogramiscurrentlypaused,andevaluatesalltheexpressionsuptothatpoint.
AfteryouexitthebreaklooptotheConsoletop-level,theConsolepromptreturnstoitsoriginalform(withoutanumberprefix).
Pleasesendusyourcommentaboutthispage
Page 150
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UnderstandingBreakLoops>
Non-ContinuableBreakLoops
Anon-continuablebreakloopisactivatedwhenanerrorcausesprograminterruptionandtheBreakonErroroptionisset.Inanon-continuablebreakloop,youcanaccessallvariablesintheerrorenvironment,butyoucannotcontinueprogramexecutionorexecuteanyoftheStepcommands.Todistinguishbetweencontinuableandnon-continuablebreakloops,checktoseeiftheStepandContinuetoolbarbuttonsareactive.
Toleaveanon-continuablebreakloopstep,useeithertheResettoTop-LevelcommandtojumptotheConsoletop-levelloop,orQuitCurrentLeveltoreturntothepreviousbreaklooplevel.
Note IfyouactivateAutoCADwhileinthemidstofanon-continuablebreakloop,youwillnotbeabletoenteranythinginthecommandwindow;infact,thewindowwillnotcontainaCommandprompt.However,ifyouaccidentallytrytypinganythingintheAutoCADcommandwindow,yourkeyboardinputwillbequeueduntilAutoCADregainscontrol(thatis,afteryouexitthebreakloopandactivatetheAutoCADwindow).Atthatpoint,anythingyoutypedisevaluatedbyAutoCADasifyouhadjustentereditattheCommandprompt.
Pleasesendusyourcommentaboutthispage
Page 151
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>
UsingBreakpoints
Breakpointsallowyoutomarkapositioninaprogramatwhichprogramexecutionshouldbeinterrupted.Youcansetbreakstooccurbeforeorafterparentheticalexpressions.BreakpointscanonlybesetfromaVLISPtexteditorwindow.
Tosetabreakpoint
1. Movethecursortothepositionatwhichyouwanttohaltexecution.Forexample,tohaltexecutionjustbeforetheopenparenthesisofanexpression,placethecursorjusttotheleftofthatopenparenthesis.
2. ChoosetheToggleBreakpointtoolbarbuttonorpressF9tosetthebreakpoint.(Forvariety,youcansetabreakpointbychoosingDebugToggleBreakpointfromtheVLISPmenu,orbyright-clickingthemouseandselectingToggleBreakpointfromtheresultingshortcutmenu.)
Ifyoumovethecursortoanambiguousposition,suchasinthemiddleofanexpression,VLISPwillmovethecursortothenearestparenthesisanddisplaythefollowingmessageaskingwhetheryouagreewiththebreakpointplacement:
3. ClickYestoacceptthebreakpointlocation,orNoifthatisnotwhere
Page 152
youwanttosetthebreak.Toremoveabreakpoint
1. Positionyourcursoratthebreakpointyouwanttoremove.
2. ChoosetheToggleBreakpointtoolbarbutton,orpressF9.TheToggleBreakpointworksasanon/offswitch.Whennobreakpointexists,ToggleBreakpointaddsabreak;ifabreakpointalreadyexistsatthecursorposition,ToggleBreakpointremovesit.YoucanalsousetheBreakpointServicedialogtoremovebreakpoints;seeListingandViewingtheBreakpointsinYourProgramforinformationonthisprocedure.
3. Toremoveallthebreakpointsyouhaveset,chooseDebug ClearAllBreakpointsfromtheVLISPmenu.ChangingBreakpointHighlightColorsDisablingBreakpointsTemporarilyListingandViewingtheBreakpointsinYourProgramLifeCycleofaBreakpoint
Pleasesendusyourcommentaboutthispage
Page 153
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UsingBreakpoints>
ChangingBreakpointHighlightColors
VLISPmarkseachbreakpointpositionwithacoloredrectangle,soyoucaneasilylocatethebreakpointsinyourprogram.Bydefault,activebreakpointsaremarkedinred.Youcanchangethiscolorbysettingthe:BPT-ACTIVEoptioninTools WindowAttributes ConfigureCurrent.SeeConfigureCurrentformoreinformationonchangingcolorsinVLISPwindows.
Pleasesendusyourcommentaboutthispage
Page 154
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UsingBreakpoints>
DisablingBreakpointsTemporarily
Whenusingmultiplebreakpointswithinasourcefile,itmaybeusefultodisableoneormorebreakpointstemporarily,butleavethebreakpointpositiondefinedforpossiblelateruse.Thissavestimeoverdeletingandrestoringthebreakpoint.
Todisableabreakpoint
1. Placethecursoratthebreakpointmarkerandpresstherightmousebutton.
2. Fromtheresultingmenu,chooseBreakpointService.VLISPdisplaysthefollowingdialogbox:
3. ClicktheDisablebuttonintheBreakpointServicedialogboxtodisablethebreakpointtemporarily.
VLISPchangesthecolorofthebreakpointmarkerwhenitdisablesthebreakpoint.Bydefault,itmarksdisabledbreakpointsinblue.Youcanchangethiscolorbyresettingthe:BPT-DISABLEoption.
Pleasesendusyourcommentaboutthispage
Page 155
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UsingBreakpoints>
ListingandViewingtheBreakpointsinYourProgram
FromtheViewmenu,chooseBreakpointsWindowtoseealistofallbreakpointscurrentlydefinedtoVLISP:
TheBreakpointsdialogboxliststhebreakpointsinallprogramsyouareeditinginVLISP,notjusttheprogramintheactiveeditorwindow.Intheexampleabove,onlyoneprogram(yinyang)containsbreakpoints.Butyoucouldhavebreakpointssetinanynumberoffiles.
EachentryintheBreakpointsdialogboxshowsthenameofthesourcefilecontainingthebreakpoint,andthelocationofthebreakpointinthesource.Aleading+or-signdifferentiatesbetweenactiveanddisabledbreakpoints.Thedialogboxallowsyoutodeleteallbreakpointsatonceortoedit(ordisplay)onebreakpointatatime.ChooseShowtodisplaythesourcepositionofthebreakpoint.TheEditbuttonopenstheBreakpointServicedialogbox,fromwhichyoucandisablethebreakpoint.
Pleasesendusyourcommentaboutthispage
Page 157
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingtheVisualLISPDebuggingFeatures>UsingBreakpoints>
LifeCycleofaBreakpoint
Youcansetbreakpointsinaprogrameitherbeforeorafteryouloadtheprogram.However,ifyouchangethetextinaprogramafterloadingtheprogram,andthenaddabreakpoint,thebreakpointonlytakeseffectafteryoureloadthecode.
BreakpointsremainineffectduringtheVLISPeditingsessionandwillsurvivebetweensessionsifyouchooseSaveSettingsfromtheToolsmenu.
Inadditiontoremovingbreakpointsusingthemethodspreviouslydescribedinthischapter,programbreakpointsareautomaticallylostwhenyoudoanyofthefollowing:
Deletethecodefragmentcontainingthebreakpoint
ModifythefileoutsidetheVLISPeditor(forexample,editandsaveitwithNotepad)
ApplyVLISPformattingcommandstocodefragmentscontainingbreakpoints
Notealsothatifyoumodifyaprogram'scodeandrunitwithoutreloadingit(withtheLoadActiveEditWindowcommand),theprogramwillbeinterruptedwhenabreakpointisreached,buttheexactsourcepositionwillnotbeshown.Thefollowingdialogboxindicatesthissituationhasoccurred:
Toenabletheproperdisplayofasourceposition,youmustreloadthecodeandrestarttheprogram.
Page 158
Pleasesendusyourcommentaboutthispage
Page 159
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>
UsingVisualLISPDataInspectionTools
VLISPgivesyoualmostunlimitedaccesstosymbols,values,andfunctionsatanystageofprogramexecution.TheVLISPdatainspectiontoolsareimplementedasmodelesswindows(exceptfortheSymbolServicedialogbox),meaningtheystayonthescreenaslongasyouneedthem,nomatterwhatyourprogramdoes.
TheWatchwindowdisplaysthecurrentvalueofanysetofvariables.
TheTraceStackwindowdisplaysthemostcurrentcallhierarchy.Atanylevelofthestackyoucanviewthecorrespondingcode,thecallingcode,thelocalvariables,andmore.
TheSymbolServicedialogboxdisplaysthecurrentvalueofasymbolaswellasitscurrentflags.Youcanmodifyboththevalueandtheflagsfromhere.
InspectwindowsdisplayanyLISPobject(fromastringtoanAutoCADblockdefinition)toanylevelofdetailneeded.
FrameBindingwindowsdisplaythevaluesofalllocalvariablesfortheirparticularstackframe(thatis,thespecificfunctioninvocationinthecallsequence).
VLISPprovidesaloggingfeaturethat,whenactive,allowsyoutocopythecontentsofaDataInspectionwindowtoalogfile.
Toturntraceloggingonandoff
1. ActivatetheTracewindow.
2. SpecifyalogfilebychoosingFile ToggleTraceLogfromtheVLISPmenu.NotethatiftheTracewindowisnotactive,theToggleTraceLog
Page 160
optionwillnotbeavailable.
3. ChooseSavetoselectthefileyouspecified.Ifthefilealreadyexists,VLISPpromptsyouwiththefollowingmessage:
IfyoureplyYes,VLISPappendsnewdatatothecurrentcontentsofthefile.IfyoureplyNo,VLISPoverwritesthefileanditsoriginalcontentswillbelost.ChooseCanceltoterminatetheoperationandspecifyadifferentfilename.
4. Toclosethelogfileandquittheloggingprocess,chooseToggleTraceLogfromtheFilemenuagain.
WhenTraceloggingisturnedon,anyinformationdisplayedintheTracewindowisalsowrittentothelogfile.MostVLISPdatainspectiontoolsprovideatoolbarbuttonforcopyingdatatotheTracewindow.
ThestateofTraceloggingisindicatedintheTracewindow'stitlebar.Ifloggingisineffect,VLISPdisplaysthenameofthelogfileinthetitlebar.Ifloggingisoff,nofilenameappearsinthetitlebar.
IfyoudonotclosethelogfilebeforeexitingVLISP,itclosesthefileautomaticallyuponexit.Afteralogfileisclosed,youcanviewitscontentswithanytexteditor,suchastheVLISPtexteditor.
UsingtheWatchWindowUnderstandingtheTraceStackWindowUsingtheSymbolServiceDialogBoxUsingInspectWindowsViewingAutoCADDrawingEntities
Pleasesendusyourcommentaboutthispage
Page 161
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>
UsingtheWatchWindow
TheWatchwindowmonitorsthevaluesofAutoLISPvariablesduringprogramexecution.EachWatchwindowelementlinedisplaysthenameofavariableanditscurrentvalue,asillustratedinthefollowingfigure:
TheWatchwindowisupdatedateachstepofaVLISPinteractivesessionandalwaysshowsthecurrentenvironmentstate.Indebuggermode,theWatchwindowisrefreshedautomaticallyattheendofeveryexpressionevaluation.
ToaddvariablestotheWatchwindow
1. HighlightthevariablenameinanyVLISPcontext(thatis,inatexteditorwindow,theConsolewindow,etc.).
2. ChoosetheAddWatchbutton,orchooseAddWatchfromtheDebugmenu.YoucanalsoselectAddWatchfromashortcutmenubyright-clickingthemousewhilethecursorisonavariablename.
3. IftheWatchwindowisalreadyactive,youcanaddvariablestothewatchlistbyclickingtheAddWatchbuttononthetoolbarintheWatchwindow.IfVLISPcannotdeterminewhichvariableyouareinterestedinbasedon
Page 162
thecursorpositionorthetextyou'veselected,itdisplaystheAddWatchwindow:
Specifythenameofthevariabletobewatchedinthiswindow,thenclickOK.
TheWatchwindowretainsitsvariablesduringaVLISPsession.ThismeansthatifyouinvokeWatch,addvariablestotheWatchwindow,andthenclosetheWatchwindow,thevariablesyouaddedwillappearintheWatchwindow,ifyouinvokeWatchagainduringthecurrentsession.
TheintroductorysectionofthischapterincludesanexampleofusingtheWatchwindow.(SeeMonitoringtheEvaluationResultsofanExpression.)
UsingtheWatchToolbarUsingtheWatchItemShortcutMenu
Pleasesendusyourcommentaboutthispage
Page 163
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingtheWatchWindow>
UsingtheWatchToolbar
ThetoolbarontheWatchwindowcontainsthefollowingbuttons:
AddWatch
InvokestheAddWatchcommandtoaddanewvariabletotheWatchwindow.ThisvariablecanbeselectedfromanyactivetextwindowortypedintheAddWatchdialogbox.
ClearWindow
RemovesallvariablesfromtheWatchwindow.
SortExpressions
SortsthevariablesintheWatchwindowalphabeticallybyname.
CopytoTrace/Log
CopiesthecontentsoftheWatchwindowtotheTracewindow.Ifloggingisactive,thecontentsoftheWatchwindowarealsocopiedtothetracelog.
Pleasesendusyourcommentaboutthispage
Page 164
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingtheWatchWindow>
UsingtheWatchItemShortcutMenu
TodisplaytheWatchItemshortcutmenu,selectaniteminthewatchlistandright-click.
ThefollowingitemsappearontheWatchItemmenu:
InspectValue
InvokestheInspectfeaturefortheselectedvalue.(SeeUsingInspectWindows.)
CopyValue
CopiesthevalueoftheselectedvariableintotheIDEglobalvariable*obj*.
PrintValue
PrintstheselectedvariablevalueintheConsolewindow,prefixedwithasinglequote(').
Symbol
CallstheSymbolServicedialogboxfortheselectedvariable.(SeeUsingtheSymbolServiceDialogBox.)
Apropos
CallstheAproposdialogboxusingtheselectedsymbol'snameastheAproposargument.
RemovefromWatch
RemovestheselectedvariablefromtheWatchwindow.
Pleasesendusyourcommentaboutthispage
Page 165
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>
UnderstandingtheTraceStackWindow
VLISPhasaspecialdebuggingtoolcalledatracestackwhichisahistoricalrecordoftheexecutionoffunctionswithinyourprogram.(Thetermstackisderivedfromacomputerprogrammingstructureofthesamename.)Thefollowingfigureillustratesaddingandremovingitemsfromastack.YoucanseewhyastackstructureisoftenreferredtoasLIFO—LastIn,FirstOut:
ThetracestackisusedbyVLISPto“rememberitswayout”ofanestedseriesofexpressions.Byviewingthestack,youcanseewhatishappeningwithinyour
Page 166
programasitisexecuting(withinasuspendedbreakmode)orimmediatelyafterithascrashed.
BeforeyouinvokeafunctionattheConsolewindoworfromAutoCAD,thetracestackisempty.Theactionofinvokingafunctioncausesarecord,orelement,tobeplacedonthestack.Asthatfunctioncallsadditionalnestedfunctionstoperformtheworkofyourprogram,additionalelementsmaybeaddedtothestack.VLISPonlyneedstoplaceelementsonthestackwhenitneedstorememberitswayoutofnestedfunctions.
Therearetwoconditionswhereitisusefultoexaminetracestacks.Thefirstiswhenyourprogramisinasuspendedstate,suchasduringabreakpointpause.Thesecondisafteranerroroccurs,causingyourprogramtofail.
StackElementListsViewingtheCurrentTraceStackDisplayingInformationonaTraceStackElementUsingtheFrameBindingWindowUnderstandingKeywordFramesUnderstandingSpecialFunctionCallFramesViewinganErrorTraceStack
Pleasesendusyourcommentaboutthispage
Page 167
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
StackElementLists
Astackelementisanindividualrecordorline-itemhistorywithinatracestack.Therearefivekindsofelementsthatmayappearwithinastack:
Functioncallframesshowoneindividualfunctioninvocation.Eachfunctioncallframeappearsinthefollowingformat:level(function-name{argument1}...)Argumentswithinthislistingaredisplayednotbytheirlocalparametername,butbythevaluesthatwereactuallypassedtothefunction.
Keywordframesaredisplayedattheverytopandbottomofatracestack.Theyaredisplayedinthefollowingform:level:keyword-{optional-data}Thekeywordindicatesthetypeoftheframe.Theoptional-datadisplaysadditionalinformationrelatingtothestateoftheprogram.
Topformsindicateanactionthatwasinitiatedbytypinganexpressionatthetop-levelConsolewindow,orfromtheinvocationofafunctionthatwastriggeredduringtheloadingofafileorselectionwithinaVLISPeditorwindow.
Lambdaformsareplacedwithinastackwheneveralambdafunctionisencounteredwithinyourprogram.
Specialformsdisplaytheinvocationoftheforeachandrepeatfunctions.Theargumentsforthesefunctionsarenotdisplayed.Theyappearas:level(function-form...)
Functioncallframesandkeywordframesarediscussedinmoredetailinthe
Page 168
followingsections.Thesesectionsusethefollowingcodetodemonstratethetracestack.Ifyouwish,youcancopythiscodeintoaVLISPeditorwindow,setabreakpointasindicatedinthecodecomments,andrunthissample:
(defunstack-tracing(indexValmaxVal)
(princ"Atthetopofthestack-tracingfunction,indexVal=")
(princindexVal)
(if(<indexValmaxVal)
(stack-tracing(1+indexVal)maxVal)
(princ"Reachedthemaximumdepth.");placeabreakpoint
;atthebeginningof
;thisline
)
)
(defunc:trace-10-deep()
(terpri)
(stack-tracing110)
)
Pleasesendusyourcommentaboutthispage
Page 169
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
ViewingtheCurrentTraceStack
Toseethestateofafunctioncallstackwhileyourprogramissuspendedatabreakpoint,chooseView TraceStackfromtheVLISPmenu,orclicktheTracetoolbarbutton.VLISPdisplaystheTraceStackwindow:
TheTraceStackwindowdisplayedaboveshowsafunctioncallframeforthestack-tracingfunction.Thesecondelement,orframe,inthetracestackishighlighted:
[2](STACK-TRACING1010)
Thenumber[2]simplyidentifiesitasthesecondelementinthestack.Thenumbersfollowingthestack-tracingfunctionname(1010)indicatethe
Page 170
actualvaluesthatwerepassedtothefunction.
Pleasesendusyourcommentaboutthispage
Page 171
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
DisplayingInformationonaTraceStackElement
Toobtainmoreinformationaboutanelementinthetracestack,selecttheelementandright-clicktodisplayashortcutmenu.
Activeitemsavailableontheshortcutmenudependonthetypeofstackelementyouselectedbeforeright-clicking.Possiblemenucommandsincludethefollowing:
Inspect
CallstheInspectfeaturefortheselectedstackelement.
Print
PrintsthestackelementtotheConsolewindow.
FunctionSymbol
CallstheSymbolServicefeatureforthefunctioncallinthestackframe,ifthefunctioniscalledbythesymbol.
Copy
CopiestheselectedtracestackelementtotheIDEglobalvariable*obj*.
LocalVariables
DisplaystheFrameBindingsdialogboxtoallowbrowsingoflocalvariablevaluesatthetimethefunctionwascalled;seeUsingtheFrameBindingWindow.
SourcePosition
Checkswhetherornotthesourcetextisavailableforthefunctioncalledattheselectedstackframe.Ifthesourcecodeisavailable,thetextwindowwith
Page 172
thesourcecodeisdisplayed,withthecurrentpositioninsidethefunctionhighlighted.
CallPointSource
Showsthepositionofthecallerexpression,similartoSourcePosition.
Pleasesendusyourcommentaboutthispage
Page 173
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
UsingtheFrameBindingWindow
ChoosethelocalvariablesitemfromtheTraceStackshortcutmenutodisplaytheFrameBindingwindow:
TheFrameBindingwindowdisplaysinformationaboutthelocalvariablesintheframe.Intheexampleshownabove,theparameternames(INDEXVAL,MAXVAL)arelisted,alongwiththevaluesassignedtotheseparameters.Thesevalueswerepassedtothefunction.Theparametersarelistedintheordertheyaredefinedwithinthefunction.
Ifyouright-clickonanentryintheFrameBindingwindow,VLISPdisplaysashortcutmenucontainingthefollowingitems:
Inspect
CallstheInspectfeaturefortheselectedvalue.
Print
DisplaystheselectedvalueintheConsolewindow.
Symbol
CallstheSymbolServicedialogboxfortheselectedsymbol.
Copy
CopiestheselectedvalueintotheIDEglobalvariable*obj*.
Page 174
AddtoWatch
AddstheselectedsymboltoaWatchwindow.
Pleasesendusyourcommentaboutthispage
Page 175
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
UnderstandingKeywordFrames
AkeywordframeindicatesaspecifictypeofoperationthatoccurswithintheVLISPenvironment.Thekeywordindicatesthetypeofoperation.Keywordframeswillappearinonlytwolocations:attheverytopofthestack,orattheverybottomofthestack.
Thefollowingtypesofkeywordframeswillappearonlyatthebottomofastack:
Keywordframes(bottom)
Frametype Operationthatoccurred
:ACAD-REQUEST Acalltothefunctionshownintheframeimmediatelyabovethe:ACAD-REQUESTkeywordframewasinvokedfromtheAutoCADcommandprompt.
:DCL-ACTION ExecutionofaDCLtileordialogactionwasrequestedfromAutoCAD.Thekeyword:DCL-ACTIONisfollowedbytwostrings:theDCLdialognameandthevalueofthe$KEYvariableintheDCLactionbody.Ifanumberappears,itisthevalueofthe$REASONvariableintheDCLactionbody.Theframe
Page 176
immediatelyabovethekeyworddescribesthefunctioncallbuiltfromtheactionstring.
:INSPECT-EVAL EvaluationofanInspectcommand.
:INSPECT-VERBOSE EntranceintoadrawingInspecthookfunction.
:TOP-COMMAND TheVLISPIDErequestedtheactionresultinginthefirstelementplacedwithinthestack.Thissituationoccurs,forexample,whenafunctionisinvokeddirectlyfromloadingaselectionorafile.
:USER-INPUT ThecharacterstringshownintheframewasenteredfromtheVLISPConsolewindow.Theframeimmediatelyabovethekeyworddescribestheexpressionasitwastranslatedfromtheuserinput.Iftheinputstringistoolong,right-clicktoopenashortcutmenu,andchooseShowMessagetoviewtheentiretext.YoucanalsochoosetheInspectcommandtoinspecttheenteredstring.
:WATCH-EVAL Evaluationofawatchexpression.
Thefollowingtypesofkeywordframesmayappearatthetopofastack:
Page 177
Keywordframes(top)
Frametype Operationthatoccurred
:ACMD-CALLBACK RegisteredAutoCADcommandcall.
:AFTER-EXP Indicatesthatyourprogramisinterruptedinadebuggingbreakmode,andtheStepIntoorStepOvercommandjuststeppedoutofanexpression.
:ARQ-SUBR-CALLBACK IndicatesanormalcallfromAutoCADtoaVLISP-definedfunction.
:AXVLO-IO-CALLBACK:DWF:DWG
SavesorrestoresaVLobjectinaDWG.
:BEFORE-EXP Debuggerbreakuponenteringthefunction.ThismessagewillappearwheneveryouaresteppingthroughusingStepIntoorStepOver,andthestepisenteringanexpression(asopposedtojustleavinganexpression,whichisindicatedbythe:AFTER-EXPkeyword).
:BREAK-POINT User-specifiedbreakpoint.
:ENTRY-NAMESPACE Acallinthecontextofaseparate-namespaceVLX.
:ERROR-BREAK Generalruntimeerror.TheShow
Page 178
Messageshortcutmenuselectionallowsyoutoviewmorespecificerrormessages.
:FUNCTION-ENTRY Debuggerbreakuponenteringthefunction.Thestackelementfollowingthismessagecontainsthecallframeforthefunctioninwhichthebreakoccurred.
:KBD-BREAK ThePAUSEkeywaspressed,placingtheprogramonhold.
:PROTECT-ASSIGN Assignmentofavaluetoaprotectedsymbol.Fromtheright-clickshortcutmenu,youcanchooseShowMessagetoviewthevariablename,thecurrentvalue,andthenewvaluethatwasattemptedtobeassignedtothevariable.YoucanalsochoosetheInspectcommandtoviewthelistcontainingthesymbol,andthenewvalueindicatedfollowing:PROTECT-ASSIGN.
:REACTOR-CALLBACK Reactorcall.
:READ-ERROR Errorduringareadoperation.TheShowMessageshortcutmenuselectionprovidesadditionalinformationabouttheerror.
:SYNTAX-ERROR VLISPencounteredincorrectAutoLISPprogramsyntax.
Page 179
Pleasesendusyourcommentaboutthispage
Page 180
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
UnderstandingSpecialFunctionCallFrames
Therearetwospecialfunctioncallframes.
TheFOREACHframeindicatesacalltotheforeachfunction.Fromtheshortcutmenu,choosetheLocalVariablesoptiontodisplaythenameandcurrentvalueoftheuser-suppliedvariableandlistvariablesboundbytheforeachfunction.Forexample,ifthefollowingexpressionwereevaluated
(foreachn'(abc)(printn))
thenselectingtheLocalVariablesoptiondisplaysaFrameBindingwindowlikethefollowing:
ThisFrameBindingwindowidentifiestheuser-suppliedvariable(N),thecurrentvalueofthatvariable(A),andtheitemsremainingtobeprocessedinthelistsuppliedtoforeach(BC).
TheREPEATframeindicatesacalltotherepeatfunction.Fromtheshortcutmenu,theLocalVariablescommanddisplaysthespecialnamecounterandthecurrentvalueoftherepeatinternalcounter.Theinternalcountervalueisinitiallysettotheintegervaluepassedtorepeat,indicatingthenumberofiterationsdesired.Thecounterdecreasesbyoneateachloopiteration.Itshowsthenumberofiterationsremaining,minusone.
Notethateachrepeatexpressionpossessesitsowncounter,butonlyonesuch
Page 181
countercanbeaddedtotheWatchwindow.
AutoLISPfunctionssuchasif,cond,and,andsetqdonotappearonthestack.TheyarenotnecessarybecausetheircallpositionmaybeviewedwithinthesourcefileintheVLISPtexteditorwindow.
Pleasesendusyourcommentaboutthispage
Page 182
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UnderstandingtheTraceStackWindow>
ViewinganErrorTraceStack
Ifyourprogramterminatesduetoanerror,chooseErrorTracefromtheViewmenutoseethestateoffunctioninvocationsuptothetimeyourprogramcrashed:
Theerrortraceisacopyofthetracestackasitappearedatthetimetheerroroccurred.IftheBreakonErrordebuggingoptionisselected,theerrortraceandthetracestackareidenticalimmediatelyafteranerroroccurs.YoucanseethisbyselectingBreakonErrorfromtheDebugmenu,intentionallycausinganerror(forexample,issuingafunctioncallthatdividesbyzero),andopeningthetwotracewindows.
ThetoolbarontheTraceStackwindowcontainstwobuttons:
Refresh
RefreshescontentsofTraceStackwindow.
CopytoTrace/Log
CopiesthewindowcontentstotheTraceStackwindoworopenlogfile.
Page 183
WhenyouissueaResetcommandtoexitabreakloop(forexample,ResettoTopLevel),pressingtheRefreshbuttonintheTraceStackwindowreplacesthatwindow'scontentswiththelatesttracestackdata.Incontrast,refreshingtheErrorTracewindowdoesnotchangethewindow'scontents,unlessasubsequenterrorhasoccurred.
Pleasesendusyourcommentaboutthispage
Page 184
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>
UsingtheSymbolServiceDialogBox
TheSymbolServicefeatureisdesignedtosimplifyaccesstothedifferentdebuggerfeaturesprovidedforsymbols.Mostfacilitiesavailableforsymbolsarealsoavailablethroughthisfeature.
ToopenaSymbolServicedialogboxandupdateasymbol
1. Highlightthenameofanysymbolinyourprogram'ssourcecodeorintheConsolewindow.
2. ChooseView SymbolServicefromtheVLISPmenu,orpresstheSymbolServicebuttonontheDebugtoolbar.
TheSymbolServicedialogboxcontainsthefollowingcomponents:
Atoolbar
Page 185
ANamefield,whereyoucanenterorchangethesymboltoworkon
AValuefieldthatdisplaysthesymbol'svalueoritsinitialsubstring
Aseriesofcheckboxesforsymbolflags
3. Toupdatethevalueofthedisplayedsymbol,enteranexpressionintheValuefield.WhenyoupressOK,VLISPevaluatestheexpressionandassignsitsvaluetothesymbol.
Ifthesymbolyouspecifiedisaprotectedsymbol,theValuefieldwillberead-only.Toremoveprotection,cleartheProtectAssigncheckbox.SeeUnderstandingSymbolFlagsformoreinformationonProtectAssign.
UsetheOKandCancelbuttonstoclosethedialogboxandtocontinueworkinginVLISP.
UsingtheSymbolServiceToolbarUnderstandingSymbolFlags
Pleasesendusyourcommentaboutthispage
Page 186
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingtheSymbolServiceDialogBox>
UsingtheSymbolServiceToolbar
TheSymbolServicetoolbarcontainsthefollowingbuttons:
Watch
AddsthesymboltotheWatchwindow.
Inspect
OpenstheInspectwindowtoshowthevalueofthesymbol.
ShowDefinition
Ifthesymbolnamesauser-definedfunction,thiscommandopensthetexteditorwindowcontainingthefunctiondefinitionandhighlightsthefunction.
Help
DisplaysinformationfromtheVLISPHelpfile,ifthesymbolreferstoabuilt-infunction.
Pleasesendusyourcommentaboutthispage
Page 187
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingtheSymbolServiceDialogBox>
UnderstandingSymbolFlags
TheSymbolServicedialogboxprovidesdirectaccesstosymbolflagsandpropertiesoffunctionalobjectsthatmaybeassociatedwiththem.Thefollowingsymbolflagoptionsareavailable:
Trace(Tr)
TheTraceflagactivatesthetracingofanyuser-definedfunction(shownasasymbolwithintheSymbolServicewindow).Tracingwillonlyoccurwhenthesymbolisafunction,andtheexpressionbeingevaluatedusesthesymbolnameasafunction(notasalocalvariablename,forexample).
ProtectAssign(Pa)
Thisflaginterceptsattemptstoassignvaluestoprotectedsymbols.Forinstance,thesymbolpiisaprotectedsymbol.Allsymbolsthatarethenamesofbuilt-inAutoLISPfunctionsareassignment-protectedbydefault.SeeProtectedSymbolsformoreinformationonsymbolprotection.Notethatsymbolprotectionworksonlyforexplicitsetq,set,ordefuninvocations.Bindingaprotectedsymbolinanargumentlistofauser-definedfunctionisnotintercepted.
DebugonEntry(De)
Ifthisflagisset,abreakpointoccursateachfunctioninvocation,regardlessofwhetherthefunctionwasloadedwithdebugginginformation.TheDeflagistestedateachfunctioninvocation,notduringloadordefunexecution.NotethatVLISPignorestheDebug-on-EntryflagforallSUBRandEXRXSUBRsymbols.
ExporttoACAD(Ea)
Page 188
IftheEaflagisset,thefunctionassociatedwiththissymbolisdefinedasanexternalsubroutine.ThismakesthefunctionavailabletoObjectARXapplications.
Pleasesendusyourcommentaboutthispage
Page 189
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>
UsingInspectWindows
TheInspectfeatureisthecomponentofVLISPthatprovidesyouwiththeabilitytobrowse,examine,andmodifyAutoLISPandAutoCADobjects.YoucanuseInspecttoviewthefollowingitems:
AnyAutoLISPobjectssuchaslists,numbers,strings,andvariables
AutoCADdrawingentities
AutoCADselectionsets
UsingInspect,youcanalsobrowsethroughcomplexdatastructures.
TheInspecttoolcreatesaseparatewindowforeachobjectyouinspect.
ToopenanInspectwindow
1. SelectanAutoLISPobjectname(forexample,avariable).
2. ChooseView InspectfromtheVLISPmenu,orpresstheInspectbuttonontheDebugtoolbar.TheInspectcommandisalsoavailablefromanumberofshortcutmenusandfromthewindowsdisplayedbytheAproposandSymbolServicefeatures.
3. IfyouinvoketheInspectcommandwithoutselectinganobjectname,VLISPpromptsyoutospecifytheobjectyouwanttoinspect,displayingthefollowingdialogbox:
Page 190
Entertheobjectorexpressionyouwanttoinspect,thenpressOKtoopentheInspectwindoworpressCanceltocanceltheaction.
VLISPsavesthelast15itemsyouenterintheInspectpromptbox.Youcanchooseapreviouslyspecifiedobjectforinspectionbyselectingitfromthedrop-downlist.
Forexample,toinspectthedefinitionoftheyinyangfunction,selectthenameinthetexteditorwindowcontainingtheyinyang.lsp,thenpresstheInspectbuttontoviewtheInspectwindow:
UsingtheInspectWindowUnderstandingObjectElementListFormatsCommonInspectCommandsCopyingInspectObjectstothe*obj*IDEGlobalVariableHandlingErrorsintheInspectCommandClosingAllInspectWindows
Pleasesendusyourcommentaboutthispage
Page 191
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
UsingtheInspectWindow
AllInspectwindowshaveasimilarappearanceandcontainacaption,anobjectline,andanobjectelementlist(whichmaybeempty).Thewindowelementscontainthefollowingcontent:
ThecaptionofanInspectdialogboxshowsthetypeofobjectbeinginspected.
Theobjectlineshowsaprintedrepresentationoftheinspectedobject.
Theelementlistdisplaysthecomponentsoftheinspectedobject.
Theelementlistmayvaryinsizeandcontentfordifferentobjecttype.Eachelementlistisshownasapair:nameandcontent.Thenameisenclosedinbrackets.Squarebrackets([])denotethatyoucanmodifytheitembyissuingaModifycommandfromtheshortcutmenuassociatedwiththeitem,andcurlybrackets({})indicatethatyoucannotmodifytheitem.
Boththeobjectlineandtheelementlistlineshavetheirownassociatedshortcutmenus.ThesemenusaredescribedinCommonInspectCommands.
VLISPwilldisplayupto50elementlinesinanInspectwindow.Iftherearemorethan50elementstobeshown,Inspectdisplaystheelementsinaseriesofpages.WhenyouscrolltothebottomoftheInspectwindowandtherearemoreentriesremainingtobedisplayed,thebottomofthelistcontainsa">>>[Nextpage]"elementline.Tonavigateamongthepages,usethefollowingprocedures:
Topagedown,double-clickonthe">>>[Nextpage]"elementline,orselectthatlineandpressALT+E.
ForInspectwindowsshowingAutoLISPlistsandselectionsets,youcanpageupbydouble-clickingthe"<<<[Previouspage]"element
Page 192
line,whichappearsatthetopofthelist.(OrselectthatlineandpressALT+E.)
ForAutoLISPlistsandselectionsets,whenyoureachthelastpageofelementlines,youcanreturntothefirstpagebydouble-clickingonthe"<<<[Firstpage]"elementline,orbyselectingthatlineandpressingALT+E.
VLISPexpandsanitemintheelementlistifyoudouble-clickonit.Forexample,the{Auxiliary}componentinthesampleInspectwindowisitselfalist.Double-clickonthe{Auxiliary}itemtoopenanotherInspectwindowshowingtheelementsinthelist:
Pleasesendusyourcommentaboutthispage
Page 193
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
UnderstandingObjectElementListFormats
ThecontentsofanInspectelementlistvary,dependingonthedatatypeoftheobjectbeinginspected.Thefollowingtableidentifiesthelistcontentsforeachdatatype.
Inspectelementlists
Datatype Contentsofelementlist
INT(integer) Thevariousrepresentationsofintegers.
REAL(floatingpointnumber) Empty.
STRING Thesequenceofcharactersinthestring,whichmayinturnbeinspectedasintegers.
SYMBOL Threeelements:value,printname,andflags.
LIST(forproperlists) Itemsoftheinspectedlist.
LIST(forimproperlists) Twoelements:thecarandcdrfields.ItservesforallcasesthatarenotproperLISPlists,thatis,wherethelastcdrisnotnil.
Page 194
FILE Thenameofthecorrespondingfileandthefile'sopeningattributes.
SUBR,EXRXSUBR,andUSUBR Thenameofthefunction(thenamethatwasspecifiedindefunoratloadtime).SUBRreferstointernalandcompiledfunctions,EXRXSUBRreferstoexternalARXfunctions,andUSUBRidentifiesuser-definedfunctions.
ENAME(drawingentity) ThefieldsinthiselementlistcorrespondtotheAutoCADDXFobjectlist,asreturnedbytheAutoLISPbuilt-infunction.
PICKSET(selectionset) ListofselectedAutoCADobjects.
VARIANT Thedatatypeandvalueofthevariant.
SAFEARRAY Thedatatype,numberofdimensions,andvalueofthesafearray.
SampleInspectwindowsforeachdatatypefollow.
INT
TheINT(integer)Inspectwindowshowsthenumberrepresentedinbinary,octal,decimal,hexadecimal,andcharacterformats.CharacterformatmeanstheASCIIcharacterthatcorrespondstothenumber(forlargenumbersittakesthelastbyte).
Page 195
TheINTInspectwindowdoesnothaveanelementlist.
REAL
TheREALInspectwindowdoesnothaveanelementlist.
STRING
Showsthestringasalistofcharactersrepresentedasnumbers:
Double-clickonalistedcharactertoseeitsnumberrepresentation.
SYMBOL
Containsthesymbolname,thesymbolvalue,andtheflagsthatrepresentsymbolattributes.Flagsmaybeoneofthefollowing:PaProtectAssignTrTraceDeDebugonentryEaExporttoACAD
Page 196
Tochangeasymbol'svalueorflagsettings,usetheobjectlinemenucommandSymbolService,whichshowstheSymbolServicewindow.NotethattheinformationsuppliedbytheSYMBOLInspectwindowisavailablemoreconvenientlythroughtheSymbolServicefeature.
LIST(properlist)
Showstheelementsofaproperlist:
LIST(improperlist)
Showsthecarandcdrofanimproperlist.Forexample,alistconstructedby(cons4'(5.0))isrepresentedasfollows:
FILE
FileInspectfieldsincludethefollowing:Filenameisthenamestringusedintheopenfunction.Modeindicateswhetherthefileisopenforinput,output,append,orwhetherthefileisclosed.IDshowstheinternalfileidentifier.Positionshowsthecurrentpositioninthefile.EOFindicateswhetherornottheendofthefilehasbeenreached.Thisfielddoesnotappearifafileisopenforoutput.
Page 197
SUBR
TheSUBRdatatyperepresentsfunctionsthatcannotbedebuggedwiththeVLISPdebuggingtools(forexample,youcannotsetbreakpoints).TheseareinternalAutoLISPfunctions,orfunctionsloadedfromFASorVLXfiles.TheSUBRInspectwindowshowsastringcontainingthenameofthesymbol,asinthefollowingexample:
USUBR
TheUSUBRdatatyperepresentsfunctionsthatcanbedebuggedwiththeVLISPdebuggingtools(forexample,youcansetbreakpointsandviewthevaluesofprogramvariables).ThesefunctionsareloadedfromLISPsourcecode.TheUSUBRInspectwindowshowsthenameofthesymbol,alistoffunctionparameters(arguments),andalistoflocalvariablesdeclaredinthefunction(listedafterthe“/”inthedefunargumentlist).ThefollowingexampleshowsanInspectwindowforafunctionthatacceptsnoargumentsanddeclaresseverallocalvariables:
EXRXSUBR
TheEXRXSUBRdatatyperepresentsfunctionsloadedfromexternalARXapplications.TheEXRXSUBRInspectwindowshowsastringcontainingthefunctionname,asinthefollowingexample:
ENAME
ThecontentsoftheENAMEInspectwindowdependonthepropertiesofthe
Page 198
entitybeinginspected.ThefollowingexampleshowsanInspectwindowforacircle:
PICKSET
ThePICKSETInspectwindowliststheelementsinaselectionset:
VARIANT
TheVARIANTInspectwindowshowsthedatatypeandvalueofthevariant.ThefollowingexampleshowsanInspectwindowforavariantthatcontainsanarrayofdoubles:
SAFEARRAY
TheSAFEARRAYInspectwindowshowsthedatatype,numberofdimensions,andvalueofthesafearray.ThefollowingexampleshowsaSafearrayInspectwindowforasingledimensionarrayofdoubles:
Page 199
YoucanalsousetheInspectfeaturetoexamineActiveX®objects.SeeUsingtheInspectTooltoViewObjectPropertiesforanexampleofthis.
Pleasesendusyourcommentaboutthispage
Page 200
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
CommonInspectCommands
TheInspectwindowsprovideshortcutmenuscontainingcommandsrelevanttothedatabeinginspected.
Todisplaytheobjectlineshortcutmenu,pressALT+0,orright-clicktheobjectline.Thefollowingcommandsmaybepresentinanobjectlineshortcutmenu:
SymbolService
InvokestheSymbolServicefeature.
Print(ALT+P)
PrintstheobjectintheConsolewindow.
PrettyPrint
FormatsandprintstheobjectintheConsolewindow.
Copy
Copiestheobjecttothe*obj*variable.
Log
CopiesthecurrentcontentsoftheInspectdialogboxtotheTracewindow.Ifloggingisactive,thecontentsarealsocopiedtothetracelog.
Update(ALT+U)
UpdatestheInspectdialogboxtoshowthemostrecentstatusoftheinspectedobject.
Theelementlineshortcutmenuappearsafterhighlightingtheelementlineandright-clicking.Thefollowingcommandsmayappearontheelementlineshortcutmenu:
Page 201
Inspect(ALT+I)
CallsInspectandpassesittheelementvalueasanargument.
Descend(ALT+D)
CallsInspect,passesittheelementvalueasanargument,andclosesthecurrentInspectwindow.
Copy
Copiesthevalueoftheinspectedelementtothe*obj*variable.
ViewSource
Activatesatexteditorwindowcontainingtheselectedtext.IfthetextwasloadedfromtheConsolewindoworfromalistrepresentation,thiscommandactivatesanewtexteditorwindow.
Thedefaultcommandforanelementline,invokedbypressingENTER,istheInspectcommand.
Pleasesendusyourcommentaboutthispage
Page 202
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
CopyingInspectObjectstothe*obj*IDEGlobalVariable
SometimesitisusefultoaccesssomepartofanobjectfromyourprogramorfromtheVLISPConsolewindow.Youmayalsowanttocopythevalueofoneobject'sitemintoanotheritemandsoon.Toperformallthesetasks,theInspectfeaturemanagesareservedglobalIDEvariablenamed*obj*.Thisvariablecanbeusedasatemporarystorageareawhilebrowsingthroughdatastructures.FrominsideanInspectdialogbox,youcanassignavaluetothisvariableandreplacethevalueofthecurrentitemwiththevalueof*obj*.
Toassignthevalueofaninspectedobjecttothe*obj*variable,right-clicktheitemintheInspectwindowandchooseCopy.
Pleasesendusyourcommentaboutthispage
Page 203
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
HandlingErrorsintheInspectCommand
Intexteditorwindowsitisnotpossibletoinspectselectedexpressionslongerthan256characters.Ifyouselectastringlongerthan256characters,youwillbepromptedtoenteranobjectname.
IfyouspecifyanobjectorexpressionthatVLISPcannotevaluate,VLISPissuesastandardAutoLISPerrormessage.Oncetheerrormessageappears,youcancorrecttheexpressioninthedialogboxandtrytoevaluateitoncemore.
Errorsarisingfromevaluationoftheobjectyouenteredcannotbeinvestigatedfromanestedbreakloop,becauseallbreaksaredisabledduringsuchevaluation.Ifyouwishtoexaminetheerror,chooseView ErrorTracefromtheVLISPmenu,orcopytheexpressiontotheConsolepromptandpressENTER.
Pleasesendusyourcommentaboutthispage
Page 204
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>UsingInspectWindows>
ClosingAllInspectWindows
TocloseallInspectwindows,chooseWindow CloseWindows InspectorsfromtheVLISPmenu.
Pleasesendusyourcommentaboutthispage
Page 205
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>
ViewingAutoCADDrawingEntities
VLISPprovidesfacilitiestowalkthroughtheAutoCADdrawingdatabaseandinspecttherawdataforeachdrawingentityreportedbyAutoCAD.YouaccessdrawingentitiesthroughtheVLISPBrowseDatabasefeature.BrowseDatabasedisplaysentityinformationinInspectwindows.YoucansetadiagnosticoptiontellingVLISPhowmuchinformationtosupplyaboutentities.
TocontroltheamountofInspectinformationdisplayedfordrawingobjects
1. ChooseTools EnvironmentOptions GeneralOptions.
2. ClicktheDiagnostictabintheGeneralOptionswindow.
3. SelectInspectDrawingObjectsVerboselytoviewdetailedentityinformation.CleartheoptioncheckboxtominimizetheamountofinformationsuppliedbyInspect.ViewingEntitiesintheDrawingDatabaseViewingSymbolTablesintheDrawingDatabaseViewingBlocksintheDrawingDatabaseViewingSelectedObjectsinaDrawingViewingExtendedData
Pleasesendusyourcommentaboutthispage
Page 206
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>ViewingAutoCADDrawingEntities>
ViewingEntitiesintheDrawingDatabase
ToOpenanInspectwindowforthecollectionofentitiesinthecurrentdrawingdatabase,chooseView BrowseDrawingDatabase BrowseAllEntitiesfromtheVLISPmenu.VLISPdisplaysawindowlistingtheentitiesinthedatabase:
NotethatVERTEXandATTRIBentitytypesarenotincludedinthislist.Youaccesstheseentitytypesthroughtheirparententities,whichareavailablewhenyouinspectPOLYLINEandINSERTentities.
TheshortcutmenucommandsavailablefortheobjectlineintheAutoCADEntitiesInspectwindowareLogandUpdate.
ToopenanInspectwindowforaspecificentity,double-clickontheentityname,orselecttheentity,thenright-click,andchooseInspect:
Page 207
Thetitlebarofthiswindowidentifiesthedrawingentitytype.Theobjectlineofthewindowdisplaystheentityname.
<Entityname:1cdf190>
TheshortcutmenufortheobjectlinecontainsthecommonInspectcommandsPrint,Copy,Log,andUpdate,plussomenewitems.
Modify
Ifavailable,thiscommandopensthestandardAutoCADDDMODIFYdialogfortheinspectedentity.
InspectRawData
DisplaysanInspectwindowcontainingthelistresultingfromanentgetfunctioncallfortheentity.
InspectNextEntity
DisplaysanInspectwindowforthenextentityintheentitieslist.
InquireExtendedData
Displaysalistofapplicationscurrentlyregisteredbyregapp.Ifyouselectanitemfromthelist,anyextendeddatarelatedtothechosenapplicationisincludedintheInspectentgetlist.SeeViewingExtendedDataformoreinformation.
Pleasesendusyourcommentaboutthispage
Page 208
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>ViewingAutoCADDrawingEntities>
ViewingSymbolTablesintheDrawingDatabase
ChoosingView BrowseDrawingDatabase BrowseTablesfromtheVLISPmenuopensanInspectwindowforthecollectionofsymboltablesinyourdrawing:
Youcaninspecteachtableasacollectionofnamedattributes.Double-clickonanametoviewitsattributes,orselectthename,right-click,andchooseInspect:
Toviewatableentryforaselectedattribute,double-clickontheattributename,orselecttheattribute,right-click,andchooseInspect:
Page 209
Pleasesendusyourcommentaboutthispage
Page 210
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>ViewingAutoCADDrawingEntities>
ViewingBlocksintheDrawingDatabase
ChooseView BrowseDrawingDatabase BrowseBlocksfromtheVLISPmenutoopenanInspectwindowfortheblocksinyourdrawing:
Double-clickontheblocknameyouareinterestedintoopenanInspectwindowfortheblock,orselecttheblock,right-click,andchooseInspect.
Page 211
Theraw-dataelementshowsthesymboltableentriesfortheinspectedblock.Double-clickonthepartsitemtoopenanInspectwindowlistingthecollectionofentitiesresidingwithintheblock.
Theraw-dataandpartselementlinesoccurinallblockInspectwindows.Otherelementlines,suchas{name},appearonlyiftheInspectDrawingObjectsVerboselyDiagnosticoptionisselected.SeeDiagnosticTab(GeneralOptionsDialogBox)forinformationonsettingVLISPdiagnosticoptions.
Pleasesendusyourcommentaboutthispage
Page 212
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>ViewingAutoCADDrawingEntities>
ViewingSelectedObjectsinaDrawing
ChooseView BrowseDrawingDatabase BrowseSelectionfromtheVLISPmenutoselectthedrawingobjectsyouwanttoview.VLISPinvokesthessgetfunctiontopromptyoutodefineaselectionsetintheAutoCADdrawingwindow.Whenyoucompletetheselection,VLISPopenstheInspectwindowforyourselection:
Double-clickonanentitynametoopenanInspectwindowfortheentity,orselectanentity,right-click,andchooseInspect.
Pleasesendusyourcommentaboutthispage
Page 213
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>DebuggingPrograms>UsingVisualLISPDataInspectionTools>ViewingAutoCADDrawingEntities>
ViewingExtendedData
ChooseView BrowseDrawingDatabase InquireExtendedDatafromtheVLISPmenutoseealistoftheapplicationscurrentlyregistered(throughregapp)ascontainingextendeddata.Ifyouselectanapplicationfromthislist,itsextendeddataisincludedintotheInspectentgetlist.
ToviewextendeddataassociatedwithanAutoCADobject
1. ChooseView BrowseDrawingDatabase InquireExtendedDatafromtheVLISPmenu.
2. Selecttheapplicationwhosedatayouareinterestedinviewing.
3. IntheAutoCADwindow,selectthedrawingobjectswhoseextendeddatayouwanttoview.
4. FromtheVLISPmenu,chooseView BrowseDrawingDatabaseBrowseSelection.VLISPdisplaysanInspectwindowlistingtheAutoCADobjectsyouselected:
5. IntheInspectwindowelementlist,double-clickonanobjectwhoseextendeddatayouwanttoview.VLISPdisplaysanInspectwindowfortheobject.
6. SelecttheobjectlineintheInspectwindowandright-clicktoviewa
Page 214
shortcutmenu.
7. ChooseInspectRawDatafromtheshortcutmenu.VLISPdisplaysanInspectwindowlikethefollowing:
Extendeddataisidentifiedbythe-3DXFgroupcode.Thelastlineintheentitylistshowstheextendeddatafortheselectedobject.Youcandouble-clickonthislinetoopenaseparateInspectwindowcontainingjusttheextendeddata.
Pleasesendusyourcommentaboutthispage
Page 215
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
BuildingApplications
Youcancompileyourprogramfilesandcreateasingleexecutablemodulethatyoucandistributetousers.
ThischapterdescribeshowtobuildapplicationswithVisualLISP®.
VLISPallowsyoutocompileyourprogramfilesandcreateasingleexecutablemodulethatyoucandistributetousers.ThefirstpartofthischapterprovidesbasicknowledgeabouttheVLISPcompilerandmaybesufficientforbuildingmacrosandsmallprogramsthatworkinasingledocument.Therestofthechapterhelpsyoubuildmorecomplexapplications.TheseremainingsectionsdiscussdesignconsiderationsforanenvironmentwhereseveralAutoCAD®
drawingsmaybeopenatthesametime,andprovideinformationonfine-tuningtheperformanceofcompiledcode.
CompilingandLinkingProgramsMakingApplicationModulesDesigningforaMultipleDocumentEnvironment
Pleasesendusyourcommentaboutthispage
Page 216
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>
CompilingandLinkingPrograms
EachtimeyouloadAutoLISP®sourcecode,thecodeistranslatedintoinstructionsthecomputerunderstands(executablecode).Theadvantageofhavingsourcecodetranslatedeachtimeyouloaditisthatyoucanmakeachangeandimmediatelytryitout.Thisisusefulforquicklytestingnewcode,andfordebuggingthatcode.
Onceyouaresureyourprogramisworkingcorrectly,translatingAutoLISPsourcecodeeachtimeitloadsistime-consuming.VLISPprovidesacompilerthatgeneratesexecutablemachinecodefilesfromyoursourcefiles.TheseexecutablefilesareknownasFASfiles.Becausetheexecutablefilescontainonlymachine-readablecode,thesourcecodeyouspentweeksormonthsdevelopingremainshiddenevenifyoudistributeyourprogramtothousandsofusers.EvenstringsandsymbolnamesareencryptedbytheVLISPfilecompiler.
VLISPalsoprovidesfeaturesforpackagingmorecomplexAutoLISPapplicationsintoVLISPexecutable(VLX)files.VLXfilescanincludeadditionalresourcesfiles,suchasVBAandDCLfiles,andcompiledAutoLISPcode.SeeMakingApplicationModulesforinstructionsonbuildingVLXfiles.
UsingVLXfiles,youcanfurthercontrolyourapplication'soperatingenvironmentbyexposingonlythosefunctionsyouchoosetoexpose,andbymaintainingawallbetweenyourprogram'svariablesandthevariablesuserscaninteractwithinAutoCAD.FormoreinformationoncontrollingtheoperatingenvironmentofaVLX,seeDesigningforaMultipleDocumentEnvironment.
UsingtheCompilerCompilingaProgramfromaFileWalkingthroughaCompileExampleLoadingandRunningCompiledProgramsLinkingFunctionCalls
Page 217
Pleasesendusyourcommentaboutthispage
Page 218
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>
UsingtheCompiler
VLISPprovidesseveralwaystoaccessandusethefilecompiler.TocompileasingleAutoLISPfile,youcanusethevlisp-compilefunction.TocompilemanyAutoLISPfilesintoasingleVLXfile,youcanusetheMakeApplicationwizard.Thevlisp-compilefunctionandtheMakeApplicationwizardaredescribedinthischapter.
IfyourapplicationconsistsofasetofAutoLISPfilesloadedinparallel,itisrecommendedthatyouusetheVLISPintegratedprojectmanagementfacilitiestocompileyourfiles.Theprojectmanagerautomaticallyrecompilesfilesthathavechanged,allowsyoutofindcodesegmentswithoutknowingwhichfilescontainthem,andoptimizestheuseoffunctioncallsandlocalvariablesinthecompiledfiles.Thesefeaturesareexplainedindetailin.
Pleasesendusyourcommentaboutthispage
Page 219
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>
CompilingaProgramfromaFile
TocompileasingleAutoLISPfile,callthevlisp-compilefunction.Thefunctionsyntaxis
(vlisp-compile'mode“filename”[out-filename])
Forthisfunction
modeisasymbolidentifyingthecompilermode
filenameisastringnamingthesourcefile
out-filenameisastringnamingthecompiledoutputfileChoosingaCompilerModeIdentifyingtheInputFileNaminganOutputFile
Pleasesendusyourcommentaboutthispage
Page 220
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>CompilingaProgramfromaFile>
ChoosingaCompilerMode
Themodeparameterindicatesthecompilationmode,whichcanbeoneofthefollowing:
st
Standardbuildmode
lsm
Optimizeandlinkindirectly
lsa
Optimizeandlinkdirectly
Thestandardmodeproducesthesmallestoutputfileandissuitableforprogramsconsistingofasinglefile.
Theoptimizationoptionsresultinmoreefficientcompiledfiles,whichbecomesimportantasyourprogramsgrowinsizeandcomplexity.Thebasicfunctionsofoptimizationareasfollows:
Linkfunctioncallstocreatedirectreferencestothecompiledfunctioninthecompiledcode,insteadoftothefunctionsymbol.Thisfeatureimprovestheperformanceofthecompiledcodeandprotectsthecodeagainstfunctionredefinitionatruntime.
Dropfunctionnamestomakethecompiledcodemoresecureandtodecreaseprogramsizeandloadtime.
Dropthenamesofalllocalvariablesanddirectlylinktheirreferences.Thisalsomakesthecompiledcodemoresecureanddecreasesprogram
Page 221
sizeandloadtime.
TheVLISPprojectmanagementfeatureallowsyoutotailortheoptimizationoptionstothespecificneedsofyourapplication.Seetolearnmoreaboutchoosingoptimizationoptions.
Pleasesendusyourcommentaboutthispage
Page 222
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>CompilingaProgramfromaFile>
IdentifyingtheInputFile
IfyoursourcefileisintheAutoCADsupportfilesearchpath,youdonothavetoincludethepathnamewhenspecifyingthefilename.ThesearchpathissetbychoosingTools OptionsfromtheAutoCADmenu,thenclickingtheFilestabandselectingSupportFileSearchPath:
Forexample,ifyouarecompilingtheyinyang.lspprogramfilethatisintheAutoCADSample\VisualLISPdirectory,andSupportFileSearchPathissetasindicatedinthepreviousfigure,youcanissuethefollowingcommandtocompiletheprogram:
Page 223
(vlisp-compile
'st"yinyang.lsp")
IftheAutoCADsample\visuallispdirectoryisnotinthesupportfilesearchpath,youmustincludetheentirepathnamewhenspecifyingthesourcefile.Forexample:
(vlisp-compile
'st"c:/programfiles/<AutoCADinstallationdirectory>/sample/visuallisp/yinyang.lsp")
Ifyouomitthefileextensionfromafilename,VLISPassumesthe.lspextension.
Whenspecifyingthefilepathname,replacethebackslashsymbol(\)younormallyuseforfilenameswitheitheraforwardslashoradoublebackslash,followingtheusualAutoCADconvention.
Pleasesendusyourcommentaboutthispage
Page 224
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>CompilingaProgramfromaFile>
NaminganOutputFile
Thecompilerproducescodeinthefast-loadAutoLISPformat(FAS).Bydefault,theoutputfilecontainingthiscodehasthesamenameastheinputfile,butwithanextensionof.fas.Youcanoverridethedefaultnamebyspecifyinganoutputfilename.Forexample,tocompileyinyang.lspandproduceanoutputfilenamedGoodKarma.fas,issuethefollowingcommand:
(vlisp-compile'st"yinyang.lsp""GoodKarma.fas")
Note Ifyouspecifyanoutputfilenamebutdonotspecifyapathnameforeithertheinputortheoutputfile,VLISPplacestheoutputfileintheAutoCADdefaultinstallationdirectory.
Inmostinstances,you'llwanttospecifythefullpathnameoftheoutputfile.Forexample:
(vlisp-compile
'st"yinyang.lsp""c:/programfiles/.../sample/visuallisp/goodkarma")
Thisensuresthattheoutputfileisplacedinthedirectoryyouwant..
Pleasesendusyourcommentaboutthispage
Page 225
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>
WalkingthroughaCompileExample
Youcanusetheyinyang.lspfileintheAutoCADsample\visuallispdirectorytoexercisethevlisp-compilefunction.
Tocompiletheyinyang.lspsampleprogram
1. AttheConsoleprompt,enterthefollowing:
(vlisp-compile
'st"c:/program
files/<AutoCADinstallationdirectory>/sample/visuallisp/yinyang.lsp")
Thiscommandrequestsastandardmodecompileoftheyinyang.lspfile.Nooutputfilenameisspecified,sothecompiledresultwillbesavedinafilenamedyinyang.fasandwillbeplacedinthesamedirectoryastheinputfile(theAutoCADsample\visuallispdirectory).
2. LookattheBuildOutputwindowdisplayedafterthecommandexecutes.Ifnecessary,scrollupinthewindowtoseeallthecompilermessages.Ifthecompilecompletedsuccessfully,thewindowcontainsmessageslikethefollowing:
Duringcompilation,thecompilerprintsfunctionnamesandvariousmessagesabouteachstageofcompilation.Thefirststageissyntaxandlexicalcheckingofthesourcecode.Ifthecompilerencounterserrors,itissuesmessagesandhalts
Page 226
thecompilationprocess.Thecompilerissueswarningsifitencountersexpressionsitconsidersdangerous,suchasredefiningexistingAutoLISPfunctionsorassigningnewvaluestoprotectedsymbols.Ifthecompilerdisplayswarningorerrormessages,youcanviewandeditthesourcecodethatcausedthesemessagesbydouble-clickingonthemessageintheBuildOutputwindow.
Ifcompilationissuccessful,asintheexamplecontainedintheaboveprocedure,theBuildOutputwindowdisplaysthenameofthecompiledoutputfile.
Pleasesendusyourcommentaboutthispage
Page 227
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>
LoadingandRunningCompiledPrograms
CompiledAutoLISPprogramscanbeloadedandrunfromeithertheVLISPConsolewindowortheAutoCADCommandprompt,orbychoosingToolsLoadApplicationfromtheAutoCADmenu.Thisistrueofboth.fasfilesand.vlxfiles,whichmaycontainmultiplecompiledprograms.(SeeMakingApplicationModulesforinformationoncreating.vlxfiles.)
TorunacompiledprogramfromtheVisualLISPConsolewindow
1. LoadtheprogrambyinvokingtheloadfunctionfromtheConsoleprompt.Forexample,toloadthecompiledyinyangprogramcreatedinWalkingthroughaCompileExample,enterthefollowingcommand:
(load"c:/programfiles/<AutoCADinstallation
directory>/sample/visuallisp/yinyang.fas")
Ifyouspecifyafilenamewithoutapathorextension,LOADlooksinthecurrentdirectoryforamatchingfilenamewitha.vlx,.fas,or.lspextension.IfLOADdoesnotfindamatch,itcontinuestosearchtherestoftheAutoCADsearchpathforamatchingfilename.Thesearchstopsinthefirstdirectorythatcontainsamatchingfilenamewithanyofthevalidextensions.Inthatdirectory,iftherearemultiplematchingfileswithvalidextensions,thefilewiththemostrecenttimestampisloaded.Iftherearemultiplefileswiththesametimestamp,thepreferenceorderisVLX,FAS,LSP.IfyouspecifyapathtoLOADbutomitthefiletype,thefunctionlooksforVLX,FAS,orLSPfileswithamatchingnameinthespecifieddirectory,andloadstheonewiththemostrecenttimestamp.Ifyoupreferlesstypingandmoreclicking,chooseFile LoadFilefromtheVLISPmenu,andusetheLoadLispFiledialogboxtoselect
Page 228
thefileyouwanttoload.RemembertousetheFilesofTypepull-downlistinthisdialogboxtospecifythetypeoffileyouwanttoload,otherwiseVLISPlistsonly.lspfilesinthedialogbox.Youcanselectfromthefollowingtypes:
LispSourceFiles(.lspfiles)
CompiledAutoLISPFiles(.fasfiles)
VLPackedApplication(.vlxfiles)
Allfiles(listsallfilesinthespecifieddirectory)ChooseOpentoloadtheselectedfiles.
2. AttheVLISPConsoleprompt,enterthenameofthefunctionyouwanttorun,enclosingthenameinparentheses.Forexample:
(yinyang)
VLISPtransferscontroltoAutoCADtodisplayprogrampromptsandacceptuserinput.
Onceyouloadaprogram,youcanrunitfromeithertheAutoCADCommandpromptortheVLISPConsolewindowprompt.Notethatifthenameofthefunctionyouarerunningbeginswithc:,youcaninvokeitfromtheAutoCADCommandpromptasifitwereanAutoCADcommand,thatis,withoutenclosingthenameinparentheses.Seeformoreinformationonthisfeature.
RefertotheAutoLISPReferenceformoreinformationontheloadfunction.LoadingExtendedAutoLISPFunctions
Pleasesendusyourcommentaboutthispage
Page 229
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>LoadingandRunningCompiledPrograms>
LoadingExtendedAutoLISPFunctions
VLISPprovidessomeextensionstotheAutoLISPlanguagethatarenotloadedautomaticallywhenyoustartAutoCAD.Thesefunctionshavenamesthatbeginwithvla-,vlax-,andvlr-.Thevla-functionsimplementAutoLISPActiveX®
support.Thevlax-functionsprovideActiveXutilityanddataconversionfunctions,dictionaryhandlingfunctions,andcurvemeasurementfunctions.Thevlr-functionsprovidesupportforAutoCADreactors.Beforeyoucanuseanyofthesefunctions,youmustloadtheAutoLISPextensionswiththefollowingfunctioncall:
(vl-load-com)
ThisfunctionfirstchecksiftheAutoLISPextensionsarealreadyloaded;ifso,thefunctiondoesnothing,otherwiseitloadstheextensions.
AutoLISPcodethatincludescallstovla-,vlax-,orvlr-functionsshouldalwaysbeginwithacalltovl-load-comtoensurethatthecodewillrun;itshouldnotbeleftuptotheusertoloadtheextensions.Ifyourapplicationdoesnotcallvl-load-com,theapplicationmayfail.
Pleasesendusyourcommentaboutthispage
Page 230
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>CompilingandLinkingPrograms>
LinkingFunctionCalls
TheprocessofcompilingfunctioncallsresultsinVLISPcreatingaloadablemodulecontainingin-linecopiesofsomeAutoLISPbuilt-infunctions.In-linecompilationofbuilt-infunctionsincreasestheefficiencyoftheresultingcode,butmaychangethebehaviorofsometrickyAutoLISPprograms.
Forexample,ifyourprogramcontainsanin-linecopyofabuilt-infunction,andthatfunctionissubsequentlyredefined,yourprogramdoesnotusethenewfunctiondefinition.Acopyoftheolddefinitionispartoftheprogram'sloadmodule,andthatversioniscalleddirectly.Youmustrecompileyourprogramtopickupthenewfunctiondefinition.
Ifyouincludebothdirectandindirectcallstothesamefunction,yourprogramcouldendupusingdifferentversionsfordifferentfunctioncalls.Thisisonereasonwhycombiningdirectandindirectcallswithinasingleprogramisnotrecommended.
Whenusingmultiple-fileapplicationsinconjunctionwithdirectlinking,itishighlyrecommendedthatyouusetheVLISPbuilt-inprojectmanagementsystemalongwithitsfunctionstooptimizecodeautomatically.Theprojectmanagementsystemprovidesagreaterdegreeofcontrolovercompilationandlinkingofprogramfilesthandoesthevlisp-compilefunction.Seefordetails.
Pleasesendusyourcommentaboutthispage
Page 231
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>
MakingApplicationModules
VLISPprovidesyouwiththeabilitytocreateasingle,stand-aloneexecutablemoduleforyourapplication.Thismoduleincorporatesallyourapplication'scompiledfiles,andcanincludeDCL,DVB,andotherfilesthatyourapplicationmayneed.ExecutableVLISPmodulesareknownasVLXfiles,andarestoredinfilesnamedwitha.vlxextension.
AMakeApplicationwizardguidesyouthroughtheapplicationbuildingprocessinVLISP.TheresultofthisprocessisaMakefile,whichisoftenreferredtobyitsfileextension,.prv.TheMakefilecontainsalltheinstructionsVLISPneedstobuildtheapplicationexecutable.
CreatingaNewApplicationLoadingandRunningVisualLISPApplicationsChangingApplicationOptionsRebuildinganApplicationUpdatinganApplication
Pleasesendusyourcommentaboutthispage
Page 232
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>
CreatingaNewApplication
Itisrecommendedyoubuildyourapplicationonlyafteryouhavefullydebuggedit.CompilererrorsduringtheMakeprocessmaypreventtheapplicationwizardfromcompletingsuccessfully.
TherearetwomodesoftheMakeApplicationwizard:simpleandexpert.Inthesimplemode,youneedonlyidentifythefilesinyourapplicationandnamethefilesyouwanttocreate.Theexpertmodeallowsformanyadditionaloptions.
TobuildanexecutablefilewiththeMakeApplicationwizard
1. ChooseFile MakeApplication NewApplicationWizardfromtheVLISPmenutostarttheMakeApplicationwizard.VLISPdisplaysaWizardModedialogboxaskingyoutochoosethemodeyouwant:
SelectExpertmode,soyoucanseeallthepossibleMakeoptions;thenpresstheNextbutton.
Page 233
2. VLISPdisplaysthefollowingApplicationDirectorydialogbox,whereyounameyourapplicationandspecifywhereyouwanttheapplicationfilesbuiltbyMakeApplicationtoreside:
TheApplicationDirectorydialogboxappearsinboththeSimpleandExpertWizardmodes.YoucanenterthefullpathnameintheApplicationLocationfield,orpresstheBrowsebuttonandidentifytheoutputdirectory(folder)usingastandardWindowsdialogbox.TheMakeApplicationwizardusestheApplicationNamewhenitcreatestheapplicationexecutable(.vlx)fileandtheMake(.prv)file.Forexample,ifyouspecifyanapplicationnameofmyapp,theMakeApplicationwizardcreatesfilesmyapp.vlxandmyapp.prv.IfyouneedtogobacktoapreviousMakeApplicationwizardstepandchangesomething,presstheBackbutton.Otherwise,pressNexttocontinue.
3. TheApplicationOptionsdialogboxisdisplayedwhenyouruntheMakeApplicationwizardinExpertmode.Inthisdialogbox,youchoosewhetheryouwantyourapplicationtoruninitsownnamespaceorinthenamespaceofthedocumentfromwhichtheVLXisloaded.SeeDesigningforaMultipleDocumentEnvironmentforadiscussionofnamespacesandseparate-namespaceVLXbehavior.TheActiveXSupportoptionisavailableifyouchoosetorunyourapplicationinaseparatenamespace.Selectingthisoptionresultsin
Page 234
automaticloadingofAutoLISPActiveXsupportfunctionswhentheVLXisloaded.
ChooseNexttocontinuebuildingtheapplication.
4. VLISPdisplaysadialogboxinwhichyouspecifytheLISPfilestobeloadedwhenyourapplicationloads.
TheLISPFilestoIncludedialogboxappearsinboththeSimpleandExpertWizardmodes.YoucanspecifyAutoLISPsourcecodefiles,compiledAutoLISP(FAS)files,oraVLISPprojectfile.Clickthepull-downbuttontochoosethetypeoffileyouwanttoinclude,thenpresstheAddbuttontodisplaythe
Page 235
followingdialogboxforselectingthefiles:
YoucanselectmultiplefilesusingthestandardWindowsfileselectionmethods.Afterselectingfilenames,pressOpentoaddthefilestoyourapplication.Toaddmorefilesofadifferenttype,choosethefiletypefromthepull-downlistandpressAddagain.IfyouspecifyAutoLISPsourcefiles,VLISPcompilesthoseprogramfileswhenitbuildstheapplication.Ifyouspecifyaprojectfile,alltheproject'sfilesarecompiledandincludedintheoutputmodule.Seeforinformationoncreatingandusingprojectfiles.Toremovefilesfromtheapplication,selectthefilesyounolongerwantandpresstheRemovebutton.Youcanalsoselectoneormorefiles,right-click,andchooseRemovefromtheshortcutmenu.VLISPloadstheapplication'sfilesintheordertheyarelistedintheListFilestoIncludedialogbox.Youmayneedtoreorderthefilelist.Forexample,ifyoucallafunctionatloadtime,thefunctionmustbedefinedbeforeitisused.Inthiscase,youwanttoplacethefiledefiningthatfunctionfirst.TheListFilestoIncludedialogboxcontainsbuttonsyoucanusetomovefilesaroundinthelist.Selectafilename,thenchoosefromamongthefollowingbuttons:
Top Movetothetopofthelist.
Up Moveaheadofthefilejustaboveinthelist.
Dn Movebehindthefilejustbelowinthelist.
Page 236
Btm Movetothebottomofthelist.Youcanalsoright-clickandchoosetheseactionsfromashortcutmenu.Notethattheloadorderofprojectfilesisspecifiedwhenyoudefinetheproject.(Seeofthechapter.)Whenyouhavefinishedspecifyingyourapplication'sAutoLISPfiles,pressNexttocontinuetothenextstepintheMakeApplicationwizard.
5. TheResourceFilestoIncludedialogboxisdisplayedwhenyouruntheMakeApplicationwizardinExpertmode.Ifyourapplicationincludesadditionalfiles,suchasdialogcontrollanguage(DCL)files,youcanincludetheminyourapplication'sVLXmodulebyselectingtheminthedialogbox.
Youcanspecifythefollowingtypesofresourcefiles:
AutoLISPsourcefiles
CompiledLISPfiles
VisualLISPprojectfiles
DCLfiles
DVBfiles
TextfilesAllprogramfilescanbeloadedbytheVLX.IfyouchooseaVisual
Page 237
LISPprojectfile,allfilesdefinedintheprojectfilesarecompiledandincludedintheVLX.Clickthepull-downbuttontochoosethetypeoffilesyouwanttoinclude,thenpresstheAddbuttontodisplaythedialogboxforselectingthefiles.Inthefileselectiondialogbox,youcanselectmultiplefilesusingthestandardWindowsfileselectionmethods.Afterselectingfilenames,pressOpentoaddthefilestoyourapplication.Toaddmorefilesofadifferenttype,choosethefiletypefromthepull-downlistandpressAddagain.Toremoveresourcefilesfromyourapplication,selectthefilesyounolongerwantandpresstheRemovebutton.Youcanalsoselectoneormorefiles,right-click,andchooseRemovefromtheshortcutmenu.Afterselectingresourcefilesforyourapplication,pressNexttocontinuetheMakeApplicationprocess.
6. TheApplicationCompilationOptionsdialogboxisdisplayedonlyinExpertmode.Youcanselectthecompilationandlinkageoptionsforyourapplicationinthedialogbox.
RefertoChoosingaCompilerModeforinformationontheseoptions.Afterselectingyourcompilationoptions,pressNexttocontinuetothefinalstepoftheMakeApplicationprocess.
7. ForthefinalstepintheMakeApplicationwizard,youcantellVLISPtobuildyourapplication.TheReviewSelections/BuildApplicationdialog
Page 238
boxappearsinbothSimpleandExpertmodes.
VLISPsavesallyourapplicationoptionsinaMake(.prv)file.TheMakefilealsoincludesalltheinstructionsthatVLISPneedstobuildtheapplication.Ifyoudonotelecttobuildtheapplicationnow,VLISPcanusetheMakefiletobuildtheapplicationlater.ChooseFinishtoconcludetheMakeApplicationprocess.UnderstandingtheOutputfromMakeApplication
Pleasesendusyourcommentaboutthispage
Page 239
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>CreatingaNewApplication>
UnderstandingtheOutputfromMakeApplication
VLISPexecutesinstructionsinaMakefiletobuildanapplication.OutputmessagesfromthisprocessappearintwoVLISPwindows:theBuildOutputwindowandtheConsolewindow.TheBuildOutputwindowcontainsmessagesrelatingtoanycompilationofAutoLISPsourcecodeinto.fasfiles.Inasuccessfulcompile,theoutputlookslikethefollowing:
Thecompilermessagesidentifythefollowingitems:
Thenameanddirectorypathofthesourcefilesbeingcompiled.
Thefunctionsdefinedinthesourcefile.Intheaboveexample,fourfunctionsareidentified:GP:GETPOINTINPUT,GP:GETDIALOGINPUT,GP:DRAWOUTLINE,andC:GPATH.
Thenameandpathoftheoutput.fasfiles.
TheVLISPConsolewindowdisplaysmessagesrelatingtothecreationoftheapplicationexecutable,the.vlxfile.IftheMakeApplicationprocesssucceeds,theConsolewindowdisplaysthepathandfilenameofthe.vlx,asinthefollowingexample:
Page 240
Pleasesendusyourcommentaboutthispage
Page 241
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>
LoadingandRunningVisualLISPApplications
ToexecutethefunctionsinaVLXapplication,youmustfirstloadtheVLXfileusinganyofthefollowingmethods:
CalltheAutoLISPloadfunction.
ChooseFile LoadFilefromtheVLISPmenu.
ChooseTools LoadApplicationfromtheAutoCADmenu.
SeeLoadingandRunningCompiledProgramsforspecificinstructionsonloadingandrunningapplicationfunctions.
Pleasesendusyourcommentaboutthispage
Page 242
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>
ChangingApplicationOptions
VLISPallowsyoutochangethewayyourapplicationisdesigned.Forexample,youcanchangecompilationoptions,oraddorremoveAutoLISPfilesfromtheapplication.
Tochangeanapplication'sdefinition
1. ChooseFile MakeApplication ExistingApplicationProperties.VLISPdisplaysadialogboxforyoutospecifyyourapplication'sMake(.prv)file,whichiswhereVLISPstorestheapplication'sproperties.
2. Specifythenameofyourapplication'sMakefile,thenpressOpen.VLISPdisplaystheApplicationPropertiesdialogbox.
3. Clickthetabofthepropertyyouwanttochange.
4. Afterchangingaproperty,pressApplytosavethechange,orpressOKtosavethechangeandexittheApplicationPropertiesdialogbox.
Page 243
Load/CompileOptions
CompileAutoLISPsourcefilesusingtheStandardcompileoption,orOptimizeandLinkthefiles.
TuneDirectories
IdentifyLISPObjectdirectoryandTargetdirectory.TheObjectdirectoryiswhereVLISPplaces.fasandtemporaryfilescreatedbythecompiler.Targetdirectoryisanothernamefor“Applicationdirectory,”whichiswhereMakeApplicationstorestheVLXfile.Ifafieldidentifyingadirectoryisblank,VLISPusesthe.prvdirectory.
ApplicationOptions
Createaseparate-namespaceVLXandincludeActiveXsupport.IfActiveXSupportisselectedalongwithSeparateNamespace,loadingtheVLXwillautomaticallyresultintheloadingofAutoLISPActiveXsupportfunctions.
LoadFiles
AutoLISPsourcefilesincludedintheapplication.
ResourceFiles
Additionalresourcefilesincludedintheapplication.
Page 244
Pleasesendusyourcommentaboutthispage
Page 245
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>
RebuildinganApplication
Afterchangingapplicationoptionsormodifyingsourcecode,youneedtorebuildyourapplicationforthechangestotakeeffect.
Torebuildanapplication
1. ChooseFile MakeApplication RebuildApplicationfromtheVLISPmenu.
2. Specifythelocationofyourapplication'sMakefile.
3. ChooseOpentorebuildtheapplication.
Inrebuildingtheapplication,VLISPrecompilesall.lspsourcefiles,applyingthespecifiedcompilationoptions,andpackagesyourapplicationfilesintoanew.vlxfile.IfyourapplicationcontainsmanyAutoLISPfiles,andyouhaveonlychangedthesourcecodeinoneortwofiles,theMakeApplicationoptioncanrebuildyourapplicationmoreefficiently.Seethefollowingsectionforinformationonusingthisoption.
Pleasesendusyourcommentaboutthispage
Page 246
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>MakingApplicationModules>
UpdatinganApplication
Ifyouchangejustasmallpieceofyourapplication'sAutoLISPsourcecode,youcanhaveVLISPrebuildyourapplicationVLXwhilecompilingonlythosefilesyou'veupdated.Tomakethistypeofupdate,chooseFile MakeApplicationMakeApplicationfromtheVLISPmenu,andselectyourapplication'sMakefile.VLISPrebuildstheapplicationbasedontheinformationcontainedintheMakefile,andautomaticallycompilesanyapplicationsourcefilesforwhicheitherofthefollowingistrue:
Thereisnocompiled(.fas)versionofthefile.
Thereisacompiledversionofthefile,butthesourcefilehasbeenmodifiedsincethatcompile(thatis,thedateofthesourcefileismorecurrentthanthedateofthe.fasfile).
Notethatifyouchangeapplicationoptions(forexample,fromStandardcompilemodetoOptimizeandLink),youmustusetheRebuildApplicationmenuoptiontocreateanewVLXwiththechangesyouspecified.TheMakeApplicationcommandonlychecksforchangestoAutoLISPsourcecodefiles,nottoapplicationoptions.
Pleasesendusyourcommentaboutthispage
Page 247
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>
DesigningforaMultipleDocumentEnvironment
UsingtheAutoCADmultipledocumentinterface(MDI),userscancopyobjectsbetweendrawingsanddisplayseveraldrawingssidebysideinasingleworksession.WhenyoudesignanAutoCADapplication,youneedtounderstandhowopendrawingdocumentsrelatetooneanother.
UnderstandingNamespacesRunninganApplicationinItsOwnNamespaceSharingDataBetweenNamespacesHandlingErrorsinanMDIEnvironmentLimitationsonUsingAutoLISPinanMDIEnvironment
Pleasesendusyourcommentaboutthispage
Page 248
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>
UnderstandingNamespaces
Theconceptofnamespaceswasintroducedtopreventapplicationsrunninginonedrawingwindowfromunintentionallyaffectingapplicationsrunninginotherwindows.AnamespaceisaLISPenvironmentcontainingasetofsymbols(forexample,variablesandfunctions).EachopenAutoCADdrawingdocumenthasitsownnamespace.Variablesandfunctionsdefinedinonedocumentnamespaceareisolatedfromvariablesandfunctionsdefinedinothernamespaces.
Youcanseehowthisworksbytryingasimpleexample.
Toseetheeffectofmultiplenamespaces
1. OpentwonewdrawingsinAutoCAD.
2. ChooseWindow TileVerticallyfromtheAutoCADmenu.YoushouldseetwoopendocumentwindowssidebysidewithinthemainAutoCADwindow:
Page 249
Thedocument'stitlebarindicateswhichwindowiscurrentlyactive.Intheprecedingexample,Drawing1.dwgisthecurrentdocument.
3. EnterthefollowingattheCommandprompt:
(setqdraw1foo"Iamdrawing1")
Thissetsthedraw1foovariabletoastring.
4. ActivateDrawing2.dwg(clickinthewindow'stitlebar).
5. Seeifdraw1foocontainsthevalueyoujustsetforit:
Command:!draw1foo
nil
Thevariableisnilbecauseithasnotbeensetinthisdocument'snamespace;yousetitinthenamespacebelongingtoDrawing1.dwg.
6. EnterthefollowingattheCommandprompt:
(setqdraw2foo"Itooamadrawing,butnumber2")
Thissetsthedraw2foovariabletoastring.
7. ActivateDrawing1.dwg.
Page 250
8. Testthevaluesofvariablesdraw1fooanddraw2foo:
Command:!draw1foo
"Iamdrawing1"
Command:!draw2foo
nil
Thedraw1foovariablecontainsthevalueyousetforit,butdraw2fooisnilbecauseyoudidnotsetittoavalueinthecurrentnamespace;yousetadifferentvariableofthesamenameinDrawing2.dwg'snamespace.
VLISPprovideswaysforyoutosharevariablesbetweennamespaces,butyoumusttakeexplicitactiontodoso.(SeeSharingDataBetweenNamespaces.)
Likevariables,functionsdefinedinanAutoLISPfileareknownonlytothedocumentthatwasactivewhenthefilewasloaded.Thefunctionsinthefileareloadedinthecurrentdocument'snamespaceandareknownonlytothatdocument.
Toseehowfunctionsareaffectedbymultiplenamespaces
1. LoadaLISPfilefromeithertheAutoCADCommandpromptortheVLISPConsoleprompt.Forexample:
(load"yinyang.lsp")
2. Invokethefunction.
3. Openaseconddrawingwindow.
4. Withtheseconddrawingwindowactive,tryinvokingthefunctionagain.Theresponsewillbeanerrormessagesayingthefunctionisnotdefined.
Youcanusethevl-load-allfunctiontoloadthecontentsofanAutoLISPfileintoallAutoCADdrawingdocuments.Forexample,thefollowingcommandcausesthecontentsoftheyinyang.lspfiletobeloadedintoallopendocuments,andintoanydocumentsopenedlaterintheAutoCADsession:
(vl-load-all"yinyang.lsp")
Thevl-load-allfunctionisusefulfortestingnewfunctionsinmultiple
Page 251
documents,butingeneralyoushoulduseacaddoc.lsptoloadfilesthatareneededineveryAutoCADdocument.
Pleasesendusyourcommentaboutthispage
Page 252
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>
RunninganApplicationinItsOwnNamespace
YoucandefineanamespaceforaVLXapplicationinVLISP.AVLXapplicationdefinedinthismannerisreferredtoasaseparate-namespaceVLX.Whenyouloadaseparate-namespaceVLX,itrunsinitsownnamespace,notthenamespaceofthedocumentfromwhereyouloadedtheVLX.TheoptiontodefineaVLXapplicationwithitsownnamespaceispartoftheMakeApplicationprocedure(seeMakingApplicationModules).
Ifyoutrytoloadaseparate-namespaceVLXthatisalreadyloaded,you'llreceiveanerrorindicatingthis.Usethevl-unload-vlxfunctiontounloadtheapplication.Thefunction'ssyntaxis
(vl-unload-vlx“appname”)
Forappname,specifythefilenameoftheVLX,withoutthepathorthe.vlxextension.
VariablesandfunctionsdefinedinaVLXapplication'snamespaceareknownonlytotheapplication,nottothedrawingdocumentthatwasactivewhentheapplicationwasloaded.Thisallowsyoutoprotectyourvariablesfromaccidentally—orintentionally—beingoverwrittenbyotherapplicationsorusers.
AVLXapplicationcanexportfunctionnamestoadocumentnamespacetoenablethosefunctionstobeaccessedwithinthecontextofthatdocument.Thefollowingdiagramillustrateshowthisworks:
Page 253
ThediagramshowsanAutoCADsessioncontainingtwoopendrawingdocuments.AVLXapplicationnamed“hangman”isloadedwithrespecttoDocument1(forexample,auseropenedDocument1andthenloadedtheVLXapplicationfromtheAutoCADCommandprompt).Thehangmanapplicationestablisheditsownnamespaceanddeclaredthebarfunctionandthedooleyvariableinthatnamespace.TheVLXexportedthebarfunctiontoDocument1'snamespace.WhenauserinvokesbarfromDocument1,barrunsintheapplication'snamespace.ThebarfunctionisunknowntoDocument2,andneitherdocumenthasaccesstothedooleyvariable(becausetheVLXdidnotexportit).YoucanloadanotherinstanceofthehangmanVLXintoDocument2,butthisinstancewillhaveitsownnamespaceanditsowncopiesofbaranddooley.
Note WhenyouloadaVLXfilethathasnotbeendefinedashavingitsownnamespace,theenvironmentissimilartothatofaloadedfile.AllfunctionsandvariablesdefinedintheVLXareloadedinthedocument'snamespace.
AccessingExternalObjectARXFunctionsfromaSeparate-NamespaceVLXMakingFunctionsAvailabletoDocumentsMakingSeparate-NamespaceFunctionsAvailabletoOtherVLXApplicationsReferencingVariablesinDocumentNamespaces
Page 254
Pleasesendusyourcommentaboutthispage
Page 255
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>RunninganApplicationinItsOwnNamespace>
AccessingExternalObjectARXFunctionsfromaSeparate-NamespaceVLX
InordertoaccessfunctionsthataredefinedinanexternalObjectARXapplicationfromaseparate-namespaceVLX,youmustfirstissuevl-arx-importtoimportthefunction.ObjectARXfunctionsareidentifiedasdatatypeEXRXSUBR.Forexample,thefollowingcommandidentifiesstartappasanexternalObjectARXfunction:
Command:(typestartapp)
EXRXSUBR
ThefollowingfunctionworkscorrectlyifloadedfromanLSPfile:
(vl-doc-export'StartApp2)
(vl-load-com)
(defunStartApp2()
(setqacadApp(vlax-get-acad-object))
(setqacadDoc(vla-Get-ActiveDocumentacadApp))
(setqacadPrefs(vla-Get-PreferencesacadApp))
(setqacadPrefFiles(vla-get-FilesacadPrefs))
(setqhlpFile(vla-Get-HelpFilePathacadPrefFiles))
(startapp"winhlp32"hlpFile)
(princ)
)
(princ"\nStartApp2isloaded,Type(StartApp2)toRun.")
(princ)
However,ifyoucompileStartApp2asaseparate-namespaceVLXandtrytorunthefunction,itfailswiththefollowingerrormessage:
"nofunctiondefinition:STARTAPP"
Tocorrectthis,importstartappusingthevl-arx-importfunction,asshowninthefollowingrevisedcode:
Page 256
(vl-doc-export'StartApp2)
(vl-load-com)
(vl-arx-import'startapp)
(defunStartApp2()
(setqacadApp(vlax-get-acad-object))
Pleasesendusyourcommentaboutthispage
Page 257
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>RunninganApplicationinItsOwnNamespace>
MakingFunctionsAvailabletoDocuments
Bydefault,functionsdefinedinaseparate-namespaceVLXarenotexposedtothedocumentnamespacefromwhichtheVLXisloaded.Youmustusethevl-doc-exportfunctiontoexposefunctionstodocumentnamespaces.WhenissuedfromaVLXthatrunsinitsownnamespace,vl-doc-exportexposesthespecifiedfunctiontoanydocumentnamespacethatloadstheVLX.Thevl-doc-exportfunctionacceptsasingleargument,asymbolidentifyingthefunctionname.Forexample,lookatthefollowingcode:
(vl-doc-export'kertrats)
(defunkertrats()
(princ"Thisfunctiongoesnowhere")
)
Thisexampledefinesthekertratsfunction,whichsimplyprintsamessage.Thedefunforthefunctionisprecededbyavl-doc-exportcallthatcausesthefunctiontobeexportedtothedocumentnamespace.
Toseehowvl-doc-exportworksinaseparate-namespaceVLX
1. InaVLISPtexteditorwindow,copythefollowingcodeintoafile:
(defunkertrats()
(princ"Thisfunctiongoesnowhere")
)
Notethatthiscodedoesnotcontainacalltovl-doc-export.
2. Savethefileyoujustcreated.
3. UsetheVLISPMakeApplicationwizardtobuildaVLXfromyourprogramfile.Specifythefollowingwizardoptions:
Page 258
Wizardmode:Expert
Applicationname:doctest
Applicationoptions:Separate-namespace
Compilationoptions:Optimize
4. FromeithertheAutoCADCommandpromptortheVLISPConsolewindowprompt,loadthedoctestVLXfile.
5. Tryrunningthekertratsfunction.Youshouldreceiveanerrormessageindicatingthefunctionisnotdefined.
6. Addthefollowinglineofcodetothebeginningofyourprogramfile:
(vl-doc-export'kertrats)
7. Savethefile,thenrebuildtheapplication.
8. Usevl-unload-vlxtounloadtheVLX,thenloadandruntheVLXagain.Thistime,kertratsshouldrunsuccessfully.
Youcanissueavl-doc-exportcalloutsidethecontextofaseparate-namespaceVLXapplication,butithasnoeffect.
Thevl-list-loaded-vlxfunctionreturnsalistofallseparate-namespaceapplicationsassociatedwiththecurrentdocument.Forexample:
_$(vl-list-loaded-vlx)
(DOCTEST)
Todeterminewhatfunctionshavebeenexportedfromaseparate-namespaceapplicationintothecurrentdocument,usevl-list-exported-functions.Whencallingthisfunction,youmustpassitastringnamingtheapplicationyouarechecking.Forexample,thefollowingcommandreturnsalistofthefunctionsexportedbythedoctestapplication:
_$(vl-list-exported-functions"doctest")
("KERTRATS")
Theresultsshowthatasinglefunction,kertrats,wasexportedfromdoctesttothecurrentdocument'snamespace.
Page 259
Note Currently,ifseparatenamespaceVLXAassociatedwithdocumentAloadsseparatenamespaceVLXB,thenallofVLXB'sexportedfunctionsareautomaticallydefinedindocumentA.NotealsothatVLXB'sexportedfunctionsarenotdefinedinVLXAuntilVLXAissuesanexplicitimport.(SeeMakingSeparate-NamespaceFunctionsAvailabletoOtherVLXApplications.)
Pleasesendusyourcommentaboutthispage
Page 260
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>RunninganApplicationinItsOwnNamespace>
MakingSeparate-NamespaceFunctionsAvailabletoOtherVLXApplications
Functionsdefinedinoneseparate-namespaceVLXarenotexposedtoanyotherseparate-namespaceVLXapplications.Ifafunctionhasbeenexportedthroughvl-doc-export,youcanusethevl-doc-importfunctiontomakethefunctionavailabletoanotherseparate-namespaceVLX.
Pleasesendusyourcommentaboutthispage
Page 261
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>RunninganApplicationinItsOwnNamespace>
ReferencingVariablesinDocumentNamespaces
Variablesdefinedinaseparate-namespaceVLXarenotknowntothedocumentnamespaceassociatedwiththeVLX.However,aseparate-namespaceVLXcanaccessvariablesdefinedinadocumentnamespaceusingthevl-doc-refandvl-doc-setfunctions.
Thevl-doc-reffunctioncopiesthevalueofavariablefromadocumentnamespace.Thefunctionrequiresasingleargument,asymbolidentifyingthevariabletobecopied.Forexample,thefollowingfunctioncallcopiesthevalueofavariablenamedaruhu:
(vl-doc-ref'aruhu)
Ifexecutedwithinadocumentnamespace,vl-doc-refisequivalenttotheevalfunction.
Thevl-doc-setfunctionsetsthevalueofavariableinadocumentnamespace.Thefunctionrequirestwoarguments:asymbolidentifyingthevariabletobeset,andthevaluetosetforthevariable.Forexample,thefollowingfunctioncallsetsthevalueofavariablenamedulus:
(vl-doc-set'ulus"Goboldlytonoone")
Ifexecutedwithinadocumentnamespace,vl-doc-setisequivalenttothesetqfunction.
Tosetthevalueofavariableinallopendocumentnamespaces,usethevl-propagatefunction.Forexample,thefollowingfunctioncallssetavariablenamedfooyallinallopendocumentnamespaces:
(setqfooyall"Goboldlyandcarryasoftstick")
Page 262
(vl-propagate'fooyall)
Thiscommandnotonlycopiesthevalueoffooyallintoallcurrentlyopendocumentnamespaces,butalsocausesfooyalltoautomaticallybecopiedtothenamespaceofanynewdrawingsopenedduringthecurrentAutoCADsession.
Pleasesendusyourcommentaboutthispage
Page 263
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>
SharingDataBetweenNamespaces
VLISPprovidesablackboardnamespaceforcommunicatingthevaluesofvariablesbetweennamespaces.TheblackboardisanamespacethatisnotattachedtoanydocumentorVLXapplication.YoucansetandreferencevariablesintheblackboardfromanydocumentorVLX.Usethevl-bb-setfunctiontosetavariable,andusevl-bb-reftoretrieveavariable'svalue.
Forexample,thefollowingcommandsetsthefoobarblackboardvariabletoastring:
Command:(vl-bb-set'foobar"Roottoottoot")
"Roottoottoot"
Thevl-bb-reffunctionreturnsthespecifiedstring.Thefollowingexampleusesvl-bb-reftoretrievethevalueoffoobarfromtheblackboard:
Command:(vl-bb-ref'foobar)
"Roottoottoot"
Notethatthesefunctionsrequireyoutopassasymbolnamingthevariableyouarereferencing('var-name),notthevariablename(var-name).
Settingorretrievingvariablevaluesintheblackboardnamespacehasnoeffectonvariablesofthesamenameinanyothernamespace.
Todemonstratethatdocumentvariablesareunaffectedbyblackboardvariables
1. FromtheVLISPConsolewindow(ortheAutoCADCommandprompt),usevl-bb-settosetthe*example*blackboardvariable.
_$(vl-bb-set'*example*0)
Page 264
0
The*example*variableissetto0intheblackboardnamespace.
2. Usevl-bb-reftoverifythevalueofthevariableyousetinthepreviousstep.
_$(vl-bb-ref'*example*)
0
3. Seewhatvalue*example*hasinthecurrentAutoCADdocument.
_$*example*
nil
The*example*variableisnilbecauseithasnotbeensetinthedocumentnamespace.
4. Set*example*inthecurrentdocument.
_$(setq*example*-1)
-1
The*example*variableissetto-1inthedocumentnamespace.
5. Checkthecurrentvalueof*example*intheblackboard.
_$(vl-bb-ref'*example*)
0
Theblackboardvariablenamed*example*isstillsettothevalueassignedinstep1;settingthedocumentvariableofthesamenameinstep4hadnoeffectontheblackboard.
VLISPalsoprovidesthevl-doc-setandvl-doc-reffunctionstosetandretrievedocumentnamespacevariablesfromaseparate-namespaceVLX,andvl-propagatetosetthevalueofavariableinallopendocumentnamespaces.ThesefunctionsaredescribedinReferencingVariablesinDocumentNamespaces.
Pleasesendusyourcommentaboutthispage
Page 265
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>
HandlingErrorsinanMDIEnvironment
Bydefault,eachdocumentnamespaceisprovidedwithitsown*error*function,whichisdefinedasfollows:
(defun*error*(msg)
(princ"error:")
(princmsg)
(princ)
)
AVLXapplicationrunningwithinadocumentnamespacesharesthedefaulterror-handlerfunction.Youmaywanttoadderror-handlinglogictoyourapplication.
HandlingErrorsinaVLXApplicationRunninginItsOwnNamespace
Pleasesendusyourcommentaboutthispage
Page 266
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>HandlingErrorsinanMDIEnvironment>
HandlingErrorsinaVLXApplicationRunninginItsOwnNamespace
ForVLXapplicationsexecutingwithintheirownnamespace,youcaneitherusethedefaulterrorfunctionoryoucandefineanerrorhandlerspecificallyfortheapplication.
IfyoudefineanerrorhandlerforaVLXrunninginitsownnamespace,youcancallthevl-exit-with-errorfunctiontopasscontrolfromtheVLXerrorhandlertothedocumentnamespace's*error*function.Thefollowingexampleusesvl-exit-with-errortopassastringtothedocument's*error*function:
(defun*error*(msg)
...;processinginVLXnamespace/executioncontext
(vl-exit-with-error(strcat"Myapplicationbombed!"msg)))
AVLX*error*handlercanusethevl-exit-with-valuefunctiontoreturnavaluetothedocumentnamespacefromwhichtheVLXwasinvoked.Thefollowingexampleusesvl-exit-with-valuetoreturntheintegervalue3totheprogramthatcalledtheVLXfromthedocumentnamespace:
(defun*error*(msg)
...;processinginVLX-Tnamespace/executioncontext
(vl-exit-with-value3))
(vl-doc-export'foo)
(defunfoo(x)
(barx)
(print3))
(defunbar(x)(list(/2x)x))
Anyinstructionspendingatthetimetheerroroccurredareflushed.
Page 267
IfyourVLXnamespaceerrorhandlerdoesnotuseeithervl-exit-with-errororvl-exit-with-value,thencontrolreturnstothecommandpromptafterexecutionoftheerrorhandler.Youcanonlycallvl-exit-with-errorandvl-exit-with-valueinthecontextofaVLXapplication'serrorhandler;itisanerrortoinvokethesefunctionsinanyothersituation.
Pleasesendusyourcommentaboutthispage
Page 268
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>BuildingApplications>DesigningforaMultipleDocumentEnvironment>
LimitationsonUsingAutoLISPinanMDIEnvironment
WhenusingnativeAutoLISPinanMDIenvironment,youcanonlyworkwithonedrawingdocumentatatime.AlthoughAutoLISPprovidessupportforexchangingvariablesandexposingfunctionstomultiplenamespaces,youcannot,forexample,runafunctioninonedocumentnamespaceandissueentmaketocreateanentityinanotherdocumentnamespace.AutoLISPdoesnotsupportaccessinginformationacrossmultipledrawings.
YoucanaccessmultipledocumentnamespacesusingActiveXautomation,andAutoLISPprovidesaccesstoActiveXmethods(see).However,accessingmultipledocumentswithActiveXisanunsupportedfeatureofAutoLISP.Forexample,anAutoLISPprogramrunninginthecontextofdocumentAcanchangetheactivedocumenttodocumentBbycallingvla-put-activedocument.Changingtheactivedocument,though,immediatelysuspendsexecutionoftheprogram.TheprogrammayresumeexecutioniftheuseractivatesthewindowcontainingdocumentAbutthesystemwillbeinanunstablestateandlikelytofail.
Warning IfyoudouseActiveXtoworkinMDI,beawarethatifyoucloseallAutoCADdrawingsyouloseaccesstoAutoLISPandwillcauseanexception.
Pleasesendusyourcommentaboutthispage
Page 269
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
MaintainingVisualLISPApplications
YoucanmaintainlargeprogramsbycreatingaVisualLISPprojectandoptimizingcode.
ThischapterdescribeshowyoucanmaintainlargeapplicationscontainingmultiplefilesbydefiningtheapplicationasaVisualLISP®project.Asidefromdefiningthecomponentsinyourapplication,youcanuseVLISPprojectstodefinecompileroptionsfortheapplication.Thischapterdescribesthevariouscompileroptionsandtheconsequencesofeach,andtellsyouhowtooverridetheseoptionsforindividualfilesinaproject.
ManagingMultipleLISPFilesDefiningaProjectWorkingwithExistingProjectsOptimizingApplicationCode
Pleasesendusyourcommentaboutthispage
Page 270
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>
ManagingMultipleLISPFiles
Manyprogramexamplesyouhaveseeninthisdocumenthavebeensmall,stand-aloneAutoLISP®files.TypicalAutoLISPapplications,however,consistoflargerfileswithmanylinesofcode.Anapplicationmayincludemanysourcecodefiles.Aftercompilingtheprogramsinsuchanapplication,youalsohaveanumberofFASfilestotrack.
Asthenumberofapplicationfilesgrows,itbecomesmoredifficulttomaintainanapplication.Determiningwhenyouneedtorecompilefilesaftersourcecodechangescanbeachallenge.VLISPprovidesfunctionsthatgreatlysimplifytheprocessofmanagingmultiple-fileapplications.
UnderstandingVisualLISPProjects
Pleasesendusyourcommentaboutthispage
Page 271
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>ManagingMultipleLISPFiles>
UnderstandingVisualLISPProjects
Toaidyouintheprocessofmaintainingmultiple-fileapplications,VLISPprovidesaconstructcalledaproject.AVLISPprojectcontainsalistofAutoLISPsourcefiles,andasetofrulesonhowtocompilethefiles.Usingtheprojectdefinition,VLISPcandothefollowing:
Checkwhich.lspfilesinyourapplicationhavechanged,andautomaticallyrecompileonlythemodifiedfiles.ThisprocedureisknownasaMakeprocedure.
Simplifyaccesstosourcefilesbylistingallsourcefilesassociatedwithaproject,makingthemaccessiblewithasingle-click.
Helpyoufindcodefragmentsbysearchingforstringswhenyoudonotknowwhichsourcefilescontainthetextyou'relookingfor.VLISPlimitsthesearchtofilesincludedinyourproject.
Optimizecompiledcodebydirectlylinkingthecorrespondingpartsofmultiplesourcefiles.
BeforediscussinghowtodefineanduseVLISPprojects,itmayhelptointroducefiletypesusedinVLISP.
LISP,FAS,andOtherFileTypes
Pleasesendusyourcommentaboutthispage
Page 272
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>ManagingMultipleLISPFiles>UnderstandingVisualLISPProjects>
LISP,FAS,andOtherFileTypes
ThebasicfiletypeinVLISPistheAutoLISPsourcefile.Typically,AutoLISPsourcefilesarenamedwithan.lspfileextension.Youhaveseen.lspfilesusedfrequentlyinpreviouschapters.
TheFAS(.fas)filetypewasintroducedinthepreviouschapter,BuildingApplicationsFASfilesarecompiledAutoLISPfiles.ThesefilesloadfasterthanAutoLISPsourcefilesandaremoresecurebecausetheircontentsarenotintelligibletousers.
HereisabriefsummaryofthetypesoffilesusedbytheVLISPprojectmanagementfeature:
VisualLISPprojectfiletypes
Fileext. Typeoffile Function
.fas CompiledAutoLISPcode
CompiledAutoLISPprograms.Maybeloadedandrun,orcompiledintoVLXmodules
.lsp AutoLISPsourcecode
Programsourcefiles
.ob Objectcode UsedinternallybyVLISP,thesefiles
Page 273
containcompiledAutoLISPcodeusedinbuildingFASfiles
.pdb Projectdatabase
UsedinternallybyVLISP,thesefilescontainsymbolinformationusedbythecompiler
.prj Projectdefinition
Containsthelocationandnamesofallsourcefilesthatbuildtheproject,aswellascertainparametersandrulesonhowtocreatethefinalFASfiles
Inadditiontothefilesrecognizedbytheprojectmanager,VLISPeithercreates,processes,orrecognizesanumberofadditionaltypesoffiles,assummarizedbelow:
AdditionalVisualLISPfiletypes
Fileext. Typeoffile Function
.dsk Desktopsave ContainsVLISPenvironmentandwindowsettings.(Note:EditingthisfilemaypermanentlychangetheVLISPenvironment.Donoteditthisfilewithoutcreatingabackupcopyfirst.)
Page 274
._xx Backupfiles Backupcopiesofeditedfiles,maintainedbytheVLISPeditor.Backupfilescontainthesamenameastheoriginal,exceptthatthefileextensionbeginswiththeunderlinecharacter(_)andisfollowedbythefirsttwocharactersoftheoriginalfile'sextension.Forexample,thebackupfileofaLSPfilehasan._LSextension;thebackupofaDCLfilehasa._DCextension.
.vlx Stand-aloneapplications
Stand-aloneAutoCADapplications,whichcanbecreatedusingtheVLISPMakeApplicationwizard.
.c,.cpp,.cch,.hpp,.hh Languagesourcefiles
Containprogramsourcecode.TheVLISPeditorrecognizesthesyntaxofthesefilesandcolor-codesreservedwords,strings,andnumbers.
.dcl Dialogcontrollanguage
ContainsdefinitionsofAutoCADdialogboxes.VLISPcanpreviewthesefiles,andyoucanincludetheminVisualLISPexecutable(VLX)
Page 275
files.
.prv Makeapplication
DefinesthefilesandoptionsusedtobuildaVLXapplicationwiththeVLISPMakeApplicationwizard.
.sql Structuredquerylanguage
ContainsSQLstatements.TheVLISPtexteditorrecognizesthisfiletypeandcolor-codesthetextaccordingtoSQLsyntaxrules.
Pleasesendusyourcommentaboutthispage
Page 276
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>
DefiningaProject
TodemonstratetheuseofprojectsinVLISP,youcanusethesampleprogramssuppliedwiththeAutoLISPTutorial.ThiscodeisavailableontheAutoCAD®
installationCD,butthetutorialfilesareonlyincludedinyourinstallationifyouchooseaFullinstall,orifyouchooseCustominstallandselecttheTutorialsitem.IfyouhavealreadyinstalledAutoCADanddidnotinstallthesamples,youcanreruntheinstallation,chooseCustom,andselectonlytheTutorialsitem.
ThesamplefilesusedinthischapterareintheTutorial\VisualLISP\Lesson5folderoftheAutoCADdefaultinstallationdirectory.Thefilesare
Gpmain.lsp
Gpdraw.lsp
Gp-io.lsp
Utils.lsp
TocreateaVLISPproject,chooseProject NewProjectfromtheVLISPmenu.VLISPdisplaysastandardWindowsdialogboxforyoutospecifyafilepathandname.Fortheexampleinthischapter,theprojectnameisTutorial.VLISPassignsa.prjextensiontotheprojectfilename.
AssigningProjectPropertiesUsingtheProjectWindowtoWorkwithProjectFiles
Pleasesendusyourcommentaboutthispage
Page 277
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>
AssigningProjectProperties
TheProjectPropertiesdialogboxisdisplayedafteryouspecifyaprojectfilename.
SelectingtheFilestoIncludeinaProjectIdentifyingthePathNameofProjectFilesChangingtheOrderinWhichVisualLISPLoadsFilesChoosingCompilerBuildOptions
Pleasesendusyourcommentaboutthispage
Page 278
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>AssigningProjectProperties>
SelectingtheFilestoIncludeinaProject
TherearetwotabsintheProjectPropertiesdialogbox.IntheProjectFilestab,youspecifytheAutoLISPsourcefilesfortheproject.
Theproject'shomedirectoryisidentifiedjustbelowthetabs.Thisiswheretheprojectfile(tutorial.prj)resides.Inthisexample,thehomedirectoryisc:\MyDocuments\VisualLISP\Examples.That'snotthedirectorycontainingthetutorialsamplefiles,though.Toidentifythesourcedirectory,pressthe[...]button.
UsetheBrowseforFolderdialogboxtoidentifythelocationoftheprojectsourcefiles.IfyouselecttheLesson5directory,theProjectPropertiesdialogboxlookslikethefollowing:
Page 279
VLISPlistsallfilesinthedirectoryhavingan.lspextension(butdoesnotdisplaytheextensioninthelist).Thewindowisdesignedsothat,bydefault,youcanselectmultiplefilenamesbyjustchoosingeachname.YoudonothavetopressandholdCTRLtoselectmorethanonefile.Toclearaselectedname,justchooseitagain.
Toincludeallthelistedfilesinyourproject,pressthebuttonlabeled“(Un)Selectall,”thenchoosetherightarrowbutton.VLISPmovesthefilenamestothewindowontheright:
Page 280
Toremoveafilefromtheproject,selectthefile'snameintherightwindowandclicktheleftarrowbutton.
Pleasesendusyourcommentaboutthispage
Page 281
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>AssigningProjectProperties>
IdentifyingthePathNameofProjectFiles
Thelistofincludedfilesdoesnotidentifythepathnameofeachfile(nordoestheLookInfield;thisjustidentifiesthepathofthefileslistedintheleftwindow).Becauseyoucanincludefilesfrommultipledirectoriesinyourproject,youneedtobeabletoidentifythepathnameofeachfile.Youcandothisbyhighlightingoneormorefilenamesandright-clickingtodisplayashortcutmenu:
Todisplaythefullpathnameandthesize(inbytes)ofsourcefilesintheproject,chooseLogFilenamesandSizefromtheshortcutmenu.Theinformationappearsinasmall,scrollablewindownearthebottomoftheProjectPropertiesdialogbox:
IfafileisintheHomedirectoryshownintheProjectPropertiesdialogbox,VLISPdoesnotspelloutitspathname.Usethescrollbartoseeinformationaboutallthefilesintheproject.
Notethatyoucannotincludetwofilesofthesamenameinaproject,eveniftheyareindifferentdirectorypaths.
Page 282
Pleasesendusyourcommentaboutthispage
Page 283
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>AssigningProjectProperties>
ChangingtheOrderinWhichVisualLISPLoadsFiles
Theshortcutmenuforthelistofincludedfilesalsoprovidescommandstomovefilesupanddowninthelist,andtosortthelistbyfilenameorbyfullpathname.VLISPloadstheproject'sfilesintheorderinwhichtheyarelisted.Sometimestheloadorderisimportant.Forexample,youmighthaveaninitializationfilethatdefinesglobalvariablesneededbyalltheotherprogramfiles,andthusmustbeloadedfirst.YoucouldselectthatfilenameandchooseMovetoToptoplaceitfirstintheproject'sfilelist.
YoucanalsousebuttonsintheProjectPropertiesdialogboxtomovefilesaroundinthelist:Top(movetotop),Up(moveup),Dn(movedown),andBtm(movetobottom).
Forthetutorialproject,thegpmain.lspfileshouldbeloadedlast.Itcontainsthefollowinginstructionsattheendofthefile:
(princ"\nTypeGPATHtodrawagardenpath.")
(princ)
Thisresultsinaprompttellingusershowtoinvoketheapplication.IfVLISPloadsgpmain.lsplast,theseinstructionswilldisplayattheAutoCADCommandprompt.
Afteryoumoveanyneededfiles,presstheApplybutton.
Pleasesendusyourcommentaboutthispage
Page 284
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>AssigningProjectProperties>
ChoosingCompilerBuildOptions
TheBuildOptionstabdisplaysadialogboxinwhichyoucanspecifycompileroptionstoVLISP.ThistopiciscoveredintheChoosingaCompilationModesectionlaterinthischapter.Fornow,chooseOKtoclosetheProjectPropertiesdialogbox.
Pleasesendusyourcommentaboutthispage
Page 285
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>
UsingtheProjectWindowtoWorkwithProjectFiles
WhenyouopenaVLISPproject,VLISPdisplaysawindowlistingthefilesintheproject:
Bydefault,VLISPliststheprojectmembersintheorderinwhichtheywillbeloaded(asdefinedintheProjectPropertiesdialogbox).YoucanchangethisorderbychoosingArrangeFilesfromtheshortcutmenuforthiswindow.
Theprojectnameappearsinthewindowtitlebar.Belowthetitlebararefiveicons.Eachiconisabuttonthatperformsafunction.Thebuttonsandtheirfunctionsareasfollows:
ProjectProperties
DisplaystheProjectPropertiesdialogboxfortheproject.Thisallowsyoutoviewthefullpathnameofeachfileintheproject,add,remove,andreorderprojectfiles,andviewandchangeprojectcompileroptions.
LoadProjectFAS
Loadsallcompiled(.fas)filesfortheproject.
LoadSourceFiles
Loadsalltheprojectsourcefiles,makingthemavailabletoberun.
Page 286
BuildProjectFAS
Compilesallprojectsourcefilesthathavebeenmodifiedsincetheirlastcompile.
RebuildProjectFAS
Recompilesallprojectsourcefiles,whetherornottheyhavechangedsincetheirlastcompile.
Ifyouright-clickwithinthefilelistoftheProjectPropertiesdialogbox,VLISPdisplaysashortcutmenu.Manyofthefunctionsavailablefromtheprojectshortcutmenucanalsobeaccomplishedinotherways.Forexample,you'vealreadyseenhowtoaddfilestoprojectsandremovefilesfromprojects.ChoosingRemoveFilefromtheshortcutmenuisaquickwayofremovingafilefromaproject,whilechoosingAddFilemerelybringsyoutotheProjectPropertiesdialogbox.
Thefollowingsummarizesthecommandsontheshortcutmenu:
Edit
Editsthesourcecodeoftheselectedprojectmembers.
AddFile
OpenstheProjectPropertiesdialogboxtoaddfilestotheproject.
RemoveFile
Removestheselectedmembersfromtheproject.
Load
LoadstheFASfilefortheselectedprojectmembers.IfnoFASfileexistsforamember,loadstheAutoLISPsourcefile.
LoadSource
Loadsthe.lspfilefortheselectedprojectmembers.
CheckSyntax
ChecksAutoLISPsyntaxofthesourcecodefortheselectedmembers.
Touch
Page 287
Indicatesthattheselectedsourcefileshavebeenupdated,butmakesnochangetothefiles.ThiscausesVLISPtorecompiletheseprogramsthenexttimeyouasktocompileallchangedprojectfiles.
ArrangeFiles
Sortstheprojectmemberlist,accordingtooneoftheavailablesuboptions(loadorder,name,type,ordate).
MultipleSelection
TellsVLISPwhetherornottoallowselectionofmultiplemembersfromthelistintheProjectPropertiesdialogbox.Ifthisoptionisselected,multipleselectionisallowed.
[Un]SelectAll
Selectsallmembersoftheprojectlist,ifnoneiscurrentlyselected.Ifanymembersarecurrentlyselected,thiscommandcancelstheirselection.
CloseProject
Closestheproject.
SaveProjectAs
Savestheproject.
SelectingMultipleProjectMembersLoadingProjectFilesCompilingandRecompilingProjectFilesEditingProjectFilesSavingandClosingtheProject
Pleasesendusyourcommentaboutthispage
Page 288
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>UsingtheProjectWindowtoWorkwithProjectFiles>
SelectingMultipleProjectMembers
TheMultipleSelectormenuitemisavailableonlyfromtheProjectPropertiesdialogboxshortcutmenu.ChoosingthisoptionallowsyoutoselectmultiplemembersfromthelistintheProjectwindow.Iftheoptionisselected,acheckmarkappearsnexttotheMultipleSelectoritemonthemenu.Clickonthemenuitemtotoggleitonandoff.
IfMultipleSelectorisineffect,clickingamembernameintheProjectPropertiesdialogboxactsasatoggletoselectordeselectthemember.Forexample,noneofthememberslistedinthefollowingwindowisselected:
IfyouclickonthenameGP-IO,thenclickonthenameGPDRAW,bothareselected.
ThisisunlikethedefaultWindowsbehavior,whereselectingthesecondlistitemcancelsthefirstitem'sselection,unlessyoupressCTRLwhileselectingtheitem.
Page 289
YoucanalsousetheProjectPropertiesdialogboxshortcutmenutoselectallmembersoftheprojectorcancelselectionofallmembers.Ifnomembersarecurrentlyselected,right-clickandchoose[Un]SelectAlltoselectallthemembers.Ifanyorallmembersarealreadyselected,[Un]SelectAllcancelsallselections.
Pleasesendusyourcommentaboutthispage
Page 290
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>UsingtheProjectWindowtoWorkwithProjectFiles>
LoadingProjectFiles
Toloadtheproject'scompiledprogramfiles,clicktheLoadProjectFASbutton.Thisallowsyoutoruntheapplication.IfVLISPdetectsthatsomeofthesourcefilesdonotexistincompiledformat,itdisplaysamessageandasksifyouwanttocompilethosefiles:
IfyouchooseYes,VLISPattemptstocompileall.lspfilesthatdonothaveacorresponding.fasfile.IfyouchooseNo,VLISPloadsallFASfilesitfindsfortheproject,andloadstheAutoLISPsourcefortheremainingprojectfiles.ChooseCanceltoaborttheloadoperation.
Toloadallprojectsourcefilesinsteadoftheircompiledversions,clicktheLoadSourceFilesbutton.Rememberthatdebuggingbreakpointsmaybesavedwithinsourcecodefilesbutareremovedfromthecompiledversionofthecode.Youmightwanttoloadsourcefilestodebugchangesyou'vemadetoyourprograms.
UsingtheProjectPropertiesdialogboxshortcutmenu,youcanchoosetoloadjustselectedfiles.Selectthefilesyouwanttoload,andthenright-clickandchooseLoadtoloadtheFASfiles,orchooseLoadSourcetoloadthesourcecode.NotethatifyouchooseLoadandaFASfiledoesnotexistforaselectedfile,VLISPloadstheAutoLISPsourcefileinstead.
Note TheLesson5examplefromtheAutoLISPTutorialrequiresaDCLfiletorunsuccessfully.TheDCLfileisincludedintheLesson5folder,butyoucannot
Page 291
defineaDCLfileaspartofaVLISPproject.Torunthisexamplesuccessfully,youmustcopytheDCLfiletoadirectoryintheAutoCADsupportfilesearchpath.YoucanalsodefinetheDCLfileasanapplicationcomponent,usingtheVLISPMakeApplicationwizard.Usingthismethod,thefiledoesnothavetobeintheAutoCADsearchpath.IncludingaProjectinaVisualLISPApplicationdemonstrateshowtodefineanapplicationcomposedofaVLISPprojectandsupportingfiles,suchasDCLfiles.
Pleasesendusyourcommentaboutthispage
Page 292
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>UsingtheProjectWindowtoWorkwithProjectFiles>
CompilingandRecompilingProjectFiles
OnekeyadvantageindefiningVLISPprojectsforyourapplicationsisthatitprovidesanefficientmethodofupdatingcompiledcode.YoucanelecttohaveVLISPrecompileallsourcefilesthathavechangedsincethelasttimetheywerecompiled.Bychoosingthisoption,youensureallFASfilesinyourapplicationcorrespondtothelatestversionsoftheprogramsourcecode.Atthesametime,yousavetimebyavoidingunnecessarycompiles.Toinvokethisfeature,clicktheBuildProjectFASbuttonintheProjectPropertiesdialogbox.
Youcanalsochoosetorecompilealltheprogramsinyourproject,whetherornottheyhavechanged.ClicktheRebuildProjectFASbuttontoenablethisfeature.
Pleasesendusyourcommentaboutthispage
Page 293
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>UsingtheProjectWindowtoWorkwithProjectFiles>
EditingProjectFiles
Toeditthesourcefileofaprojectmember,selectthememberfromthelistintheProjectwindow,thenright-clickandchooseEdit.IftheMultipleSelectoroptionison,youcanselectmultiplemembers,andVLISPwillopenatexteditorwindowforeach.
Note IftheMultipleSelectoroptionisnotturnedon,youcansimplydouble-clickamembernametoeditit.
Pleasesendusyourcommentaboutthispage
Page 294
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>DefiningaProject>UsingtheProjectWindowtoWorkwithProjectFiles>
SavingandClosingtheProject
Tosavetheprojectpropertiesyoudefinedormodified,right-clickintheProjectwindowandchooseSaveProjectAsfromtheshortcutmenu.VLISPdisplaysalistofprojectfiles.Youcaneitherselectthenameofthecurrentprojectfiletoupdateitscontents,orenteranewfilenametosavethechangesasanewproject.
Whenyouarefinishedworkingwithaproject,right-clickintheProjectwindowandchooseCloseProject.Notethatthisonlyclosesthe.prjfile;anyprojectfilesthatareopeninVLISPeditorwindowsremainopen.
Note IfyouclosetheProjectPropertiesdialogboxbyclickingtheClosebutton,thisdoesnotclosetheprojectitself.TheProjectisstillopen,andyoucanreopenaProjectwindowforitbychoosingitfromtheProjectmenu,asdescribedinthenextsection,OpeningaProject
Pleasesendusyourcommentaboutthispage
Page 295
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>
WorkingwithExistingProjects
SomeVLISPfeaturesdescribedinpreviouschaptershavespecialapplicationwithVLISPprojects.ThefeaturesdescribedinthissectionarethetexteditorsearchfunctionsandtheMakeApplicationwizard.
OpeningaProjectFindingaStringinProjectSourceFilesIncludingaProjectinaVisualLISPApplication
Pleasesendusyourcommentaboutthispage
Page 296
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>WorkingwithExistingProjects>
OpeningaProject
Toopenanexistingproject,chooseProject OpenProjectfromtheVLISPmenu:
Iftheprojectfileyouwanttoopenisinthecurrentdirectory,youcansimplyentertheprojectnamehere.Iftheprojectfileisnotinthecurrentdirectory,orifyoudon'tknowwhatthecurrentdirectoryis,presstheBrowsebuttontoobtainastandardOpendialogbox.
Notethatyoucanhavemorethanoneprojectopenatatime.YoucanviewalistofallopenprojectsbychoosingtheProjectmenuandlookingatthebottomofthemenudisplayed:
Atanytime,onlyoneoftheprojectsisactive.Thecheckmarkinfrontoftheprojectnameindicatestheactiveproject.ThecommandsintheProjectmenu,
Page 297
suchasLoadandBuild,applytotheactiveproject.ThesecommandsworkthesamewhenselectedfromaProjectwindow.
Ifyouattempttoopenaprojectthathasthesamenameastheactiveproject(thatis,theprojectfilehasthesamename,butisinadifferentdirectorythanthecurrentactiveproject),VLISPdisplaysamessageboxaskingyouifyouwantto“relocatetheprojectdefinition.”Ifyouchoose“Yes,”VLISPloadsthenewprojectfileandreplacestheactiveproject.Ifyouchoose“No,”VLISPdoesnotloadthenewprojectfile,leavingthecurrentactiveprojectinplace.
Pleasesendusyourcommentaboutthispage
Page 298
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>WorkingwithExistingProjects>
FindingaStringinProjectSourceFiles
TheVLISPtextsearchfunction,describedinSearchingforText,providesyouwiththeabilitytosearchallofaproject'ssourcefilesforastringoftext.
Forexample,supposeinreviewinggpmain.lspyouseecallstoafunctioncalledgp:getPointInput,andyoucannotrememberinwhichsourcefilethisfunctionisdefined.Tosearchforit,chooseSearch FindfromtheVLISPmenu.IntheFinddialogbox,selectProjectinthelistofSearchoptions:
AProjectselectionfieldnowappearsatthebottomoftheFinddialogbox.Ifthenameoftheprojectyouwanttosearchisnotalreadydisplayedinthisfield,chooseitfromthepull-downlist.ChoosetheFindbuttontoperformthesearch.VLISPdisplaystheresultsinaFindOutputwindowlikethefollowing:
Page 299
Theoutputshowsthatfourfilesweresearched(therearefoursourcefilesintheproject),andfouroccurrencesofgp:getPointInputwerefound.Theoccurrenceswerefoundintwofiles;thedefunforthefunctionisingp-io.lsp.Youcanopenaneditorwindowforthefilebydouble-clickinganywherewithinthehighlightedtextintheFindOutputwindow.YoucanalsopressSHIFT+F11todisplaythefirstsourcelocationatwhichthetextstringwasfound,andthenrepeatedlypressF11toviewsubsequentoccurrencesinthesourcefiles.
Pleasesendusyourcommentaboutthispage
Page 300
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>WorkingwithExistingProjects>
IncludingaProjectinaVisualLISPApplication
Afteryou'vemadechangestoanapplication'ssourcefiles,you'llwanttoincorporatethosechangesintheapplication'sexecutablefile.MakingApplicationModulesshowedyouhowtokeepindividualapplicationfilessynchronized,sothattheapplicationexecutablecontainedthelatestversionsofallitssourcefiles.Definingtheapplicationfilesasmembersofasingleprojectsimplifiesthisprocessfurther.Insteadoflistingeverysourcefileinyourapplication'sMakefile,youcanpointtotheVLISPprojectfileandusetheprojectfiletoidentifyyoursourcefiles.
TodefineanapplicationthatincludesaVisualLISPproject
1. ChooseFile MakeApplication NewApplicationWizardfromtheVLISPmenutostarttheMakeApplicationwizard.
2. SelectExpertmode,thenpressNext.
3. IdentifythedirectorypathinwhichyouwantVLISPtosaveyourapplicationfiles,andenteranamefortheapplication.ChooseNexttocontinue.
4. ChooseNexttoacceptthedefaultapplicationoptions.
5. IntheLISPFilestoIncludedialogbox,clickthepull-downmenutotherightoftheAddbuttonandchooseVisualLISPprojectfileasthetypeoffiletoinclude.ChoosetheAddbuttontodisplaytheAddVisualLISPProjectFilesdialogbox.
6. Specifythe.prjfileyoucreatedfortheLesson5tutorialexample,thenpressOpentoaddthefiletoyourapplication.Alltheproject'sfileswillbeincludedintheapplication.
Page 301
ChooseNexttocontinuetothenextstepintheMakeApplicationwizard.
7. IntheResourceFilestoIncludedialogbox,clickonthepull-downtotherightoftheAddbuttonandchooseDCLfiles,thenpresstheAddbuttontodisplaythedialogboxforselectingtheDCLfiles.SelecttheDCLfileintheTutorial\VisualLISP\Lesson5directory,thenpressOpentoaddthefiletoyourapplication.ChooseNexttocontinuetheMakeApplicationwizard.
8. AcceptthedefaultoptionsintheremainingstepsandcompletetheMakeApplicationprocess.IfyouaddfilestotheVLISPprojectyouincludedinyourapplication,thenewfilesareautomaticallyincludedthenexttimeyoubuildtheapplication.
Pleasesendusyourcommentaboutthispage
Page 302
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>
OptimizingApplicationCode
TheoptimizationfeaturesofVLISPcanproducemoreefficientcompiledfiles,andareusefulasyourprogramsgrowinsizeandcomplexity.WiththeVLISPprojectmanagementfeature,youcantailortheoptimizationoptionstothespecificneedsofyourapplication.
DefiningBuildOptionsChoosingaCompilationModeChoosingaLinkModeUnderstandingSafeOptimization
Pleasesendusyourcommentaboutthispage
Page 303
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>
DefiningBuildOptions
VLISPprovidesanumberofoptionsforcompilingandlinkingaproject'ssourcecodethataffecttheefficiencyofthecompiledcode.Forexample,youcanspecifywhethertocreateaseparateFASfileforeachsourcefileormergeallcompiledfilesintoasingleFASfile.Youcanchoosetohavethecompilerremovethenamesofalllocalsymbolsfromyourcompiledfiles.YouspecifytheseoptionsintheProjectPropertiesdialogbox.
Tospecifyprojectbuildoptions
1. Opentheprojectfile(chooseProject OpenProjectfromtheVLISPmenu).
2. ChoosetheProjectPropertiesbuttonintheProjectwindowtoolbar.
3. SelecttheBuildOptionstabintheProjectPropertiesdialogbox.VLISPdisplaystheBuildOptionsdialogbox:
Page 304
Someofthebuildoptionsrequireextensivebackgroundinformation,whichisprovidedinthefollowingsectionsofthischapter.Thebuildoptionsare:
CompilationMode
Choosebetweenstandardandoptimizedcompilation.Optimizedcompilationcreatessmallerandfasterprogramsbutisnotsuitedforeveryproject.SeeChoosingaCompilationModeformoreinformationonthistopic.
MergeFilesMode
TellthecompilerwhethertocreateaseparateFASfileforeachsourcefile,ortomergeallcompiledfilesintoasingleFASfile.AsingleFASfileisfastertoloadandisrequiredforcertaintypesofoptimization.Sometimes,however,youwillprefertoloadyourcodeonefileatatime.Thisisimportantifyouhavenotcompletedthedebuggingormodificationoftheapplication'scode.FASfilesdonotallowsourcecodedebugging,soitisrecommendedthatyoucompileyourcodeonlyaftertheinitialdebuggingisdone.
EditGlobalDeclarations
Page 305
Createoreditaglobaldeclarationsfilefortheproject.ThisfeatureisprovidedforcompatibilitywiththePreviewversionofVLISP.
FASDirectory
Specifythedirectoryforcompiledfiles.Ifyouindicatearelativepath,VLISPappliesitinrelationtotheproject'shomedirectory.Ifyouleavethefieldblank,VLISPplacescompiledfilesinthesamedirectoryastheprojectdefinition(.prj)file.
TmpDirectory
Specifythedirectoryforproject-relatedtemporaryfiles.Arelativepathisappliedinrelationtotheproject'shomedirectory.
LinkMode
Specifyhowfunctioncallsaretobeoptimized.Thisoptionisonlyavailableifoptimizedcompilationisselected.Choosefromthefollowing:
Donotlink:Thisresultsinindirectlinkingoffunctions.Thecompilerstorestheaddressofthesymbolnamingthefunction.
Link:Ifselected,thecompilerdirectlyaddressesfunctiondefinitionsandallcallswherethefunctionsarereferenced.
Internal:Thisdirectlylinksfunctioncallsandremoves(drops)thefunctionnamesfromtheresultingFASfiles.
SeeChoosingaLinkModeforfurtherinformationontheseoptions.
LocalizeVariables
Ifthisoptionisselected,thecompilerremoves(drops)thenamesofalllocalsymbolsfromcompiledfilesanddirectlylinkstheirreferences,whereverpossible.Thismeanstheprogramcodepointstotheaddresswhereavariableisstored,nottoasymbolusedtofindtheaddressofthevariable.
SafeOptimize
Ifthisoptionisselected,thisoptiondirectsthecompilertorefusesometypesofoptimization,ifthereisachancetheywillresultinincorrectcode.Formoreinformationonoptimization,seeChoosingaCompilationModebelow.
MessageMode
Page 306
SelectthelevelofdetailyouwantVLISPtoproduceinitscompilationreports.Youcanchoosetoreceiveareportshowingonlyfatalerrors(thosecausingcompilationfailure),areportshowingerrorsandwarningmessages,orafullreportshowingerrors,warnings,andcompilerstatistics.
Pleasesendusyourcommentaboutthispage
Page 307
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>
ChoosingaCompilationMode
Combiningcompiledcodefrommultiplefilestoasinglebinaryfileallowsthecompilertoaddahighlevelofoptimization.Italsomeansthattherearemorechoicestomake.
Whenproducingstandard,non-optimizedbinarycode,theVLISPcompilerpreservesthesymbolnamesassociatedwithfunctionsandglobalvariables,becausethesesymbolsmaybereferencedfromotherfiles.Whenthesymbolisreferenced,VLISPlooksinatabletodeterminewhatareainmemoryisassignedtothesymbol.
Whenoptimizingcode,theVLISPcompilerassumesallfilesinaprojectworktogethertoformacompleteapplication.Thisallowsthecompilertodiscardthesymbolnamesand,whenexecutingthecode,jumpdirectlytothememorylocationcontainingthevalueassociatedwiththesymbol.
AnalyzingforOptimizationCorrectness
Pleasesendusyourcommentaboutthispage
Page 308
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>ChoosingaCompilationMode>
AnalyzingforOptimizationCorrectness
Optimizingcodemayintroducebugstosoftwarethatrunsperfectlywhennon-optimized.Also,thelevelofperformancegaindependshighlyontheinternalstructureofthesourcecode.LISPisalanguageinwhichyoucaneasilywriteprogramsthatcreateormodifyfunctionsatruntime.Thisuseofthelanguagebydefinitioncontradictscompile-timeoptimization.
TheVLISPcompileranalyzesthecodeitcompilesandlinks,thenitcreatesareportpointingyoutoallsourcecodesegmentsthatmaycauseproblemswhenoptimized.Ifyoudonotreceiveanyoptimizationwarningmessages,youcanassumeoptimizationdidnotintroducenewproblemstoyourcode.
ThecompilerisabletodetectmostproblematicsituationsinAutoLISPcode.However,therearesituationsinwhichitisimpossibletodetectcodethatmaybecomeincorrectduringtheoptimization.Ifyourprogramusesoneofthefollowingconstructs,thecompilerwillnotbeabletoprovecorrectnessoftheoptimizedcodedefinitively:
InteractionwithexternalObjectARXapplicationsthatsetorretrieveAutoLISPvariables
DynamiccallstofunctionsdefinedbyotherObjectARXapplications
Evaluationofdynamicallybuiltcodeusingeval,apply,mapcar,orload
Useofsettosetdynamicallysuppliedvariables
Dynamic(programevaluated)actionstringsinaction_tileandnew_dialog
Rememberthatanyoptimizationwillchangeprogramsemantics.Thecompiler
Page 309
intendstopreservethebehaviorofprojectcomponentsrelativetooneanother.Thecompilercannotguaranteeunchangedbehaviorbetweenyourprojectandexternalprocedures.Typicaleffectsofoptimizationincludethefollowing:
OuterapplicationsandtheVLISPConsolewindowloseaccesstoprogramfunctionsandsymbols.
FunctionsavailablefromtheConsolewindowininterpretermodeareunknownincompiledmode.
FunctionsareavailablefromtheConsolewindow,butredefiningthemdoesnotchangetheprogram'sbehavior.
Pleasesendusyourcommentaboutthispage
Page 310
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>
ChoosingaLinkMode
IfyouinstructtheVLISPcompilertolinkfunctionsinyourprojectdirectly,thecompilertriestoresolveallexplicitfunctioncallsbyreferencingthefunction'sdefinitioninmemory.Incontrast,whenyouindirectlylinkyourfunctions,thecompilercreatesreferencestosymbolsthatVLISPlaterusestolookuptheactualmemorylocationofthefunction.Directlinkingimprovestheperformanceofthecompiledcodeandprotectsthecodeagainstfunctionredefinition.However,ifyourapplicationneedstoredefineafunction,youcannotdirectlylinkthatfunction.
Oncefunctioncallsaredirectlylinked,thecompilercanoptimizeonelevelfurtherbydroppingthefunctionnamecompletelysothatthefunctionbecomesinvisibletousers.Toselectthisfeature,choosetheInternalLinkmodeoption.NotethatsymbolsexportedtoAutoCAD(forexample,functionnamesstartingwithC:)areneverdropped.
Pleasesendusyourcommentaboutthispage
Page 311
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>
UnderstandingSafeOptimization
ChoosingtheSafeOptimizeoptionreducestheamountofcompileroptimizationbutprotectsyourcodeagainstcompiler-inducederrors.Safeoptimizingpreventsruntimeuncertaintythatcouldcauseanoptimizedprogramtofail,eventhoughthesourcecodeseemstobecorrect.Forexample,imaginethefollowingsituation:
Thefunctionsymbolfishlipsisdefinedbydefunandusedsomewhereinyourcode.Thisisatypicalcandidateforlinkoptimization.
Inanothersegmentofyourcode,avariablenamedfishlipsisassignedusing(setqfishlipsexpression).
Nowtherearetwopossibleconditions.Ifthevalueassignedthroughsetqisintendedtoalterthedefinitionofthefunctionfishlips,directlinkingwillpreventthisfromhappening.Thefirstdefinitionwillbereferenceddirectlyandcannotbechangedbythesetqfunction.Ontheotherhand,iftheidenticalnamesarehandledindependently,fishlipscanbelinkedwithoutcreatingincorrectcode.
Ifsafeoptimizingison,thecompilerwillalwaysstayonthesafeside,evenifyouexplicitlyrequestthatfishlipsbedirectlylinked.Thismayresultinlessefficientcode,butitensurescodecorrectness.Ifsafeoptimizingisoff,youcanoverridethecompiler'srecommendationtolinkfishlipsindirectly.Youareresponsibleforthelinkoption.
TheSafeOptimizemodeisonbydefault.Besureyoufullyunderstandtheconsequencesbeforeyouturnitoff.
OptimizationConditionsBypassedbySafeOptimizationSafeOptimizationWarningMessages
Page 312
CompilerCheckingofOptimizingConditions
Pleasesendusyourcommentaboutthispage
Page 313
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>UnderstandingSafeOptimization>
OptimizationConditionsBypassedbySafeOptimization
WhenSafeOptimizationisineffect,theVLISPcompilerignoresanoptimizationoptionifitdeterminesthatadheringtotheoptionmayinduceanerrorcondition.Thefollowinglistidentifiestheconditionsunderwhichanoptionisignored:
Link
IfthecompilerencountersthefollowingsituationswhileSafeOptimizeison,itignoresanyrelatedLinkdirective:
Asymbolisboundasaparameteranywhereintheproject.
Asymbolisboundasanauxiliaryvariableandreferencedbyvalueanywhereintheproject.
Asymbolisexplicitlyassignedsomewhere(bysetq).
Drop
Ifthecompilerencountersasymbolreferencedbyvalue,itignoresanyDropdirectiveforthesymbol.
Localize
Ifthecompilerencountersthefollowingsituationswhilesafeoptimizeison,itignorestheLocalizedirectiveorthecorrespondingvariable:
Avariablehasanon-localreferenceorassignmenttoitwithintheproject.
Avariableiscalledbyname.
Page 314
Pleasesendusyourcommentaboutthispage
Page 315
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>UnderstandingSafeOptimization>
SafeOptimizationWarningMessages
Ifoptimizedcompilationisonandthecompilerfindsaconditionthatforbidsacertainlevelofoptimization,itissuesawarningmessage.Forexample,ifthefunctionfishlipscannotbelinkedbecausethecompilerfoundtwodefinitionsforthefunction,you'llsee:
;***WARNING:CannotLINKfishlips;
TwoDEFUNsfound.
SeeAnotherDEFUN
Right-clickonawarningmessagetoopenashortcutmenu.Inadditiontodisplayingsymbolcommands,themenuallowsyoutoviewthesourcecodeassociatedwiththemessage.Double-clickonthehighlightedmessagetoshowthesourcecode.Tobrowseallsourcefilesrelatedtothecompilermessages,pressF11repeatedly,orpressSHIFT+F11toreturntothefirstmessage.
Eachlineofthepreviouswarningmessageguidesyoutoadifferentcodesegment.Forexample:
;***WARNING:CannotLINKfishlips
showsthefunctioncallthatcouldnotbelinked.
;TwoDEFUNsfound
showsthefirstdefunfoundforfunctionfishlips.
;SeeAnotherDEFUN
showstheseconddefunfoundforfunctionfishlips.
WhenthecompilerworksinSafeOptimizationmodeandfindsaproblem
Page 316
condition,thewarningstartswith:
;***WARNING:Safe:Cannot…
IfSafeOptimizationisoff,butmessagemodeissettoFullreport,thesamewarningsareprefixedby:
;***WARNING:Dangerous…
IfyoudisableSafeOptimizemode,theseproblematicconditionsresultincompilerwarnings.
Pleasesendusyourcommentaboutthispage
Page 317
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>MaintainingVisualLISPApplications>OptimizingApplicationCode>UnderstandingSafeOptimization>
CompilerCheckingofOptimizingConditions
Thecompileralwayschecksforoptimizingconsistency.Ifyouspecifyanoptimizationoptionthatcontradictscertainsecurityrules,thecompilerwillissuewarningmessages.Thesecurityrulesare:
Link
ThecompilerdirectlylinksAutoLISPfunctioncallsonlyifthefollowingconditionsaremet:
Thefunctionisdefinedonlyonce,orispredefinedbyAutoLISPandnouserdefunredefinesit.
Thefunctionnamedoesnotappearintheparameterlistofanotherfunction.
Thefunctionisnotassignedanywhereintheproject.
Drop
Thecompilertriestodropafunctionsymbolonlyifallcorrespondingfunctioncallsaredirectlylinkedtothefunctiondefinition.Thecompilerdoesnotdropthesymbolforafunctiondefinitioniftheprogramcallsthefunctionbyitssymbolname.Afunctioniscalledbysymbolinthefollowingcases:
Thesymbolappearsinavl-acad-defundeclaration.
ThefunctionwascalledfromanACTION_TILEactionstring.
Thefunctionsymbolisaquotedargumentforapply,mapcar,orevalsomewhereintheproject.
Notethatforfunctionscalledfromtop-levelexpressions,theDropdeclarationwillbeignoredwithoutwarningmessages.
Page 318
Localize
Thecompilerdoesnotlocalizeavariableinboundlistsofdefun,lambda,andforeachexpressionsifanyofthefollowingconditionsaretrue:
Thevariablehasanon-localreference(orassignment)toitwithintheoutertop-levelexpression.
Thevariableiscalledasafunctionbyname.
Thevariablesymbolappearsasafunctioncallsomewhereinthetop-levelread-evalloop.
Otherthantheseconditions,whichalwayscanceltheoptimizationandresultinwarningmessages,thereareotherconditionsthatmayormaynotresultinincorrectcode.ChoosetheSafeOptimizeoptionfortheprojecttodisallowtheseconditionsaswell.DisablingSafeOptimizationresultsincompilerwarningsiftheseconditionsaremet.SeeUnderstandingSafeOptimizationformoreinformationonthistopic.
Pleasesendusyourcommentaboutthispage
Page 319
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
WorkingwithActiveX
WithVisualLISP,youcanaccesstheAutoCADobjectmodel.
VisualLISP®notonlymakesprogramdevelopmenteasierandfaster,italsoprovidesnewfunctionalitytoAutoLISP®applications.Forexample,youcanuseVLISPtoaccessActiveX®objectsfromAutoLISPcode.YoucanalsouseActiveXtointeractwithotherWindowsapplicationsthatsupportActiveXmethodology.
UsingActiveXObjectswithAutoLISPUnderstandingtheAutoCADObjectModelAccessingAutoCADObjectsUsingVisualLISPFunctionswithActiveXMethodsUsingActiveXtoInteractwithOtherApplications
Pleasesendusyourcommentaboutthispage
Page 320
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>
UsingActiveXObjectswithAutoLISP
ActiveXAutomationisawaytoworkprogrammaticallywiththecontentsofanAutoCAD®drawing.Inmanyinstances,ActiveXworksfasterthantraditionalAutoLISPfunctionsinmanipulatingAutoCADdrawingobjects.
TheActiveXprogramminginterfaceisusableinanumberoflanguagesandenvironments.WhenyouworkwithActiveXobjectsinAutoLISP,youworkwiththesameobjectmodel,properties,andmethodsthatcanbemanipulatedfromotherprogrammingenvironments.
ObjectsarethemainbuildingblocksofanActiveXapplication.Insomeways,youarealreadyfamiliarwiththisnotion.Forexample,AutoCADdrawingitemssuchaslines,arcs,polylines,andcircleshavelongbeenreferredtoasobjects.ButintheActiveXschema,thefollowingAutoCADcomponentsarealsorepresentedasobjects:
Stylesettings,suchaslinetypesanddimensionstyles
Organizationalstructures,suchaslayers,groups,andblocks
Thedrawingdisplay,suchastheviewandviewport
Thedrawing'smodelspaceandpaperspace
EventhedrawingandtheAutoCADapplicationitselfareconsideredobjects.
Note ToaccessdrawingpropertiessuchasTitle,Subject,Author,andKeywords,theIAcadSummaryInfointerface,accessibleasapropertyoftheDocumentobjectintheAutoCADobjectmodel,mustbeused.Formoreinformation,seeAccessingDrawingProperties.
ActiveXincludesmuchofthefunctionalityprovidedbystandardAutoLISPfunctionssuchasentget,entmod,andsetvar.Comparedtothesefunctions,ActiveXrunsfasterandprovideseasieraccesstoobjectproperties.
Page 321
Forexample,toaccesstheradiusofacirclewithstandardAutoLISPfunctions,youmustuseentgettoobtainalistofentitiesandassoctofindthepropertyyouwant.Youmustalsoknowthecodenumber(DXFkeyvalue)associatedwiththatpropertytoobtainitwithassoc,asshowninthefollowingexample:
(setqradius(cdr(assoc40(entgetcircle-entity))))
WithanActiveXfunction,yousimplyaskfortheradiusofacircleasfollows:
(setqradius(vla-get-radiuscircle-object))
Pleasesendusyourcommentaboutthispage
Page 322
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>
UnderstandingtheAutoCADObjectModel
AutoCADobjectsarestructuredinahierarchicalfashion,withtheApplicationobjectattheroot.Theviewofthishierarchicalstructureisreferredtoastheobjectmodel.Itshowsyouwhichobjectprovidesaccesstothenextlevelofobjects.TheAutoCADobjectmodelisdescribedinthefollowingfigure:
Page 324
UsingActiveXisnotalwaysamatterofchoice.Forexample,youmustuseActiveXtoaccessdrawingobjectsfromreactorcallbackfunctions.You'lllearnmoreaboutthisinAttachingReactorstoAutoCADDrawings.
ObjectPropertiesObjectMethodsCollectionsofObjects
Pleasesendusyourcommentaboutthispage
Page 325
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UnderstandingtheAutoCADObjectModel>
ObjectProperties
AllobjectsintheAutoCADobjectmodelhaveoneormoreproperties.Forexample,acircleobjectcanbedescribedbypropertiessuchasradius,area,orlinetype.Anellipseobjectalsohasareaandlinetypeproperties,butitcannotbedescribedintermsofitsradius.Rather,youdescribeitintermsofitsmajortominoraxisratio,apropertynamedRadiusRatio.PropertynamesarenecessarywhenaccessingAutoCADdatathroughActiveXfunctions.
Pleasesendusyourcommentaboutthispage
Page 326
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UnderstandingtheAutoCADObjectModel>
ObjectMethods
ActiveXobjectsalsocontainmethods,whicharesimplytheactionsavailableforaparticularkindofobject.SomemethodscanbeappliedtomostAutoCADdrawingobjects.Forexample,theMirrormethod(creatingamirrorimagecopyofanobjectaroundamirroraxis),andtheMovemethod(movingadrawingobjectalongaspecifiedvector)canbeappliedtomostdrawingobjects.Bycontrast,theOffsetmethod,whichcreatesanewobjectataspecifieddistancefromanexistingobject,appliesonlytoafewclassesofAutoCADobjectssuchasArc,Circle,Ellipse,andLine.
InVLISP,ActiveXmethodsareimplementedasAutoLISPfunctions.You'llseemanyreferencestoActiveXfunctionsinVLISPdocumentation,butkeepinmindthatinActiveXterminology,theyarealwaysknownasmethods.
TodeterminewhichmethodsandpropertiesapplytoaspecifictypeofAutoCADobject,refertotheActiveXandVBAReference.ThisreferenceisavailablefromtheVLISPandAutoCADHelpmenus,orbyopeningtheacadauto.chmfileintheAutoCADHelpdirectory.
YouwillprobablywanttoleavetheActiveXandVBAReferenceopenwhenyouaredevelopingVLISPprogramsthatuseActiveX.Ifyouopentheacadauto.chmfilefromtheAutoCADHelpdirectory,youcankeepthereferenceopenwhenyouuseVLISPonlineHelp.
Note YoucanaccesstheHelptopicforavlax-orvla-functionbyhighlightingthetextofthefunctionintheVLISPeditorandclickingtheHelpbuttonontheToolstoolbar.
Pleasesendusyourcommentaboutthispage
Page 327
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UnderstandingtheAutoCADObjectModel>
CollectionsofObjects
AllobjectsintheAutoCADobjectmodelaregroupedincollections.Forexample,theBlockscollectionismadeupofallblocksinanAutoCADdrawing,andtheModelSpacecollectioncomprisesallgraphicalobjects(circles,lines,polylines,andsoon)inthedrawing'smodelspace.Collectionsarelabeledintheobjectmodeldiagram.
Pleasesendusyourcommentaboutthispage
Page 328
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>
AccessingAutoCADObjects
TheApplicationobjectistherootobjectfortheAutoCADobjectmodel.FromtheApplicationobject,youcanaccessanyoftheotherobjects,orthepropertiesormethodsassignedtoobjects.
BeforeyoucanuseActiveXfunctionswithAutoLISP,youneedtoloadthesupportingcodethatenablesthesefunctions.IssuethefollowingfunctioncalltoloadActiveXsupport:
(vl-load-com)
ThisfunctionfirstchecksifActiveXsupportisalreadyloaded;ifso,thefunctiondoesnothing.IfActiveXsupportisnotalreadyloaded,vl-load-comloadsActiveXandotherVisualLISPextensionstotheAutoLISPlanguage.
Note AllapplicationsthatuseActiveXshouldbeginbycallingvl-load-com.Ifyourapplicationdoesnotcallvl-load-com,theapplicationwillfail,unlesstheuserhasalreadyloadedActiveXsupport.
AfterloadingtheActiveXsupportfunctions,thefirststepinaccessingAutoCADobjectsistoestablishaconnectiontotheAutoCADApplicationobject.Usethevlax-get-acad-objectfunctiontoestablishthisconnection,asinthefollowingexample:
(setqacadObject(vlax-get-acad-object))
Thevlax-get-acad-objectfunctionreturnsapointertotheAutoCADApplicationobject.Intheexampleabove,thepointerisstoredintheacadObjectvariable.ThisreturnvalueexistsasauniqueVLISPdatatypecalledVLA-object(VLISPActiveXobject).
WhenyourefertoAutoCADobjectswithActiveXfunctions,youmustspecifya
Page 329
VLA-objecttype.Forthisreason,youcannotuseentgettoaccessanobjectandthenrefertothatobjectwithanActiveXfunction.Theentgetfunctionreturnsanobjectofdatatypeename.AlthoughyoucannotusethisobjectdirectlywithanActiveXfunction,youcanconvertittoaVLA-objectusingthevlax-ename->vla-objectfunction.(SeeConvertingObjectReferences.)
UsingtheInspectTooltoViewObjectPropertiesMovingForwardfromtheApplicationObjectSummarizingtheProcessPerformanceConsiderations
Pleasesendusyourcommentaboutthispage
Page 330
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>AccessingAutoCADObjects>
UsingtheInspectTooltoViewObjectProperties
ToviewthepropertiesassociatedwithanApplicationobject,youcanselectthevariablethatpointstotheobject(acadobject,inthepreviousexample),andchoosetheInspectbuttonontheVLISPViewtoolbarasfollows:
YoucanreadilyidentifymanyofthepropertieslistedintheVLA-objectInspectwindow.Forexample,FullNameisthefilenameoftheAutoCADexecutablefile,VersionisthecurrentAutoCADversion,andCaptionisthecontentsoftheAutoCADwindowtitlebar.An[RO]followingapropertynameindicatesthepropertyisread-only;youcannotchangeit.
Anypropertyidentifiedasa#<VLA-OBJECT...>referstoanotherAutoCADActiveXobject.LookatthePreferencesproperty,forexample.IfyourefertothediagramoftheAutoCADobjectmodel,you'llseethatthePreferencesobjectisjustbelowtheApplicationobjectinthemodelhierarchy.Toviewthepropertiesassociatedwithanobject,double-clicktheobjectlineintheInspectwindow(orright-clickandchooseInspect).HereistheInspectwindowforthePreferences
Page 331
object:
YoumaynoticethatthepropertiesofthePreferencesobjectcorrespondtothetabsontheAutoCADOptionsdialogbox.Double-clickontheFilespropertytodisplaythefollowingInspectwindow:
IfyoucomparethepropertiesshowninthiswindowtotheoptionsavailableundertheFilestabintheAutoCADOptionsdialogbox,you'llbeabletoseetheconnectionbetweenthetwo.ThefollowingfigureshowstheFilesoptions:
Page 332
Forexample,theAutoSavePathpropertycorrespondstotheAutomaticSaveFileLocationoption,andtheHelpFilePathpropertywouldbeasub-optionundertheMenu,Help,andMiscellaneousFileNamesoption.
You'lllearnhowtouseActiveXfunctionstoaccessobjectsandmodifypropertiesinUsingVisualLISPFunctionswithActiveXMethods.
Pleasesendusyourcommentaboutthispage
Page 333
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>AccessingAutoCADObjects>
MovingForwardfromtheApplicationObject
FollowingtheAutoCADobjectmodelhierarchy,theActiveDocumentpropertyoftheApplicationobjectleadsyoutoaDocumentobject.ThisDocumentobjectrepresentsthecurrentAutoCADdrawing.ThefollowingAutoLISPcommandreturnstheactivedocument:
(setqacadDocument(vla-get-ActiveDocumentacadObject))
TheDocumentobjecthasmanyproperties.Accesstonon-graphicalobjects(layers,linetypes,andgroups,forexample)isprovidedthroughlike-namedpropertiessuchasLayers,Linetypes,andGroups.TogettothegraphicalobjectsintheAutoCADdrawing,youmustaccesseitherthedrawing'smodelspace(throughtheModelSpaceproperty)orpaperspace(throughthePaperSpaceproperty).Forexample:
(setqmSpace(vla-get-ModelSpaceacadDocument))
Atthispoint,youhaveaccesstotheAutoCADdrawingandcanaddobjectstothedrawing.Forexample,youcanaddacircletothemodelspacewiththefollowingcommand:
(setqmycircle(vla-addCirclemSpace
(vlax-3d-point'(3.03.00.0))2.0))
Pleasesendusyourcommentaboutthispage
Page 334
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>AccessingAutoCADObjects>
SummarizingtheProcess
Inthissection,yousawcodeexamplesthatledtothedrawingofacircleobjectinanAutoCADdrawingusingActiveXAutomation.Thefollowingsequenceoffunctioncallswasused:
(vl-load-com)
(setqacadObject(vlax-get-acad-object))
(setqacadDocument(vla-get-ActiveDocumentacadObject))
(setqmSpace(vla-get-ModelSpaceacadDocument))
(setqmycircle(vla-addCirclemSpace
(vlax-3d-point'(3.03.00.0))2.0))
Thestatementsinthisexampleaccomplishedthefollowing:
LoadedAutoLISPActiveXsupportfunctions.
ReturnedapointertotheApplicationobject.
ObtainedapointertothecurrentactiveDocumentobject,usingtheActiveDocumentpropertyoftheApplicationobject.ThisprovidedaccesstothecurrentAutoCADdrawing.
ObtainedapointertotheModelSpaceobject,usingtheModelSpacepropertyoftheDocumentobject.
DrewacircleintheModelSpace.
ThehierarchicalpathtraversedintheAutoCADobjectmodelispicturedbelow:
Page 335
Pleasesendusyourcommentaboutthispage
Page 336
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>AccessingAutoCADObjects>
PerformanceConsiderations
RepeatedcallstoaccesstheAutoCADApplication,activeDocument,andModelSpaceobjectsshouldbeavoided,astheynegativelyimpactperformance.Youshoulddesignyourapplicationstoobtaintheseobjectsonetime,andrefertotheobtainedobjectpointersthroughouttheapplication.
ThefollowingcodeexamplesillustratethreefunctionsyoucandefinetoreturntheApplication,activeDocument,andModelSpaceobjects,respectively:
(setq*acad-object*nil);Initializeglobalvariable
(defunacad-object()
(cond(*acad-object*);Returnthecachedobject
(t
(setq*acad-object*(vlax-get-acad-object))
)
)
)
(setq*active-document*nil);Initializeglobalvariable
(defunactive-document()
(cond(*active-document*);Returnthecachedobject
(t
(setq*active-document*(vla-get-activedocument(acad-object)))
)
)
)
(setq*model-space*nil);Initializeglobalvariable
(defunmodel-space()
(cond(*model-space*);Returnthecachedobject
(t
(setq*model-space*(vla-get-modelspace(active-document)))
)
)
)
Forexample,youcandrawacircleusingthefollowingfunctioncall:
Page 337
(vla-addCircle(model-space)(vlax-3d-point'(3.03.00.0))2.0)
Themodel-spacefunctionreturnsthemodelspaceoftheactivedocument,usingtheactive-documentfunctiontoaccesstheDocumentobject,ifnecessary.Theactive-documentfunction,inturn,callsacad-objecttoobtaintheApplicationobject,ifnecessary.
Pleasesendusyourcommentaboutthispage
Page 338
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>
UsingVisualLISPFunctionswithActiveXMethods
VLISPaddsasetoffunctionstotheAutoLISPlanguagethatprovidesaccesstoActiveXobjects.Thefunctionnamesareprefixedwithvla-:forexample,vla-addCircle,vla-get-ModelSpace,vla-getColor.Thesefunctionscanbefurthercategorizedasfollows:
vla-functionscorrespondtoeveryActiveXmethod.Usethesefunctionstoinvokethemethod(forexample,vla-addCircleinvokestheAddcirclemethod).
vla-get-functionscorrespondtoeveryproperty,enablingyoutoretrievethevalueofthatproperty(forexample,vla-get-Colorobtainsanobject'scolorproperty).
vla-put-functionscorrespondtoeveryproperty,enablingyoutoupdatethevalueofthatproperty(forexample,vla-put-Colorupdatesanobject'scolorproperty).
VLISPalsoaddsasetofActiveX-relatedfunctionswhosenamesareprefixedwithvlax-.ThesearemoregeneralActiveXfunctions,eachofwhichcanbeappliedtonumerousmethods,objects,orproperties.Forexample,withthevlax-get-propertyfunction,youcanobtainanypropertyofanyActiveXobject.IfyourdrawingcontainscustomActiveXobjects,orifyouneedtoaccessobjectsfromotherapplications,suchasaMicrosoftExcelspreadsheet,youcanusethevlax-invoke-method,vlax-get-property,andvlax-put-propertyfunctionstoaccesstheirmethodsandproperties;you'llseeexamplesusingthesefunctionsinUsingActiveXwithoutImportingaTypeLibrary.
DeterminingtheVisualLISPFunctionYouNeedDeterminingHowtoCallaFunction
Page 339
ConvertingAutoLISPDataTypestoActiveXDataTypesViewingandUpdatingObjectPropertiesUsingActiveXMethodsThatReturnValuesinArgumentsListinganObject'sPropertiesandMethodsWorkingwithCollectionObjectsReleasingObjectsandFreeingMemoryConvertingObjectReferencesHandlingErrorsReturnedbyActiveXMethods
Pleasesendusyourcommentaboutthispage
Page 340
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
DeterminingtheVisualLISPFunctionYouNeed
TheVLISPActiveXfunctionsactuallyprovideaccesstoActiveXmethods.Forexample,lookatthefollowingAutoLISPstatement,whichwasenteredattheVLISPConsoleprompt:
_$(setqmycircle(vla-addCircle
mSpace
(vlax-3d-point
'(3.03.00.0))2.0))#<VLA-OBJECTIAcadCircle03ad067c>
Thiscommandaddsacircletoadrawing,usingtheAddcirclemethod.Thefunctioncalledtodrawthecircleisvla-addCircle.
IfyoudonotknowwhatfunctionaddsacircletoanAutoCADdrawing,youcanfigureitoutbylookingintheActiveXandVBAReference.IfyoulookupthedefinitionforaCircleobject,here'swhattheentrylookslike:
Page 341
Sometimes,asinthisCircleentry,thereisdescriptivetextthatidentifiesthemethodyouneed.Often,though,you'llneedtolookthroughthelistofmethodstofindtheonethatmatchestheactionyouwanttotake.
Onceyoufindthenameofthemethod,addavla-prefixtothemethodnametogetthenameoftheVLISPfunctionthatimplementsthemethod.Inthisexample,itisvla-AddCircle.NoteinVLISPthefunctionnameisnotcase-sensitive;vla-addcircleisthesameasvla-AddCircle.
Pleasesendusyourcommentaboutthispage
Page 342
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
DeterminingHowtoCallaFunction
OnceyouidentifytheVLISPfunctionyouneed,youstillmustdeterminehowtocallthefunction.Youneedtoknowtheargumentstospecifyandthedatatypeofthosearguments.TheActiveXandVBAReferencecontainstheinformationrequiredforcodingcallstoActiveXfunctions.
Forexample,fromthereferencepagefortheCircleobject,choosetheAddCirclehyperlinktoviewthedefinitionofthismethod:
Page 343
NotethatyoucanalsogettothispagebychoosingtheMethodsbuttonnearthetopoftheHelpwindow,thenchoosingAddCirclefromalistofmethods.
ThesyntaxdefinitionsinthereferenceweredesignedforVisualBasic6users,sotheymaytakesomegettingusedto.ForAddCircle,thesyntaxisdefinedasfollows:
RetVal=object.AddCircle(Center,Radius)
Substitutingthevariablenamesusedinthischapter'sexamples,thesyntaxis:
mycircle=mspace.AddCircle(Center,Radius)
TheAutoLISPsyntaxrequiredforthesameoperationis:
Page 344
(setqmyCircle(vla-addCirclemSpace
(vlax-3d-point'(3.03.00.0))2.0))
Thereturnvalue(RetVal,inVisualBasic6)isstraightforward.TheActiveXandVBAReferencedefinesthisasaCircleobject.InVLISP,wheneveranAutoCADobjectisreturnedbyanActiveXfunction,itisstoredasaVLAobjectdatatype.
Theobjectreferredtobeforethemethodname(object.AddCircle)isalwaysthefirstargumentinavlafunctioncall.ThisistheAutoCADobjectyouareviewingormodifying.Forexample,addacircletothedrawingmodelspacewiththefollowing:
(vla-addCirclemSpace...)
Inthisexample,mspacereferstotheModelSpaceobject.RecallfromthediscussionontheAutoCADobjectmodel(inAccessingAutoCADObjects),thatyouusethepropertiesofoneAutoCADobjecttoaccessanotherobjectinahierarchicalmanner.TheModelSpaceobjectprovidesaccesstothemodelspaceofthecurrentdrawing.
TheCenterandRadiusargumentsrefertodatatypesthatmaybeunfamiliartoLISPusers.Thefollowingsectionexplainsthesedatatypes.
NotethatsomeActiveXmethodsrequireargumentsthataredescribedasoutputonly.SeeUsingActiveXMethodsThatReturnValuesinArgumentsforinformationonhowtocodethesearguments.
Pleasesendusyourcommentaboutthispage
Page 345
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
ConvertingAutoLISPDataTypestoActiveXDataTypes
Whenaddingacircletoadrawing,youmustspecifythecenterpointofthecircleandtheradiusofthecircle.InthedefinitionfortheAddCirclemethodintheActiveXandVBAReference,theseargumentsarereferredtoasCenterandRadius.Centerisdefinedasavariant(three-elementarrayofdoubles),andRadiusislistedasadouble:
RetVal=object.AddCircle(Center,Radius)
Elements
Center
Variant(three-elementarrayofdoubles);inputonly.A3DWCScoordinatespecifyingthecircle'scenter.
Radius
Double;inputonly.Theradiusofthecircle.Mustbeapositivenumber.
Thereferenceexplainswhattheseparametersareusedfor,butthedatatypesindicatedfortheseparametersmaybeunfamiliartoLISPusers.Variantsareessentiallyself-definingstructuresthatcancontaindifferenttypesofdata.Forexample,strings,integers,andarrayscanallberepresentedbyvariants.Storedalongwiththedataisinformationidentifyingthetypeofdata.Thisself-definingfeaturemakesvariantsusefulforpassingparameterstoActiveXservers,becauseitenablesserversbasedonanylanguagetounderstandthedatavalue.
WorkingwithVariantsWorkingwithSafearraysUsingSafearrayswithVariants
Page 346
ConvertingOtherAutoLISPDataTypesforActiveXMethods
Pleasesendusyourcommentaboutthispage
Page 347
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingAutoLISPDataTypestoActiveXDataTypes>
WorkingwithVariants
SeveralAutoLISPfunctionsallowyoutocreateandworkwithvariants:
vlax-make-variantcreatesavariant.
vlax-variant-typereturnsthedatatypeofavariant.
vlax-variant-valuereturnsthevalueofavariantvariable.
vlax-variant-change-typechangesthedatatypeofavariantvariable.
Thevlax-make-variantfunctionacceptstwoarguments:valueandtype.Thevalueargumentisthevaluetobeassignedtothevariant.Thetypeargumentspecifiesthetypeofdatatobestoredinthevariant.Fortype,specifyoneofthefollowingconstants:
vlax-vbEmpty
Uninitialized(defaultvalue)
vlax-vbNull
Containsnovaliddata
vlax-vbInteger
Integer
vlax-vbLong
Longinteger
vlax-vbSingle
Single-precisionfloating-pointnumber
Page 348
vlax-vbDouble
Double-precisionfloating-pointnumber
vlax-vbString
String
vlax-vbObject
Object
vlax-vbBoolean
Boolean
vlax-vbArray
Array
Theconstantsevaluatetointegervalues.Becausetheintegervaluescanchange,youshouldalwaysrefertotheconstant,nottheintegervalue.Seetheentryforvlax-make-variantintheAutoLISPReferenceforthecurrentintegervalueassignedtoeachconstant.
Forexample,thefollowingfunctioncallcreatesanintegervariantandsetsitsvalueto5:
_$(setqvarint(vlax-make-variant
5vlax-vbInteger))#<variant25>
Thereturnvalueindicatesthevariant'sdatatype(2,whichisvbInteger)andthevariant'svalue(5).
Ifyoudonotspecifyadatatypetovlax-make-variant,thefunctionassignsadefaulttype.Forexample,thefollowingfunctioncallcreatesavariantandassignsitavalueof5butdoesnotspecifyadatatype:
_$(setqvarint(vlax-make-variant
5))#<variant35>
Bydefault,vlax-make-variantassignedthespecifiedintegervaluetoaLongIntegerdatatype,notInteger,asyoumightexpect.Whenassigninga
Page 349
numericvaluetoavariant,youshouldexplicitlystatethedatatypeyouwant.Refertovlax-make-variantintheAutoLISPReferenceforacompletelistofdefaulttypeassignments.
Ifyoudonotspecifyavalueordatatype,vlax-make-variantallocatesanuninitialized(vlax-vbEmpty)variant.
Pleasesendusyourcommentaboutthispage
Page 350
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingAutoLISPDataTypestoActiveXDataTypes>
WorkingwithSafearrays
ArrayspassedtoActiveXmethodsmustbeofthesafearraytype.Thesearraysaresafebecauseyoucannotaccidentallyassignvaluesoutsidethearrayboundsandcauseadataexceptiontooccur.Usethevlax-make-safearrayfunctiontocreateasafearrayandusevlax-safearray-put-elementorvlax-safearray-filltopopulateasafearraywithdata.
Thevlax-make-safearrayfunctionrequiresaminimumoftwoarguments.Thefirstargumentidentifiesthetypeofdatathatwillbestoredinthearray.Specifyoneofthefollowingconstantsforthedatatype:
vlax-vbInteger
Integer
vlax-vbLong
Longinteger
vlax-vbSingle
Single-precisionfloating-pointnumber
vlax-vbDouble
Double-precisionfloating-pointnumber
vlax-vbString
String
vlax-vbObject
Object
vlax-vbBoolean
Page 351
Boolean
vlax-vbVariant
Variant
Theconstantsevaluatetointegervalues.Becausetheintegervaluescanchange,youshouldalwaysrefertotheconstant,nottheintegervalue.Seetheentryforvlax-make-safearrayintheAutoLISPReferenceforthecurrentintegervalueassignedtoeachconstant.
Theremainingargumentstovlax-make-safearrayspecifytheupperandlowerboundsofeachdimensionofthearray.Youcancreatesingleormultidimensionalarrayswithvlax-make-safearray.Thelowerboundforanindexcanbezerooranypositiveornegativeinteger.
Forexample,thefollowingfunctioncallcreatesasingle-dimensionarrayconsistingofdoubles,withastartingindexof0:
_$(setqpoint(vlax-make-safearray
vlax-vbDouble'(0.2)))#<safearray...>
Theupperboundspecifiedinthisexampleis2,sothearraywillholdthreeelements(element0,element1,andelement2).
Differentdimensionscanhavedifferentbounds.Forexample,thefollowingfunctioncallcreatesatwo-dimensionarrayofstrings.Thefirstdimensionstartsatindex0andcontainstwoelements,whiletheseconddimensionstartsatindex1andcontainsthreeelements:
_$(setqmat2(vlax-make-safearray
vlax-vbString'(0.1)'(1.3)))#<safearray...>
Youcanuseeithervlax-safearray-fillorvlax-safearray-put-elementtopopulatearrayswithdata.
Usingvlax-safearray-fill
Thevlax-safearray-fillfunctionrequirestwoarguments:thevariablecontainingthearrayyouarepopulatingandalistofthevaluestobeassignedto
Page 352
thearrayelements.Youmustspecifyasmanyvaluesasthereareelementsinthearray.Forexample,thefollowingcodepopulatesasingle-dimensionarrayofthreedoubles:
(vlax-safearray-fillpoint'(1001000))
Youcandisplaythecontentsofthisarrayinlistformwiththevlax-safear-ray->listfunction:
_$(vlax-safearray->list
point)(100.0100.00.0)
Ifyoudonotspecifyavalueforeveryelementinthearray,vlax-safear-ray-fillresultsinanerror.
Toassignvaluestoamulti-dimensionalarray,specifyalistofliststovlax-safearray-fill,witheachlistcorrespondingtoadimension.Forexample,thefollowingcommandassignsvaluestoatwo-dimensionarrayofstringsthatcontainsthreeelementsineachdimension:
_$(vlax-safearray-fill
mat2'(("a""b""c")("d""e""f")))#<safearray...>
Usethevlax-safearray->listfunctiontoconfirmthecontentsofmat2:
_$(vlax-safearray->list
mat2)(("a""b""c")("d""e""f"))
Usingvlax-safearray-put-element
Thevlax-safearray-put-elementfunctioncanbeusedtoassignvaluestooneormoreelementsofasafearray.Thenumberofargumentsrequiredbythisfunctiondependsonthenumberofdimensionsinthearray.Thefollowingrulesapplytospecifyingargumentstovlax-safearray-put-element:
Thefirstargumentalwaysnamesthesafearraytowhichyouareassigningavalue.
Page 353
Thenextsetofargumentsidentifiesindexvaluespointingtotheelementtowhichyouareassigningavalue.Forasingle-dimensionarray,specifyoneindexvalue;foratwo-dimensionarray,specifytwoindexvalues,andsoon.
Thefinalargumentisalwaysthevaluetobeassignedtothesafearrayelement.
Forexample,thefollowingcodepopulatesasingle-dimensionarrayofthreedoubles:
(vlax-safearray-put-elementpoint0100)
(vlax-safearray-put-elementpoint1100)
(vlax-safearray-put-elementpoint20)
Tochangethesecondelementofthearraytoavalueof50,issuethefollowingcommand:
(vlax-safearray-put-elementpoint150)
Thefollowingexamplepopulatesatwo-dimensionarrayofstrings.Thefirstdimensionofthearraystartsatindex0,whiletheseconddimensionstartsatindex1:
(vlax-safearray-put-elementmat201"a")
(vlax-safearray-put-elementmat202"b")
(vlax-safearray-put-elementmat203"c")
(vlax-safearray-put-elementmat211"d")
(vlax-safearray-put-elementmat212"e")
(vlax-safearray-put-elementmat213"f")
Youcanusevlax-safearray->listtoconfirmthecontentsofthearray:
_$(vlax-safearray->list
mat2)(("a""b""c")("d""e""f"))
Pleasesendusyourcommentaboutthispage
Page 354
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingAutoLISPDataTypestoActiveXDataTypes>
UsingSafearrayswithVariants
SafearraydatamustbepassedtoActiveXmethodsthroughvariants.Thatis,youcreateasafearray,thenyouassignthesafearraytoavariantbeforepassingittoamethod.Formethodsthatrequireyoutopassathree-elementarrayofdoubles(typicallytospecifyapoint),youcanusethevlax-3d-pointfunctiontobuildtherequireddatastructure.Forexample,thefollowingcalltakesalistofpointsandconvertsthelistintoanarrayofthreedoubles:
_$(setqcircCenter
(vlax-3d-point'(3.03.00.0)))#<variant8197...>
Youcanalsopassvlax-3d-pointtwoorthreenumbers,insteadofalist.Forexample:
$(setqcircCenter
(vlax-3d-point3.03.0))#<variant8197...>
Whenyouomitthethirdpointfromyourargument,vlax-3d-pointsetsittozero.Youcanusevlax-safearray->listtoverifythecontentsofthevariablesetbyvlax-3d-point:
$(vlax-safearray->list
(vlax-variant-valuecirccenter))(3.03.00.0)
Thevlax-TMatrixfunctionperformsasimilartaskfortransformationmatrices,whicharerequiredbythevla-TransformByfunction.Itbuildsthetransformationmatrixfromfourlistsoffournumberseach,convertingall
Page 355
numberstoreals,ifnecessary.Forexample:
_$(vlax-tmatrix'((1
110)(1230)(2345)(2983)))#<variant8197...>
Ifyouneedtocreateavariantforanarraycontaininganythingotherthanthreedoublesoratransformationmatrix,youmustbuildityourself.
Tocreateavariantcontaininganarrayoffourdoubles
1. Allocatespaceforthearray:
(setq4dubs(vlax-make-safearray
vlax-vbDouble'(0.3)))
2. Populatethearray:
(vlax-safearray-fill
4dubs'(3.06.07.21.0))
3. Storethesafearrayinavariant:
(setqvar4dubs(vlax-make-variant
4dubs))
Thevar4dubsvariablenowcontainsavariantcontaininganarrayofdoubles.
Pleasesendusyourcommentaboutthispage
Page 356
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingAutoLISPDataTypestoActiveXDataTypes>
ConvertingOtherAutoLISPDataTypesforActiveXMethods
TheRadiusargumenttotheAddCirclemethodrequiresaDouble,buttheActiveXfunctionsmakethenecessaryconversionifyouspecifyarealinAutoLISP.ThefollowingtableidentifiestheAutoLISPdatatypethatActiveXfunctionswillacceptinplaceoftherequiredActiveXdatatype.EachrowinthetablerepresentsadatatypeusedbyActiveXfunctions.EachcolumninthetablerepresentsanAutoLISPdatatype.Wherevertheintersectingcellscontainaplus(+)symbol,youcanspecifythecorrespondingAutoLISPdatatypefortherequiredActiveXdatatype.
AutoLISPdatatypesacceptedinplaceofanActiveXdatatype
Integer Real String VLA-object Variant Safe-
array
:vlax-true
:vlax-false
Byte +
Boolean +
Integer +
Long +
Single + +
Page 357
Double + +
Object +
String +
Variant +
Array +
InsomeinstancesanAutoLISPActiveXfunctionwillacceptandconvertadatatypethatisnotindicatedasacceptablebytheprecedingtable,butyoushouldnevercountonthis.
Pleasesendusyourcommentaboutthispage
Page 358
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
ViewingandUpdatingObjectProperties
VLISPprovidesAutoLISPfunctionsforreadingandupdatingobjectproperties.Youcanusethesefunctionstoobtainthepropertiesofexistingdrawingobjects(forexample,thecenterpointofacircle),andtomodifydrawingobjects(forexample,movingthecenterpointofthecircle).
ReadingObjectPropertiesUpdatingObjectPropertiesDeterminingWhetheranObjectIsAvailableforUpdating
Pleasesendusyourcommentaboutthispage
Page 359
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ViewingandUpdatingObjectProperties>
ReadingObjectProperties
Functionsthatreadobjectpropertiesarenamedwithavla-getprefixandrequirethefollowingsyntax:
(vla-get-propertyobject)
Forexample,vla-get-centerreturnsthecenterpointofacircle.
Toobtainanobject'spropertyandapplythepropertytoanewobject
1. EnterthefollowingattheVLISPConsoleprompt:
(setqmyCircle(vla-addcircle
mspace(vlax-3d-point
(getpoint"\nPick
thecenterpointforacircle:"))2.0))
Thisfunctioncallpromptsyoutopickacenterpointforacircle,theninvokestheAddcirclemethodtodrawthecircle.Thevlax-3d-pointfunctionconvertsthepointyoupickintothedatatyperequiredbyvla-addcir-cle.
2. Usevla-get-centertodrawasecondcircleconcentrictothefirst:
(vla-addCirclemSpace
(vla-get-centermyCircle)1.0)
TheAutoCADdrawingwindownowcontainsthefollowingobjects:
Page 360
Pleasesendusyourcommentaboutthispage
Page 361
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ViewingandUpdatingObjectProperties>
UpdatingObjectProperties
Functionsthatupdatepropertiesareprefixedwithvla-putandusethefollowingsyntax:
(vla-put-propertyobjectnew-value)
Forexample,vla-put-centerchangesthecenterpointofacircle.
TochangetheXaxisofacircle
1. Obtainthecurrentcenterpointofthecircle:
_$(setqmyCenter(vla-get-center
myCircle))#<variant8197
Thecenterpointisreturnedinavariantoftypesafearray.Thesafearraycontainsthreedoubles(X,Y,andZcoordinates).
2. Savethecenterpointinlistform:
$(setqcenterpt(vlax-safearray->list
(vlax-variant-value
myCenter)))(17.86855.027810.0)
Convertingthecenterpointfromavariantsafearraytoalistmakesiteasiertomodifythecoordinates.
3. Subtract1fromtheXaxisofthecenterpoint:
Page 362
_$(setqnewXaxis(-
(carcenterpt)1))16.8685
TheresultissavedinvariablenewXaxis.
4. Constructanewpointlistforthecenterpoint,usingthenewXaxisandtheoriginalYandZvalues:
_$(setqnewcenter(list
newXaxis(cadrcenterpt)
(caddrcenterpt)))(16.86854.525940.0)
Theconstructedlistissavedinvariablenewcenter.
5. Usevla-put-centertoupdatethecirclewiththenewXaxis:
_$(vla-put-centermyCircle
(vlax-3d-pointnewcenter))nil
Notethatthiscommandusesvlax-3d-pointtoconvertthenewcenterpointlistintothedatatyperequiredbyvla-put-center.TheAutoCADdrawingwindowshowstheresult:
Notethatchanginganobject'spropertymaynotimmediatelyaffectthedisplayoftheobjectintheAutoCADdrawing.AutoCADdelayspropertychangestoallowyoutochangemorethanonepropertyatatime.Ifyouneedtoupdatethedrawingwindowexplicitly,issuethevla-updatefunction:
(vla-updateobject)
Page 363
Sometimesyoucanusepre-definedconstantstoupdateanobject'sproperty.Forexample,tosetthefillcolorofacircletored,youcanusetheconstantacRedinsteadofspecifyinganumericindexvalue:
(vla-put-colormyCircleacRed)
TheActiveXandVBAReferencelistsanypredefinedconstantsundertheentrydescribingtheproperty.YoucanusetheseconstantsinVLISPActiveXfunctioncalls.
Pleasesendusyourcommentaboutthispage
Page 364
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ViewingandUpdatingObjectProperties>
DeterminingWhetheranObjectIsAvailableforUpdating
IfotherapplicationsareworkingwithanyAutoCADobjectsatthesametimeasyourprogram,thoseobjectsmaynotbeaccessible.Thisisespeciallyimportanttolookoutforifyourapplicationincludesreactors,becausereactorsexecutecodesegmentsinresponsetoexternaleventsthatcannotbepredictedinadvance(seeAttachingReactorstoAutoCADDrawings).Evenasimplethingsuchasalockedlayercanpreventyoufromchanginganobject'sproperties.
VLISPprovidesthefollowingfunctionstotesttheaccessibilityofanobjectbeforetryingtousetheobject:
vlax-read-enabled-ptestswhetheryoucanreadanobject.
vlax-write-enabled-pdetermineswhetheryoucanmodifyanobject'sproperties.
vlax-erased-pcheckstoseeifanobjecthasbeenerased.Erasedobjectsmaystillexistinthedrawingdatabase.
ThesetestfunctionsreturnTiftrue,niliffalse.Thefollowingexamplestestalineobject:
Determinewhetherthelineisreadable:
$(vlax-read-enabled-p
WhatsMyLine)T
Determinewhetherthelineismodifiable:
$(vlax-write-enabled-p
WhatsMyLine)
Page 365
T
Seeifthelinehasbeenerased:
$(vlax-erased-pWhatsMyLine)nil
EraseWhatsMyLine:
_$(vla-deleteWhatsMyLine)nil
Issuevlax-read-enabled-ptoseeifWhatsMyLineisstillreadable:
$(vlax-read-enabled-p
WhatsMyLine)nil
Issuevlax-erased-pagaintoconfirmtheobjectwasdeleted:
$(vlax-erased-pWhatsMyLine)T
Pleasesendusyourcommentaboutthispage
Page 366
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
UsingActiveXMethodsThatReturnValuesinArguments
SomeActiveXmethodsrequirethatyousupplythemwithvariablesintowhichthemethodscanplacevalues.TheGetBoundingBoxmethodisanexampleofthistypeofmethod.HereishowitisdefinedintheActiveXandVBAReference:
Page 367
NotethattheMinPointandMaxPointparametersaredescribedasoutputonly.Youmustprovideoutputargumentsasquotedvariablenames.ThefollowingexampleshowsaVLISPfunctioncalltoreturntheminimumandmaximumboundingpointsofacircle:
_$(vla-getboundingbox
myCircle'minpoint'maxpoint)nil
Thevaluesoutputbyvla-getboundingboxarestoredintheminpointandmaxpointvariablesassafearraysofthreedoubles.Youcanviewthevaluesusingvlax-safearray->list:
_$(vlax-safearray->list
minpoint)(1.01.0-1.0e-008)
_$(vlax-safearray->list
maxpoint)(5.05.01.0e-008)
NotethatthequotedsymbolparametersyoupasstothefunctionbecomeAutoLISPvariablesjustliketheonescreatedthroughsetq.Becauseofthis,youshouldincludethemaslocalvariablesinyourfunctiondefinitionsotheydonotbecomeglobalvariablesbydefault.
Pleasesendusyourcommentaboutthispage
Page 368
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
ListinganObject'sPropertiesandMethods
Earlierinthischapter,youlearnedhowtousetheVLISPInspecttooltodisplayanobject'sproperties.Anotherwaytoviewanobject'spropertiesistocallthevlax-dump-objectfunction.YoucaninvokethisfunctionfromtheVLISPConsolewindoworfromanapplicationprogram.Thevlax-dump-objectfunctionprintsalistofthepropertiesofthespecifiedobjectandreturnsT.Forexample,thefollowingcodeobtainsthelastobjectaddedtothemodelspace,thenissuesvlax-dumpObjecttoprinttheobject'sproperties:
_$(setqWhatsMyLine
(vla-itemmSpace(-(vla-get-countmspace)1)))#<VLA-OBJECTIAcadLWPolyline036f1d0c>
_$(vlax-dump-object
WhatsMyLine);IAcadLWPolyline:AutoCADLightweightPolylineInterface
;Propertyvalues:
;Application(RO)=#<VLA-OBJECTIAcadApplication00a4ae24>
;Area(RO)=2.46556
;Closed=0
;Color=256
;ConstantWidth=0.0
;Coordinate=...Indexedcontentsnotshown...
;Coordinates=(8.499177.0015511.29963.7313714.85.74379...)
;Database(RO)=#<VLA-OBJECTIAcadDatabase01e3da44>
;Elevation=0.0
;Handle(RO)="53"
;HasExtensionDictionary(RO)=0
;Hyperlinks(RO)=#<VLA-OBJECTIAcadHyperlinks01e3d7d4>
;Layer="0"
;Linetype="BYLAYER"
;LinetypeGeneration=0
;LinetypeScale=1.0
;Lineweight=-1
;Normal=(0.00.01.0)
;ObjectID(RO)=28895576
Page 369
;ObjectName(RO)="AcDbPolyline"
;PlotStyleName="ByLayer"
;Thickness=0.0
;Visible=-1
T
Thereisanoptionalsecondargumentyoucansupplytovlax-dump-objectthatcausesittoalsolistallthemethodsthatapplytotheobject.Simplyspecify“T”followingtheobjectname:
(vlax-dump-objectWhatsMyLineT)
Notethatvlax-dump-objectdisplaystheinformationinthewindowfromwhichyouissuedthecommand.However,thefunctionreturnsTtothecallingprogram,nottheinformationdisplayedintheCommandwindow.
DeterminingIfaMethodorPropertyAppliestoanObject
Pleasesendusyourcommentaboutthispage
Page 370
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ListinganObject'sPropertiesandMethods>
DeterminingIfaMethodorPropertyAppliestoanObject
Tryingtouseamethodthatdoesnotapplytothespecifiedobjectwillresultinanerror.Tryingtoreferenceapropertythatdoesnotapplytoanobjectalsoresultsinanerror.Ininstanceswhereyouarenotsurewhatapplies,usethevlax-method-applicable-pandvlax-property-available-pfunctionstotesttheobjects.ThesefunctionsreturnTifthemethodorpropertyisavailablefortheobject,andnilifitisnot.
Thesyntaxforvlax-method-applicable-pis:
(vlax-method-applicable-pobjectmethod)
ThefollowingcommandcheckstoseeiftheCopymethodcanbeappliedtotheobjectreferencedbyWhatsMyLine:
_$(vlax-method-applicable-p
WhatsMyLine"Copy")T
ThefollowingcommanddetermineswhetherornottheAddBoxmethodcanbeappliedtotheobject:
_$(vlax-method-applicable-p
WhatsMyLine"AddBox")nil
Forvlax-property-available-p,thesyntaxis:
(vlax-property-available-pobjectproperty[T])
Forexample,thefollowingcommandsdetermineifColorandCenterare
Page 371
propertiesofWhatsMyLine:
_$(vlax-property-available-p
WhatsMyLine"Color")T
_$(vlax-property-available-p
WhatsMyLine"Center")nil
Supplyingtheoptional“T”argumenttovlax-property-available-pchangesthemeaningofthetest.Ifyousupplythisargument,thefunctionreturnsTonlyiftheobjecthasthepropertyandthepropertycanbemodified.Iftheobjecthasnosuchpropertyorthepropertyisread-only,vlax-property-available-preturnsnil.Forexample,anellipsecontainsanAreaproperty,butyoucannotupdateit.Ifyoucheckthepropertywithoutspecifyingtheoptionalargument,theresultisT:
_$(vlax-property-available-p
myEllipse"area")T
Ifyousupplytheoptionalargument,theresultisnil:
_$(vlax-property-available-p
myEllipse"area"T)nil
Pleasesendusyourcommentaboutthispage
Page 372
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
WorkingwithCollectionObjects
TheconceptofcollectionswasintroducedinUnderstandingtheAutoCADObjectModelRecallthatallActiveXobjectsintheAutoCADobjectmodelaregroupedincollections.Forexample,theBlockscollectionismadeupofallblocksinanAutoCADdocument.VLISPprovidesfunctionstohelpyouworkwithcollectionsofAutoCADobjects.Thesefunctionsarevlax-map-collectionandvlax-for.
Thevlax-map-collectionfunctionappliesafunctiontoeveryobjectinacollection.Thesyntaxis:
(vlax-map-collectioncollection-objectfunction)
Forexample,thefollowingcommanddisplaysallpropertiesofeveryobjectinadrawing'smodelspace:
$(vlax-map-collection
(vla-get-ModelSpaceacadDocument)'vlax-dump-Object);IAcadLWPolyline:AutoCADLightweightPolylineInterface
;Propertyvalues:
;Application(RO)=#<VLA-OBJECTIAcadApplication00b3b91c>
;Area(RO)=3.67152
;Closed=-1
;Color=256
;Coordinates=(9.592474.448729.258145.347154.19915.679...)
;EntityName(RO)="AcDbPolyline"
;EntityType(RO)=24
;Handle(RO)="4C"
;Layer="0"
;.
;.
;.
;Thickness=0.0
;Visible=-1
Page 373
(Notethattheprecedingexampledoesnotshoweverypropertyreturnedbyvlax-dump-Object.)
Toevaluateaseriesoffunctionswitheachobjectinacollection,usevlax-for:
(vlax-forsymbolcollection[expressions]...)
Liketheforeachfunction,vlax-forreturnstheresultofthelastexpressionevaluatedinsidetheforloop.Notethatmodifyingthecollection(thatis,addingorremovingmembers)whileiteratingthroughitmaycauseanerror.
Thefollowingexampledefinesafunctionthatusesvlax-fortoshowcolorstatisticsforeachobjectintheactivedrawing:
(defunshow-Color-Statistics(/objectColorcolorSublistcolorList)
(setqmodelSpace(vla-get-ModelSpace
(vla-get-ActiveDocument(vlax-get-Acad-Object))
)
)
(vlax-forobjmodelSpace
(setqobjectColor(vla-get-Colorobj))
(if(setqcolorSublist(assocobjectColorcolorList))
(setqcolorList
(subst(consobjectColor(1+(cdrcolorSublist)))
colorSublist
colorList
)
)
(setqcolorList(cons(consobjectColor1)colorList))
)
)
(ifcolorList
(progn(setq
colorList(vl-sortcolorList
'(lambda(lst1lst2)(<(carlst1)(carlst2)))
)
)
(princ"\nColorList=")
(princcolorList)
(foreachsubListcolorList
(princ"\nColor")
(princ(carsubList))
(princ"isfoundin")
(princ(setqcount(cdrsubList)))
(princ"object")
(princ(if(=count1)
Page 374
"."
"s."
)
))))
(princ)
)
Thisfunctionlistseachcolorinthedrawingandthenumberofobjectswherethecolorisfound.
RetrievingMemberObjectsinaCollection
Pleasesendusyourcommentaboutthispage
Page 375
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>WorkingwithCollectionObjects>
RetrievingMemberObjectsinaCollection
TheItemmethodretrievesamemberobjectfromacollection.TheCountpropertyshowsthenumberofitemsinacollection.UsingtheItemmethodandCountproperty,youcanindividuallyprocesseachobjectinacollection.Forexample,youcanlookateachobjectinamodelspace,determinethetypeofobject,andprocessonlythetypesofobjectsyouareinterestedin.Thefollowingcodeprintsthestartangleforeacharcobjectinamodelspace:
(setqindex0)
(repeat(vla-get-countmspace)
(if(="AcDbArc"(vla-get-objectname(vla-itemmspaceindex)))
(progn
(princ"\nThestartangleofthearcis")
(princ(vla-get-startangle(vla-itemmspaceindex)))
)
)
(setqindex(+index1))
)
NotethatItemandCountalsoapplytogroupsandselectionsets.
Pleasesendusyourcommentaboutthispage
Page 376
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
ReleasingObjectsandFreeingMemory
JustasyoucanhavedifferentvariablespointingtothesameAutoCADentity,youcanhavemultipleVLA-objectspointingtothesamedrawingobject.YoucancomparetwoVLA-objectswiththeequalfunction,whichreturnsTifbothobjectspointtothesamedrawingobject.
AslongasaVLA-objectpointstoadrawingobject,AutoCADwillkeepallthememoryneededfortheobject.Whenyounolongerneedtoreferenceanobject,usethevlax-release-objectfunctiontoindicatethistoAutoCAD:
(vlax-release-objectobject)
Afterreleasinganobject,itisnolongeraccessiblethroughtheVLA-objectpointer.Thisissimilartoclosingafile.Nomemoryisnecessarilyfreedwhenyouissuevlax-release-object,butAutoCADcanreclaimthememoryifneeded,onceallreferencestotheobjecthavebeenreleased.
Totestwhetherornotanobjecthasbeenreleased,usethevlax-object-released-pfunction:
(vlax-object-released-pobject)
ThisfunctionreturnsTiftheobjecthasbeenreleased,nilifithasnot.
Pleasesendusyourcommentaboutthispage
Page 377
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
ConvertingObjectReferences
ThereareanumberofwaystorefertoAutoCADdrawingobjectswithAutoLISP.Theseincludethefollowing:
VLA-objects,returnedbyActiveXfunctions
Entitynames(enames),returnedbyentgetandentsel,identifyingobjectsinanopendrawing
Handles,returnedbyhandent,whichentitiesretainacrossAutoCADsessions
ObjectIDs,usedbyARXtoidentifyobjects
AutoLISPprovidesfunctionstoconvertfromonetypeofobjectidentifiertoanother.
ConvertingbetweenEnamesandVLA-objectsObtainingOneObjectIdentifierfromAnother
Pleasesendusyourcommentaboutthispage
Page 378
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingObjectReferences>
ConvertingbetweenEnamesandVLA-objects
Thevlax-ename->vla-objectfunctionallowsyoutoconvertentitynames(enames)obtainedthroughfunctions,suchasentget,toVLA-objectsyoucanusewithActiveXfunctions.Forexample,thefollowingcodesetsavariabletoanename,thenusesvlax-ename->vla-objecttoconverttheenametoaVLA-object:
_$(setqename-circle
(car(entsel"\nPickaCircle:")))<Entityname:27f0538>
_$(setqvlaobject-circle
(vlax-ename->vla-objectename-circle))#<VLA-OBJECTIAcadCircle03642c24>
ToconvertVLA-objectstoenames,usevlax-vla-object->ename.Forexample:
$(setqnew-ename-circle
(vlax-vla-object->enamevlaobject-circle))<Entityname:27f0538>
Pleasesendusyourcommentaboutthispage
Page 379
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>ConvertingObjectReferences>
ObtainingOneObjectIdentifierfromAnother
Youmayfindthesamedrawingobjectrepresentedbydifferentidentifiersanddatatypessuchasahandlestring,anename,aVLA-object,oranObjectARXobjectIDinteger.Toobtaintheidentifierwiththedatatypeyourprogramrequires,usethefollowingstrategies:
Tofindthehandleassociatedwithanename,usetheDXF5groupoftheename'sassociationlist:_$(setqhandle-circle(cdr(assoc5(entget
ename-circle))))
"4F"
Tofindtheenameassociatedwithahandle,usethehandentfunction:_$(handenthandle-circle)
<Entityname:27f0538>
TofindtheVLA-objectassociatedwithahandle,usethevla-handleToObjectfunction:_$(setqvla-circle(vla-handleToObject
acadDocument
handle-circle))
#<VLA-OBJECTIAcadCircle03642c24>
TofindthehandleassociatedwithaVLA-object,usevla-get-handletoobtainthehandleproperty:_$(vla-get-handlevla-circle)
"4F"
Page 380
TofindtheObjectARXobjectIDofaVLA-object,usevla-get-objectidtogettheobjectIDproperty:_$(setqobjid-Circle(vla-get-objectidvla-
circle))
41878840
TofindtheVLA-objectidentifiedbyanObjectARXobjectID,usetheObjectID-toObjectmethodontheAutoCADDocumentobject:_$(vla-ObjectIDtoObjectacadDocumentobjid-
circle)
#<VLA-OBJECTIAcadCircle03642c24>
Pleasesendusyourcommentaboutthispage
Page 381
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingVisualLISPFunctionswithActiveXMethods>
HandlingErrorsReturnedbyActiveXMethods
WhenActiveXmethodsfail,theyraiseexceptionsratherthanreturningerrorvaluesthatyourprogramcaninterpret.IfyourprogramusesActiveXmethods,youmustprepareittocatchexceptions,otherwisetheprogramhalts,leavingtheuserataCommandprompt.Youcanusevl-catch-all-applytointercepterrorsreturnedbyActiveXmethods.
TointercepterrorsreturnedbyActiveXmethods
1. Loadthefollowingfunctionandinvokeitbyissuing(init-motivate)attheVLISPConsoleprompt:
(defuninit-motivate()
(vl-load-com)
(setqmspace
(vla-get-modelspace
(vla-get-activedocument(vlax-get-acad-object))
)
)
(vla-addraymspace(vlax-3d-point000)(vlax-3d-point110))
)
Thisfunctionaddsarayobjecttothecurrentmodelspace.Arayhasafinitestartingpointandextendstoinfinity.
2. TheGetBoundingBoxmethodobtainstwopointsofaboxenclosingaspecifiedobject,returningthosepointsinvariablesyousupplytothemethod.(SeeUsingActiveXMethodsThatReturnValuesinArgumentsforanexampleusingthis.)Thefollowingcodeobtainsapointertothelastobjectaddedtoadrawing'smodelspaceandusesvla-getboundingboxtoobtainthepointsenclosingtheobject:
(defunbnddrop(/bbox)
Page 382
(setqbbox(vla-getboundingbox
(vla-itemmspace(-1(vla-get-countmspace)))
'll
'ur
)
)
(list"Dosomethingwithboundingbox."bbox)
)
Loadthiscodeandrunitbyissuing(bnddrop)attheConsoleprompt.Becausearayextendstoinfinity,itisnotpossibletoencloseitwithabox,andGetBoundingBoxresultsinthefollowingerror:
;error:AutomationError.Invalidextents
Ifthiscodewerepartofyourapplicationprogram,executionwouldhaltatthispoint.
3. Byinvokingvla-getboundingboxthroughthevl-catch-all-applyfunction,youcanintercepterrorsreturnedbyActiveX.Loadthefollowingcodeandrunitbyissuing(bndcatch)attheConsoleprompt:
(defunbndcatch(/bbox)
(setqbbox(vl-catch-all-apply
'vla-getboundingbox
(list(vla-itemmspace(-1(vla-get-countmspace)))
'll
'ur
)
)
)
(if(vl-catch-all-error-pbbox)
(list"Exception:"(vl-catch-all-error-messagebbox))
(list"Dosomethingwithboundingbox."bbox)
)
)
Thisfunctionusesvl-catch-all-applytocallvla-getboundingbox.Itpassesvl-catch-all-applytwoarguments:thesymbolnamingthefunctionbeingcalled('vla-getboundingbox)andalistofargumentstobepassedtovla-getboundingbox.IftheGetBoundingBoxmethodcompletessuccessfully,vl-catch-all-applystoresthereturnvalueinvariablebbox.Ifthecallisunsuccessful,vl-catch-all-apply
Page 383
storesanerrorobjectinbbox.Atthispointinthebnddropfunction,vla-getboundingboxwasissueddirectly,anerrorresulted,andexecutionhalted.Butinbndcatch,vl-catch-all-applyinterceptstheerrorandprogramexecutioncontinues.Acalltovl-catch-all-error-pchecksthereturnvaluefromvl-catch-all-applyandreturnsTifitisanerrorobject,nilotherwise.Ifthereturnvalueisanerrorobject,asitwouldbeinthisexample,thefunctionissuesvl-catch-all-error-messagetoobtainthemessagefromtheerrorobject.Programexecutioncontinuesfromthispoint.CatchingErrorsandContinuingProgramExecutionincludesanon-ActiveXexamplethatusesthevl-catch-*functionstointercepterrors.Foradditionalinformationonthesefunctions,seetheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 384
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>
UsingActiveXtoInteractwithOtherApplications
ThepowerofActiveXextendsbeyondtheabilitytointeractwithstandardAutoCADobjects.VisualLISPprovidesAutoLISPfunctionsthatallowyoutoaccessobjectsfromotherapplicationsthatsupportActiveX.Forexample,youcanopenaMicrosoft®Worddocument,retrievetextdatafromanAutoCADdrawing,andcopythetextintotheWorddocument.OryoumightaccesscellsinaMicrosoftExcelspreadsheetandusethedatawithyourAutoCADdrawing.
TowriteAutoLISPcodethatinteractswithotherActiveXapplications,you'llneedtorefertothedocumentationforthoseapplicationstolearntheapplication'sobjectnamesandhowtoworkwithitsmethodsandproperties.Typically,theonlineHelpforanActiveX-enabledWindowsapplicationcontainsinformationonitsActiveXinterface.Forexample,AutoCADprovidestheActiveXandVBAReference,aswellastheActiveXandVBADeveloper'sGuideforworkingwithActiveXusingVisualBasicforApplications(VBA).
ThefollowingtopicsinthissectionapplywhenyouworkwithanyActiveXapplicationfromAutoLISP.ThecodeexamplesillustratetheprocessofobtainingtextfromanAutoCADdrawingandtheninsertingthetextintoaMicrosoftWorddocument.
ImportingaTypeLibraryEstablishingaConnectiontoanApplicationCodingaSampleApplicationUsingActiveXwithoutImportingaTypeLibrary
Pleasesendusyourcommentaboutthispage
Page 385
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>
ImportingaTypeLibrary
VLISPprovidesanAutoLISPfunctionthatallowsyoutoimportthetypelibraryoftheActiveXapplicationyouwanttoaccess.Whenyouimportatypelibrary,AutoCADcreatesasetofwrapperfunctionsthatprovideaccesstotheapplication'smethodsandproperties.Infact,thevla-functionsyouhaveseensofararewrapperfunctionscreatedfortheAutoCADtypelibrary.
Usethevlax-import-type-libraryfunctiontoimportatypelibrary.Whencallingthisfunction,identifythetypelibraryandtellAutoCADwhatprefixestouseinnamingthewrapperfunctionsfortheapplication'smethodsandproperties.Alsospecifyaprefixfortheapplication'sconstants.Thevlax-import-type-libraryfunctiontakesthefollowingsyntax:
(vlax-import-type-library:tlb-filenamefilename
[:methods-prefixmprefix:properties-prefixpprefix:constants-prefixc
Thefilenameargumentisastringthatnamesthetypelibrary.Ifyoudonotspecifyapath,AutoCADlooksforthefileinthesupportfilesearchpath.
Themprefixargumentspecifiestheprefixtobeusedformethodwrapperfunctions.Forexample,ifthetypelibrarycontainsaCalculatemethodandthemprefixparameterissetto"cc-",AutoCADgeneratesawrapperfunctionnamedcc-Calculate.Thisparameterdefaultsto"".
Thepprefixargumentspecifiestheprefixtobeusedforpropertywrapperfunctions,andthecprefixargumentdefinestheprefixtobeusedforconstantscontainedinthetypelibrary.Theseparametersalsodefaultto"".
Notetherequireduseofkeywordswhenpassingargumentstovlax-import-type-library.Forexample,thefollowingcodeimportsaMicrosoftWordtypelibrary,assigningtheprefixmswm-tomethods,mswp-toproperties,andmswc-toconstants:
Page 386
(if(equalnilmswc-wd100Words);checkforaWinWordconstant
(vlax-import-type-library
:tlb-filename"c:/MicrosoftOffice/Office/msword8.olb"
:methods-prefix"mswm-"
:properties-prefix"mswp-"
:constants-prefix"mswc-"
)
)
Afterimportingthetypelibrary,youcanusetheVLISPAproposfeaturetolisttheActiveXwrapperfunctionsresultingfromtheimport.Forexample,entermswmintheAproposOptionsdialogboxandselecttheMatchbyPrefixoptiontolistallMicrosoftWordActiveXmethods.
Importinganapplication'stypelibraryenablesyoutouseVLISPfeaturessuchasAproposontheapplication'spropertiesandmethods,butyoucanaccesstheapplicationevenifyoudonotimportitstypelibrary.SeeUsingActiveXwithoutImportingaTypeLibrary.
CodingHintsforUsingvlax-import-type-library
Pleasesendusyourcommentaboutthispage
Page 387
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>ImportingaTypeLibrary>
CodingHintsforUsingvlax-import-type-library
InAutoCAD,vlax-import-type-libraryisexecutedatruntimeratherthanatcompiletime.Thefollowingpracticesarerecommendedwhenusingvlax-import-type-library:
Ifyouwantyourcodetorunondifferentmachines,avoidspecifyinganabsolutepathinthetlb-filenameparameter.
Ifpossible,avoidusingvlax-import-type-libraryfrominsideanyAutoLISPexpression(inotherwords,alwayscallitfromatop-levelposition).
InyourAutoLISPsourcefile,codethevlax-import-type-librarycallbeforeanycodethatusesmethodorpropertywrappersorconstantsdefinedinthetypelibrary.
Pleasesendusyourcommentaboutthispage
Page 388
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>
EstablishingaConnectiontoanApplication
IfaninstanceofMicrosoftWordisalreadyrunningonyourPC,usevlax-get-objecttoestablishaconnectiontotheapplication.Forexample,thefollowingfunctioncallestablishesaconnectiontoaMicrosoftWordapplication,andsavesapointertotheapplicationinavariablenamedmsw:
(setqmsw(vlax-get-object"Word.Application"))
Thevlax-create-objectfunctioncreatesanewinstanceofanapplicationobject.Forexample,ifthereturnvaluefromvlax-get-objectisnil,indicatingthattherequestedapplicationdoesnotexist,youcanusevlax-create-objecttostarttheapplication.ThefollowingcallstartsMicrosoftWordandsavesapointertotheapplicationinvariablemsw:
(setqmsw(vlax-create-object"Word.Application"))
Alternatively,youcanusevlax-get-or-create-objecttoaccessanapplication.Thisfunctionattemptstoconnecttoanexistinginstanceofanapplication,andstartsanewinstanceifitdoesn'tfindone.
Theapplicationobjectdoesnotappearuntilyoumakeitvisible.YoumakeanobjectvisiblebysettingitsVisiblepropertytoTRUE.Forexample,thefollowingcallmakestheMicrosoftWordapplicationvisible:
(vla-put-visiblemsw:vlax-true)
Pleasesendusyourcommentaboutthispage
Page 389
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>
CodingaSampleApplication
Afteraccessingtheapplicationobject,theremainingAutoLISPcodeisspecifictotheapplicationyou'reworkingwithandthetasksyouwanttoaccomplish.Forexample,thefollowingfunctioncallaccessesthedocumentscollectionobjectinMicrosoftWord:
(setqdocs(vla-get-documentsmsw))
ThefollowingcommandcreatesanewWorddocument:
(setqdoc(mswm-adddocs))
ThefollowingprocedurecreatesanActiveXapplicationthatworkswithMicrosoftWord97andanAutoCADdrawingthatcontainsmtext.
TocopymtextfromanAutoCADdrawingintoaMicrosoftWorddocument
1. IssuethefollowingcommandtoensurethatAutoLISPActiveXsupportisloaded:
(vl-load-com)
2. ObtaintheAutoCADapplicationandcurrentModelSpaceobjectsandsavetheirpointers:
(setq*AcadApp*(vlax-get-acad-object));GetAutoCADapplication
(setq*ModelSpace*(vla-get-ModelSpace
(vla-get-ActiveDocument*AcadApp*)));Getmodelspace
3. ImporttheMicrosoftWordtypelibrary.Changethe:tlb-filenameargumentinthefollowingcodetopointtothemsword8.olbfileonyour
Page 390
system,thenrunthecode:
(if(equalnilmswc-wd100Words);checkforaWordconstant
(vlax-import-type-library
:tlb-filename"c:/MicrosoftOffice/Office/msword8.olb"
:methods-prefix"mswm-"
:properties-prefix"mswp-"
:constants-prefix"mswc-"
)
)
ThiscodefirstcheckstoseeifaknownMicrosoftWordconstantisdefinedwithavalue.Iftheconstanthasavalue,itisassumedthattheWordtypelibraryhasalreadybeenimportedandnofurtheractionisnecessary.Iftheconstantisnil,vlax-import-type-libraryisinvoked.
4. EstablishaconnectiontoaMicrosoftWordapplicationbyrunningthefollowingcode:
(setqmsw(vlax-get-object"Word.Application.8"))
(if(equalnilmsw)
(progn
;Wordisnotrunning.Startit.
(setqmsw(vlax-create-object"Word.Application.8"))
(vla-put-visiblemsw:vlax-true)
)
)
Thecodeissuesvlax-get-objecttoestablishaconnectiontoarunningMicrosoftWordapplication.(Inthisexample,version8—Word97—isspecified;ifthe8wereomitted,anyinstanceofWordwouldbeaccepted.)IfthereisnorunninginstanceofWord,vlax-create-objectisissuedtostartone.
5. Theremainingcodefollows.Commentsinthecodeexplaintheprocessing.
(if(/=nilmsw)
(progn
;;Getthedocumentcollectionobject.
(setqdocs(vla-get-documentsmsw))
;;Addanewdocument
(setqdoc(mswm-adddocs))
;;Gettheparagraphsofthedocument(todosomeformatting)
Page 391
(setqparagraphs(mswp-get-paragraphsdoc))
;;Nowiteratethroughthemodelspaceandexportanymtext
;;everyMtextentitytoWord.
(vlax-forent*ModelSpace*
(if(equal(vla-get-ObjectNameent)"AcDbMText")
(progn
;;GetthefollowinginformationfromtheMtextentity:
;;othetextstring
;;othelocationofacornerofthetextboundary
(setqtext(vla-get-TextStringent)
textpos(vla-get-InsertionPointent)
arrayTextpos(vlax-variant-valuetextpos)
textinfo
(strcat
(rtos(vlax-safearray-get-elementarrayTextpos0)22)
","
(rtos(vlax-safearray-get-elementarrayTextpos1)22)
","
(rtos(vlax-safearray-get-elementarrayTextpos2)22)
)
);_endofsetq
;Printsomeinfo(withformatting)
;Getthelastparagraphinthedocument
(setqpg(mswp-get-lastparagraphs))
;Obtaintherangeoftheparagraph
(setqrange(mswp-get-rangepg))
;Dosomeformatting
(mswp-put-boldrange1);bold
(mswp-put-underlinerangemswc-wdUnderlineSingle);underline
;4)Insertinfoaboutthetextattheendoftheparagraph
(mswm-InsertAfterrange
(strcat"AcDbMTextatposition"textinfo"\n"))
;Nowshowthetextstring(fromtheACADtextentity)
(setqpg(mswp-get-lastparagraphs))
(setqrange(mswp-get-rangepg))
(mswp-put-boldrange0)
(mswp-put-underlinerangemswc-wdUnderlineNone)
(mswm-InsertAfterrange(strcattext"\n\n"))
);_endofprogn
);_endofifAcDbMText
);_endofvlax-for
);_endofprogn
(princ"\nNoMicrosoftWordapplicationfound.\n")
)
LoadandrunthecodeandlookattheresultinMicrosoftWord.
Pleasesendusyourcommentaboutthispage
Page 393
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>
UsingActiveXwithoutImportingaTypeLibrary
ImportinganapplicationtypelibraryandusingtheresultingActiveXwrapperfunctionsisconvenientandprovidesaccesstoVLISPfeaturessuchasApropos,butitcomesatacost.ApplicationssuchasMicrosoftWordandMicrosoftExcelcontainhundredsofmethodsandproperties,andcreatingwrappersforeachoftheseaddsuptosignificantmemoryusage.Also,youmayneedtouseanActiveXpropertyormethodforwhichthereisnogeneratedAutoLISPwrapperfunction.Inthisinstance,andtoavoidtheoverheadinvolvedinimportingatypelibrary,VLISPprovidesthefollowingAutoLISPfunctions:
vlax-invoke-method
vlax-get-property
vlax-put-property
CallinganActiveXMethodwithvlax-invoke-methodObtaininganActiveXPropertywithvlax-get-propertyUpdatinganActiveXPropertywithvlax-put-property
Pleasesendusyourcommentaboutthispage
Page 394
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>UsingActiveXwithoutImportingaTypeLibrary>
CallinganActiveXMethodwithvlax-invoke-method
Thevlax-invoke-methodfunctioncallsanActiveXmethoddirectly.Thefunctionrequiresthefollowingarguments:
TheVLA-objectthemethodistoworkon
Asymbolorstringnamingthemethodtobecalled
Oneormoreargumentstobepassedtothemethod
Thereturnvaluefromvlax-invoke-methoddependsonthemethodbeinginvoked.
Forexample,thefollowinginvokestheAddCirclemethodtodrawacircleinthemodelspace(representedbythemspacevariable)ofthecurrentAutoCADdrawing:
_$(setqmycircle
(vlax-invoke-method
mspace'AddCirclecircCenter3.0))#<VLA-OBJECTIAcadCircle00bfd6e4>
Inthisexample,circCenterisavariant(containingathree-elementarrayofdoubles)identifyingthecenterofthecircle,and3.0istheradiusofthecircle.ThemethodreturnsaVLA-object,thecircledrawn.
Pleasesendusyourcommentaboutthispage
Page 395
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>UsingActiveXwithoutImportingaTypeLibrary>
ObtaininganActiveXPropertywithvlax-get-property
Thevlax-get-propertyfunctionreturnsthepropertyofanobject.Thefunctionrequiresthefollowingarguments:
AVLA-objectidentifyingtheobjectwhosepropertyyouareinterestedin
Asymbolorstringnamingthepropertytoberetrieved
Forexample,thereisnowrapperfunctionavailabletoobtaintheCommandBarspropertyofanMicrosoftWordapplicationobject,butthefollowingcommandachievesthis:
_$(setqComBars(vlax-get-property
msw'CommandBars))#<VLA-OBJECTCommandBars0016763c>
Youcanusevlax-get-property(andvlax-invoke-methodandvlax-put-property)evenifawrapperfunctionisavailableforthetask.Forexample,thefollowingreturnstheAutoCAD'sActiveDocumentproperty:
_$(vlax-get-property
acadObject'ActiveDocument)#<VLA-OBJECTIAcadDocument00302a18>
Inthisinstance,youcouldhaveinsteadusedvla-get-ActiveDocumenttoobtaintheActiveDocumentproperty.
Pleasesendusyourcommentaboutthispage
Page 396
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>WorkingwithActiveX>UsingActiveXtoInteractwithOtherApplications>UsingActiveXwithoutImportingaTypeLibrary>
UpdatinganActiveXPropertywithvlax-put-property
Thevlax-put-propertyfunctionupdatesthepropertyofanobject.Thefunctionrequiresthefollowingarguments:
AVLA-objectidentifyingtheobjectwhosepropertyyouareupdating
Asymbolorstringnamingthepropertytobeset
Thevaluetosetthepropertyto
Ifvlax-put-propertyupdatesthepropertysuccessfully,itreturnsnil.
ThefollowingfunctioncallchangesthesizeoftheMicrosoftWordtoolbarbuttonsbyupdatingtheLargeButtonspropertyoftheCommandBarsobject:
_$(vlax-put-property
combars'LargeButtons:vlax-true)nil
Pleasesendusyourcommentaboutthispage
Page 397
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>
AdvancedTopics
Youcanusereactorsforeventnotification.
VisualLISP®notonlymakesprogramdevelopmenteasierandfaster,italsoprovidesnewfunctionalitytoLISPapplications.Forexample,youcanattachreactorstoentitiesintheAutoCAD®drawingwindow,allowingyourapplicationtorespondtouseractionsontheseentities.
AttachingReactorstoAutoCADDrawings
Pleasesendusyourcommentaboutthispage
Page 398
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>
AttachingReactorstoAutoCADDrawings
AreactorisanobjectyouattachtoAutoCADdrawingobjectstohaveAutoCADnotifyyourapplicationwheneventsyouareinterestedinoccur.Forexample,ifausermovesanentitythatyourapplicationhasattachedareactorto,yourapplicationwillreceivenotificationthattheentityhasmoved.Ifyoudesignittodoso,yourapplicationcanreacttothisnotificationwithappropriateactions,suchasmovingotherentitiesassociatedwiththeonemoved,orperhapsupdatingatexttagthatrecordsrevisioninformationonthealtereddrawingfeature.
Areactorcommunicateswithyourapplicationbycallingafunctionyouhaveassociatedwiththereactor.Suchafunctionisreferredtoasacallbackfunction.Thereisn'tanythingparticularlyunusualaboutreactorcallbackfunctions—theyarelikeotherfunctionsyouwritewithVLISP.Theybecomecallbackfunctionswhenyouattachthemtoreactorevents.
BeforeyoucanusereactorfunctionswithAutoLISP,youmustloadthesupportingcodethatenablesthesefunctions.Issuethefollowingfunctioncalltoloadreactorsupport:
vl-load-com
Thisfunctionfirstcheckswhetherreactorsupportisalreadyloaded;ifreactorsupportisloaded,thefunctiondoesnothing,otherwise,itloadsreactorsupportandotherAutoLISPextendedfunctions.
Note Allapplicationsthatusereactors—includingallcallbackfunctions—shouldbeginbycallingvl-load-com.
UnderstandingReactorTypesandEventsDefiningCallbackFunctionsCreatingReactors
Page 399
WorkingwithReactorsinMultipleNamespacesQuerying,Modifying,andRemovingReactorsTransientversusPersistentReactorsReactorUseGuidelines
Pleasesendusyourcommentaboutthispage
Page 400
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
UnderstandingReactorTypesandEvents
TherearemanytypesofAutoCADreactors.EachreactortyperespondstooneormoreAutoCADevents.Thedifferenttypesofreactorsaregroupedintothefollowingcategories:
DatabaseReactors
Databasereactorsnotifyyourapplicationwhenspecificeventsoccurtothedrawingdatabase,suchaswhenanobjecthasbeenaddedtothedatabase.
DocumentReactors
Documentreactorsnotifyyourapplicationofachangetothecurrentdrawingdocument,suchasopeninganewdrawingdocument,activatingadifferentdocumentwindow,andchangingadocument'slockstatus.
EditorReactors
EditorreactorsnotifyyoueachtimeanAutoCADcommandisinvoked;adrawingopens,closes,orissaved;aDXFfileisimportedorexported;orasystemvariablechangesvalue.
LinkerReactors
LinkerreactorsnotifyyourapplicationeverytimeanObjectARXapplicationisloadedorunloaded.
ObjectReactors
Objectreactorsnotifyyoueachtimeaspecificobjectischanged,copied,ordeleted.
WiththeexceptionofEditorreactors,thereisonetypeofreactorforeachreactorcategory.ThefollowingtableliststhenamebywhicheachreactortypeisidentifiedinAutoLISPcode:
Page 401
Generalreactortypes
Reactortypeidentifier Description
:VLR-AcDb-Reactor
Databasereactor
:VLR-DocManager-Reactor
Documentmanagementreactor
:VLR-Editor-Reactor
GeneralEditorreactor—maintainedforbackward-compatibility
:VLR-Linker-Reactor
Linkerreactor
:VLR-Object-Reactor
Objectreactor
BeginningwithAutoCAD2000,thebroadclassofEditorreactorsisbrokendownintomorespecificreactortypes.The:VLR-Editor-Reactortypeisretainedforbackward-compatibility,butanynewEditorreactorsintroducedwithAutoCAD2000cannotbereferencedthrough:VLR-Editor-Reactor.ThefollowingtableliststhetypesofEditorreactorsavailablebeginningwithAutoCAD2000.
Editorreactortypes
Reactortype Description
:VLR-Command-Reactor
Providesnotificationofacommandevent
Page 402
:VLR-DeepClone-Reactor
Providesnotificationofadeepcloneevent
:VLR-DWG-Reactor
Providesnotificationofadrawingevent(forexample,openingorclosingadrawingfile)
:VLR-DXF-Reactor
ProvidesnotificationofaneventrelatedtoreadingorwritingofaDXFfile
:VLR-Insert-Reactor
Providesnotificationofaneventrelatedtoblockinsertion
:VLR-Lisp-Reactor
ProvidesnotificationofanAutoLISPevent
:VLR-Miscellaneous-Reactor
Doesnotfallunderanyoftheothereditorreactortypes
:VLR-Mouse-Reactor
Providesnotificationofamouseevent(forexample,adouble-click)
:VLR-SysVar-Reactor
Providesnotificationofachangetoasystemvariable
:VLR-Toolbar-Reactor
Providesnotificationofachangetothebitmapsinatoolbar
:VLR-Undo-Reactor
Providesnotificationofanundoevent
Page 403
:VLR-Wblock-Reactor
Providesnotificationofaneventrelatedtowritingablock
:VLR-Window-Reactor
ProvidesnotificationofaneventrelatedtomovingorsizinganAutoCADwindow
:VLR-XREF-Reactor
Providesnotificationofaneventrelatedtoattachingormodifyingxrefs
Usethevlr-typesfunctiontoreturnthecompletelistofreactortypes.ReactorCallbackEvents
Pleasesendusyourcommentaboutthispage
Page 404
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>UnderstandingReactorTypesandEvents>
ReactorCallbackEvents
Foreachreactortypethereareanumberofeventsthatcancausethereactortonotifyyourapplication.Theseeventsareknownascallbackevents,becausetheycausethereactortocallafunctionyouassociatewiththeevent.Forexample,whenyouissuetheSavecommandtosaveadrawing,a:vlr-beginSaveeventoccurs.Whenyoucompletethesaveprocess,a:vlr-saveCompleteeventoccurs.Indesigningareactor-basedapplication,itisuptoyoutodeterminetheeventsyouareinterestedin,andtowritethecallbackfunctionstobetriggeredwhentheseeventsoccur.
Thevlr-reaction-namesfunctionreturnsalistofallavailableeventsforagivenreactortype:
(vlr-reaction-namesreactortype)
Forexample,thefollowingcommandreturnsalistofalleventsrelatedtoObjectreactors:
$(vlr-reaction-names
:VLR-Object-Reactor)(:VLR-cancelled:VLR-copied:VLR-erased:VLR-unerased:VLR-goodbye:VLR-openedForModify:VLR-modified:VLR-subObjModified:VLR-modifyUndone:VLR-modifiedXData:VLR-unappended:VLR-reappended:VLR-objectClosed)
Note Ifthisoranyothervlr-*commandfailswitha“nofunctiondefinition”message,youmayhaveforgottentocallvl-load-com,thefunctionthatloadsAutoLISPreactorsupportfunctions.
Youcanprintoutalistofallavailablereactorevents,sortedbyreactortype,byloadingandrunningthefollowingcodeinVLISP:
(defunprint-reactors-and-events()
(foreachrtype(vlr-types)
Page 405
(princ(strcat"\n"(vl-princ-to-stringrtype)))
(foreachrname(vlr-reaction-namesrtype)
(princ(strcat"\n\t"(vl-princ-to-stringrname)))))
(princ))
TheAutoLISPReferencelistseacheventavailableforareactortype.Foreachreactortype,youcanfindthisinformationbylookingupthedescriptionofthefunctionyouusetodefineareactorofthattype.Thesefunctionshavethesamenameasthereactortype,minustheleadingcolon.Forexample,vlr-acdb-reactorcreatesadatabasereactor,vlr-toolbar-reactorcreatesatoolbarreactor,andsoon.
Pleasesendusyourcommentaboutthispage
Page 406
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
DefiningCallbackFunctions
Toaddreactorfunctionalitytoyourapplication,youfirstneedtowriteacallbackfunctionthatperformsthetasksneededatthetimeofthereactorevent.Afteryoudefineacallbackfunction,youlinkthefunctiontoaneventbycreatingareactorobject.
AcallbackfunctionisaregularAutoLISPfunction,whichyoudefineusingdefun.However,therearesomerestrictionsonwhatyoucandoinacallbackfunction.YoucannotcallAutoCADcommandsusingthecommandfunction.Also,toaccessdrawingobjects,youmustuseActiveX®functions;entgetandentmodarenotallowedinsidecallbackfunctions.SeeReactorUseGuidelinesformoreinformation.
Callbackfunctionsforallreactors,otherthanObjectreactors,mustbedefinedtoaccepttwoarguments:
ThefirstargumentidentifiestheReactorobjectthatcalledthefunction.
ThesecondargumentisalistofparameterssetbyAutoCAD.
ThefollowingexampleshowsafunctionnamedsaveDrawingInfo,whichdisplaysfilepathandsizeinformation.ThisfunctionwillbeattachedtoaDWGEditorreactorthatwillfirewhenanAutoCADdrawingissaved.
(defunsaveDrawingInfo(calling-reactorcommandInfo/dwgnamefilesize)
(vl-load-com)
(setqdwgname(cadrcommandInfo)
filesize(vl-file-sizedwgname)
)
(alert(strcat"Thefilesizeof"dwgname"is"
(itoafilesize)"bytes."
)
)
(princ)
Page 407
)
Inthisexample,thecalling-reactorvariableidentifiesthereactorthatinvokedthefunction.ThefunctionretrievesthedrawingnamefromthecommandInfoparameter,thenusesthevl-file-sizefunctiontoretrievethesizeofthedrawing.Finally,thefunctiondisplaystheinformationinanalertboxintheAutoCADwindow.
Theparameterspassedtoacallbackfunctiondependonthetypeofeventassociatedwiththefunction.Forexample,saveDrawingInfowillbeassociatedwithasaveCompleteevent.ThiseventindicatesthataSavecommandhasbeencompleted.ForsaveCompleteevents,AutoCADpassesthecallbackfunctionastringcontainingthenameofthefilethedrawingwassavedin.Ontheotherhand,acallbackfunctionthatreactstochangestosystemvariables(sysVarChangedevent)receivesaparameterlistcontainingthenameofasystemvariable(astring)andaflagindicatingifthechangewassuccessful.Youcanfindalistofeventsforeachreactortype,andtheparametersassociatedwitheachevent,intheAutoLISPReference.Theeventsarelistedunderthedescriptionofthefunctionsusedtodefineeachtypeofreactor.
AutoCADcomeswithtwopredefinedcallbackfunctions.Youcanusethesefunctionswhentestingyourreactors:
vlr-beep-reactionisasimplefunctionthatbeepsyourPC.
vlr-trace-reactionprintsalistofargumentstotheVLISPTracewindoweachtimeareactorfiresthiscallbackfunction.DefiningObjectReactorCallbackFunctions
Pleasesendusyourcommentaboutthispage
Page 408
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>DefiningCallbackFunctions>
DefiningObjectReactorCallbackFunctions
UnlikeotherAutoCADreactors,objectreactorsareattachedtospecificAutoCADentities(objects).Whenyoudefineanobjectreactor,youmustidentifytheentitythereactoristobeattachedto.Socallbackfunctionsforobjectreactorsmustbedefinedtoacceptthreearguments:
Thefirstargumentidentifiestheobjectthatfiredthenotification.
ThesecondargumentidentifiestheReactorobjectthatcalledthefunction.
Thethirdargumentisalistofparametersspecifictothecallbackcondition.
Forexample,thefollowingcodedefinesacallbackfunctionnamedprint-radius.Thisfunctioncanbeusedtoprinttheradiusofacircle:
(defunprint-radius(notifier-objectreactor-objectparameter-list)
(vl-load-com)
(cond
(
(vlax-property-available-p
notifier-object
"Radius"
)
(princ"Theradiusis")
(princ(vla-get-radiusnotifier-object))
)
)
)
Notethatthecodeusesthevlax-property-available-pfunctiontoverifythatthedrawingobjectthatnotifiedthisfunctioncontainsaradiusproperty.
Page 409
Pleasesendusyourcommentaboutthispage
Page 410
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
CreatingReactors
Youlinkacallbackfunctiontoaneventwhenyoucreateareactor.ThereisanAutoLISPfunctionforcreatingeachtypeofreactor.Thesefunctionshavethesamenameasthereactortype,minustheleadingcolon.Forexample,vlr-acdb-reactorcreatesadatabasereactor,vlr-toolbar-reactorcreatesatoolbarreactor,andsoon.Exceptforobjectreactors,thereactorcreationfunctionsrequirethefollowingarguments:
AutoLISPdatatobeassociatedwiththeReactorobject
Alistofpairsnamingtheeventandthecallbackfunctiontobeassociatedwiththatevent(event-name.callback_function)
Forexample,thefollowingcommanddefinesaDWGEditorreactor.ThereactorwillinvokethesaveDrawingInfofunctioninresponsetoauserissuingaSAVEcommand:
(vlr-dwg-Reactornil'((:vlr-saveComplete.saveDrawingInfo)))
Inthisexample,thefirstargumentisnilbecausethereisnoapplication-specificdatatoattachtothisreactor.Thesecondargumentisalistconsistingofdottedpairlists.Eachdottedpairlistidentifiesaneventthereactoristobenotifiedabout,andthecallbackfunctiontoberuninresponsetothatevent.Inthiscasethereactorisnotifiedofonlyoneevent,:vlr-saveComplete.
Editorreactorsarenotifiedeachtimetheuserissuesacommand,whetherthroughtheAutoCADcommandline,amenu,atoolbar,oranAutoLISPprogram.So,thecallbackfunctionforthisDWGreactorneedstodeterminepreciselywhatitisrespondingto.Inthecurrentexample,save-drawingInfosimplychecksfortheSavecommand.
PossibleeventsforeachreactortypearelistedintheAutoLISPReference.To
Page 411
findthelistofeventsforareactor,refertotheentryintheAutoLISPReferencethatdescribesthefunctionusedtocreatethereactor.Forexample,tofindthelistofpossibleeventsforaDWGreactor,refertotheentryforvlr-DWG-reactor.
AllreactorconstructionfunctionsreturnaReactorobject.UsingObjectReactorsAttachingDatatoReactorObjects
Pleasesendusyourcommentaboutthispage
Page 412
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>CreatingReactors>
UsingObjectReactors
UnlikeotherAutoCADreactors,objectreactorsareattachedtospecificAutoCADentities(objects).Whenyoudefineanobjectreactor,youmustidentifytheentitytowhichthereactoristobeattached.Thevlr-object-reactorfunction,whichcreatesobjectreactors,requiresthefollowingarguments:
AlistofVLA-objectsidentifyingthedrawingobjectsthataretofirenotificationstothereactor.Theseobjectsarereferredtoasthereactorowners.
AutoLISPdatatobeassociatedwiththeReactorobject.
Alistofpairsnamingtheeventandthecallbackfunctiontobeassociatedwiththatevent(event-name.callback_function).
Warning Youcannotmodifyanobjectinacallbackfunctionifitisincludedintheobjectreactor'sownerlist.AttemptstodosowillgenerateanerrormessageandcancauseAutoCADtofail.
Forexample,thefollowingstatementdefinesanobjectreactorwithasingleowner(theobjectidentifiedbymyCircle),thenattachesthestring“CircleReactor”tothereactorandtellsAutoCADtoinvoketheprint-radiusfunctionwhenausermodifiesmyCircle:
(setqcircleReactor(vlr-object-reactor(listmyCircle)
"CircleReactor"'((:vlr-modified.print-radius))))
TheReactorobjectisstoredinvariablecircleReactor;youcanrefertothereactorusingthisvariable,asdescribedinQuerying,Modifying,andRemovingReactors.
Whendefiningalistofowners,youmustspecifyVLA-objectsonly;Ename
Page 413
objectsarenotallowed.VLA-objectsarerequiredbecausecallbackfunctionscanonlyuseActiveXmethodstomodifyAutoCADobjects,andActiveXmethodsrequireaVLA-objecttoworkon.
Notethat,althoughyoucannotuseobjectsobtainedthroughfunctionssuchasentlastandentgetwithcallbackreactors,youcanconverttheseEnameobjectsintoVLA-objectsusingthevlax-ename->vla-objectfunction.SeetheAutoLISPReferenceformoreinformationonvlax-ename->vla-object.
Toseehowanobjectreactorworks
1. Loadthefollowingcodetodefineacircleobject;youwillbepromptedtodrawthecircle:
(setqmyCircle
;Promptforthecenter
pointandradius:
(progn(setqctrPt
(getpoint"\nCirclecenterpoint:")
radius(distancectrPt
(getpointctrpt"\nRadius:")
)
)
;Addacircletothe
drawingmodelspace.Nestthefunction
;callstoobtainthe
pathtothecurrentdrawing'smodel
;space:AcadObject>
ActiveDocument>ModelSpace
(vla-addCircle
(vla-get-ModelSpace
(vla-get-ActiveDocument(vlax-get-acad-object))
)
(vlax-3d-pointctrPt)
radius
)
)
)
Thiscodeusesvla-addCircletodrawacircle,assigningthereturnvaluetovariablemyCircle.ThereturnvalueisaVLA-object,whichcontainsapointertotheCircleobjectdrawn.
2. Loadtheprint-radiuscallbackfunctionshowninDefiningObject
Page 414
ReactorCallbackFunctions.
3. Definethereactorwiththefollowingcommand:
(setqcircleReactor(vlr-object-reactor(listmyCircle)
"CircleReactor"'((:vlr-modified.print-radius))))
4. IntheAutoCADdrawingwindow,selectthecircleandchangeitssize.Theprint-radiusfunctionwilldisplayamessageintheAutoCADCommandwindow.Forexample,ifyouusetheSTRETCHcommandtoenlargethecircle,themessagelookslikethefollowing:
Specifystretchpointor[Basepoint/Copy/Undo/eXit]:Theradiusis3.75803
Pleasesendusyourcommentaboutthispage
Page 415
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>CreatingReactors>
AttachingDatatoReactorObjects
TheobjectreactorcreationexampleinUsingObjectReactorsincludedastring,“CircleReactor,”inthecalltovlr-object-reactor.Youdonothavetospecifyanydatatobeincludedwiththereactor;youcanspecifynilinstead.However,anobjectmayhaveseveralreactorsattachedtoit.Includeanidentifyingtextstring,orotherdatayourapplicationcanuse,toallowyoutodistinguishamongthedifferentreactorsattachedtoanobject.
Pleasesendusyourcommentaboutthispage
Page 416
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
WorkingwithReactorsinMultipleNamespaces
ThecurrentimplementationofAutoLISPsupportsworkinginonedrawingdocumentatatime.SomeAutoCADAPIs,suchasObjectARXandVBA,dosupporttheabilityofanapplicationtoworksimultaneouslyinmultipledocuments.Asaresult,anapplicationmaymodifyanopendrawingthatisnotcurrentlyactive.ThisisnotsupportedinAutoLISP.(NotethataVLXmayruninaseparate-namespacefromthedocumentitisloadedfrom,butitisstillassociatedwiththatdocumentandcannotmanipulateobjectsinanotherdocument.)
AutoLISPdoesprovidelimitedsupportforreactorcallbackfunctionsexecutinginadocumentthatisnotactive.Bydefault,areactorcallbackfunctionwillexecuteonlyifanotificationeventoccurswhenthedocumentitwasdefinedinistheactivedocument.Youcanalterthisbehaviorusingthevlr-set-notificationfunction.
Tospecifythatareactorshouldexecuteitscallbackfunctionevenifthedocumentitwasdefinedinisnotactive(forexample,ifanapplicationinanothernamespacetriggersanevent),issuethefollowingfunctioncall:
(vlr-set-notificationreactor-object'all-documents)
Tomodifyareactorsoitonlyexecutesitscallbackfunctionifaneventoccurswhenthedocumentitwasdefinedinisactive,issuethefollowing:
(vlr-set-notificationreactor-object'active-document-only)
Thevlr-set-notificationfunctionreturnsthespecifiedreactorobject.Forexample,thefollowingsequenceofcommandsdefinesareactorandsetsittorespondtoeventswhetherornotitsassociateddocumentisactive:
_$(setqcircleReactor
Page 417
(vlr-object-reactor(listmyCircle)
"CircleReactor"
'((:vlr-modified.print-radius))))#<VLR-Object-Reactor>
_$(vlr-set-notification
circleReactor'all-documents)#<VLR-Object-Reactor>
Todeterminethenotificationsettingofareactor,usethevlr-notificationfunction.Forexample:
_$(vlr-notification
circleReactor)all-documents
Thevlr-set-notificationfunctionaffectsonlythespecifiedreactor.Allreactorsarecreatedwiththedefaultnotificationsettoactive-document-only.
Warning Ifyouchoosetosetareactortoexecuteitscallbackfunctioneveniftriggeredwhenitsdocumentisnotactive,thecallbackfunctionshoulddonothingotherthansetandreadAutoLISPvariables.Anyotheractionmaycausesysteminstability.
Pleasesendusyourcommentaboutthispage
Page 418
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
Querying,Modifying,andRemovingReactors
Therearevariouswaystoobtaininformationaboutreactors.VLISPsuppliesAutoLISPfunctionstoqueryreactors,andyoucanusestandardVLISPdatainspectiontoolstoviewinformationonthem.
TouseAutoLISPtolistallreactorsinadrawing,callthevlr-reactorsfunction.Thefunctionreturnsalistofreactorlists.Eachreactorlistbeginswithasymbolidentifyingthereactortype,followedbypointerstoeachreactorofthattype.Forexample:
_$(vlr-reactors)((:VLR-Object-Reactor#<VLR-Object-Reactor>)(:VLR-Editor-Reactor#<VLR-Editor-Reactor>))
Inthisexample,vlr-reactorsreturnedalistcontainingtwolists,oneidentifyingasingleobjectreactorandoneidentifyingasingleEditorreactor.
Tolistallreactorsofagiventype,supplyvlr-reactorswithanargumentidentifyingthereactortype.Specifyoneofthevaluesreturnedbythevlr-typesfunction;thesearelistedin“UnderstandingReactorTypesandEvents”.Forexample,thefollowinglistsallDWGreactors:
_$(vlr-reactors
:vlr-dwg-reactor)((:VLR-DWG-Reactor#<VLR-DWG-Reactor>#<VLR-DWG-Reactor>))
Inthiscase,thereturnvalueisalistcontainingonelist.TheonelistidentifiespointerstotwoDWGreactors.
InspectingReactorsQueryingReactorsUsingFunctionCallsModifyingReactors
Page 419
RemovingReactors
Pleasesendusyourcommentaboutthispage
Page 420
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>Querying,Modifying,andRemovingReactors>
InspectingReactors
YoucanexaminereactorsusingtheVLISPInspecttool.Forexample,theobjectreactordefinedinUsingObjectReactorswasreturnedtothevariablecircleReactor.IfyouopenanInspectwindowforthisvariable,VLISPdisplaysthefollowinginformation:
ThelistitemsintheInspectwindowshowthefollowing:
Objectsowningthereactor
Eventandassociatedcallbackfunction
Whetherornotthereactorisactive(yesifadded-pisT,noifadded-pisnil)
Userdataattachedtothereactor
Documentrangeinwhichthereactorwillfire(if0,itfiresonlyinthecontextofthedrawingdocumentitwascreatedin;if1,thereactorrespondsinthecontextofanydocument(seeWorkingwithReactorsinMultipleNamespacesformoreinformationonthistopic))
TheAutoCADdocumentattachedtotheobjectreactor
Double-clickontheitemthatbeginswith{Owners}toviewalistoftheowner
Page 421
objects:
Double-clickonalistitemtoobtaindetailedinformationaboutanowner.
Pleasesendusyourcommentaboutthispage
Page 422
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>Querying,Modifying,andRemovingReactors>
QueryingReactorsUsingFunctionCalls
VLISPalsoprovidesfunctionstoinspectareactordefinitionfromwithinanapplicationprogram,orattheConsoleprompt:
vlr-typereturnsthetypeofthespecifiedreactor.Forexample:$(vlr-typecircleReactor)
:VLR-Object-Reactor
vlr-current-reaction-namereturnsthenameoftheeventthatcausedthecallbackfunctiontobecalled.
vlr-datareturnstheapplication-specificdatavalueattachedtothereactor,asshowninthefollowingexample:$(vlr-datacircleReactor)
"CircleReactor"
Youcanusethisdatatodistinguishamongmultiplereactorsthatcanfirethesamecallbackfunction.
vlr-ownersreturnsalistoftheobjectsinanAutoCADdrawingthatfirenotificationstoanobjectreactor.ThefollowingfunctioncallliststheobjectsthatfirenotificationstocircleReactor:_$(vlr-ownerscircleReactor)
(#<VLA-OBJECTIAcadCircle03ad077c>)
vlr-reactionsreturnsthecallbacklistofcondition-functionpairsofthespecifiedreactor.ThefollowingexamplereturnsinformationaboutcircleReactor:$(vlr-reactionscircleReactor)
Page 423
((:vlr-modified.PRINT-RADIUS))
Pleasesendusyourcommentaboutthispage
Page 424
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>Querying,Modifying,andRemovingReactors>
ModifyingReactors
VLISPprovidesfunctionstomodifyreactordefinitions:
vlr-reaction-setchangesthecallbackfunctionlinkforthespecifiedreactorevent.Thefunctionsyntaxis:(vlr-reaction-setreactorcallback-condition
'callback-function)
Forexample,thefollowingcommandchangesthecircleReactorreactortocalltheprint-areafunctionwhenanobjectismodified:$(vlr-reaction-setcircleReactor:vlr-modified
'print-area)
PRINT-AREA
vlr-data-setchangestheapplication-specificdataassociatedwiththereactor.Forexample,thefollowingcallreplacesthetextstringusedtoidentifythecircleReactorreactor:$(vlr-data-setcircleReactor"CircleArea
Reactor")
"CircleAreaReactor"
YoucanverifythatthereactorhaschangedbyusingtheVLISPInspectfeature.IftheInspectwindowshowninInspectingReactorsisstilldisplayedinyourVLISPsession,right-clickinthewindow'sobjectlineandchooseUpdate.Ifyou'vemodifiedthecircleReactorreactorasshowninthissection,theupdatedInspectwindowwilllooklikethefollowing:
Page 425
vlr-owner-addaddsadatabaseobjecttothelistofownersofthespecifiedreactor.Inthefollowingexample,anARCobjectnamedarchieisaddedtotheownerlistofreactorcircleReactor:$(vlr-owner-addcircleReactorarchie)
#<VLA-OBJECTIAcadArc03ad0bcc>
Now,ifausermodifiesthearchieobject,thecallbackfunctiondefinedforreactorcircleReactorisinvoked.Youcanverifythisbyinspectingthereactor.UpdatetheInspectwindowforthecircleReactorreactor,thenright-clickonthelistitemthatbeginswith{Owners}andchooseInspect:
BoththeArcandCircleobjectsarelistedintheInspectwindow.
vlr-owner-removeremovesanOwnerobjectfromthelistofreactorowners.Forexample,thefollowingcommandremovesarchiefromthecircleReactorownerlist:$(vlr-owner-removecircleReactorarchie)
#<VLA-OBJECTIAcadArc03ad0bcc>
Pleasesendusyourcommentaboutthispage
Page 426
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>Querying,Modifying,andRemovingReactors>
RemovingReactors
Usethevlr-removefunctiontodisableareactor.Disablingthereactordoesnotdeleteit:theReactorobjectstillexistsandyoucanactivateitagainusingthevlr-addfunction.Todeterminewhetherornotareactorisactive(registeredtoAutoCAD),usethevlr-added-pfunction:
_$(vlr-added-pcircleReactor)T
Thevlr-added-pfunctionreturnsTifthereactorisactive,nilifitisnot.
ThefollowingcommanddisablesreactorcircleReactor:
_$(vlr-removecircleReactor)#<VLR-Object-reactor>
Youcanusevlr-added-ptoverifythecircleReactorobjectreactorhasbeendisabled:
$(vlr-added-pcircleReactor)nil
ToenablethecircleReactorreactor,usevlr-add:
$(vlr-addcircleReactor)#<VLR-Object-reactor>
Youcanusethevlr-remove-allfunctiontodisableallreactorsinyourdrawing.Todisableallreactorsofaparticulartype,specifythereactortypewhencallingvlr-remove-all.Thefollowingfunctioncalldisablesallobjectreactors:
Page 427
$(vlr-remove-all:vlr-object-reactor)(#<VLR-Object-reactor>)
Pleasesendusyourcommentaboutthispage
Page 428
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
TransientversusPersistentReactors
Reactorsmaybetransientorpersistent.Transientreactorsarelostwhenadrawingcloses;thisisthedefaultreactormode.Persistentreactorsaresavedwiththedrawingandexistwhenthedrawingisnextopened.
Usethevlr-persfunctiontomakeareactorpersistent.Toremovepersistencefromareactorandmakeittransient,usevlr-pers-release.EachfunctiontakesaReactorobjectasitsonlyargument.Forexample,thefollowingcommandmakesareactorpersistent:
_$(vlr-perscircleReactor)#<VLR-Object-Reactor>
Ifsuccessful,vlr-persreturnsthespecifiedReactorobject.
TodeterminewhetheraReactorobjectispersistentortransient,issuevlr-pers-p.Forexample:
_$(vlr-pers-pcircleReactor)#<VLR-Object-Reactor>
Thevlr-pers-pfunctionreturnstheReactorobjectifitispersistent,nilifitisnot.
OpeningaDrawingContainingPersistentReactors
Pleasesendusyourcommentaboutthispage
Page 429
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>TransientversusPersistentReactors>
OpeningaDrawingContainingPersistentReactors
Areactorisonlyalinkbetweenaneventandacallbackfunction.Whilethislinkremains,thecallbackfunctionitselfisnotpartofthereactor,andisnormallynotpartofthedrawing.ThereactorssavedinthedrawingareonlyusableiftheirassociatedcallbackfunctionsareloadedinAutoCAD.Youcancausethistooccurautomaticallywhenadrawingisopenedifyoudefinethereactorandcallbackfunctionsinaseparate-namespaceVLX.
IfyouopenadrawingcontainingVLISPreactorinformationandtheassociatedcallbackfunctionsarenotloaded,AutoCADdisplaysanerrormessage.Youcanusethevlr-pers-listfunctiontoreturnalistofallPersistentreactorsinadrawingdocument.
Pleasesendusyourcommentaboutthispage
Page 430
AutoLISPDeveloper'sGuide>UsingtheVisualLISPEnvironment>AdvancedTopics>AttachingReactorstoAutoCADDrawings>
ReactorUseGuidelines
Whenusingreactors,trytoadheretothefollowingguidelines.Reactorsthatviolatetheseguidelinescanresultinunpredictableresultsforyourapplicationiftheinternalimplementationofreactorschanges.
Donotrelyonthesequenceofreactornotifications.Itisrecommendedthat,withafewexceptions,youdonotrelyonthesequenceofreactornotifications.Forexample,anOPENcommandtriggersBeginCommand,BeginOpen,EndOpen,andEndCommandevents.However,theymaynotoccurinthatorder.TheonlyeventsequenceyoucansafelyrelyonisthataBegineventwilloccurbeforethecorrespondingEndevent.Forexample,commandWillStart()alwaysoccursbeforecommandEnded(),andbeginInsert()alwaysoccursbeforeendInsert().Relyingonmorecomplexsequencesmayresultinproblemsforyourapplicationifthesequenceischangedasaresultofnewnotificationsbeingintroducedinthefutureandexistingonesbeingrearranged.
Donotrelyonthesequenceoffunctioncallsbetweennotifications.Itisnotguaranteedthatcertainfunctionswillbecalledbetweencertainnotifications.Forexample,whenyoureceive:vlr-erasednotificationonobjectA,allitmeansisthatobjectAiserased.Ifyoureceive:vlr-erasednotificationonAfollowedbya:vlr-erasednotificationonB,allitmeansisthatbothobjectsAandBareerased;itdoesnotensurethatBwaserasedafterA.Ifyoutieyourapplicationtothislevelofdetail,thereisaveryhighprobabilityofyourapplicationbreakinginfuturereleases.Insteadofrelyingonsequences,relyonreactorstoindicatethestateofthesystem.
Donotuseanyinteractivefunctionsinyourreactorcallbackfunction
Page 431
(forexample,donotusegetPoint,entsel).Attemptingtoexecuteinteractivefunctionsfromwithinareactorcallbackfunctioncancauseseriousproblems,asAutoCADmaystillbeprocessingacommandatthetimetheeventistriggered.Therefore,avoidtheuseofinput-acquisitionmethodssuchasgetPoint,entsel,andgetkword,aswellasselectionsetoperationsandthecommandfunction.
Donotlaunchadialogboxfromwithinaneventhandler.DialogboxesareconsideredinteractivefunctionsandcaninterferewiththecurrentoperationofAutoCAD.However,messageboxesandalertboxesarenotconsideredinteractiveandcanbeissuedsafely.
Donotupdatetheobjectthatissuedtheeventnotification.TheeventcausinganobjecttotriggeracallbackfunctionmaystillbeinprogressandtheobjectstillinusebyAutoCADwhenthecallbackfunctionisinvoked.Therefore,donotattempttoupdateanobjectfromacallbackfunctionforthesameobject.Youcan,however,safelyreadinformationfromtheobjecttriggeringanevent.Forexample,supposeyouhaveafloorfilledwithtilesandyouattachareactortotheborderofthefloor.Ifyouchangethesizeofthefloor,thereactorcallbackfunctionwillautomaticallyaddorsubtracttilestofillthenewarea.Thefunctionwillbeabletoreadthenewareaoftheborder,butitcannotattemptanychangesontheborderitself.
Donotperformanyactionfromacallbackfunctionthatwilltriggerthesameevent.Ifyouperformanactioninyourreactorcallbackfunctionthattriggersthesameevent,youwillcreateaninfiniteloop.Forexample,ifyouattempttoopenadrawingfromwithinaBeginOpenevent,AutoCADwillsimplycontinuetoopenmoredrawingsuntilthemaximumnumberofopendrawingsisreached.
Verifythatareactorisnotalreadysetbeforesettingit,oryoumayendupwithmultiplecallbacksonthesameevent.
RememberthatnoeventswillbefiredwhileAutoCADisdisplayingamodaldialog.
Page 432
Pleasesendusyourcommentaboutthispage
Page 433
AutoLISPDeveloper'sGuide>
UsingtheAutoLISPLanguage
AutoLISPBasicsYoucanusenumber,string,andlist-handlingfunctionstocustomizeAutoCAD.UsingAutoLISPtoCommunicatewithAutoCADQueryandcommandfunctionsprovidedirectaccesstoAutoCADcommandsanddrawingservices.UsingAutoLISPtoManipulateAutoCADObjectsYoucanselectandhandleobjects,andusetheirextendeddata.
Pleasesendusyourcommentaboutthispage
Page 434
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>
AutoLISPBasics
Youcanusenumber,string,andlist-handlingfunctionstocustomizeAutoCAD.
ThischapterintroducesthebasicconceptsoftheAutoLISP®programminglanguage.ItdescribesthecorecomponentsanddatatypesusedinAutoLISP,andpresentsexamplesofsimplenumber-,string-,output-,andlist-handlingfunctions.
AutoLISPcodedoesnotneedtobecompiled,soyoucanenterthecodeataCommandlineandimmediatelyseetheresults.SomeexamplesinthischapterareintendedtobeenteredattheVisualLISP®(VLISP)Consolewindowprompt(_$),whileothersareenteredattheAutoCAD®Commandprompt(Command:).
AutoLISPExpressionsAutoLISPDataTypesAutoLISPProgramFilesAutoLISPVariablesNumberHandlingStringHandlingBasicOutputFunctionsEqualityandConditionalListHandlingSymbolandFunctionHandlingErrorHandlinginAutoLISP
Pleasesendusyourcommentaboutthispage
Page 435
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
AutoLISPExpressions
AnAutoLISPprogramconsistsofaseriesofexpressions.AutoLISPexpressionshavethefollowingform:
(functionarguments)
Eachexpressionbeginswithanopen(left)parenthesisandconsistsofafunctionnameandoptionalargumentstothatfunction.Eachargumentcanalsobeanexpression.Theexpressionendswitharightparenthesis.Everyexpressionreturnsavaluethatcanbeusedbyasurroundingexpression.Thevalueofthelastinterpretedexpressionisreturnedtothecallingexpression.
Forexample,thefollowingcodeexampleinvolvesthreefunctions:
(fun1(fun2arguments)(fun3arguments))
IfyouenterthiscodeattheVisualLISPConsolepromptortheAutoCADCommandprompt,theAutoCADAutoLISPinterpreterprocessesthecode.Thefirstfunction,fun1,hastwoarguments,andtheotherfunctions,fun2andfun3,eachhaveoneargument.Thefunctionsfun2andfun3aresurroundedbyfunctionfun1,sotheirreturnvaluesarepassedtofun1asarguments.Functionfun1evaluatesthetwoargumentsandreturnsthevaluetothewindowfromwhichyouenteredthecode.
Thefollowingexampleshowstheuseofthe*(multiplication)function,whichacceptsoneormorenumbersasarguments:
_$ (* 2 27)54
Becausethiscodeexamplehasnosurroundingexpression,AutoLISPreturnstheresulttothewindowfromwhichyouenteredthecode.
Page 436
Expressionsnestedwithinotherexpressionsreturntheirresulttothesurroundingexpression.Thefollowingexampleusestheresultfromthe+(addition)functionasoneoftheargumentsforthe*(multiplication)function.
_$ (* 2 (+ 5 10))30
Ifyouentertheincorrectnumberofclose(right)parentheses,AutoLISPdisplaysthefollowingprompt:
(_>
Thenumberofopenparenthesesinthispromptindicateshowmanylevelsofopenparenthesesremainunclosed.Ifthispromptappears,youmustentertherequirednumberofcloseparenthesesfortheexpressiontobeevaluated.
_$ (* 2 (+ 5 10((_>))30
Acommonmistakeistoomittheclosingquotationmark(")inatextstring,inwhichcasethecloseparenthesesareinterpretedaspartofthestringandhavenoeffectinresolvingtheopenparentheses.Tocorrectthiscondition,pressSHIFT+ESCtocancelthefunction,thenre-enteritcorrectly.
AutoLISPFunctionSyntax
Pleasesendusyourcommentaboutthispage
Page 437
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPExpressions>
AutoLISPFunctionSyntax
Inthisguide,thefollowingconventionsdescribethesyntaxforAutoLISPfunctions:
Inthisexample,thefoofunctionhasonerequiredargument,string,andoneoptionalargument,number.Additionalnumberargumentscanbeprovided.Frequently,thenameoftheargumentindicatestheexpecteddatatype.Theexamplesinthefollowingtableshowbothvalidandinvalidcallstothefoofunction.
Validandinvalidfunctioncallexamples
Validcalls Invalidcalls
(foo
"catch")
(foo44
13)
(foo"catch"
22)
(foo"fi"
"foe"44
13)
Page 438
(foo"catch"
2231)
(foo)
Pleasesendusyourcommentaboutthispage
Page 439
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
AutoLISPDataTypes
AutoLISPexpressionsareprocessedaccordingtotheorderanddatatypeofthecodewithintheparentheses.BeforeyoucanfullyutilizeAutoLISP,youmustunderstandthedifferencesamongthedatatypesandhowtousethem.
IntegersRealsStringsListsSelectionSetsEntityNamesVLA-objectsFileDescriptorsSymbolsandVariables
Pleasesendusyourcommentaboutthispage
Page 440
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
Integers
Integersarewholenumbersthatdonotcontainadecimalpoint.AutoLISPintegersare32-bitsignednumberswithvaluesrangingfrom+2,147,483,647to-2,147,483,648.(Note,however,thatthegetintfunctiononlyaccepts16-bitnumbersrangingfrom+32767to-32678.)WhenyouexplicitlyuseanintegerinanAutoLISPexpression,thatvalueisknownasaconstant.Numberssuchas2,-56,and1,200,196arevalidAutoLISPintegers.
Ifyouenteranumberthatisgreaterthanthemaximumintegerallowed(resultinginintegeroverflow),AutoLISPconvertstheintegertoarealnumber.However,ifyouperformanarithmeticoperationontwovalidintegers,andtheresultisgreaterthanthemaximumallowableinteger,theresultingnumberwillbeinvalid.ThefollowingexamplesillustratehowAutoLISPhandlesintegeroverflow.
Thelargestpositiveintegervalueretainsitsspecifiedvalue:
_$21474836472147483647
Ifyouenteranintegerthatisgreaterthanthelargestallowablevalue,AutoLISPreturnsthevalueasareal:
_$21474836482.14748e+009
Anarithmeticoperationinvolvingtwovalidintegers,butresultinginintegeroverflow,producesaninvalidresult:
_$(+21474836463)-2147483647
Page 441
Inthisexampletheresultisclearlyinvalid,astheadditionoftwopositivenumbersresultsinanegativenumber.Butnotehowthefollowingoperationproducesavalidresult:
_$(+21474836482)2.14748e+009
Inthisinstance,AutoLISPconverts2147483648toavalidrealbeforeadding2tothenumber.Theresultisavalidreal.
Thelargestnegativeintegervalueretainsitsspecifiedvalue:
_$-2147483647-2147483647
Ifyouenteranegativeintegerlargerthanthegreatestallowablenegativevalue,AutoLISPreturnsthevalueasareal:
_$-2147483648-2.14748e+009
Thefollowingoperationconcludessuccessfully,becauseAutoLISPfirstconvertstheoverflownegativeintegertoavalidreal:
_$(--21474836481)-2.14748e+009
Pleasesendusyourcommentaboutthispage
Page 442
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
Reals
Arealisanumbercontainingadecimalpoint.Numbersbetween-1and1mustcontainaleadingzero.Realnumbersarestoredindouble-precisionfloating-pointformat,providingatleast14significantdigitsofprecision.NotethatVLISPdoesnotshowyouallthesignificantdigits.
Realscanbeexpressedinscientificnotation,whichhasanoptionaleorEfollowedbytheexponentofthenumber(forexample,0.0000041isthesameas4.1e-6).Numberssuchas3.1,0.23,-56.123,and21,000,000.0arevalidAutoLISPreals.
Pleasesendusyourcommentaboutthispage
Page 443
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
Strings
Astringisagroupofcharacterssurroundedbyquotationmarks.Withinquotedstringsthebackslash(\)characterallowscontrolcharacters(orescapecodes)tobeincluded.WhenyouexplicitlyuseaquotedstringinanAutoLISPexpression,thatvalueisknownasaliteralstringorastringconstant.
Examplesofvalidstringsare“string1”and“\nEnterfirstpoint:”.
Pleasesendusyourcommentaboutthispage
Page 444
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
Lists
AnAutoLISPlistisagroupofrelatedvaluesseparatedbyspacesandenclosedinparentheses.Listsprovideanefficientmethodofstoringnumerousrelatedvalues.AutoCADexpresses3Dpointsasalistofthreerealnumbers.
Examplesoflistsare(1.01.00.0),(“this”“that”“theother”),and(1“ONE”).
Pleasesendusyourcommentaboutthispage
Page 445
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
SelectionSets
Selectionsetsaregroupsofoneormoreobjects(entities).Youcaninteractivelyaddobjectsto,orremoveobjectsfrom,selectionsetswithAutoLISProutines.
Thefollowingexampleusesthessgetfunctiontoreturnaselectionsetcontainingalltheobjectsinadrawing.
_$ (ssget"X")<Selectionset:1>
Pleasesendusyourcommentaboutthispage
Page 446
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
EntityNames
Anentitynameisanumericlabelassignedtoobjectsinadrawing.ItisactuallyapointerintoafilemaintainedbyAutoCAD,andcanbeusedtofindtheobject'sdatabaserecordanditsvectors(iftheyaredisplayed).ThislabelcanbereferencedbyAutoLISPfunctionstoallowselectionofobjectsforprocessinginvariousways.Internally,AutoCADreferstoobjectsasentities.
Thefollowingexampleusestheentlastfunctiontogetthenameofthelastobjectenteredintothedrawing.
_$ (entlast)<Entityname:27f0540>
Entitynamesassignedtoobjectsinadrawingareonlyineffectduringthecurrenteditingsession.Thenexttimeyouopenthedrawing,AutoCADassignsnewentitynamestotheobjects.Youcanuseanobject'shandletorefertoitfromoneeditingsessiontoanother;seeEntityHandlesandTheirUsesforinformationonusinghandles.
Pleasesendusyourcommentaboutthispage
Page 447
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
VLA-objects
ObjectsinadrawingcanberepresentedasVisualLISPActiveX®(VLA)objects,adatatypeintroducedwithVisualLISP.WhenworkingwithActiveXfunctions,youmustrefertoVLA-objects,nottheenamepointerreturnedbyfunctionssuchasentlast.ForinformationonworkingwithActiveXobjects,seeUsingActiveXObjectswithAutoLISP.
Pleasesendusyourcommentaboutthispage
Page 448
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
FileDescriptors
AfiledescriptorisapointertoafileopenedbytheAutoLISPopenfunction.Theopenfunctionreturnsthispointerasanalphanumericlabel.YousupplythefiledescriptorasanargumenttootherAutoLISPfunctionsthatreadorwritetothefile.
Thefollowingexampleopensthemyinfo.datfileforreading.Theopenfunctionreturnsthefiledescriptor:
_$ (setqfile1(open"c:\\myinfo.dat""r"))#<file"c:\\myinfo.dat">
Inthisexample,thefiledescriptorisstoredinthefile1variable.
FilesremainopenuntilyouexplicitlyclosetheminyourAutoLISPprogram.Theclosefunctionclosesafile.Thefollowingcodeclosesthefilewhosefiledescriptorisstoredinthefile1variable:
_$ (closefile1)nil
Pleasesendusyourcommentaboutthispage
Page 449
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>
SymbolsandVariables
AutoLISPusessymbolstorefertodata.Symbolnamesarenotcasesensitiveandmayconsistofanysequenceofalphanumericandnotationcharacters,exceptthefollowing:
Charactersrestrictedfromsymbolnames
( (OpenParenthesis)
) (CloseParenthesis)
. (Period)
' (Apostrophe)
" (QuoteSymbol)
; (Semicolon)
Asymbolnamecannotconsistonlyofnumericcharacters.
Technically,AutoLISPapplicationsconsistofeithersymbolsorconstantvalues,suchasstrings,reals,andintegers.Forthesakeofclarity,thisguideusesthetermsymboltorefertoasymbolnamethatstoresstaticdata,suchasbuilt-inanduser-definedfunctions.Thetermvariableisusedtorefertoasymbolnamethatstoresprogramdata.Thefollowingexampleusesthesetqfunctiontoassignthestringvalue"thisisastring"tothestr1variable:
Page 450
_$ (setqstr1"thisisastring")"thisisastring"
Helpyourselfandotherswhoneedtoreadyourcode.Choosemeaningfulnamesforyourprogramsymbolsandvariables.
ProtectedSymbols
Pleasesendusyourcommentaboutthispage
Page 451
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPDataTypes>SymbolsandVariables>
ProtectedSymbols
YoumaybewarnedifyouattempttochangethevalueofsomesymbolsusedbytheAutoLISPlanguage.Thesesymbolsareknownasprotectedsymbols,andincludeitemssuchasarithmeticoperators(forexample,+,-)andthevaluesTandnil.YoucanusetheVisualLISPSymbolServicefeaturetodetermineifasymbolisprotected.
WhenyoufirststartAutoCAD,protectedsymbolsreceivenospecialprotection.IfyousetaprotectedsymbolattheAutoCADCommandprompt,youreceivenoindicationthatthesymbolhasanyspecialstatus.However,onceyoustartVisualLISP,thischanges.FromthemomentyoustartVisualLISPuntiltheendofyourAutoCADsession,AutoLISPinterceptsanyattempttomodifyaprotectedsymbol.ProcessingofprotectedsymbolsdependsonthestatusofaVisualLISPenvironmentoption.Youcanspecifyoneofthefollowingoptions:
Transparent Protectedsymbolsaretreatedlikeanyothersymbol.
Printmessage AutoLISPissuesawarningmessagewhenyoumodifyaprotectedsymbolbutcarriesoutthemodification.Forexample,thefollowingdemonstrateswhathappenswhenyoumodifythesymbolT:Command:(setqt"lookout");*U*WARNING:assignmenttoprotectedsymbol:T<-"lookout""lookout"
Prompttoenterbreakloop Thisisthedefaultoption,resultinginAutoLISPdisplayingthefollowingmessageboxwhenyouattempttomodifyaprotectedsymbol:
Page 452
IfyouchooseNo,thesymbol'svalueismodified,andprocessingcontinuesnormally.IfyouchooseYes,processingisinterrupted,andyouenteraVisualLISPbreakloop.ControlswitchestotheVisualLISPConsolewindow.Tosetthesymbolandcontinueprocessing,presstheContinuebuttonontheVisualLISPtoolbar;toabortmodification,pressReset.
Error Thisoptionprohibitsmodificationofprotectedsymbols.Anyattempttomodifyaprotectedsymbolresultsinanerrormessage.
TospecifyhowAutoLISPrespondstoattemptstomodifyprotectedsymbols,chooseTools EnvironmentOptions GeneralOptionsfromtheVisualLISPmenu.
Pleasesendusyourcommentaboutthispage
Page 453
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
AutoLISPProgramFiles
AlthoughyoucanenterAutoLISPcodeintheVisualLISPConsolewindoworattheAutoCADCommandprompt,testinganddebuggingaseriesofinstructionsareconsiderablyeasierwhenyousaveAutoLISPcodeinafileratherthanre-enteringiteachtimeyoumakearefinement.AutoLISPsourcecodeisusuallystoredinASCIItextfileswithan.lspextension.However,youcanloadAutoLISPcodefromanyASCIItextfile.
TocreateanewsourcefileinVLISP,chooseNewFilefromtheVLISPFilemenu.
ToeditexistingAutoLISPsourcecodeinVLISP,chooseOpenFilefromtheVLISPFilemenu,andusetheOpenFiledialogboxtoselectyourfile.VLISPloadsthisfileintoitstexteditoranddisplaysthecontentsinaneweditorwindow.
FormattingAutoLISPCodeCommentsinAutoLISPProgramFilesColorCoding
Pleasesendusyourcommentaboutthispage
Page 454
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPProgramFiles>
FormattingAutoLISPCode
TheextensiveuseofparenthesesinAutoLISPcodecanmakeitdifficulttoread.Thetraditionaltechniqueforcombattingthisconfusionisindentation.Themoredeeplynestedalineofcodeis,thefarthertotherightyoupositiontheline.
IfyouusetheVLISPtexteditortoenteryourcode,VLISPautomaticallyformatsthecodeasyouenterit.VLISPalsohasfeaturestoreformataselectionoranentirefile.Thisimprovestheappearanceofyourcode,makingitmorereadable.Forinformationonusingthesefeatures,seeFormattingCodewithVisualLISP.
SpacesinAutoLISPCode
Pleasesendusyourcommentaboutthispage
Page 455
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPProgramFiles>FormattingAutoLISPCode>
SpacesinAutoLISPCode
InAutoLISP,multiplespacesbetweenvariablenames,constants,andfunctionnamesareequivalenttoasinglespace.Theendofalineisalsotreatedasasinglespace.
Thefollowingtwoexpressionsproducethesameresult:
(setqtest1123test2456)
(setq
test1123
test2456
)
Pleasesendusyourcommentaboutthispage
Page 456
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPProgramFiles>
CommentsinAutoLISPProgramFiles
ItisgoodpracticetoincludecommentsinAutoLISPprogramfiles.Commentsareusefultoboththeprogrammerandfutureuserswhomayneedtoreviseaprogramtosuittheirneeds.Usecommentstodothefollowing:
Giveatitle,authorship,andcreationdate
Provideinstructionsonusingaroutine
Makeexplanatorynotesthroughoutthebodyofaroutine
Makenotestoyourselfduringdebugging
Commentsbeginwithoneormoresemicolons(;)andcontinuethroughtheendoftheline.
;Thisentirelineisacomment
(setqarea(*pirr));Computeareaofcircle
Anytextwithin;|...|;isignored.Therefore,commentscanbeincludedwithinalineofcodeorextendformultiplelines.Thistypeofcommentisknownasanin-linecomment.
(setqtmode;|somenotehere|;(getvar"tilemode"))
Thefollowingexampleshowsacommentthatcontinuesformultiplelines:
(setvar"orthomode"1);|commentstartshere
andcontinuestothisline,
butendswaydownhere|;(princ"\nORTHOMODEsetOn.")
ItisrecommendedthatyouusecommentsliberallywhenwritingAutoLISPprograms.ThetutorialfilesprovidedwithVLISPcontaingoodexamplesofcommentingstyle.Ifyou'veinstalledtheAutoLISPTutorialfiles,you'llfindthe
Page 457
AutoLISPtutorialcodeintheTutorial\VisualLISPdirectory.VisualLISPCommentStyles
Pleasesendusyourcommentaboutthispage
Page 458
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPProgramFiles>CommentsinAutoLISPProgramFiles>
VisualLISPCommentStyles
TheVLISPcodeformatterrecognizesfivetypesofcommentsandpositionseachcommentaccordingtoitstype.RefertoApplyingVisualLISPCommentStylesforadescriptionofeachcommentstyle.
Regardlessofyourcommentingstyle,itismoreimportantthatcommentsbepresentratherthantheyobeyanyparticularlayoutrules.
Pleasesendusyourcommentaboutthispage
Page 459
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPProgramFiles>
ColorCoding
VLISPprovidesanadditionalsolutiontomakeAutoLISPtexteasiertoread:colorcoding.VLISPlooksateachwordoftextandtriestodeterminewhattypeofAutoLISPlanguageelementthewordrepresents(forexample,abuilt-infunction,anumber,orastring).Everytypeofelementisassigneditsowncolor,soyoucaneasilydistinguishamongthemwhenviewingthecode.SeeUnderstandingVisualLISPColorCodingformoreinformationontheVLISPcolorcodingfeature.
KeepinmindthatcolorcodingisaVLISPtexteditorfeature,anditispossiblethatsomeonewhodoesnothaveaccesstoVLISPmayneedtoreadyourcodesomeday.Forthisreason,youshouldstilluseindentationandalignmenttoenhanceyourprogram'sreadability.
Pleasesendusyourcommentaboutthispage
Page 460
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
AutoLISPVariables
AnAutoLISPvariableassumesthedatatypeofthevalueassignedtoit.Untiltheyareassignednewvalues,variablesretaintheiroriginalvalues.YouusetheAutoLISPsetqfunctiontoassignvaluestovariables.
(setqvariable_name1value1
[variable_name2value2...])
Thesetqfunctionassignsthespecifiedvaluetothevariablenamegiven.Itreturnsthevalueasitsfunctionresult.IfyouissuesetqattheVisualLISPConsoleprompt,theresultisdisplayedintheConsolewindow:
_$ (setq val 3abc 3.875)3.875
_$ (setq layr "EXTERIOR-WALLS")"EXTERIOR-WALLS"
_$
DisplayingtheValueofaVariableNilVariablesPredefinedVariables
Pleasesendusyourcommentaboutthispage
Page 461
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPVariables>
DisplayingtheValueofaVariable
TodisplaythecurrentvalueofavariablewhenworkinginVisualLISP,justenterthevariablenameattheConsolepromptasfollows:
_$abc3.875
TodisplaythevalueofavariablefromtheAutoCADCommandprompt,youmustprecedethevariablenamewithanexclamationpoint(!).Forexample:
Command:!abc
3.875
Pleasesendusyourcommentaboutthispage
Page 462
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPVariables>
NilVariables
AnAutoLISPvariablethathasnotbeenassignedavalueissaidtobenil.Thisisdifferentfromblank,whichisconsideredacharacterstring,anddifferentfrom0,whichisanumber.So,inadditiontocheckingavariableforitscurrentvalue,youcantesttodetermineifthevariablehasbeenassignedavalue.
Eachvariableconsumesasmallamountofmemory,soitisgoodprogrammingpracticetoreusevariablenamesorsetvariablestonilwhentheirvaluesarenolongerneeded.Settingavariabletonilreleasesthememoryusedtostorethatvariable'svalue.Ifyounolongerneedthevalvariable,youcanreleaseitsvaluefrommemorywiththefollowingexpression:
_$ (setq val nil)nil
Anotherefficientprogrammingpracticeistouselocalvariableswheneverpossible.SeeLocalVariablesinFunctionsonthistopic.
Pleasesendusyourcommentaboutthispage
Page 463
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>AutoLISPVariables>
PredefinedVariables
ThefollowingpredefinedvariablesarecommonlyusedinAutoLISPapplications:
PAUSE
Definedasastringconsistingofadoublebackslash(\\)character.Thisvariableisusedwiththecommandfunctiontopauseforuserinput.
PI
Definedastheconstantp(pi).Itevaluatestoapproximately3.14159.
T
DefinedastheconstantT.Thisisusedasanon-nilvalue.
Note Youcanchangethevalueofthesevariableswiththesetqfunction.However,otherapplicationsmightrelyontheirvaluesbeingconsistent;therefore,itisrecommendedthatyoudonotmodifythesevariables.VisualLISP,bydefault,protectsthesevariablesfromredefinition.YoucanoverridethisprotectionthroughtheVLISPSymbolServicefeatureorbysettingaVLISPenvironmentoption.
Pleasesendusyourcommentaboutthispage
Page 464
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
NumberHandling
AutoLISPprovidesfunctionsforworkingwithintegersandrealnumbers.Inadditiontoperformingcomplexmathematicalcomputationsinapplications,youcanusethenumber-handlingfunctionstohelpyouinyourdailyuseofAutoCAD.Ifyouaredrawingasteelconnectiondetailthatusesa2.5"boltthatis0.5"indiameter,howmanythreadsarethereifthebolthas13threadsperinch?Usethe*(multiplication)functionattheConsoleprompt,asinthefollowingexample:
_$ (*2.513)32.5
Thearithmeticfunctionsthathaveanumberargument(asopposedtonumorangle,forexample)returndifferentvaluesifyouprovideintegersorrealsasarguments.Ifallargumentsareintegers,thevaluereturnedisaninteger.However,ifoneoralltheargumentsarereals,thevaluereturnedisareal.Toensureyourapplicationpassesrealvalues,becertainatleastoneargumentisareal.
_$ (/125)2
_$ (/12.05)2.4
Acompletelistofnumber-handlingfunctionsisinAutoLISPFunctionSynopsisundertheheadingArithmeticFunctionsThesefunctionsaredescribedintheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 465
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
StringHandling
AutoLISPprovidesfunctionsforworkingwithstringvalues.Forexample,thestrcasefunctionreturnstheconversionofallalphabeticcharactersinastringtouppercaseorlowercase.Itacceptstwoarguments:astringandanoptionalargumentthatspecifiesthecaseinwhichthecharactersarereturned.Iftheoptionalsecondargumentisomitted,itevaluatestonilandstrcasereturnsthecharactersconvertedtouppercase.
_$ (strcase"ThisisaTEST.")"THISISATEST."
IfyouprovideasecondargumentofT,thecharactersarereturnedaslowercase.AutoLISPprovidesthepredefinedvariableTtouseinsimilarsituationswhereanon-nilvalueisusedasatypeoftrue/falsetoggle.
_$ (strcase"ThisisaTEST."T)"thisisatest."
Thestrcatfunctioncombinesmultiplestringsintoasinglestringvalue.Thisisusefulforplacingavariablestringwithinaconstantstring.Thefollowingcodesetsavariabletoastringvalueandthenusesstrcattoinsertthatstringintothemiddleofanotherstring.
_$ (setqstr"BIG")(setqbigstr(strcat"Thisisa"str"test."))"ThisisaBIGtest."
Ifthevariablebigstrissettotheprecedingstringvalue,youcanusethestrlenfunctiontofindoutthenumberofcharacters(includingspaces)inthat
Page 466
string.
_$ (strlenbigstr)19
Thesubstrfunctionreturnsasubstringofastring.Ithastworequiredargumentsandoneoptionalargument.Thefirstrequiredargumentisthestring.Thesecondargumentisapositiveintegerthatspecifiesthefirstcharacterofthestringyouwanttoincludeinthesubstring.Ifthethirdargumentisprovided,itspecifiesthenumberofcharacterstoincludeinthesubstring.Ifthethirdargumentisnotprovided,substrreturnsallcharactersincludingandfollowingthespecifiedstartcharacter.
Asanexample,youcanusethesubstrfunctiontostripoffthethree-letterextensionfromafilename(notethatyoucanactuallyusethevl-file-name-basefunctiontodothis).First,setavariabletoafilename.
_$ (setqfilnam"bigfile.txt")"bigfile.txt"
Youneedtogetastringthatcontainsallcharactersexceptthelastfour(theperiodandthethree-letterextension).Usestrlentogetthelengthofthestringandsubtract4fromthatvalue.Thenusesubstrtospecifythefirstcharacterofthesubstringanditslength.
_$ (setqnewlen(-(strlenfilnam)4))7
_$ (substrfilnam1newlen)"bigfile"
Ifyourapplicationhasnoneedforthevalueofnewlen,youcancombinethesetwolinesofcodeintoone.
_$ (substrfilnam1(-(strlenfilnam)4))"bigfile"
Additionalstring-handlingfunctionsarelistedinAutoLISPFunctionSynopsisundertheheadingString-HandlingFunctionsThesefunctionsaredescribedin
Page 467
theAutoLISPReference.
AutoLISPalsoprovidesanumberoffunctionsthatconvertstringvaluesintonumericvaluesandnumericvaluesintostringvalues.ThesefunctionsarediscussedinConversions.
Pleasesendusyourcommentaboutthispage
Page 468
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
BasicOutputFunctions
AutoLISPincludesfunctionsforcontrollingtheAutoCADdisplay,includingbothtextandgraphicswindows.SomefunctionsalsodisplayinformationintheVisualLISPConsolewindow.Themajortextdisplayfunctionsare:
prin1
princ
print
prompt
Thesefunctionsarediscussedinthefollowingsections.TheremainingdisplayfunctionsarecoveredinUsingAutoLISPtoCommunicatewithAutoCAD,beginningwiththeDisplayControltopic.
DisplayingMessagesControlCharactersinStringsWild-CardMatching
Pleasesendusyourcommentaboutthispage
Page 469
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>BasicOutputFunctions>
DisplayingMessages
WhenenteredfromVLISP,thepromptfunctiondisplaysamessage(astring)intheAutoCADCommandwindowandreturnsniltotheVLISPConsolewindow.Theprinc,prin1,andprintfunctionsalldisplayanexpression(notnecessarilyastring)intheAutoCADCommandwindowandreturntheexpressiontotheVLISPConsolewindow.Optionally,thesefunctionscansendoutputtoafile.Thedifferencesareasfollows:
princdisplaysstringswithouttheenclosingquotationmarks.
prin1displaysstringsenclosedinquotationmarks.
printdisplaysstringsenclosedinquotationmarksbutplacesablanklinebeforetheexpressionandaspaceafterward.
Thefollowingexamplesdemonstratethedifferencesbetweenthefourbasicoutputfunctionsandhowtheyhandlethesamestringoftext.IfyouentertheexamplesfromVLISP,thetextfollowingprintsiswhatyouseeattheAutoCADCommandprompt;textfollowingreturnsappearswithintheVLISPConsolewindoworwithinanapplication.SeeControlCharactersinStringsforanexplanationofthecontrolcharactersusedintheexample.
(setqstr"The\"allowable\"toleranceis\261\274\"")
(promptstr)printsThe"allowable"tolerance
is1/4"andreturnsnil
(princstr)printsThe"allowable"tolerance
is1/4"andreturns"The\"allowable\"toleranceis1/4\""
(prin1str)prints"The\"allowable\"
toleranceis1/4""andreturns"The\"allowable\"toleranceis1/4\""
(printstr)prints<blankline>
Page 470
"The\"allowable\"
toleranceis1/4""<space>andreturns"The\"allowable\"toleranceis1/4\""
Notethatthewrite-charandwrite-linefunctionscanalsodisplayoutputtoaCommandwindow.RefertotheAutoLISPReferenceforinformationonthesefunctions.
ExitingQuietly
Pleasesendusyourcommentaboutthispage
Page 471
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>BasicOutputFunctions>DisplayingMessages>
ExitingQuietly
Ifyouinvoketheprincfunctionwithoutpassinganexpressiontoit,itdisplaysnothingandhasnovaluetoreturn.SoifyouwriteanAutoLISPexpressionthatendswithacalltoprincwithoutanyarguments,theendingnilissuppressed(becauseithasnothingtoreturn).Thispracticeiscalledexitingquietly.
Pleasesendusyourcommentaboutthispage
Page 472
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>BasicOutputFunctions>
ControlCharactersinStrings
Withinquotedstrings,thebackslash(\)characterallowscontrolcharacters(orescapecodes)tobeincluded.Thefollowingtableshowsthecurrentlyrecognizedcontrolcharacters:
AutoLISPcontrolcharacters
Code Description
\\ \character
\" "character
\e Escapecharacter
\n Newlinecharacter
\r Returncharacter
\t Tabcharacter
\nnn Characterwhoseoctalcodeisnnn
ThepromptandprincfunctionsexpandthecontrolcharactersinastringanddisplaytheexpandedstringintheAutoCADCommandwindow.
Ifyouneedtousethebackslashcharacter(\)orquotationmark(")withina
Page 473
quotedstring,itmustbeprecededbythebackslashcharacter(\).Forexample,ifyouenter
_$ (princ"The\"filename\"is:D:\\ACAD\\TEST.TXT.")
thefollowingtextisdisplayedintheAutoCADCommandwindow:
The"filename"is:D:\ACAD\TEST.TXT
YouwillalsoseethisoutputintheVLISPConsolewindow,alongwiththereturnvaluefromtheprincfunction(whichisyouroriginalinput,withtheunexpandedcontrolcharacters).
Toforcealinebreakataspecificlocationinastring,usethenewlinecharacter(\n).
_$ (prompt"Anexampleofthe\nnewlinecharacter.")Anexampleofthe
newlinecharacter.
Youcanalsousetheterprifunctiontocausealinebreak.
Thereturncharacter(\r)returnstothebeginningofthecurrentline.Thisisusefulfordisplayingincrementalinformation(forexample,acountershowingthenumberofobjectsprocessedduringaloop).
TheTabcharacter(\t)canbeusedinstringstoindentortoprovidealignmentwithothertabbedtextstrings.Inthisexample,notetheuseoftheprincfunctiontosuppresstheendingnil.
_$ (prompt"\nName\tOffice\n-----\t-----
(_>\nSue\t101\nJoe\t102\nSam\t103\n")
(princ)
Name Office
----- -----
Page 474
Sue 101
Joe 102
Sam 103
Pleasesendusyourcommentaboutthispage
Page 475
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>BasicOutputFunctions>
Wild-CardMatching
Thewcmatchfunctionenablesapplicationstocompareastringtoawild-cardpattern.Youcanusethisfacilitywhenyoubuildaselectionset(inconjunctionwithssget)andwhenyouretrieveextendedentitydatabyapplicationname(inconjunctionwithentget).
Thewcmatchfunctioncomparesasinglestringtoapattern.ThefunctionreturnsTifthestringmatchesthepattern,andnilifitdoesnot.Thewild-cardpatternsaresimilartotheregularexpressionsusedbymanysystemandapplicationprograms.Inthepattern,alphabeticcharactersandnumeralsaretreatedliterally;bracketscanbeusedtospecifyoptionalcharactersorarangeoflettersordigits;aquestionmark(?)matchesasinglecharacter;anasterisk(*)matchesasequenceofcharacters;and,certainotherspecialcharactershavespecialmeaningswithinthepattern.Whenyouusethe*characteratthebeginningandendofthesearchpattern,youcanlocatethedesiredportionanywhereinthestring.
Inthefollowingexamples,astringvariablecalledmatchmehasbeendeclaredandinitialized:
_$ (setqmatchme"thisisastring-test1test2theend")"thisisastring-test1test2theend"
Thefollowingcodecheckswhetherornotmatchmebeginswiththefourcharacters"this":
_$ (wcmatchmatchme"this*")T
Thefollowingcodeillustratestheuseofbracketsinthepattern.Inthiscase,
Page 476
wcmatchreturnsTifmatchmecontains"test4","test5","test6"(4-6),or"test9"(notetheuseofthe*character):
_$ (wcmatchmatchme"*test[4-69]*")nil
Inthiscase,wcmatchreturnsnilbecausematchmedoesnotcontainanyofthestringsindicatedbythepattern.
However,
_$ (wcmatchmatchme"*test[4-61]*")T
returnstruebecausethestringcontains"test1".
Thepatternstringcanspecifymultiplepatterns,separatedbycommas.ThefollowingcodereturnsTifmatchmeequals"ABC",orifitbeginswith"XYZ",orifitendswith"end".
_$ (wcmatchmatchme"ABC,XYZ*,*end")T
Pleasesendusyourcommentaboutthispage
Page 477
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
EqualityandConditional
AutoLISPincludesfunctionsthatprovideequalityverificationaswellasconditionalbranchingandlooping.TheequalityandconditionalfunctionsarelistedinAutoLISPFunctionSynopsisundertheheadingEqualityandConditionalFunctionsThesefunctionsaredescribedintheAutoLISPReference.
Whenwritingcodethatchecksstringandsymboltablenames,keepinmindthatAutoLISPautomaticallyconvertssymboltablenamestouppercaseinsomeinstances.Whentestingsymbolnamesforequality,youneedtomakethecomparisoninsensitivetothecaseofthenames.Usethestrcasefunctiontoconvertstringstothesamecasebeforetestingthemforequality.
Pleasesendusyourcommentaboutthispage
Page 478
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
ListHandling
AutoLISPprovidesfunctionsforworkingwithlists.Thissectionprovidesexamplesoftheappend,assoc,car,cons,list,nth,andsubstfunctions.Asummaryofalllist-handlingfunctionsisinAutoLISPFunctionSynopsisundertheheadingListManipulationFunctionsEachlist-handlingfunctionisdescribedintheAutoLISPReference.
Listsprovideanefficientandpowerfulmethodofstoringnumerousrelatedvalues.Afterall,LISPisso-namedbecauseitistheLIStProcessinglanguage.Onceyouunderstandthepoweroflists,you'llfindthatyoucancreatemorepowerfulandflexibleapplications.
SeveralAutoLISPfunctionsprovideabasisforprogrammingtwo-dimensionalandthree-dimensionalgraphicsapplications.Thesefunctionsreturnpointvaluesintheformofalist.
Thelistfunctionprovidesasimplemethodofgroupingrelateditems.Theseitemsdonotneedtobeofsimilardatatypes.Thefollowingcodegroupsthreerelateditemsasalist:
_$ (setqlst1(list1.0"One"1))(1.0"One"1)
Youcanretrieveaspecificitemfromthelistinthelst1variablewiththenthfunction.Thisfunctionacceptstwoarguments.Thefirstargumentisanintegerthatspecifieswhichitemtoreturn.A0specifiesthefirstiteminalist,1specifiestheseconditem,andsoon.Thesecondargumentisthelistitself.Thefollowingcodereturnstheseconditeminlst1.
_$ (nth1lst1)"One"
Page 479
Thecdrfunctionreturnsallelements,exceptthefirst,fromalist.Forexample:
_$(cdrlst1)("One"1)
Thecarfunctionprovidesanotherwaytoextractitemsfromalist.Formoreexamplesusingcarandcdr,andcombinationsofthetwo,seePointLists.
Threefunctionsletyoumodifyanexistinglist.Theappendfunctionreturnsalistwithnewitemsaddedtotheendofit,andtheconsfunctionreturnsalistwithnewitemsaddedtothebeginningofthelist.Thesubstfunctionreturnsalistwithanewitemsubstitutedforeveryoccurrenceofanolditem.Thesefunctionsdonotmodifytheoriginallist;theyreturnamodifiedlist.Tomodifytheoriginallist,youmustexplicitlyreplacetheoldlistwiththenewlist.
Theappendfunctiontakesanynumberoflistsandrunsthemtogetherasonelist.Therefore,allargumentstothisfunctionmustbelists.Thefollowingcodeaddsanother"One"tothelistlst1.Notetheuseofthequote(or')functionasaneasywaytomakethestring"One"intoalist.
_$ (setqlst2(appendlst1'("One")))(1.0"One"1"One")
Theconsfunctioncombinesasingleelementwithalist.Youcanaddanotherstring"One"tothebeginningofthisnewlist,lst2,withtheconsfunction.
_$ (setqlst3(cons"One"lst2))("One"1.0"One"1"One")
Youcansubstitutealloccurrencesofaniteminalistwithanewitemwiththesubstfunction.Thefollowingcodereplacesallstrings"One"withthestring"one".
_$ (setqlst4(subst"one""One"lst3))("one"1.0"one"1"one")
PointListsDottedPairs
Page 480
Pleasesendusyourcommentaboutthispage
Page 481
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>ListHandling>
PointLists
AutoLISPobservesthefollowingconventionsforhandlinggraphicscoordinates.Pointsareexpressedaslistsoftwoorthreenumberssurroundedbyparentheses.
2Dpoints
Expressedaslistsoftworealnumbers(XandY,respectively),asin(3.47.52)
3Dpoints
Expressedaslistsofthreerealnumbers(X,Y,andZ,respectively),asin(3.47.521.0)
Youcanusethelistfunctiontoformpointlists,asshowninthefollowingexamples:
_$(list 3.8751.23)(3.875 1.23)_$(list88.0 14.77 3.14)(88.0 14.77 3.14)
Toassignparticularcoordinatestoapointvariable,youcanuseoneofthefollowingexpressions:
_$(setqpt1(list3.875
1.23))(3.875 1.23)_$(setqpt2(list88.0
14.773.14))(88.0 14.77 3.14)_$(setqabc3.45)
Page 482
3.45
_$(setqpt3(listabc
1.23))(3.45 1.23)
ThelatterusesthevalueofvariableabcastheXcomponentofthepoint.
Ifallmembersofalistareconstantvalues,youcanusethequotefunctiontoexplicitlydefinethelist,ratherthanthelistfunction.Thequotefunctionreturnsanexpressionwithoutevaluation,asfollows:
_$ (setqpt1(quote(4.57.5)))(4.5 7.5)
Thesinglequotationmark(')canbeusedasshorthandforthequotefunction.Thefollowingcodeproducesthesameresultastheprecedingcode.
_$ (setqpt1'(4.57.5))(4.5 7.5)
YoucanrefertoX,Y,andZcomponentsofapointindividually,usingthreeadditionalbuilt-infunctionscalledcar,cadr,andcaddr.ThefollowingexamplesshowhowtoextracttheX,Y,andZcoordinatesfroma3Dpointlist.Theptvariableissettothepoint(1.53.22.0):
_$ (setqpt'(1.5 3.2 2.0))(1.5 3.2 2.0)
Thecarfunctionreturnsthefirstmemberofalist.InthisexampleitreturnstheXvalueofpointpttothex_valvariable.
_$ (setqx_val(carpt))1.5
Thecadrfunctionreturnsthesecondmemberofalist.InthisexampleitreturnstheYvalueoftheptpointtothey_valvariable.
_$ (setqy_val(cadrpt))
Page 483
3.2
Thecaddrfunctionreturnsthethirdmemberofalist.InthisexampleitreturnstheZvalueofpointpttothevariablez_val.
_$ (setqz_val(caddrpt))2.0
Youcanusethefollowingcodetodefinethelower-leftandupper-right(pt1andpt2)cornersofarectangle,asfollows:
_$ (setqpt1'(1.02.0)pt2'(3.04.0))(3.0 4.0)
Youcanusethecarandcadrfunctionstosetthept3variabletotheupper-leftcorneroftherectangle,byextractingtheXcomponentofpt1andtheYcomponentofpt2,asfollows:
_$ (setqpt3(list(carpt1)(cadrpt2)))(1.0 4.0)
Theprecedingexpressionsetspt3equaltopoint(1.0,4.0).
AutoLISPsupportsconcatenationsofcarandcdruptofourlevelsdeep.Thefollowingarevalidfunctions:
caaaar cadaar cdaaar cddaar
caaadr cadadr cdaadr cddadr
caaar cadar cdaar cddar
caadar caddar cdadar cdddar
caaddr cadddr cdaddr cddddr
caadr caddr cdadr cdddr
Page 484
caar cadr cdar cddr
Theseconcatenationsaretheequivalentofnestedcallstocarandcdr.Eacharepresentsacalltocar,andeachdrepresentsacalltocdr.Forexample:
(caarx)isequivalent
to(car(carx))
(cdarx)isequivalent
to(cdr(carx))
(cadarx)isequivalent
to(car(cdr(carx)))
(cadrx)isequivalent
to(car(cdrx))
(cddrx)isequivalent
to(cdr(cdrx))
(caddrx)isequivalentto(car(cdr(cdrx)))
Pleasesendusyourcommentaboutthispage
Page 485
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>ListHandling>
DottedPairs
AnotherwayAutoLISPusesliststoorganizedataiswithaspecialtypeoflistcalledadottedpair.Thislistmustalwayscontaintwomembers.Whenrepresentingadottedpair,AutoLISPseparatesthemembersofthelistwithaperiod(.).Mostlist-handlingfunctionswillnotacceptadottedpairasanargument,soyoushouldbesureyouarepassingtherightkindoflisttoafunction.
Dottedpairsareanexampleofan"improperlist."Animproperlistisoneinwhichthelastcdrisnotnil.Inadditiontoaddinganitemtothebeginningofalist,theconsfunctioncancreateadottedpair.Ifthesecondargumenttotheconsfunctionisanythingotherthananotherlistornil,itcreatesadottedpair.
_$ (setqsublist(cons'lyr"WALLS"))(LYR."WALLS")
Thecar,cdr,andassocfunctionsareusefulforhandlingdottedpairs.Thefollowingcodecreatesanassociationlist,whichisalistoflists,andisthemethodAutoLISPusestomaintainentitydefinitiondata.(EntitydefinitiondataisdiscussedinUsingAutoLISPtoManipulateAutoCADObjects)Thefollowingcodecreatesanassociationlistofdottedpairs:
_$ (setqwallinfo(listsublist(cons'len240.0)(cons'hgt96.0)))((LYR."WALLS")(LEN.240.0)(HGT.96.0))
Theassocfunctionreturnsaspecifiedlistfromwithinanassociationlistregardlessofthespecifiedlist'slocationwithintheassociationlist.Theassocfunctionsearchesforaspecifiedkeyelementinthelists,asfollows:
Page 486
_$(assoc'lenwallinfo)(LEN.240.0)
_$(cdr(assoc'lyr
wallinfo))"WALLS"
_$(nth1wallinfo)(LEN.240.0)
_$(car(nth1wallinfo))LEN
Pleasesendusyourcommentaboutthispage
Page 487
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
SymbolandFunctionHandling
AutoLISPprovidesanumberoffunctionsforhandlingsymbolsandvariables.Thesymbol-handlingfunctionsarelistedinAutoLISPFunctionSynopsisundertheheadingSymbol-HandlingFunctionsEachsymbol-handlingfunctionisdescribedintheAutoLISPReference.
AutoLISPprovidesfunctionsforhandlingoneormoregroupsoffunctions.Thissectionprovidesexamplesofthedefunfunction.Theremainingfunction-handlingfunctionsarelistedinAutoLISPFunctionSynopsisundertheheadingSymbol-HandlingFunctionsThefunctionsaredescribedintheAutoLISPReference.
UsingdefuntoDefineaFunctionC:XXXFunctionsLocalVariablesinFunctionsFunctionswithArguments
Pleasesendusyourcommentaboutthispage
Page 488
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>
UsingdefuntoDefineaFunction
WithAutoLISP,youcandefineyourownfunctions.Oncedefined,thesefunctionscanbeusedattheAutoCADCommandprompt,theVisualLISPConsoleprompt,orwithinotherAutoLISPexpressions,justasyouusethestandardfunctions.YoucanalsocreateyourownAutoCADcommands,becausecommandsarejustaspecialtypeoffunction.
Thedefunfunctioncombinesagroupofexpressionsintoafunctionorcommand.Thisfunctionrequiresatleastthreearguments,thefirstofwhichisthenameofthefunction(symbolname)todefine.Thesecondargumentistheargumentlist(alistofargumentsandlocalvariablesusedbythefunction).Theargumentlistcanbeniloranemptylist().ArgumentlistsarediscussedingreaterdetailinFunctionswithArguments.Iflocalvariablesareprovided,theyareseparatedfromtheargumentsbyaslash(/).LocalvariablesarediscussedinLocalVariablesinFunctions.Followingtheseargumentsaretheexpressionsthatmakeupthefunction;theremustbeatleastoneexpressioninafunctiondefinition.
(defunsymbol_name(args/local_variables)
expressions
)
Thefollowingcodedefinesasimplefunctionthatacceptsnoargumentsanddisplays“bye”intheAutoCADCommandwindow.Notethattheargumentlistisdefinedasanemptylist(()):
_$ (defunDONE()(prompt"\nbye!"))DONE
NowthattheDONEfunctionisdefined,youcanuseitasyouwouldanyotherfunction.Forexample,thefollowingcodeprintsamessage,thensays“bye”in
Page 489
theAutoCADCommandwindow:
_$ (prompt"Thevalueis127.")(DONE)(princ)Thevalueis127
bye!
Notehowthepreviousexampleinvokestheprincfunctionwithoutanyarguments.Thissuppressesanendingnilandachievesaquietexit.
Functionsthatacceptnoargumentsmayseemuseless.However,youmightusethistypeoffunctiontoquerythestateofcertainsystemvariablesorconditionsandtoreturnavaluethatindicatesthosevalues.
AutoCADcanautomaticallyloadyourfunctionseachtimeyoustartanewAutoCADsessionoropenanewAutoCADdrawingfile;seeAutomaticallyLoadandExecuteVBAProjectsintheAutoCADCustomizationGuideforfurtherinformationonautomaticloading.
AnycodeinanAutoLISPprogramfilethatisnotpartofadefunstatementisexecutedwhenthatfileisloaded.Youcanusethistosetupcertainparametersortoperformanyotherinitializationproceduresinadditiontodisplayingtextualinformation,suchashowtoinvoketheloadedfunction.
CompatibilityofdefunwithPreviousVersionsofAutoCAD
Pleasesendusyourcommentaboutthispage
Page 490
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>UsingdefuntoDefineaFunction>
CompatibilityofdefunwithPreviousVersionsofAutoCAD
TheinternalimplementationofdefunchangedinAutoCAD2000.ThischangewillbetransparenttothegreatmajorityofAutoLISPusersupgradingfromearlierversionsofAutoCAD.ThechangeonlyaffectsAutoLISPcodethatmanipulateddefundefinitionsasaliststructure,suchasbyappendingonefunctiontoanother,asinthefollowingcode:
(appends::startup(cdrmystartup))
Forsituationslikethis,youcanusedefun-qtodefineyourfunctions.Anattempttouseadefunfunctionasalistresultsinanerror.Thefollowingexampleillustratestheerror:
_$(defunfoo(x)4)foo
_$(appendfoo'(34));error:Invalidattempttoaccessacompiledfunctiondefinition.
Youmaywanttodefineitusingdefun-q:#<SUBR@024bda3cFOO>
Theerrormessagealertsyoutothepossibilityofusingdefun-qinsteadofdefun.
Thedefun-qfunctionisprovidedstrictlyforbackwardcompatibilitywithpreviousversionsofAutoLISPandshouldnotbeusedforotherpurposes.Formoreinformationonusingdefun-q,andtherelateddefun-q-list-setanddefun-q-list-reffunctions,seetheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 491
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>
C:XXXFunctions
IfanAutoLISPfunctionisdefinedwithanameoftheformC:xxx,itcanbeissuedattheAutoCADCommandpromptinthesamemannerasabuilt-inAutoCADcommand.ThisistrueregardlessofwhetheryoudefineandloadthefunctioninVLISPorattheAutoCADCommandprompt.YoucanusethisfeaturetoaddnewcommandstoAutoCADortoredefineexistingcommands.
TousefunctionsasAutoCADcommands,besuretheyadheretothefollowingrules:
ThefunctionnamemustusetheformC:XXX(upper-orlowercasecharacters).TheC:portionofthenamemustalwaysbepresent;theXXXportionisacommandnameofyourchoice.C:XXXfunctionscanbeusedtooverridebuilt-inAutoCADcommands.(SeeRedefiningAutoCADCommands.)
Thefunctionmustbedefinedwithnoarguments.However,localvariablesarepermittedanditisagoodprogrammingpracticetousethem.
Afunctiondefinedinthismannercanbeissuedtransparentlyfromwithinanypromptofanybuilt-inAutoCADcommand,providedthefunctionissuedtransparentlydoesnotcallthecommandfunction.(ThisistheAutoLISPfunctionyouusetoissueAutoCADcommands;seetheentryoncommandintheAutoLISPReference.)WhenissuingaC:XXXdefinedcommandtransparently,youmustprecedetheXXXportionwithasinglequotationmark(').
Youcanissueabuilt-incommandtransparentlywhileaC:XXXcommandisactivebyprecedingitwithasinglequotationmark('),asyouwouldwithallcommandsthatareissuedtransparently.However,youcannotissueaC:XXXcommandtransparentlywhileaC:XXXcommandisactive.
Page 492
Note WhencallingafunctiondefinedasacommandfromthecodeofanotherAutoLISPfunction,youmustusethewholename,includingtheparentheses;forexample,(C:HELLO).YoualsomustusethewholenameandtheparentheseswhenyouinvokethefunctionfromtheVLISPConsoleprompt.
AddingCommandsRedefiningAutoCADCommands
Pleasesendusyourcommentaboutthispage
Page 493
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>C:XXXFunctions>
AddingCommands
UsingtheC:XXXfeature,youcandefineacommandthatdisplaysasimplemessage.
_$ (defunC:HELLO()(princ"Helloworld.\n")(princ))C:HELLO
HELLOisnowdefinedasacommand,inadditiontobeinganAutoLISPfunction.ThismeansyoucanissuethecommandfromtheAutoCADCommandprompt.
Command: hello
Helloworld.
Thisnewcommandcanbeissuedtransparentlybecauseitdoesnotcallthecommandfunctionitself.AttheAutoCADCommandprompt,youcoulddothefollowing:
Command: line
Frompoint: 'hello
Helloworld.
Frompoint:
Remember:torunthisfunctionfromtheVLISPConsolewindow,youneedtoissuethefunctioncallwiththeparenthesesbecauseVLISPdoesnotrecognizeAutoCADcommands.
_$(c:hello)Helloworld.
Ifyoufollowyourfunctiondefinitionwithacalltothesetfunhelpfunction,youcanassociateaHelpfileandtopicwithauser-definedcommand.Whenhelp
Page 494
isrequestedduringexecutionoftheuser-definedcommand,thetopicspecifiedbysetfunhelpdisplays.SeetheAutoLISPReferenceformoreinformationonusingsetfunhelp.
YoucannotusuallyuseanAutoLISPstatementtorespondtopromptsfromanAutoLISP-implementedcommand.However,ifyourAutoLISProutinemakesuseoftheinitgetfunction,youcanusearbitrarykeyboardinputwithcertainfunctions.ThisallowsanAutoLISP-implementedcommandtoacceptanAutoLISPstatementasaresponse.Also,thevaluesreturnedbyaDIESELexpressioncanperformsomeevaluationofthecurrentdrawingandreturnthesevaluestoAutoLISP.SeeKeywordOptionsformoreinformationonusinginitget,andrefertotheAutoCADCustomizationGuideforinformationontheDIESELstringexpressionlanguage.
Pleasesendusyourcommentaboutthispage
Page 495
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>C:XXXFunctions>
RedefiningAutoCADCommands
UsingAutoLISP,externalcommands,andthealiasfeature,youcandefineyourownAutoCADcommands.YoucanusetheUNDEFINEcommandtoredefineabuilt-inAutoCADcommandwithauser-definedcommandofthesamename.Torestorethebuilt-indefinitionofacommand,usetheREDEFINEcommand.TheUNDEFINEcommandisineffectforthecurrenteditingsessiononly.
Youcanalwaysactivateanundefinedcommandbyspecifyingitstruename,whichisthecommandnameprefixedbyaperiod.Forexample,ifyouundefineQUIT,youcanstillaccessthecommandbyentering.quitattheAutoCADCommandprompt.ThisisalsothesyntaxthatshouldbeusedwithintheAutoLISPcommandfunction.
Considerthefollowingexample.WheneveryouusetheLINEcommand,youwantAutoCADtoremindyouaboutusingthePLINEcommand.YoucandefinetheAutoLISPfunctionC:LINEtosubstituteforthenormalLINEcommandasfollows:
_$ (defunC:LINE()(_>(princ"Shouldn't
youbeusingPLINE?\n")
(_>(command".LINE")
(princ))C:LINE
Inthisexample,thefunctionC:LINEisdesignedtoissueitsmessageandthentoexecutethenormalLINEcommand(usingitstruename,.LINE).BeforeAutoCADwilluseyournewdefinitionfortheLINEcommand,youmustundefinethebuilt-inLINEcommand.Enterthefollowingtoundefinethebuilt-inLINEcommand:
Page 496
_$ (command"undefine""line")
Now,ifyouenterlineattheAutoCADCommandprompt,AutoCADusestheC:LINEAutoLISPfunction:
Command: line
Shouldn'tyoubeusingPLINE?
.LINESpecifyfirstpoint:Specifyfirstpoint:
ThepreviouscodeexampleassumestheCMDECHOsystemvariableissetto1(On).IfCMDECHOissetto0(Off),AutoCADdoesnotechopromptsduringacommandfunctioncall.ThefollowingcodeusestheCMDECHOsystemvariabletopreventtheLINEcommandpromptfromrepeating:
_$ (defunC:LINE(/cmdsave)
(_>(setqcmdsave(getvar
"cmdecho"))
(_>(setvar"cmdecho"
0)
(_>(princ"Shouldn't
youbeusingPLINE?\n")
(_>(command".LINE")
(_>(setvar"cmdecho"
cmdsave)
(_>(princ))C:LINE
NowifyouenterlineattheAutoCADCommandprompt,thefollowingtextisdisplayed:
Shouldn'tyoubeusingPLINE?
Specifyfirstpoint:
Youcanusethisfeatureinadrawingmanagementsystem,forexample.YoucanredefinetheNEW,OPEN,andQUITcommandstowritebillinginformationtoalogfilebeforeyouterminatetheeditingsession.
Itisrecommendedthatyouprotectyourmenus,scripts,andAutoLISPprogramsbyusingtheperiod-prefixedformsofallcommands.Thisensuresthatyourapplicationsusethebuilt-incommanddefinitionsratherthanaredefined
Page 497
command.
SeetheOverviewofFileOrganizationtopicintheAutoCADCustomizationGuideforadescriptionofthestepsAutoCADtakestoevaluatecommandnames.
Pleasesendusyourcommentaboutthispage
Page 498
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>
LocalVariablesinFunctions
AutoLISPprovidesamethodfordefiningalistofsymbols(variables)thatareavailableonlytoyourfunction.Theseareknownaslocalvariables.
LocalVariablesversusGlobalVariablesExampleUsingLocalVariables
Pleasesendusyourcommentaboutthispage
Page 499
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>LocalVariablesinFunctions>
LocalVariablesversusGlobalVariables
Theuseoflocalvariablesensuresthatthevariablesinyourfunctionsareunaffectedbythesurroundingapplicationandthatyourvariablesdonotremainavailableafterthecallingfunctionhascompleteditstask.
Manyuser-definedfunctionsareusedasutilityfunctionswithinlargerapplications.User-definedfunctionsalsotypicallycontainanumberofvariableswhosevaluesandusearespecifictothatfunction.
Thedangerinusingglobalvariables,insteadoflocalvariables,isyoumayinadvertentlymodifythemoutsideofthefunctiontheyweredeclaredinandintendedfor.Thiscanleadtounpredictablebehavior,anditcanbeverydifficulttoidentifythesourceofthistypeofproblem.
AnotheradvantageofusinglocalvariablesisthatAutoCADcanrecyclethememoryspaceusedbythesevariables,whereasglobalvariableskeepaccumulatingwithinAutoCADmemoryspace.
Therearesomelegitimateusesforglobalvariables,buttheseshouldbekepttoaminimum.Itisalsoagoodpracticetoindicatethatyouintendavariabletobeglobal.Acommonwayofdoingthisistoaddanopeningandclosingasterisktothevariablename,forexample,*default-layer*.
Pleasesendusyourcommentaboutthispage
Page 500
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>LocalVariablesinFunctions>
ExampleUsingLocalVariables
Thefollowingexampleshowstheuseoflocalvariablesinauser-definedfunction(becertainthereisatleastonespacebetweentheslashandthelocalvariables).
_$ (defunLOCAL(/aaabbb)
(_> (setqaaa"A"bbb"B")
(_> (princ(strcat"\naaahasthevalue"aaa))
(_> (princ(strcat"\nbbbhasthevalue"bbb))
(_> (princ))LOCAL
Beforeyoutestthenewfunction,assignvariablesaaaandbbbtovaluesotherthanthoseusedintheLOCALfunction.
_$ (setqaaa1bbb2)2
Youcanverifythatthevariablesaaaandbbbareactuallysettothosevalues.
_$ aaa1
_$ bbb2
NowtesttheLOCALfunction.
Page 501
_$ (local)aaahasthevalueA
bbbhasthevalueB
Youwillnoticethefunctionusedthevaluesforaaaandbbbthatarelocaltothefunction.Youcanverifythatthecurrentvaluesforaaaandbbbarestillsettotheirnonlocalvalues.
_$ aaa1
_$ bbb2
Inadditiontoensuringthatvariablesarelocaltoaparticularfunction,thistechniquealsoensuresthememoryusedforthosevariablesisavailableforotherfunctions.
Pleasesendusyourcommentaboutthispage
Page 502
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>
FunctionswithArguments
WithAutoLISP,youcandefinefunctionsthatacceptarguments.UnlikemanyofthestandardAutoLISPfunctions,user-definedfunctionscannothaveoptionalarguments.Whenyoucallauser-definedfunctionthatacceptsarguments,youmustprovidevaluesforallthearguments.
Thesymbolstouseasargumentsaredefinedintheargumentlistbeforethelocalvariables.Argumentsaretreatedasaspecialtypeoflocalvariable;argumentvariablesarenotavailableoutsidethefunction.Youcannotdefineafunctionwithmultipleargumentsofthesamename.
Thefollowingcodedefinesafunctionthatacceptstwostringarguments,combinesthemwithanotherstring,andreturnstheresultingstring.
_$ (defunARGTEST(arg1arg2/ccc)
(_> (setqccc"Constantstring")
(_> (strcatccc","arg1","arg2))ARGTEST
TheARGTESTfunctionreturnsthedesiredvaluebecauseAutoLISPalwaysreturnstheresultsofthelastexpressionitevaluates.ThelastlineinARGTESTusesstrcattoconcatenatethestrings,andtheresultingvalueisreturned.Thisisoneexamplewhereyoushouldnotusetheprincfunctiontosuppressthereturnvaluefromyourprogram.
Thistypeoffunctioncanbeusedanumberoftimeswithinanapplicationtocombinetwovariablestringswithoneconstantstringinaspecificorder.Becauseitreturnsavalue,youcansavethevaluetoavariableforuselaterintheapplication.
Page 503
_$ (setqnewstr(ARGTEST"String1""String2"))"Constantstring,String1,String2"
Thenewstrvariableisnowsettothevalueofthethreestringscombined.
NotethatthecccvariablewasdefinedlocallywithintheARGTESTfunction.Oncethefunctionrunstocompletion,AutoLISPrecyclesthevariable,recapturingthememoryallocatedtoit.Toprovethis,checkfromtheVLISPConsolewindowtoseeifthereisstillavalueassignedtoccc.
_$cccnil
SpecialForms
Pleasesendusyourcommentaboutthispage
Page 504
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>SymbolandFunctionHandling>FunctionswithArguments>
SpecialForms
CertainAutoLISPfunctionsareconsideredspecialformsbecausetheyevaluateargumentsinadifferentmannerthanmostAutoLISPfunctioncalls.Atypicalfunctionevaluatesallargumentspassedtoitbeforeactingonthosearguments.Specialformseitherdonotevaluatealltheirarguments,oronlyevaluatesomeargumentsundercertainconditions.
ThefollowingAutoLISPfunctionsareconsideredspecialforms:
AND
COMMAND
COND
DEFUN
DEFUN-Q
FOREACH
FUNCTION
IF
LAMBDA
OR
PROGN
QUOTE
REPEAT
SETQ
Page 505
TRACE
UNTRACE
VLAX-FOR
WHILE
YoucanreadabouteachofthesefunctionsintheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 506
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>
ErrorHandlinginAutoLISP
TheAutoLISPlanguageprovidesseveralfunctionsforerrorhandling.Youcanusethesefunctionstodothefollowing:
Provideinformationtouserswhenanerroroccursduringtheexecutionofaprogram.
RestoretheAutoCADenvironmenttoaknownstate.
Intercepterrorsandcontinueprogramexecution.
Thecompletelistoferror-handlingfunctionsisinAutoLISPFunctionSynopsisundertheheadingError-HandlingFunctionsEacherror-handlingfunctionisdescribedintheAutoLISPReference.
Ifyourprogramcontainsmorethanoneerrorinthesameexpression,youcannotdependontheorderinwhichAutoLISPdetectstheerrors.Forexample,theintersfunctionrequiresseveralarguments,eachofwhichmustbeeithera2Dor3Dpointlist.Acalltointerslikethefollowing:
(inters'a)
isanerrorontwocounts:toofewargumentsandinvalidargumenttype.Youwillreceiveeitherofthefollowingerrormessages:
;***ERROR:toofewarguments
;***ERROR:badargumenttype:2D/3Dpoint
Yourprogramshouldbedesignedtohandleeithererror.
NotealsothatinAutoCAD,AutoLISPevaluatesallargumentsbeforecheckingtheargumenttypes.InpreviousreleasesofAutoCAD,AutoLISPevaluatedandcheckedthetypeofeachargumentsequentially.Toseethedifference,lookatthefollowingcodeexamples:
Page 507
(defunfoo()
(print"Evaluatingfoo")
'(12))
(defunbar()
(print"Evaluatingbar")
'b)
(defunbaz()
(print"Evaluatingbaz")
'c)
ObservehowanexpressionusingtheintersfunctionisevaluatedinAutoCAD:
Command:(inters(foo)(bar)(baz))
"Evaluatingfoo"
"Evaluatingbar"
"Evaluatingbaz"
;***ERROR:toofewarguments
EachargumentwasevaluatedsuccessfullybeforeAutoLISPpassedtheresultstointersanddiscoveredthattoofewargumentswerespecified.
InAutoCADRelease14orearlier,thesameexpressionevaluatedasfollows:Command:(inters(foo)(bar)(baz))
"Evaluatingfoo"
"Evaluatingbar"error:badargumenttype
AutoLISPevaluated(foo),thenpassedtheresulttointers.Sincetheresultwasavalid2Dpointlist,AutoLISPproceedstoevaluate(bar),whereitdeterminesthattheevaluatedresultisastring,aninvalidargumenttypeforinters.
Usingthe*error*FunctionCatchingErrorsandContinuingProgramExecution
Pleasesendusyourcommentaboutthispage
Page 508
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>ErrorHandlinginAutoLISP>
Usingthe*error*Function
Properuseofthe*error*functioncanensurethatAutoCADreturnstoaparticularstateafteranerroroccurs.Throughthisuser-definablefunctionyoucanassesstheerrorconditionandreturnanappropriatemessagetotheuser.IfAutoCADencountersanerrorduringevaluation,itprintsamessageinthefollowingform:
Error: text
Inthismessage,textdescribestheerror.However,ifthe*error*functionisdefined(thatis,ifitisnotnil),AutoLISPexecutes*error*insteadofprintingthemessage.The*error*functionreceivestextasitssingleargument.
If*error*isnotdefinedorisnil,AutoLISPevaluationstopsanddisplaysatracebackofthecallingfunctionanditscallers.Itisbeneficialtoleavethiserrorhandlerineffectwhileyoudebugyourprogram.
AcodeforthelasterrorissavedintheAutoCADsystemvariableERRNO,whereyoucanretrieveitbyusingthegetvarfunction.SeeErrorHandlinginAutoLISPforalistoferrorcodesandtheirmeaning.
Beforedefiningyourown*error*function,savethecurrentcontentsof*error*sothatthepreviouserrorhandlercanberestoreduponexit.Whenanerrorconditionexists,AutoCADcallsthecurrentlydefined*error*functionandpassesitoneargument,whichisatextstringdescribingthenatureoftheerror.Your*error*functionshouldbedesignedtoexitquietlyafteranESC(cancel)oranexitfunctioncall.Thestandardwaytoaccomplishthisistoincludethefollowingstatementsinyourerror-handlingroutine.
(if
(or
(=msg"Functioncancelled")
Page 509
(=msg"quit/exitabort")
)
(princ)
(princ(strcat"\nError:"msg))
)
Thiscodeexaminestheerrormessagepassedtoitandensuresthattheuserisinformedofthenatureoftheerror.Iftheusercancelstheroutinewhileitisrunning,nothingisreturnedfromthiscode.Likewise,ifanerrorconditionisprogrammedintoyourcodeandtheexitfunctioniscalled,nothingisreturned.Itispresumedyouhavealreadyexplainedthenatureoftheerrorbyusingprintstatements.Remembertoincludeaterminatingcalltoprincifyoudon'twantareturnvalueprintedattheendofanerrorroutine.
Themaincaveatabouterror-handlingroutinesistheyarenormalAutoLISPfunctionsthatcanbecanceledbytheuser.Keepthemasshortandasfastaspossible.Thiswillincreasethelikelihoodthatanentireroutinewillexecuteifcalled.
Youcanalsowarntheuserabouterrorconditionsbydisplayinganalertbox,whichisasmalldialogboxcontainingamessagesuppliedbyyourprogram.Todisplayanalertbox,callthealertfunction.
Thefollowingcalltoalertdisplaysanalertbox:
(alert"Filenotfound")
Pleasesendusyourcommentaboutthispage
Page 510
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>AutoLISPBasics>ErrorHandlinginAutoLISP>
CatchingErrorsandContinuingProgramExecution
Yourprogramcaninterceptandattempttoprocesserrorsinsteadofallowingcontroltopassto*error*.Thevl-catch-all-applyfunctionisdesignedtoinvokeanyfunction,returnavaluefromthefunction,andtrapanyerrorthatmayoccur.Thefunctionrequirestwoarguments:asymbolidentifyingafunctionorlambdaexpression,andalistofargumentstobepassedtothecalledfunction.Thefollowingexampleusesvl-catch-all-applytodividetwonumbers:
_$(setqcatchit(vl-catch-all-apply
'/'(505)))10
Theresultfromthisexampleisthesameasifyouhadusedapplytoperformthedivision.
Thevalueofvl-catch-all-applyisincatchingerrorsandallowingyourprogramtocontinueexecution.
Tocatcherrorswithvl-catch-all-apply
1. Thefollowingcodedefinesafunctionnamedcatch-me-if-you-can.CopythecodeintoaVLISPtexteditorwindow:
(defuncatch-me-if-you-can(dividenddivisor/errobj)
(setqerrobj(vl-catch-all-apply'/(listdividenddivisor)))
(if(vl-catch-all-error-perrobj)
(progn
(print(strcat"Anerroroccurred:"
(vl-catch-all-error-messageerrobj)
)
)
(prompt"Doyouwanttocontinue?(Y/N)->")
Page 511
(setqans(getstring))
(if(equal(strcaseans)"Y")
(print"Okay,I'llkeepgoing")
)
)
(printerrobj)
)
(princ)
)
Thisfunctionacceptstwonumberargumentsandusesvl-catch-all-applytodividethefirstnumberbythesecondnumber.Thevl-catch-all-error-pfunctiondetermineswhetherthereturnvaluefromvl-catch-all-applyisanerrorobject.Ifthereturnvalueisanerrorobject,catch-me-if-you-caninvokesvl-catch-all-error-messagetoobtainthemessagefromtheerrorobject.
2. Loadthefunction.
3. Invokethefunctionwiththefollowingcommand:
(catch-me-if-you-can
502)
Thefunctionshouldreturn25.
4. Intentionallycauseanerrorconditionbyinvokingthefunctionwiththefollowingcommand:
(catch-me-if-you-can
500)
ThefunctionshouldissuethefollowingpromptintheAutoCADCommandwindow:
"Anerroroccurred:dividebyzero"Doyouwanttocontinue?(Y/N)->
Ifyouentery,catch-me-if-you-canindicatesthatitwillcontinueprocessing.Trymodifyingthisexamplebychangingvl-catch-all-applytoapply.Loadandruntheexamplewithadividebyzeroagain.Whenapplyresultsinanerror,executionimmediatelyhaltsand*error*iscalled,resultinginanerrormessage.
Page 512
Thevl-catch-*functionsareespeciallyimportantwhenyouuseActiveXwithAutoLISP.ManyoftheAutoCADActiveXautomationmethodsaredesignedtobeusedinthe“programmingbyexception”style.Thismeanstheyeitherreturnusefulvaluesiftheysucceed,orraiseanexceptioniftheyfail(insteadofreturninganerrorvalue).IfyourprogramusesActiveXmethods,youmustprepareittocatchexceptions,otherwisetheprogramhalts,leavingtheuserataCommandprompt.SeeHandlingErrorsReturnedbyActiveXMethodsforanexampleusingvl-catch-all-applywithActiveX.
Pleasesendusyourcommentaboutthispage
Page 513
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>
UsingAutoLISPtoCommunicatewithAutoCAD
QueryandcommandfunctionsprovidedirectaccesstoAutoCADcommandsanddrawingservices.
AutoLISP®providesvariousfunctionsforexaminingthecontentsofthecurrentlyloadeddrawing.Thischapterintroducesthesefunctionsanddescribeshowtousetheminconjunctionwithotherfunctions.
AccessingCommandsandServicesDisplayControlGettingUserInputGeometricUtilitiesConversionsFileHandlingDeviceAccessandControl
Pleasesendusyourcommentaboutthispage
Page 514
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
AccessingCommandsandServices
ThequeryandcommandfunctionsdescribedinthissectionprovidedirectaccesstoAutoCAD®commandsanddrawingservices.TheirbehaviordependsonthecurrentstateoftheAutoCADsystemandenvironmentvariables,andonthedrawingthatiscurrentlyloaded.See##xrefhere-QueryandCommandFunctions(appAUtilityfunctions)inAutoLISPFunctionSynopsisforacompletelistofqueryandcommandfunctions.
Note TheAutoLISPexamplesinthischaptershowcodeenteredattheAutoCADCommandprompt,nottheVisualLISPConsolewindow.
CommandSubmissionSystemandEnvironmentVariablesConfigurationControl
Pleasesendusyourcommentaboutthispage
Page 515
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>
CommandSubmission
ThecommandfunctionsendsanAutoCADcommanddirectlytotheAutoCADCommandprompt.Thecommandfunctionhasavariable-lengthargumentlist.Theseargumentsmustcorrespondtothetypesandvaluesexpectedbythatcommand'spromptsequence;thesemaybestrings,realvalues,integers,points,entitynames,orselectionsetnames.Datasuchasangles,distances,andpointscanbepassedeitherasstringsorasthevaluesthemselves(asintegerorrealvalues,oraspointlists).Anemptystring("")isequivalenttopressingtheSPACEBARorENTERonthekeyboard.
Therearesomerestrictionsonthecommandsthatyoucanusewiththecommandfunction.SeetheAutoLISPReferencedefinitionofthisfunctionforinformationontheserestrictions.
Thefollowingcodefragmentshowsrepresentativecallstocommand.
(command"circle""0,0""3,3")
(command"thickness"1)
(setqp1'(1.01.03.0))
(setqrad4.5)
(command"circle"p1rad)
IfAutoCADisattheCommandpromptwhenthesefunctionsarecalled,AutoCADperformsthefollowingactions:
1. ThefirstcalltocommandpassespointstotheCIRCLEcommandasstrings(drawsacirclecenteredat0.0,0.0andpassesthrough3.0,3.0).
2. ThesecondcallpassesanintegertotheTHICKNESSsystemvariable(changesthecurrentthicknessto1.0).
3. Thelastcallusesa3Dpointandareal(floating-point)value,bothofwhicharestoredasvariablesandpassedbyreferencetotheCIRCLE
Page 516
command.Thisdrawsanextrudedcirclecenteredat(1.0,1.0,3.0)witharadiusof4.5.ForeignLanguageSupportPausingforUserInputPassingPickPointstoAutoCADCommandsUndoingCommandsIssuedwiththecommandFunction
Pleasesendusyourcommentaboutthispage
Page 517
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>CommandSubmission>
ForeignLanguageSupport
IfyoudevelopAutoLISPprogramsthatcanbeusedwithaforeignlanguageversionofAutoCAD,thestandardAutoCADcommandsandkeywordsareautomaticallytranslatedifyouprecedeeachcommandorkeywordwithanunderscore(_).
(command"_line"pt1pt2pt3"_c")
Ifyouareusingthedotprefix(toavoidusingredefinedcommands),youcanplacethedotandunderscoreineitherorder.Both"._line"and"_.line"arevalid.
Pleasesendusyourcommentaboutthispage
Page 518
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>CommandSubmission>
PausingforUserInput
IfanAutoCADcommandisinprogressandthepredefinedsymbolPAUSEisencounteredasanargumenttocommand,thecommandissuspendedtoallowdirectuserinput(usuallypointselectionordragging).Thisissimilartothebackslashpausemechanismprovidedformenus.
ThePAUSEsymbolisdefinedasastringconsistingofasinglebackslash.Whenyouuseabackslash(\)inastring,youmustprecedeitbyanotherbackslash(\\).
MenuinputisnotsuspendedbyanAutoLISPpause.Ifamenuitemisactivewhenthecommandfunctionpausesforinput,thatinputrequestcanbesatisfiedbythemenu.Ifyouwantthemenuitemtobesuspendedaswell,youmustprovideabackslashinthemenuitem.Whenvalidinputisfound,boththecommandfunctionandthemenuitemresume.
Note YoucanuseabackslashinsteadofthePAUSEsymbol.However,itisrecommendedthatyoualwaysusethePAUSEsymbolratherthananexplicitbackslash.Also,ifthecommandfunctionisinvokedfromamenuitem,thebackslashsuspendsthereadingofthemenuitem,whichresultsinpartialevaluationoftheAutoLISPexpression.
Ifyouissueatransparentcommandwhileacommandfunctionissuspended,thecommandfunctionremainssuspended.Therefore,userscan'ZOOMand'PANwhileatacommandpause.ThepauseremainsineffectuntilAutoCADgetsvalidinput,andnotransparentcommandisinprogress.Forexample,thefollowingcodebeginstheCIRCLEcommand,setsthecenterpointat(5,5),andthenpausestolettheuserdragthecircle'sradius.Whentheuserspecifiesthedesiredpoint(ortypesinthedesiredradius),thefunctionresumes,drawingalinefrom(5,5)to(7,5),asfollows:
Page 519
(command"circle""5,5"pause"line""5,5""7,5""")
IfPAUSEisencounteredwhenacommandisexpectinginputofatextstringoranattributevalue,AutoCADpausesforinputonlyiftheTEXTEVALsystemvariableisnonzero.Otherwise,AutoCADdoesnotpauseforuserinputbutusesthevalueofthePAUSEsymbol(asinglebackslash)text.
Whenthecommandfunctionpausesforuserinput,thefunctionisconsideredactive,sotheusercannotenteranotherAutoLISPexpressiontobeevaluated.
ThefollowingisanexampleofusingthePAUSEsymbol(thelayerNEW_LAYandtheblockMY_BLOCKmustexistinthedrawingpriortotestingthiscode):
(setqblk"MY_BLOCK")
(setqold_lay(getvar"clayer"))
(command"layer""set""NEW_LAY""")
(command"insert"blkpause""""pause)
(command"layer""set"old_lay"")
TheprecedingcodefragmentsetsthecurrentlayertoNEW_LAY,pausesforuserselectionofaninsertionpointfortheblockMY_BLOCK(whichisinsertedwithXandYscalefactorsof1),andpausesagainforuserselectionofarotationangle.Thecurrentlayeristhenresettotheoriginallayer.
IfthecommandfunctionspecifiesaPAUSEtotheSELECTcommandandaPICKFIRSTsetisactive,theSELECTcommandobtainsthePICKFIRSTsetwithoutpausingfortheuser.
Warning TheRadiusandDiametersubcommandsoftheDimpromptissueadditionalpromptsinsomesituations.ThiscancauseafailureofAutoLISPprogramswrittenpriortoRelease11thatusethesecommands.
Pleasesendusyourcommentaboutthispage
Page 520
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>CommandSubmission>
PassingPickPointstoAutoCADCommands
SomeAutoCADcommands(suchasTRIM,EXTEND,andFILLET)requiretheusertospecifyapickpointaswellastheobjectitself.TopasssuchpairsofobjectandpointdatabymeansofthecommandfunctionwithouttheuseofaPAUSE,youmustfirststorethemasvariables.Pointscanbepassedasstringswithinthecommandfunctionorcanbedefinedoutsidethefunctionandpassedasvariables,asshowninthefollowingexample.Thiscodefragmentshowsonemethodofpassinganentitynameandapickpointtothecommandfunction.
(command"circle""5,5""2")Draws
circle
(command"line""3,5""7,5""")Draws
line
(setqel(entlast))Gets
lastentityname
(setqpt'(57))Setspointpt
(command"trim"el""pt"")Performs
trim
IfAutoCADisattheCommandpromptwhenthesefunctionsarecalled,AutoCADperformsthefollowingactions:
1. Drawsacirclecenteredat(5,5)witharadiusof2.
2. Drawsalinefrom(3,5)to(7,5).
3. Createsavariableelthatisthenameofthelastobjectaddedtothedatabase.(SeeUsingAutoLISPtoManipulateAutoCADObjectsformorediscussionofobjectsandobject-handlingfunctions.)
4. Createsaptvariablethatisapointonthecircle.(Thispointselectstheportionofthecircletobetrimmed.)
Page 521
5. PerformstheTRIMcommandbyselectingtheelobjectandbyselectingthepointspecifiedbypt.
Pleasesendusyourcommentaboutthispage
Page 522
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>CommandSubmission>
UndoingCommandsIssuedwiththecommandFunction
AnUNDOgroupisexplicitlycreatedaroundeachcommandusedwiththecommandfunction.IfauserentersU(orUNDO)afterrunninganAutoLISProutine,onlythelastcommandwillbeundone.AdditionalentriesofUNDOwillstepbackwardthroughthecommandsusedinthatroutine.Ifyouwantagroupofcommandstobeconsideredagroup(ortheentireroutine),usetheUNDOBeginandUNDOEndoptions.
Pleasesendusyourcommentaboutthispage
Page 523
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>
SystemandEnvironmentVariables
Withthegetvarandsetvarfunctions,AutoLISPapplicationscaninspectandchangethevalueofAutoCADsystemvariables.Thesefunctionsuseastringtospecifythevariablename.Thesetvarfunctionspecifiesavalueofthetypethatthesystemvariableexpects.AutoCADsystemvariablescomeinvarioustypes:integers,realvalues,strings,2Dpoints,and3Dpoints.Valuessuppliedasargumentstosetvarmustbeoftheexpectedtype.Ifaninvalidtypeissupplied,anAutoLISPerrorisgenerated.
ThefollowingcodefragmentensuresthatsubsequentFILLETcommandsusearadiusofatleast1:
(if(<(getvar"filletrad")1)
(setvar"filletrad"1)
)
SeetheCommandReferenceforalistofAutoCADsystemvariablesandtheirdescriptions.
Anadditionalfunction,getenv,providesAutoLISProutineswithaccesstothecurrentlydefinedoperatingsystemenvironmentvariables.
Pleasesendusyourcommentaboutthispage
Page 524
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>AccessingCommandsandServices>
ConfigurationControl
AutoCADusestheacadxx.cfgfiletostoreconfigurationinformation(thexxinthefilenamereferstotheAutoCADreleasenumber).TheAppDatasectionofthisfileisprovidedforusersanddeveloperstostoreconfigurationinformationpertainingtotheirapplications.ThegetcfgandsetcfgfunctionsallowAutoLISPapplicationstoinspectandchangethevalueofparametersintheAppDatasection.
Pleasesendusyourcommentaboutthispage
Page 525
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
DisplayControl
AutoLISPincludesfunctionsforcontrollingtheAutoCADdisplayinbothtextandgraphicswindows.Somefunctionspromptfor,ordependon,inputfromtheAutoCADuser.
Theprompt,princ,prin1,andprintfunctionsaretheprimarytextoutputfunctions.ThesefunctionsweredescribedintheAutoLISPBasicschapter,undertheheading,BasicOutputFunctions
SeeDisplayControlFunctionsinAutoLISPFunctionSynopsisforacompletelistofdisplaycontrolfunctions.
ControllingMenusControlofGraphicsandTextWindowsControlofLow-LevelGraphics
Pleasesendusyourcommentaboutthispage
Page 526
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>DisplayControl>
ControllingMenus
Themenucmdfunctioncontrolsthedisplayofthegraphicswindowmenus.Itdisplays,modifies,orqueriesoneofthesubmenusofthecurrentmenu,andacceptsastringargumentthatspecifiesthesubmenuandtheactiontoperformonthatsubmenu.
Themenucmdfunctiontakesastringargumentthatconsistsoftwofields,separatedbyanequalsign,inthefollowingform:
"menu_area=action"
Thissyntaxcanloadasubmenuintoaspecifiedmenuarea,orperformanactiononamenuitemoracurrentlyloadedmenuarea.Themenu_areafieldspecifieswhichpartofthemenuistoreceivetheaction.Thisfieldcanspecifyamenuarea,suchasP0(fortheshortcutmenu)orS(forthescreenmenu),oraspecificmenuitem.Theactionfieldspecifiestheactiontoperformonthemenuareaormenuitem,orasubmenutoloadintothemenuarea.Themenuareasthatcanreceiveanactionarethesameasthoseusedinmenufilesubmenureferences.
Everymenuareahasacurrentlyloadedsubmenu.Bydefault,thefirstsubmenufollowingamenusectionlabelisloadedintothatmenuarea.
Ifmenu_areaspecifiesapull-downmenuorimagetilemenu,actioncanbeanasterisk(*).Thiscausesthemenutodisplay(pull-downmenusandimagetilemenusarenotautomaticallydisplayedwhentheyarecalled).InWindows,onlytheP0(cursor)menuandimagetilemenusaredisplayedwiththeasterisk.
Note Donotincludethedollarsignthatintroducesthesimilarinstructionsinamenufileinthestringargument.Also,donotincludetheasterisksthatprecedesubmenulabelsinthemenufileintheactionfieldofthestringargument.
Page 527
Thefollowingmenucmdfunctioncallcausesthe**OSNAPscreensubmenudefinedinthecurrentmenufiletobedisplayed(assumingthescreenmenuiscurrentlyenabled).
(menucmd"S=OSNAP")
InWindows,youcanreferencethemenugroup.Thiscanbeusefuliftherearemultiplemenusloadedthatcontainthesamesubmenuname.Thefollowingcodedisplaysthe**OSNAPscreensubmenuintheACADmenugroup.
(menucmd"S=ACAD.OSNAP")
ThemenucmdfunctioncanloadsubmenusintotheBUTTONSandAUXmenuareas.YoumightwantyourdigitizerbuttonstofunctiondifferentlydependingonwhetherTabletmodeisonoroff.Youcanhavetwosubmenusdefinedinthe***BUTTONS1section,**DIG-BUTTONSand**TAB-BUTTONS,andswitchbetweenthemwiththefollowingcode.
(menucmd"B1=DIG-BUTTONS")EnablestheDIG-BUTTONSsubmenu
(menucmd"B1=TAB-BUTTONS")EnablestheTAB-BUTTONSsubmenu
Thefollowingcodeloadsthe***POP0menuintotheP0(cursor)menuareaanddisplaysit.
(menucmd"P0=POP0")Loads
the***POP0menuintotheP0menuarea
(menucmd"P0=*") Displays
it
Ifyouaresurethecorrectmenuisloadedintoaparticularmenuarea,youdonotneedtoloaditspecificallyeachtimeyouwanttodisplayit.
Thefollowingcalldisplaysthepull-downmenucurrentlyloadedintheP1(firstpull-downmenu)location.
(menucmd"P1=*")
Using"P1=*"withoutpreviouslyloadingthemenucanresultinunexpectedbehavior.Althoughyoucanloadvirtuallyanymenuatapull-downorshortcutmenulocation,itisbesttouseonlymenusspecificallydesignedforthatmenuarea.Forexample,ifyouhaveasubmenucalled**MORESTUFF,youcanloaditattheP1locationwiththefollowingcode:
Page 528
(menucmd"P1=MORESTUFF")Loadsthe**MORESTUFFmenuinthe
P1menulocation
(menucmd"P1=*")Displays
it
Thismenuremainsinthislocationuntilyoureplaceitbyloadinganothermenu,asinthefollowing:
(menucmd"P1=POP1")
Ifyourmenuusesthedisabling(graying-out)andmarkingfeatures,youcanretrieveandchangethestateofamenulabelwiththemenucmdfunction.Thefollowingcallretrievesthecurrentstateofthefourthlabelinthepull-downmenuP2.
(menucmd"P2.4=#?")If
disabledreturns"P2.4=~"
Thesefunctioncallsenableanddisablethatsamelabel:
(menucmd"P2.4=")Enables
thelabel
(menucmd"P2.4=~")Disables
thelabel
Youcanalsoplaceandremovemarkstotheleftofmenulabels.
Thepreviouslydescribedmethodofmenuitemhandlingworksrelativelywellwithasinglestaticmenu.However,itbecomesunreliablewhenmenuitemlocationschangewhenyouloadmultiplepartialmenufiles.Youcanmakeuseofthemenu-groupandname-tagfeaturestokeeptrackofmenuitems.Insteadofspecifyingamenuitembyitslocationinthemenufile,youspecifythemenugroupandnametagassociatedwiththemenuitem.
Whenyouusethemenugrouptoenable,disable,andmarkmenulabels,youmustprecedethegroupnamewithaG,asshowninthefollowingexamples.
(menucmd"Gacad.ID_New=~")Disablesthe
label
(menucmd"Gacad.ID_New=")Enablesthe
label
NotonlycananAutoLISPfunctionenableanddisablemenulabels,itcanalsomodifythetextdisplayedinthelabelbyplacingaDIESELstringexpressionin
Page 529
thelabel.BecauseDIESELacceptsonlystringsasinput,youcanpassinformationtotheDIESELexpressionthroughaUSERS1-5systemvariablethathasbeensettoavaluereturnedbyyourfunction.
YoucanalsousethemenucmdfunctiontoevaluateDIESELstringexpressionswithinanAutoLISPfunction.Thefollowingroutinereturnsthecurrenttime:
(defunC:CTIME(/ctim)
(setqctim
(menucmd"M=$(edtime,$(getvar,date),H:MMam/pm)"))
(princ(strcat"\nThecurrenttimeis"ctim))
(princ)
)
ForinformationontheuseofDIESELexpressionswithAutoLISPandacatalogofDIESELfunctions,seetheCustomizationGuide.ReferalsototheCustomizationGuideforfurtherinformationonmenus.
Pleasesendusyourcommentaboutthispage
Page 530
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>DisplayControl>
ControlofGraphicsandTextWindows
YoucancontrolthedisplayofthegraphicsandtextwindowsfromanAutoLISPapplication.Onsingle-screenAutoCADinstallations,acalltographscrdisplaysthegraphicswindow,andacalltotextscrdisplaysthetextwindow.UsingthesefunctionsisequivalenttotogglingtheFlipScreenfunctionkey.Thefunctiontextpageisequivalenttotextscr.
TheredrawfunctionissimilartotheAutoCADREDRAWcommandbutprovidesmorecontroloverwhatisdisplayed.Itnotonlyredrawstheentiregraphicsareabutcanalsospecifyasingleobjecttoberedrawnorundrawn(thatis,blankedout).Iftheobjectisacomplexobjectsuchasanold-stylepolylineorablock,redrawcandraw(orundraw)eithertheentireobjectoritsheader.Theredrawfunctioncanalsohighlightandunhighlightspecifiedobjects.
Pleasesendusyourcommentaboutthispage
Page 531
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>DisplayControl>
ControlofLow-LevelGraphics
AutoLISPprovidesfunctionsthatcontrolthelow-levelgraphicsandallowdirectaccesstotheAutoCADgraphicsscreenandinputdevices.
Thegrtextfunctiondisplaystextdirectlyinthestatusormenuareas,withorwithouthighlighting.Thegrdrawfunctiondrawsavectorinthecurrentviewportwithcontrolovercolorandhighlighting.Thegrvecsfunctiondrawsmultiplevectors.
Note BecausethesefunctionsdependoncodeinAutoCAD,theiroperationcanbeexpectedtochangefromreleasetorelease.Thereisnoguaranteethatapplicationscallingthesefunctionswillbeupwardcompatible.Also,theydependoncurrenthardwareconfigurations.Inparticular,applicationsthatcallgrtextarenotlikelytoworkthesameonallconfigurationsunlessthedeveloperisverycarefultousethemasdescribed(seetheCustomizationGuide)andtoavoidhardware-specificfeatures.Finally,becausetheyarelow-levelfunctions,theydoalmostnoerrorreportingandcanalterthegraphicsscreendisplayunexpectedly(seethefollowingexampleforawaytofixthis).
Thefollowingsequencerestoresthedefaultgraphicswindowdisplaycausedbyincorrectcallstogrtext,grdraw,orgrvecs:
(grtext)Restores
standardtext
(redraw)
Pleasesendusyourcommentaboutthispage
Page 532
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
GettingUserInput
SeveralfunctionsenableanAutoLISPapplicationtoprompttheuserforinputofdata.SeeUserInputFunctionsinAutoLISPFunctionSynopsisforacompletelistofuserinputfunctions.
ThegetxxxFunctionsControlofUser-InputFunctionConditions
Pleasesendusyourcommentaboutthispage
Page 533
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>
ThegetxxxFunctions
Eachuser-inputgetxxxfunctionpausesfordataentryoftheindicatedtypeandreturnsthevalueentered.Theapplicationspecifiesanoptionalprompttodisplaybeforethefunctionpauses.Thefollowingtableliststhegetxxxfunctionsandthetypeofuserinputrequested.
Allowableinputtothegetxxxuser-inputfunctions
Functionname Typeofuserinput
getint Anintegervalueonthecommandline
getreal Arealorintegervalueonthecommandline
getstring Astringonthecommandline
getpoint Apointvalueonthecommandlineorselectedfromthescreen
getcorner Apointvalue(theoppositecornerofabox)onthecommandlineorselectedfromthescreen
getdist Arealorintegervalue(ofdistance)onthecommandlineordeterminedbyselectingpointsonthescreen
Page 534
getangle Ananglevalue(inthecurrentangleformat)onthecommandlineorbasedonselectedpointsonthescreen
getorient Ananglevalue(inthecurrentangleformat)onthecommandlineorbasedonselectedpointsonthescreen
getkword Apredefinedkeywordoritsabbreviationonthecommandline
Note Althoughthegetvar,getcfg,andgetenvfunctionsbeginwiththelettersg,e,andt,theyarenotuser-inputfunctions.TheyarediscussedinAccessingCommandsandServices.
Thefunctionsgetint,getreal,andgetstringpauseforuserinputontheAutoCADcommandline.Theyreturnavalueonlyofthesametypeasthatrequested.
Thegetpoint,getcorner,andgetdistfunctionspauseforuserinputonthecommandlineorfrompointsselectedonthegraphicsscreen.Thegetpointandgetcornerfunctionsreturn3Dpointvalues,andgetdistreturnsarealvalue.
Bothgetangleandgetorientpauseforinputofananglevalueonthecommandlineorasdefinedbypointsselectedonthegraphicsscreen.Forthegetorientfunction,the0angleisalwaystotheright:“East”or“3o'clock.”Forgetangle,the0angleisthevalueofANGBASE,whichcanbesettoanyangle.Bothgetangleandgetorientreturnananglevalue(areal)inradiansmeasuredcounterclockwisefromabase(0angle),forgetangleequaltoANGBASE,andforgetorienttotheright.
Forexample,ANGBASEissetto90degrees(north),andANGDIRissetto1(clockwisedirectionforincreasingangles).Thefollowingtableshowswhatgetangleandgetorientreturn(inradians)forrepresentativeinputvalues(indegrees).
Possiblereturnvaluesfrom
Page 535
getangleandgetorient
Input
(degrees)getangle getorient
0 0.0 1.5708
-90 1.5708 3.14159
180 3.14159 4.71239
90 4.71239 0.0
ThegetanglefunctionhonorsthesettingsofANGDIRandANGBASEwhenacceptinginput.Youcanusegetangletoobtainarotationamountforablockinsertion,becauseinputof0degreesalwaysreturns0radians.ThegetorientfunctionhonorsonlyANGDIR.Youusegetorienttoobtainanglessuchasthebaselineangleforatextobject.Forexample,giventheprecedingsettingsofANGBASEandANGDIR,foralineoftextcreatedatanangleof0,getorientreturnsananglevalueof90.
Theuser-inputfunctionstakeadvantageoftheerror-checkingcapabilityofAutoCAD.TrivialerrorsaretrappedbyAutoCADandarenotreturnedbytheuser-inputfunction.Apriorcalltoinitgetprovidesadditionalfilteringcapabilities,lesseningtheneedforerror-checking.
Thegetkwordfunctionpausesfortheinputofakeywordoritsabbreviation.Keywordsmustbedefinedwiththeinitgetfunctionbeforethecalltogetkword.Alluser-inputfunctions(exceptgetstring)canacceptkeywordvaluesinadditiontothevaluestheynormallyreturn,providedthatinitget
Page 536
hasbeencalledtodefinethekeywords.
Alluser-inputfunctionsallowforanoptionalpromptargument.Itisrecommendedyouusethisargumentratherthanapriorcalltothepromptorprincfunctions.Ifapromptargumentissuppliedwiththecalltotheuser-inputfunction,thatpromptisreissuedinthecaseofinvaliduserinput.Ifnopromptargumentissuppliedandtheuserentersincorrectinformation,thefollowingmessageappearsattheAutoCADpromptline:
Tryagain:
Thiscanbeconfusing,becausetheoriginalpromptmayhavescrolledoutoftheCommandpromptarea.
TheAutoCADusercannottypicallyrespondtoauser-inputfunctionbyenteringanAutoLISPexpression.IfyourAutoLISProutinemakesuseoftheinitgetfunction,arbitrarykeyboardinputispermittedtocertainfunctionsthatcanallowanAutoLISPstatementasresponsetoacommandimplementedinAutoLISP.ThisisdiscussedinArbitraryKeyboardInput.
Pleasesendusyourcommentaboutthispage
Page 537
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>
ControlofUser-InputFunctionConditions
Theinitgetfunctionprovidesalevelofcontroloverthenextuser-inputfunctioncall.Theinitgetfunctionestablishesvariousoptionsforusebythenextentsel,nentsel,nentselp,orgetxxxfunction(exceptgetstring,getvar,andgetenv).Thisfunctionacceptstwoarguments,bitsandstring,bothofwhichareoptional.Thebitsargumentspecifiesoneormorecontrolbitsthatenableordisablecertaininputvaluestothenextuser-inputfunctioncall.Thestringargumentcanspecifykeywordsthatthenextuser-inputfunctioncallwillrecognize.
Thecontrolbitsandkeywordsestablishedbyinitgetapplyonlytothenextuser-inputfunctioncall.Theyarediscardedafterthatcall.Theapplicationdoesn'thavetocallinitgetasecondtimetoclearspecialconditions.
InputOptionsforUser-InputFunctionsKeywordOptionsArbitraryKeyboardInputInputValidation
Pleasesendusyourcommentaboutthispage
Page 538
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>ControlofUser-InputFunctionConditions>
InputOptionsforUser-InputFunctions
Thevalueofthebitsargumentrestrictsthetypesofuserinputtothenextuser-inputfunctioncall.Thisreduceserror-checking.Thesearesomeoftheavailablebitvalues:1disallowsnullinput,2disallowsinputof0(zero),and4disallowsnegativeinput.Ifthesevaluesareusedwithafollowingcalltothegetintfunction,theuserisforcedtoenteranintegervaluegreaterthan0.
Tosetmorethanoneconditionatatime,addthevaluestogether(inanycombination)tocreateabitsvaluebetween0and255.Ifbitsisnotincludedorissetto0,noneofthecontrolconditionsappliestothenextuser-inputfunctioncall.(Foracompletelistingofinitgetbitsettings,seeinitgetintheAutoLISPReference.)
(initget(+124))
(getint"\nHowoldareyou?")
Thissequencerequeststheuser'sage.AutoCADdisplaysanerrormessageandrepeatsthepromptiftheuserattemptstoenteranegativeorzerovalue,oriftheuseronlypressesENTER,orentersastring(thegetintfunctionrejectsattemptstoenteravaluethatisnotaninteger).
Pleasesendusyourcommentaboutthispage
Page 539
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>ControlofUser-InputFunctionConditions>
KeywordOptions
Theoptionalstringargumentspecifiesalistofkeywordsrecognizedbythenextuser-inputfunctioncall.
Theinitgetfunctionallowskeywordabbreviationstoberecognizedinadditiontothefullkeywords.Theuser-inputfunctionreturnsapredefinedkeywordiftheinputfromtheusermatchesthespellingofakeyword(notcasesensitive),oriftheuserenterstheabbreviationofakeyword.Therearetwomethodsforabbreviatingkeywords;botharediscussedintheinitgettopicintheAutoLISPReference.
Thefollowinguser-definedfunctionshowsacalltogetreal,precededbyacalltoinitget,thatspecifiestwokeywords.Theapplicationchecksforthesekeywordsandsetstheinputvalueaccordingly.
(defunC:GETNUM(/num)
(initget1"PiTwo-pi")
(setqnum(getreal"Pi/Two-pi/<number>:"))
(cond
((eqnum"Pi")pi)
((eqnum"Two-pi")(*2.0pi))
(Tnum)
)
)
Thisinitgetcallinhibitsnullinput(bits=1)andestablishesalistoftwokeywords,"Pi"and"Two-pi".Thegetrealfunctionisthenusedtoobtainarealnumber,issuingthefollowingprompt:
Pi/Two-pi/<number>:
Theresultisplacedinlocalsymbolnum.Iftheuserentersanumber,thatnumberisreturnedbyC:GETNUM.However,iftheuserentersthekeywordPi
Page 540
(orsimplyP),getrealreturnsthekeywordPi.Thecondfunctiondetectsthisandreturnsthevalueofpinthiscase.TheTwo-pikeywordishandledsimilarly.
Note Youcanalsouseinitgettoenableentsel,nentsel,andnentselptoacceptkeywordinput.Formoreinformationonthesefunctions,seeObjectHandlingandtheentsel,nentselandnentselpfunctiondefinitionsintheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 541
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>ControlofUser-InputFunctionConditions>
ArbitraryKeyboardInput
Theinitgetfunctionalsoallowsarbitrarykeyboardinputtomostgetxxxfunctions.Thisinputispassedbacktotheapplicationasastring.AnapplicationusingthisfacilitycanbewrittentopermittheusertocallanAutoLISPfunctionatagetxxxfunctionprompt.
ThesefunctionsshowamethodforallowingAutoLISPresponsetoagetxxxfunctioncall:
(defunC:ARBENTRY(/pt1)
(initget128);Setsarbitraryentrybit
(setqpt1(getpoint"\nPoint:"));Getsvaluefromuser.
(if(='STR(typept1));Ifit'sastring,convertit
(setqpt1(eval(readpt1)));toasymbol,tryevaluating
;itasafunction;otherwise,
pt1;justreturnthevalue.
)
)
(defunREF()
(setvar"LASTPOINT"(getpoint"\nReferencepoint:"))
(getpoint"\nNextpoint:"(getvar"LASTPOINT"))
)
IfboththeC:ARBENTRYandREFfunctionsareloadedintothedrawing,thefollowingcommandsequenceisacceptable.
Command: arbentry
Point: (ref)
Referencepoint: Selectapoint
Nextpoint: @1,1,0
Pleasesendusyourcommentaboutthispage
Page 542
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GettingUserInput>ControlofUser-InputFunctionConditions>
InputValidation
Youshouldprotectyourcodefromunintentionalusererrors.TheAutoLISPuserinputgetxxxfunctionsdomuchofthisforyou.However,it'sdangeroustoforgettocheckforadherencetootherprogramrequirementsthatthegetxxxfunctionsdonotcheckfor.Ifyouneglecttocheckinputvalidity,theprogram'sintegritycanbeseriouslyaffected.
Pleasesendusyourcommentaboutthispage
Page 543
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
GeometricUtilities
Agroupoffunctionsallowsapplicationstoobtainpuregeometricinformationandgeometricdatafromthedrawing.SeeGeometricFunctionsinAutoLISPFunctionSynopsisforacompletelistofgeometricutilityfunctions.
TheanglefunctionfindstheangleinradiansbetweenalineandtheXaxis(ofthecurrentUCS),distancefindsthedistancebetweentwopoints,andpolarfindsapointbymeansofpolarcoordinates(relativetoaninitialpoint).Theintersfunctionfindstheintersectionoftwolines.Theosnapandtextboxfunctionsaredescribedseparately.
Thefollowingcodefragmentshowscallstothegeometricutilityfunctions:
(setqpt1'(3.06.00.0))
(setqpt2'(5.02.00.0))
(setqbase'(1.07.00.0))
(setqrads(anglept1pt2));AngleinXYplaneofcurrentUCS
;(valueisreturnedinradians)
(setqlen(distancept1pt2));Distancein3Dspace
(setqendpt(polarbaseradslen))
Thecalltopolarsetsendpttoapointthatisthesamedistancefrom(1,7)aspt1isfrompt2,andatthesameanglefromtheXaxisastheanglebetweenpt1andpt2.
ObjectSnapTextExtents
Pleasesendusyourcommentaboutthispage
Page 544
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GeometricUtilities>
ObjectSnap
TheosnapfunctioncanfindapointbyusingoneoftheAutoCADObjectSnapmodes.TheSnapmodesarespecifiedinastringargument.
Thefollowingcalltoosnaplooksforthemidpointofanobjectnearpt1:
(setqpt2(osnappt1"midp"))
Thefollowingcalllooksforthemidpoint,theendpoint,orthecenterofanobjectnearestpt1:
(setqpt2(osnappt1"midp,endp,center"))
Inbothexamples,pt2issettothesnappointifoneisfoundthatfulfillstheosnaprequirements.Ifmorethanonesnappointfulfillstherequirements,thepointisselectedbasedonthesettingoftheSORTENTSsystemvariable.Otherwise,pt2issettonil.
Note TheAPERTUREsystemvariabledeterminestheallowableproximityofaselectedpointtoanobjectwhenyouuseObjectSnap.
Pleasesendusyourcommentaboutthispage
Page 545
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>GeometricUtilities>
TextExtents
Thetextboxfunctionreturnsthediagonalcoordinatesofaboxthatenclosesatextobject.Ittakesanentitydefinitionlistofthetypereturnedbyentget(anassociationlistofgroupcodesandvalues)asitssingleargument.Thislistcancontainacompleteassociationlistdescriptionofthetextobjectorjustalistdescribingthetextstring.
Thepointsreturnedbytextboxdescribetheboundingbox(animaginaryboxthatenclosesthetextobject)ofthetextobject,asifitsinsertionpointwerelocatedat(0,0,0)anditsrotationanglewere0.Thefirstlistreturnedisthepoint(0.00.00.0),unlessthetextobjectisobliqueorverticaloritcontainsletterswithdescenders(suchasgandp).Thevalueofthefirstpointlistspecifiestheoffsetdistancefromthetextinsertionpointtothelower-leftcornerofthesmallestrectangleenclosingthetext.Thesecondpointlistspecifiestheupper-rightcornerofthatbox.Thereturnedpointlistsalwaysdescribethebottom-leftandupper-rightcornersofthisboundingbox,regardlessoftheorientationofthetextbeingmeasured.
Thefollowingexampleshowstheminimumallowableentitydefinitionlistthattextboxaccepts.Becausenoadditionalinformationisprovided,textboxusesthecurrentdefaultsfortextstyleandheight.
Command: (textbox'((1."Helloworld")))
((0.00.00.0)(2.809521.00.0))
Theactualvaluesreturnedbytextboxwillvarydependingonthecurrenttextstyle.
Thefollowingexampledemonstratesonemethodofprovidingthetextboxfunctionwithanentitydefinitionlist.
Command: dtext
Justify/Style/<Startpoint>: 1,1
Page 546
Height<1.0000>: ENTER
Rotationangle<0>: ENTER
Text: test
Text: ENTER
Command: (setqe(entget(entlast)))
((-1.<Entityname:1ba3568>)(0."TEXT")(330.<Entityname:1ba34f8>)(5.
"2D")(100."AcDbEntity")(67.0)(410."Model")(8."0")(100.
"AcDbText")(101.01.00.0)(40.1.0)(1."test")(50.0.0)(41.1.0)(51
.0.0)(7."Standard")(71.0)(72.0)(110.00.00.0)(2100.00.01.0)
(100."AcDbText")(73.0))
Command: (textboxe)
((0.00.00.0)(0.80.20.0))
Thefollowingfigureshowstheresultsofapplyingtextboxtoatextobjectwithaheightof1.0.Thefigurealsoshowsthebaselineandinsertionpointofthetext.
Ifthetextisverticalorrotated,pt1isstillthebottom-leftcornerandpt2istheupper-rightcorner;thebottom-leftpointmayhavenegativeoffsetsifnecessary.
Thefollowingfigureshowsthepointvalues(pt1andpt2)thattextboxreturnsforsamplesofverticalandalignedtext.Inbothsamples,theheightofthelettersis1.0.(Forthealignedtext,theheightisadjustedtofitthealignmentpoints.)
Whenusingverticaltextstyles,thepointsarestillreturnedinleft-to-right,bottom-to-toporderastheyareforhorizontalstyles,sothatthefirstpointlist
Page 547
willcontainnegativeoffsetsfromthetextinsertionpoint.
Regardlessofthetextorientationorstyle,thepointsreturnedbytextboxaresuchthatthetextinsertionpoint(groupcode10)directlytranslatestotheoriginpointoftheobjectcoordinatesystem(OCS)fortheassociatedtextobject.Thispointcanbereferencedwhentranslatingthecoordinatesreturnedfromtextboxintopointsthatdefinetheactualextentofthetext.Thetwosampleroutinesthatfollowusetextboxtoplaceaboxaroundselectedtextregardlessofitsorientation.
Thefirstroutineusesthetextboxfunctiontodrawaboxaroundaselectedtextobject:
(defunC:TBOX(/textenttbllurullr)
(setqtextent(car(entsel"\nSelecttext:")))
(command"ucs""Object"textent)
(setqtb(textbox(list(cons-1textent)))
ll(cartb)
ur(cadrtb)
ul(list(carll)(cadrur))
lr(list(carur)(cadrll))
)
(command"pline"lllrurul"Close")
(command"ucs""p")
(princ)
)
Thesecondroutine,whichfollows,accomplishesthesametaskasthefirstroutinebyperformingthegeometriccalculationswiththesinandcosAutoLISPfunctions.TheresultiscorrectonlyifthecurrentUCSisparalleltotheplaneofthetextobject.
Page 548
(defunC:TBOX2(/textentangsinrotcosrot
t1t2p0p1p2p3p4)
(setqtextent(entget(car(entsel"\nSelecttext:"))))
(setqp0(cdr(assoc10textent))
ang(cdr(assoc50textent))
sinrot(sinang)
cosrot(cosang)
t1(car(textboxtextent))
t2(cadr(textboxtextent))
p1(list
(+(carp0)
(-(*(cart1)cosrot)(*(cadrt1)sinrot))
)
(+(cadrp0)
(+(*(cart1)sinrot)(*(cadrt1)cosrot))
)
)
p2(list
(+(carp0)
(-(*(cart2)cosrot)(*(cadrt1)sinrot))
)
(+(cadrp0)
(+(*(cart2)sinrot)(*(cadrt1)cosrot))
)
)
p3(list
(+(carp0)
(-(*(cart2)cosrot)(*(cadrt2)sinrot))
)
(+(cadrp0)
(+(*(cart2)sinrot)(*(cadrt2)cosrot))
)
)
p4(list
(+(carp0)
(-(*(cart1)cosrot)(*(cadrt2)sinrot))
)
(+(cadrp0)
(+(*(cart1)sinrot)(*(cadrt2)cosrot))
)
)
)
(command"pline"p1p2p3p4"c")
(princ)
)
Pleasesendusyourcommentaboutthispage
Page 549
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
Conversions
Thefunctionsdescribedinthissectionareutilitiesforconvertingdatatypesandunits.SeeinAutoLISPFunctionSynopsisforacompletelistofconversionfunctions.
StringConversionsAngularConversionASCIICodeConversionUnitConversionCoordinateSystemTransformations
Pleasesendusyourcommentaboutthispage
Page 550
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>
StringConversions
Thefunctionsrtos(realtostring)andangtos(angletostring)convertnumericvaluesusedinAutoCADtostringvaluesthatcanbeusedinoutputorastextualdata.Thertosfunctionconvertsarealvalue,andangtosconvertsanangle.TheformatoftheresultstringiscontrolledbythevalueofAutoCADsystemvariables:theunitsandprecisionarespecifiedbyLUNITSandLUPRECforreal(linear)valuesandbyAUNITSandAUPRECforangularvalues.Forbothfunctions,thedimensioningvariableDIMZINcontrolshowleadingandtrailingzerosarewrittentotheresultstring.
Thefollowingcodefragmentsshowcallstortosandthevaluesreturned(assumingtheDIMZINsystemvariableequals0).Precision(thethirdargumenttortos)issetto4placesinthefirstcalland2placesintheothers.
(setqx17.5)
(setqstr"\nValueformattedas")
(setqfmtval(rtosx14));Mode1=scientific
(princ(strcatstrfmtval));displays Valueformattedas1.7500E+01(setqfmtval(rtosx22));Mode2=decimal
(princ(strcatstrfmtval));displays Valueformattedas17.50(setqfmtval(rtosx32));Mode3=engineering
(princ(strcatstrfmtval));displays Valueformattedas1'-5.50"(setqfmtval(rtosx42));Mode4=architectural
(princ(strcatstrfmtval));displays Valueformattedas1'-51/2"(setqfmtval(rtosx52));Mode5=fractional
(princ(strcatstrfmtval));displays Valueformattedas171/2
WhentheUNOTHODEsystemvariableissetto1,specifyingthatunitsaredisplayedasentered,thestringreturnedbyrtosdiffersforengineering(modeequals3),architectural(modeequals4),andfractional(modeequals5)units.Forexample,thefirsttwolinesoftheprecedingsampleoutputwouldbethesame,butthelastthreelineswouldappearasfollows:
Valueformattedas1'5.50"
Page 551
Valueformattedas1'5-1/2"
Valueformattedas17-1/2''
BecausetheangtosfunctiontakestheANGBASEsystemvariableintoaccount,thefollowingcodealwaysreturns"0":
(angtos(getvar"angbase"))
ThereisnoAutoLISPfunctionthatreturnsastringversion(inthecurrentmode/precision)ofeithertheamountofrotationofANGBASEfromtruezero(East)oranarbitraryangleinradians.
TofindtheamountofrotationofANGBASEfromAutoCADzero(East)orthesizeofanarbitraryangle,youcandooneofthefollowing:
AddthedesiredangletothecurrentANGBASE,andthenchecktoseeiftheabsolutevalueoftheresultisgreaterthan2pi;(2*pi).Ifso,subtract2pi;;iftheresultisnegative,add2pi;,thenusetheangtosfunctionontheresult.
StorethevalueofANGBASEinatemporaryvariable,setANGBASEto0,evaluatetheangtosfunction,thensetANGBASEtoitsoriginalvalue.
Subtractingtheresultof(atof(angtos0))from360degrees(2pi;radiansor400grads)alsoyieldstherotationofANGBASEfrom0.
Thedistof(distancetofloatingpoint)functionisthecomplementofrtos.Therefore,thefollowingcalls,whichusethestringsgeneratedinthepreviousexamples,allreturnthesamevalue:17.5.(Notetheuseofthebackslash(\)withmodes3and4.)
(distof"1.7500E+01"1);Mode1=scientific
(distof"17.50"2);Mode2=decimal
(distof"1'-5.50\""3);Mode3=engineering
(distof"1'-51/2\""4);Mode4=architectural
(distof"171/2"5);Mode5=fractional
Thefollowingcodefragmentsshowsimilarcallstoangtosandthevaluesreturned(stillassumingthatDIMZINequals0).Precision(thethirdargumenttoangtos)issetto0placesinthefirstcall,4placesinthenextthreecalls,and2placesinthelast.
Page 552
(setqang3.14159str2"\nAngleformattedas")
(setqfmtval(angtosang00));Mode0=degrees
(princ(strcatstr2fmtval));displays Angleformattedas180(setqfmtval(angtosang14));Mode1=deg/min/sec
(princ(strcatstr2fmtval));displays Angleformattedas180d0'0"(setqfmtval(angtosang24));Mode2=grads
(princ(strcatstr2fmtval));displays Angleformattedas200.0000g(setqfmtval(angtosang34));Mode3=radians
(princ(strcatstr2fmtval));displays Angleformattedas3.1416r(setqfmtval(angtosang42));Mode4=surveyor's
(princ(strcatstr2fmtval));displays AngleformattedasW
TheUNITHODEsystemvariablealsoaffectsstringsreturnedbyangtoswhenitreturnsastringinsurveyor'sunits(modeequals4).IfUNITMODEequals0,thestringreturnedcanincludespaces(forexample,"N45dE");ifUNITMODEequals1,thestringcontainsnospaces(forexample,"N45dE").
Theangtoffunctioncomplementsangtos,soallofthefollowingcallsreturnthesamevalue:3.14159.
(angtof"180"0);Mode0=degrees
(angtof"180d0'0\""1);Mode1=deg/min/sec
(angtof"200.0000g"2);Mode2=grads
(angtof"3.14159r"3);Mode3=radians
(angtof"W"4);Mode4=surveyor's
Whenyouhaveastringspecifyingadistanceinfeetandinches,oranangleindegrees,minutes,andseconds,youmustprecedethequotationmarkwithabackslash(\")soitdoesn'tlookliketheendofthestring.Theprecedingexamplesofangtofanddistofdemonstratethisaction.
Pleasesendusyourcommentaboutthispage
Page 553
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>
AngularConversion
Ifyourapplicationneedstoconvertangularvaluesfromradianstodegrees,youcanusetheangtosfunction,whichreturnsastring,andthenconvertthatstringintoafloatingpointvaluewithatof.
(setqpt1'(11)pt2'(12))
(setqrad(anglept1pt2))
(setqdeg(atof(angtosrad02)))returns90.0
However,amoreefficientmethodmightbetoincludeaRadian->Degreesfunctioninyourapplication.Thefollowingcodeshowsthis:
;Convertvalueinradianstodegrees
(defunRadian->Degrees(nbrOfRadians)
(*180.0(/nbrOfRadianspi))
)
Afterthisfunctionisdefined,youcanusetheRadian->Degreesfunctionthroughoutyourapplication,asin
(setqdegrees(Radian->Degreesrad))returns90.0
Youmayalsoneedtoconvertfromdegreestoradians.Thefollowingcodeshowsthis:
;Convertvalueindegreestoradians
(defunDegrees->Radians(numberOfDegrees)
(*pi(/numberOfDegrees180.0))
);_endofdefun
Pleasesendusyourcommentaboutthispage
Page 554
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>
ASCIICodeConversion
AutoLISPprovidestheasciiandchrfunctionsthathandledecimalASCIIcodes.TheasciifunctionreturnstheASCIIdecimalvalueassociatedwithastring,andchrreturnsthecharacterassociatedwithanASCIIdecimalvalue.
Toseeyoursystem'scharacterswiththeircodesindecimal,octal,andhexadecimalform,savethefollowingAutoLISPcodetoafilenamedascii.lsp.ThenloadthefileandenterthenewASCIIcommandattheAutoCADCommandprompt.ThiscommandprintstheASCIIcodestothescreenandtoafilecalledascii.txt.TheC:ASCIIfunctionmakesuseoftheBASEfunction.Youmayfindthisconversionutilityusefulinotherapplications.
;BASEconvertsfromadecimalintegertoastringinanotherbase.
(defunBASE(basint/retyyyzot)
(defunzot(i1i2/xxx)
(if(>(setqxxx(remi2i1))9)
(chr(+55xxx))
(itoaxxx)
)
)
(setqret(zotbasint)yyy(/intbas))
(while(>=yyybas)
(setqret(strcat(zotbasyyy)ret))
(setqyyy(/yyybas))
)
(strcat(zotbasyyy)ret)
)
(defunC:ASCII(/chkoutctcodedecocthex)
(initget"Yes")
(setqchk(getkword"\nWritingtoASCII.TXT,continue?<Y>:"))
(if(or(=chk"Yes")(=chknil))(progn
(setqout(open"ascii.txt""w")chk1code0ct0)
(princ"\n\nCHARDECOCTHEX\n")
(princ"\n\nCHARDECOCTHEX\n"out)
(whilechk
Page 555
(setqdec(strcat""(itoacode))
oct(base8code)hex(base16code))
(setqdec(substrdec(-(strlendec)2)3))
(if(<(strlenoct)3)(setqoct(strcat"0"oct)))
(princ(strcat"\n"(chrcode)""dec""
oct""hex))
(princ(strcat"\n"(chrcode)""dec""
oct""hex)out)
(cond
((=code255)(setqchknil))
((=ct20)
(setqxxx(getstring
"\n\nPress'X'toeXitoranykeytocontinue:"))
(if(=(strcasexxx)"X")
(setqchknil)
(progn
(setqct0)
(princ"\n\nCHARDECOCTHEX\n")
)
)
)
)
(setqct(1+ct)code(1+code))
)
(closeout)
(setqoutnil)
)
)
(princ)
)
Pleasesendusyourcommentaboutthispage
Page 556
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>
UnitConversion
Theacad.untfiledefinesvariousconversionsbetweenreal-worldunitssuchasmilestokilometers,FahrenheittoCelsius,andsoon.Thefunctioncvunittakesavalueexpressedinonesystemofunitsandreturnstheequivalentvalueinanothersystem.Thetwosystemsofunitsarespecifiedbystringscontainingexpressionsofunitsdefinedinacad.unt.
Thecvunitfunctiondoesnotconvertincompatibledimensions.Forexample,itdoesnotconvertinchesintograms.
Thefirsttimecvunitconvertstoorfromaunitduringadrawingeditorsession,itmustlookupthestringthatspecifiestheunitinacad.unt.Ifyourapplicationhasmanyvaluestoconvertfromonesystemofunitstoanother,itismoreefficienttoconvertthevalue1.0byasinglecalltocvunitandthenusethereturnedvalueasascalefactorinsubsequentconversions.Thisworksforallunitsdefinedinacad.unt,excepttemperaturescales,whichinvolveanoffsetaswellasascalefactor.
ConvertingfromInchestoMetersTheUnitDefinitionFile
Pleasesendusyourcommentaboutthispage
Page 557
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>UnitConversion>
ConvertingfromInchestoMeters
Ifthecurrentdrawingunitsareengineeringorarchitectural(feetandinches),thefollowingroutineconvertsauser-specifieddistanceofinchesintometers:
(defunC:I2M(/eng_lenmetric_lenengmetric)
(princ"\nConvertinginchestometers.")
(setqeng_len
(getdist"\nEnteradistanceininches:"))
(setqmetric_len(cvuniteng_len"inches""meters"))
(setqeng(rtoseng_len24)
metric(rtosmetric_len24))
(princ
(strcat"\n\t"eng"inches="metric"meters."))
(princ)
)
Pleasesendusyourcommentaboutthispage
Page 558
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>UnitConversion>
TheUnitDefinitionFile
WiththeAutoCADunitdefinitionfileacad.unt,youcandefinefactorstoconvertdatainonesetofunitstoanothersetofunits.Thedefinitionsinacad.untareinASCIIformatandareusedbytheunit-conversionfunctioncvunit.
Youcanmakenewunitsavailablebyusingatexteditortoaddtheirdefinitionstoacad.unt.Adefinitionconsistsoftwolinesinthefile—theunitnameandtheunitdefinition.Thefirstlinemusthaveanasterisk(*)inthefirstcolumn,followedbythenameoftheunit.Aunitnamecanhaveseveralabbreviationsoralternatespellings,separatedbycommas.Ifaunitnamehassingularandpluralforms,youcanspecifytheseusingthefollowingformat:
*[[common][([singular.]plural)]]...
Youcanspecifymultipleexpressions(singularandplural).Theydon'thavetobelocatedattheendoftheword,andapluralformisn'trequired.Thefollowingareexamplesofvalidunitnamedefinitions:
*inch(es)
*milleni(um.a)
*f(oot.eet)or(foot.feet)
Thelinefollowingthe*unitnamelinedefinestheunitaseitherfundamentalorderived.
FundamentalUnits
Afundamentalunitisanexpressioninconstants.Ifthelinefollowingthe*unitnamelinebeginswithsomethingotherthananequalsign(=),itdefinesfundamentalunits.Fundamentalunitsconsistoffiveintegersandtworealnumbersinthefollowingform:
Page 559
c,e,h,k,m,r1,r2
Thefiveintegerscorrespondtotheexponentsofthesefiveconstants:
cVelocityoflightinavacuum
eElectroncharge
hPlanck'sconstant
kBoltzman'sconstant
mElectronrestmass
Asagroup,theseexponentsdefinethedimensionalityoftheunit:length,mass,time,volume,andsoon.
Thefirstrealnumber(r1)isamultiplier,andthesecond(r2)isanadditiveoffset(usedonlyfortemperatureconversions).Thefundamentalunitdefinitionallowsfordifferentspellingsoftheunit(forexample,meterandmetre);thecaseoftheunitisignored.Anexampleofafundamentalunitdefinitionisasfollows:
*meter(s),metre(s),m
-1,0,1,0,-1,4.1214856408e11,0
Inthisexample,theconstantsthatmakeonemeterareasfollows:
DerivedUnits
Aderivedunitisdefinedintermsofotherunits.Ifthelinefollowingthe*unitnamelinebeginswithanequalsign(=),itdefinesderivedunits.Validoperatorsinthesedefinitionsare*(multiplication),/(division),+(addition),-(subtraction),and^(exponentiation).Youcanspecifyapredefinedunitbynamingit,andyoucanuseabbreviations(ifprovided).Theitemsinaformulaaremultipliedtogetherunlesssomeotherarithmeticoperatorisspecified.Forexample,theunitsdatabasedefinesthedimensionlessmultipleandsubmultiplenames,soyoucanspecifyaunitsuchasmicro-inchesbyenteringmicroinch.Thefollowingareexamplesofderivedunitdefinitions.
Page 560
;Unitsofarea
*township(s)
=93239571.456meter^2
Thedefinitionofatownshipisgivenas93,239,571.456squaremeters.
;Electromagneticunits
*volt(s),v
=watt/ampere
Inthisexample,avoltisdefinedasawattdividedbyanampere.Intheacad.unt,bothwattsandamperesaredefinedintermsoffundamentalunits.
UserComments
Toincludecomments,beginthelinewithasemicolon.Thecommentcontinuestotheendoftheline.
;Thisentirelineisacomment.
Listtheacad.untfileitselfformoreinformationandexamples.
Pleasesendusyourcommentaboutthispage
Page 561
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>
CoordinateSystemTransformations
Thetransfunctiontranslatesapointoradisplacementfromonecoordinatesystemintoanother.Ittakesapointargument,pt,thatcanbeinterpretedaseithera3Dpointora3Ddisplacementvector,distinguishedbyadisplacementargumentcalleddisp.Thedispargumentmustbenonzeroifptistobetreatedasadisplacementvector;otherwise,ptistreatedasapoint.Afromargumentspecifiesthecoordinatesysteminwhichptisexpressed,andatoargumentspecifiesthedesiredcoordinatesystem.Thefollowingisthesyntaxforthetransfunction:
(transptfromto[disp])
ThefollowingAutoCADcoordinatesystemscanbespecifiedbythefromandtoarguments:
WCS
Worldcoordinatesystem—thereferencecoordinatesystem.AllothercoordinatesystemsaredefinedrelativetotheWCS,whichneverchanges.ValuesmeasuredrelativetotheWCSarestableacrosschangestoothercoordinatesystems.
UCS
Usercoordinatesystem—theworkingcoordinatesystem.TheuserspecifiesaUCStomakedrawingtaskseasier.AllpointspassedtoAutoCADcommands,includingthosereturnedfromAutoLISProutinesandexternalfunctions,arepointsinthecurrentUCS(unlesstheuserprecedesthemwitha*attheCommandprompt).IfyouwantyourapplicationtosendcoordinatesintheWCS,OCS,orDCStoAutoCADcommands,youmustfirstconvertthemtotheUCSbycallingthetransfunction.
OCS
Page 562
Objectcoordinatesystem—pointvaluesreturnedbyentgetareexpressedinthiscoordinatesystem,relativetotheobjectitself.ThesepointsareusuallyconvertedintotheWCS,currentUCS,orcurrentDCS,accordingtotheintendeduseoftheobject.Conversely,pointsmustbetranslatedintoanOCSbeforetheyarewrittentothedatabasebymeansoftheentmodorentmakefunctions.Thisisalsoknownastheentitycoordinatesystem.
DCS
Displaycoordinatesystem—thecoordinatesystemintowhichobjectsaretransformedbeforetheyaredisplayed.TheoriginoftheDCSisthepointstoredintheAutoCADsystemvariableTARGET,anditsZaxisistheviewingdirection.Inotherwords,aviewportisalwaysaplanviewofitsDCS.ThesecoordinatescanbeusedtodeterminewheresomethingwillbedisplayedtotheAutoCADuser.Whenthefromandtointegercodesare2and3,ineitherorder,2indicatestheDCSforthecurrentmodelspaceviewportand3indicatestheDCSforpaperspace(PSDCS).Whenthe2codeisusedwithanintegercodeotherthan3(oranothermeansofspecifyingthecoordinatesystem),itisassumedtoindicatetheDCSofthecurrentspace,whetherpaperspaceormodelspace.Theotherargumentisalsoassumedtoindicateacoordinatesysteminthecurrentspace.
PSDCS
PaperspaceDCS—thiscoordinatesystemcanbetransformedonlytoorfromtheDCSofthecurrentlyactivemodelspaceviewport.Thisisessentiallya2Dtransformation,wheretheXandYcoordinatesarealwaysscaledandareoffsetifthedispargumentis0.TheZcoordinateisscaledbutisnevertranslated.Therefore,itcanbeusedtofindthescalefactorbetweenthetwocoordinatesystems.ThePSDCS(integercode2)canbetransformedonlyintothecurrentmodelspaceviewport.Ifthefromargumentequals3,thetoargumentmustequal2,andviceversa.
Boththefromandtoargumentscanspecifyacoordinatesysteminanyofthefollowingways:
AsanintegercodethatspecifiestheWCS,currentUCS,orcurrentDCS(ofeitherthecurrentviewportorpaperspace).
Asanentitynamereturnedbyoneoftheentitynameorselectionset
Page 563
functionsdescribedinUsingAutoLISPtoManipulateAutoCADObjectsThisspecifiestheOCSofthenamedobject.Forplanarobjects,theOCScandifferfromtheWCS,asdescribedintheAutoCADUser'sGuide.IftheOCSdoesnotdiffer,conversionbetweenOCSandWCSisanidentityoperation.
Asa3Dextrusionvector.ExtrusionvectorsarealwaysrepresentedinWorldcoordinates;anextrusionvectorof(0,0,1)specifiestheWCSitself.
Thefollowingtableliststhevalidintegercodesthatcanbeusedasthetoandfromarguments:
Coordinatesystemcodes
Code Coordinatesystem
0 World(WCS)
1 User(currentUCS)
2 Display;DCSofcurrentviewportwhenusedwithcode0or1,DCSofcurrentmodelspaceviewportwhenusedwithcode3
3 PaperspaceDCS,PSDCS(usedonlywithcode2)
ThefollowingexampletranslatesapointfromtheWCSintothecurrentUCS.
(setqpt'(1.02.03.0))
(setqcs_from0);WCS
(setqcs_to1);UCS
(transptcs_fromcs_to0);disp
=0indicatesthatptisapoint
IfthecurrentUCSisrotated90degreescounterclockwisearoundtheWorldZ
Page 564
axis,thecalltotransreturnsapoint(2.0,-1.0,3.0).However,ifyouswapthetoandfromvalues,theresultdiffersasshowninthefollowingcode:
(transptcs_tocs_from0);the
resultis (-2.0,1.0,3.0)
PointTransformations
Pleasesendusyourcommentaboutthispage
Page 565
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>Conversions>CoordinateSystemTransformations>
PointTransformations
Ifyouaredoingpointtransformationswiththetransfunctionandyouneedtomakethatpartofaprogramrunfaster,youcanconstructyourowntransformationmatrixontheAutoLISPsidebyusingtransoncetotransformeachofthebasisvectors(000),(100),(010),and(001).WritingmatrixmultiplicationfunctionsinAutoLISPcanbedifficult,soitmaynotbeworthwhileunlessyourprogramisdoingalotoftransformations.
Pleasesendusyourcommentaboutthispage
Page 566
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
FileHandling
AutoLISPprovidesfunctionsforhandlingfilesanddataI/O.SeeFile-HandlingFunctionsinAutoLISPFunctionSynopsisforacompletelistoffile-handlingfunctions.
FileSearchAccessingDrawingPropertiesAccessingHelpFiles
Pleasesendusyourcommentaboutthispage
Page 567
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>FileHandling>
FileSearch
Anapplicationcanusethefindfilefunctiontosearchforaparticularfilename.Theapplicationcanspecifythedirectorytosearch,oritcanusethecurrentAutoCADlibrarypath.
Inthefollowingcodefragment,findfilesearchesfortherequestedfilenameaccordingtotheAutoCADlibrarypath:
(setqrefname"refc.dwg")
(setqfil(findfilerefname))
(iffil
(setqrefnamefil)
(princ(strcat"\nCouldnotfindfile"refname"."))
)
Ifthecalltofindfileissuccessful,thevariablerefnameissettoafullyqualifiedpathnamestring,asfollows:
"/home/work/ref/refc.dwg"
Whenspecifyingapathname,youmustprecedethebackslash(\)withanotherbackslashsothepathnamewillberecognizedbyAutoLISP.Alternatively,youcanusetheslashcharacter(/)asadirectoryseparator.
Thegetfiledfunctiondisplaysadialogboxcontainingalistofavailablefilesofaspecifiedextensiontypeinthespecifieddirectory.ThisgivesAutoLISProutinesaccesstotheAutoCADGetFiledialogbox.
Acalltogetfiledtakesfourargumentsthatdeterminetheappearanceandfunctionalityofthedialogbox.Theapplicationmustspecifythefollowingstringvalues,eachofwhichcanbenil:atitle,placedatthetopofthedialogbox;adefaultfilename,displayedintheeditboxatthebottomofthedialogbox;andanextensiontype,whichdeterminestheinitialfilesprovidedforselectioninthe
Page 568
listbox.Thefinalargumentisanintegervaluethatspecifieshowthedialogboxinteractswithselectedfiles.
Thissimpleroutineusesgetfiledtoletyouviewyourdirectorystructureandselectafile:
(defunC:DDIR()
(setqdfil(getfiled"DirectoryListing"""""2))
(princ(strcat"\nVariable'dfil'settoselectedfile"dfil))
(princ)
)
Thisisausefulutilitycommand.Thedfilvariableissettothefileyouselect,whichcanthenbeusedbyotherAutoLISPfunctionsorasaresponsetoacommandlinepromptforafilename.Tousethisvariableinresponsetoacommandlineprompt,enter!dfil.
Note Youcannotuse!dfilinadialogbox.Itisvalidonlyatthecommandline.
Formoreinformation,seegetfiledintheAutoLISPReference.
Pleasesendusyourcommentaboutthispage
Page 569
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>FileHandling>
AccessingDrawingProperties
ToaccessdrawingpropertiessuchasTitle,Subject,Author,andKeywords,usetheIAcadSummaryInfointerface.ThisinterfaceisaccessibleasapropertyoftheDocumentobjectintheAutoCADobjectmodel.
Inthefollowingexample,theIAcadSummaryInfointerfaceisusedtoaddstandardandcustompropertiestoadrawingnamedMyDrawing.dwg:
(vl-load-com)
(defunc:ADD_PROPS(/docdbsiauthorncnc2nc3value3value4)
(setqdoc(vla-get-ActiveDocument(vlax-get-Acad-Object)))
(setqdb(vla-get-Databasedoc))
(setqsi(vla-get-SummaryInfodb))
(vla-put-authorsi"John")
(vla-put-commentssi"Newcomments")
(vla-put-hyperlinkbasesi"http://AddURL")
(vla-put-keywordssi"Newkeywords")
(vla-AddCustomInfosi"siPutKey""siPutValue")
(setqnc(vla-numcustominfosi))
(vla-SetCustomByKeysi"siPutKey""siPutValueByKey")
(vla-GetCustomByKeysi"siPutKey"'value3)
(if(/="siPutValueByKey"value3)
(princ"***ErrorSetCustomByKey\n")
)
(vla-SetCustomByIndexsi(1-nc)"siPutCustomByIndexKey"
"siPutCustomByIndexValue")
(vla-GetCustomByKeysi"siPutCustomByIndexKey"'value4)
(if(/="siPutCustomByIndexValue"value4)
(princ"***ErrorSetCustomByIndex\n")
)
(vla-RemoveCustomByIndexsi(1-nc))
(setqnc2(vla-numcustominfosi))
(if(/=nc2(1-nc))
(princ"***ErrorRemoveCustomByIndex")
)
(vla-AddCustomInfosi"siPutKey""siPutValue")
;Removeproperty
Page 570
(vla-RemoveCustomByKeysi"siPutKey")
(setqnc3(vla-numcustominfosi))
(if(/=nc2(1-nc))
(princ"***ErrorRemoveCustomByKey")
)
(vla-AddCustomInfosi"siPutKey""siPutValue")
(vlax-release-objectsi)
(vlax-release-objectdb)
(vlax-release-objectdoc)
(princ)
)
(princ)
Drawingpropertiescanbereadusingthesameinteface,theIAcadSummaryInfointerface,asinthefollowingexample:
(vl-load-com)
(defunc:GET_PROPS(/docdbsiauthor)
(if(/="MyDrawing.dwg"(getvar"DWGNAME"))
(princ"OpenMyDrawing.dwg")
(progn
(setqdoc(vla-get-ActiveDocument(vlax-get-Acad-Object)))
(setqdb(vla-get-Databasedoc))
(setqsi(vla-get-SummaryInfodb))
(princ"\nAuthor:\n")
(if(/="John"(setqauthor(vla-get-authorsi)))
(princ"***vla-get-authorerror")
(princauthor)
)
(princ"\n")
(princ"\nComments:\n")
(princ(vla-get-commentssi))
(princ"\n")
(princ"\nHyperlink-base:\n")
(princ(vla-get-HyperlinkBasesi))
(princ"\n")
(princ"\nNumberofcustomproperties:")
(princ(setqnc(vla-numcustominfosi)))
(princ"\n")
(while(>nc0)
(princ"Customproperty")
(princnc)
(vla-GetCustomByIndexsi(-nc1)'key'value)
(princ":key(")
(princkey)
(princ")")
(princ"value(")
(princvalue)
(princ")\n")
Page 571
(vla-GetCustomByKeysikey'value2)
(if(/=valuevalue2)
(princ"\n***ErrorGetCustomByKeyreturnedunexpected
result.\n")
)
(setqnc(1-nc))
)
(vlax-release-objectsi)
(vlax-release-objectdb)
(vlax-release-objectdoc)
)
)
(princ)
)
Formoreinformationonthepropertiesandmethodsusedtoaccessdrawingproperties,seetheActiveXandVBAReference.
Pleasesendusyourcommentaboutthispage
Page 572
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>FileHandling>
AccessingHelpFiles
ThehelpfunctionprovidesaccesstobothAutoCADHelpfiles(.ahp)andWindowsHelpfiles(.hlp).DependingontheHelpfile'sextension,thehelpfunctioncallstheAutoCADortheWindowsHelpviewerwiththespecifiedfile.YoucanusethisfunctiontoaddaHelpfacilitytoyourapplications.ThefollowingcodefragmentcallsthedefaultAutoCADHelpfileandprovidesinformationabouttheLINEcommand.
(help"""line")
YoucancreateaHelpfilethatprovidesinformationaboutyourapplicationsoraboutproceduresyouuseinyourbusiness.Thefollowinguser-definedcommanddisplaysthemorehelp.hlpHelpfileasfollows:
(defunC:MYHELP()
(help"morehelp.hlp")
(princ)
)
SeetheCustomizationGuideforinformationoncreatingandmodifyinghelpfiles.
Thesetfunhelpfunctionprovideshelpforuser-definedcommands.Afterthedefinitionofyournewcommand,addingacalltosetfunhelpassociatesaspecifichelpfileandtopicwiththatcommand.Thefollowingexampleassignsthehelptopic“Mycmd”inthefilemorehelp.hlptotheuser-definedMYCMDcommand:
(defunC:MYCMD()
.
.Commanddefinition
.
)
Page 573
(setfunhelpc:mycmd"morehelp.hlp""mycmd")
Pleasesendusyourcommentaboutthispage
Page 574
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>
DeviceAccessandControl
AutoLISPprovidesthegrreadandtabletfunctionsforaccessingdatafromthevariousinputdevices.
Notethattheread-charandread-linefile-handlingfunctionscanalsoreadinputfromthekeyboardinputbuffer.SeetheAutoLISPReferenceformoreinformationonthesefunctions.
AccessingUserInputCalibratingTablets
Pleasesendusyourcommentaboutthispage
Page 575
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>DeviceAccessandControl>
AccessingUserInput
Thegrreadfunctionreturnsrawuserinput,whetherfromthekeyboardorfromthepointingdevice(mouseordigitizer).Ifthecalltogrreadenablestracking,thefunctionreturnsadigitizedcoordinatethatcanbeusedforthingssuchasdragging.
Note Thereisnoguaranteethatapplicationscallinggrreadwillbeupwardcompatible.Becauseitdependsonthecurrenthardwareconfiguration,applicationsthatcallgrreadarenotlikelytoworkinthesamewayonallconfigurations.
Pleasesendusyourcommentaboutthispage
Page 576
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoCommunicatewithAutoCAD>DeviceAccessandControl>
CalibratingTablets
AutoCADuserscancalibrateadigitizingtabletbyusingtheTABLETcommand(seetheCommandReferenceforadescriptionofthiscommand).Thetabletfunctionenablesapplicationstomanagecalibrationbysettingthecalibrationsdirectlyandbysavingthosesettingsforfutureuse.
Thefirstargumenttothetabletfunctionisanintegercode.Ifcodeisequalto0,thefunctionreturnsthecurrentcalibration.Ifcodeisequalto1,thecalibrationissetaccordingtotheremainingarguments.Calibrationsareexpressedasfour3Dpoints(inadditiontothecode).Thefirstthreepoints—row1,row2,androw3—arethethreerowsofthetablet'stransformationmatrix.Thefourthpoint,direction,isavectorthatisnormaltotheplaneinwhichthetablet'ssurfaceisassumedtolie(expressedinWCS,theWorldCoordinateSystem).WhenthecalibrationissetwiththeTABLETcommand,thetablet'ssurfaceisassumedtolieintheXYplaneofthecurrentUCS.
Note TheTABMODEsystemvariablecontrolswhetherTabletmodeisturnedon(1)oroff(0).Youcancontrolitbyusingthesetvarfunction.
Thefollowingsampleroutineretrievesthecurrenttabletcalibrationandstoresitinthevariabletcal:
(defunC:TABGET()
(setqtcal(tablet0))
(iftcal
(princ
(strcat"\nConfigurationsaved,"
"useTABSETtoretrievecalibration.")
)
(princ"\nCalibrationnotobtainable")
)
(princ)
)
Page 577
Iftheprecedingroutinewassuccessful,thesymboltcalnowcontainsthelistreturnedbythetabletfunction.Thislistmightappearasfollows:
(1(0.00561717-0.000978942-7.5171)
(0.0009789420.00561717-9.17308)
(0.00.01.0)
(0.00.01.0)
)
Toresetthecalibrationtothevaluesretrievedbytheprecedingroutine,youcanusetheC:TABSETroutine,asfollows:
(defunC:TABSET()
(if(not(apply'tablettcal))
(princ"\nUnabletoresetcalibration.")
(progn
(princ"\nTabletcalibrationreset.")
(setvar"tabmode"1)
(if(=(getvar"tabmode")0)
(princ"\nUnabletoturnontabletmode")
)
)
)
(princ)
)
Thetransformationmatrixpassedasrow1,row2,androw3isa3×3transformationmatrixthatismeanttotransforma2Dpoint.The2Dpointisexpressedasacolumnvectorinhomogeneouscoordinates(byappending1.0asthethirdelement),sothetransformationlookslikethis:
Thecalculationofapointissimilartothe3Dcase.AutoCADtransformsthepointbyusingthefollowingformulas:
Page 578
Toturntheresultingvectorbackintoa2Dpoint,thefirsttwocomponentsaredividedbythethirdcomponent(thescalefactorD')yieldingthepoint(X'/D',Y'/D').
Forprojectivetransformations,themostgeneralcase,tabletdoesthefullcalculation.Butforaffineandorthogonaltransformations,M20andM21areboth0,soD'wouldbe1.0.ThecalculationofD'andthedivisionareomitted;theresulting2Dpointissimply(X',Y').
Asthepreviousparagraphimplies,anaffinetransformationisaspecial,uniformcaseofaprojectivetransformation.Anorthogonaltransformationisaspecialcaseofanaffinetransformation:notonlyareM20andM21zero,butM00=M11andM10=-M01.
Note Whenyousetacalibration,thelistreturneddoesnotequalthelistprovidedifthedirectionisn'tnormalized.AutoCADnormalizesthedirectionvectorbeforeitreturnsit.Also,itensuresthethirdelementinthethirdcolumn(row3[Z])isequalto1.ThissituationshouldnotariseifyousetthecalibrationbyusingvaluesretrievedfromAutoCADbymeansoftablet.However,itcanhappenifyourprogramcalculatesthetransformationitself.
Pleasesendusyourcommentaboutthispage
Page 579
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>
UsingAutoLISPtoManipulateAutoCADObjects
Youcanselectandhandleobjects,andusetheirextendeddata.
MostAutoLISP®functionsthathandleselectionsetsandobjectsidentifyasetoranobjectbytheentityname.Forselectionsets,whicharevalidonlyinthecurrentsession,thevolatilityofnamesposesnoproblem,butitdoesforobjectsbecausetheyaresavedinthedrawingdatabase.Anapplicationthatmustrefertothesameobjectsinthesamedrawing(ordrawings)atdifferenttimescanusetheobjects'handles.
AutoLISPusessymboltablestomaintainlistsofgraphicandnon-graphicdatarelatedtoadrawing,suchasthelayers,linetypes,andblockdefinitions.EachsymboltableentryhasarelatedentitynameandhandleandcanbemanipulatedinamannersimilartothewayotherAutoCAD®entitiesaremanipulated.
SelectionSetHandlingObjectHandlingExtendedData-xdataXrecordObjectsSymbolTableandDictionaryAccess
Pleasesendusyourcommentaboutthispage
Page 580
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>
SelectionSetHandling
AutoLISPprovidesanumberoffunctionsforhandlingselectionsets.Foracompletelistofselectionsetfunctions,seeSelectionSetManipulationFunctionsinAutoLISPFunctionSynopsis
Thessgetfunctionprovidesthemostgeneralmeansofcreatingaselectionset.Itcancreateaselectionsetinoneofthefollowingways:
Explicitlyspecifyingtheobjectstoselect,usingtheLast,Previous,Window,Implied,WPolygon,Crossing,CPolygon,orFenceoptions
Specifyingasinglepoint
Selectingtheentiredatabase
Promptingtheusertoselectobjects
Withanyoption,youcanusefilteringtospecifyalistofattributesandconditionsthattheselectedobjectsmustmatch.
Note Selectionsetandentitynamesarevolatile.Thatis,theyapplyonlytothecurrentdrawingsession.
Thefirstargumenttossgetisastringthatdescribeswhichselectionoptiontouse.Thenexttwoarguments,pt1andpt2,specifypointvaluesfortherelevantoptions(theyshouldbeleftoutiftheydon'tapply).Apointlist,pt-list,mustbeprovidedasanargumenttotheselectionmethodsthatallowselectionbypolygons(thatis,Fence,CrossingPolygon,andWindowPolygon).Thelastargument,filter-list,isoptional.Iffilter-listissupplied,itspecifiesthelistofentityfieldvaluesusedinfiltering.Forexample,youcanobtainaselectionsetthatincludesallobjectsofagiventype,onagivenlayer,orofagivencolor.SelectionfiltersaredescribedinmoredetailinSelectionSetFilterLists.
Page 581
SeethessgetentryintheAutoLISPReferenceforalistoftheavailableselectionmethodsandtheargumentsusedwitheach.
Thefollowingtableshowsexamplesofcallstossget:
SSGETExamples
Functioncall Effect
(setqpt1'(0.00.00.0)
pt2'(5.05.00.0)
pt3'(4.01.00.0)
pt4'(2.06.00.0))
Setspt1,pt2,pt3,andpt4topointvalues
(setqss1(ssget)) Askstheuserforageneralobjectselectionandplacesthoseitemsinaselectionset
(setqss1(ssget"P")) Createsaselectionsetfromthemostrecentlycreatedselectionset
(setqss1(ssget"L")) Createsaselectionsetofthelastobjectaddedtothedatabasethatisvisibleonthescreen
(setqss1(ssgetpt2)) Createsaselectionsetofanobjectpassingthroughpoint(5,5)
(setqss1(ssget"W"pt1
pt2))
Createsaselectionsetoftheobjectsinsidethewindowfrom(0,0)to(5,5)
(setqss1(ssget"F"
(listpt2pt3pt4)))
Createsaselectionsetoftheobjectscrossingthefenceand
Page 582
definedbythepoints(5,5),(4,1),and(2,6)
(setqss1(ssget"WP"
(listpt1pt2pt3)))
Createsaselectionsetoftheobjectsinsidethepolygondefinedbythepoints(0,0),(5,5),and(4,1)
(setqss1(ssget"X")) Createsaselectionsetofallobjectsinthedatabase
Whenanapplicationhasfinishedusingaselectionset,itisimportanttoreleaseitfrommemory.Youcandothisbysettingittonil:
(setqss1nil)
Attemptingtomanagealargenumberofselectionsetssimultaneouslyisnotrecommended.AnAutoLISPapplicationcannothavemorethan128selectionsetsopenatonce.(Thelimitmaybeloweronyoursystem.)Whenthelimitisreached,AutoCADwillnotcreatemoreselectionsets.Keepaminimumnumberofsetsopenatatime,andsetunneededselectionsetstonilassoonaspossible.Ifthemaximumnumberofselectionsetsisreached,youmustcallthegcfunctiontofreeunusedmemorybeforeanotherssgetwillwork.
SelectionSetFilterListsPassingSelectionSetsbetweenAutoLISPandObjectARXApplications
Pleasesendusyourcommentaboutthispage
Page 583
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>
SelectionSetFilterLists
AnentityfilterlistisanassociationlistthatusesDXFgroupcodesinthesameformatasalistreturnedbyentget.(SeetheDXFReferenceforalistofgroupcodes.)Thessgetfunctionrecognizesallgroupcodesexceptentitynames(group-1),handles(group5),andxdatacodes(groupsgreaterthan1000).Ifaninvalidgroupcodeisusedinafilter-list,itisignoredbyssget.Tosearchforobjectswithxdata,usethe-3codeasdescribedinFilteringforExtendedData.
Whenafilter-listisprovidedasthelastargumenttossget,thefunctionscanstheselectedobjectsandcreatesaselectionsetcontainingthenamesofallmainentitiesmatchingthespecifiedcriteria.Forexample,youcanobtainaselectionsetthatincludesallobjectsofagiventype,onagivenlayer,orofagivencolor.
Thefilter-listspecifieswhichproperty(orproperties)oftheentitiesaretobecheckedandwhichvaluesconstituteamatch.
Thefollowingexamplesdemonstratemethodsofusingafilter-listwithvariousobjectselectionoptions.
SSGETexamplesusingfilterlists
Functioncall Effect
(setqss1(ssget'((0.
"TEXT")))
)
Promptsforgeneralobjectselectionbutaddsonlytextobjectstotheselectionset.
(setqss1(ssget"P" Createsaselectionsetcontaining
Page 584
'((0."LINE")))
)
alllineobjectsfromthelastselectionsetcreated.
(setqss1(ssget"W"pt1
pt2
'((8."FLOOR9")))
)
CreatesaselectionsetofallobjectsinsidethewindowthatarealsoonlayerFLOOR9.
(setqss1(ssget"X"
'((0."CIRCLE")))
)
CreatesaselectionsetofallobjectsinthedatabasethatareCircleobjects.
(ssget"I"'((0."LINE")
(62.5)))
CreatesaselectionsetofallblueLineobjectsthatarepartoftheImpliedselectionset(thoseobjectsselectedwhilePICKFIRSTisineffect).Notethatthisfilterpicksuplinesthathavebeenassignedcolor5(blue),butnotbluelinesthathavehadtheircolorappliedbytheByLayerorByBlockproperties.
Ifboththecodeandthedesiredvalueareknown,thelistmaybequotedasshownpreviously.Ifeitherisspecifiedbyavariable,thelistmustbeconstructedusingthelistandconsfunction.Forexample,thefollowingcodecreatesaselectionsetofallobjectsinthedatabasethatareonlayerFLOOR3:
(setqlay_name"FLOOR3")
(setqss1
(ssget"X"
(list(cons8lay_name))
)
)
Page 585
Ifthefilter-listspecifiesmorethanoneproperty,anentityisincludedintheselectionsetonlyifitmatchesallspecifiedconditions,asinthefollowingexample:
(ssget"X"(list(cons0"CIRCLE")(cons8lay_name)(cons621)))
ThiscodeselectsonlyCircleobjectsonlayerFLOOR3thatarecoloredred.ThistypeoftestperformsaBoolean“AND”operation.AdditionaltestsforobjectpropertiesaredescribedinLogicalGroupingofFilterTests.
Thessgetfunctionfiltersadrawingbyscanningtheselectedentitiesandcomparingthefieldsofeachmainentityagainstthespecifiedfilteringlist.Ifanentity'spropertiesmatchallspecifiedfieldsinthefilteringlist,itisincludedinthereturnedselectionset.Otherwise,theentityisnotincludedintheselectionset.Thessgetfunctionreturnsnilifnoentitiesfromthoseselectedmatchthespecifiedfilteringcriteria.
Note Themeaningofcertaingroupcodescandifferfromentitytoentity,andnotallgroupcodesarepresentinallentities.Ifaparticulargroupcodeisspecifiedinafilter,entitiesnotcontainingthatgroupcodeareexcludedfromtheselectionsetthatssgetreturns.
Whenssgetfiltersadrawing,theselectionsetitretrievesmightincludeentitiesfrombothpaperspaceandmodelspace.However,whentheselectionsetispassedtoanAutoCADcommand,onlyentitiesfromthespacethatiscurrentlyineffectareused.(Thespacetowhichanentitybelongsisspecifiedbythevalueofits67group.RefertotheCustomizationGuideforfurtherinformation.)
Wild-CardPatternsinFilterListsFilteringforExtendedDataRelationalTestsLogicalGroupingofFilterTestsSelectionSetManipulation
Pleasesendusyourcommentaboutthispage
Page 586
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>SelectionSetFilterLists>
Wild-CardPatternsinFilterLists
Symbolnamesspecifiedinfilteringlistscanincludewild-cardpatterns.Thewild-cardpatternsrecognizedbyssgetarethesameasthoserecognizedbythewcmatchfunction,andaredescribedinWild-CardMatching,andunderwcmatchintheAutoLISPReference.
Whenfilteringforanonymousblocks,youmustprecedethe*characterwithareversesinglequotationmark(`),alsoknownasanescapecharacter,becausethe*isreadbyssgetasawild-cardcharacter.Forexample,youcanretrieveananonymousblocknamed*U2withthefollowing:
(ssget"X"'((2."`*U2")))
Pleasesendusyourcommentaboutthispage
Page 587
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>SelectionSetFilterLists>
FilteringforExtendedData
Usingthessgetfilter-list,youcanselectallentitiescontainingextendeddataforaparticularapplication.(SeeExtendedData-xdata.)Todothis,usethe-3groupcode,asshowninthefollowingexample:
(ssget"X"'((0."CIRCLE")(-3("APPNAME"))))
Thiscodewillselectallcirclesthatincludeextendeddataforthe"APPNAME"application.Ifmorethanoneapplicationnameisincludedinthe-3group'slist,anANDoperationisimpliedandtheentitymustcontainextendeddataforallofthespecifiedapplications.So,thefollowingstatementwouldselectallcircleswithextendeddataforboththe"APP1"and"APP2"applications:
(ssget"X"'((0."CIRCLE")(-3("APP1")("APP2"))))
Wild-cardmatchingispermitted,soeitherofthefollowingstatementswillselectallcircleswithextendeddataforeitherorbothoftheseapplications.
(ssget"X"'((0."CIRCLE")(-3("APP[12]"))))
(ssget"X"'((0."CIRCLE")(-3("APP1,APP2"))))
Pleasesendusyourcommentaboutthispage
Page 588
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>SelectionSetFilterLists>
RelationalTests
Unlessotherwisespecified,anequivalencyisimpliedforeachiteminthefilter-list.Fornumericgroups(integers,reals,points,andvectors),youcanspecifyotherrelationsbyincludingaspecial-4groupcodethatspecifiesarelationaloperator.Thevalueofa-4groupisastringindicatingthetestoperatortobeappliedtothenextgroupinthefilter-list.
Thefollowingselectsallcircleswitharadius(groupcode40)greaterthanorequalto2.0:
(ssget"X"'((0."CIRCLE")(-4.">=")(40.2.0)))
Thepossiblerelationaloperatorsareshowninthefollowingtable:
Relationaloperatorsforselectionsetfilterlists
Operator Description
"*" Anythinggoes(alwaystrue)
"=" Equals
"!=" Notequalto
"/=" Notequalto
"<>" Notequalto
Page 589
"<" Lessthan
"<=" Lessthanorequalto
">" Greaterthan
">=" Greaterthanorequalto
"&" BitwiseAND(integergroupsonly)
"&=" Bitwisemaskedequals(integergroupsonly)
Theuseofrelationaloperatorsdependsonthekindofgroupyouaretesting:
Allrelationaloperatorsexceptforthebitwiseoperators("&"and"&=")arevalidforbothreal-andinteger-valuedgroups.
Thebitwiseoperators"&"and"&="arevalidonlyforinteger-valuedgroups.ThebitwiseAND,"&",istrueif((integer_group&filter)/=0)—thatis,ifanyofthebitssetinthemaskarealsosetintheintegergroup.Thebitwisemaskedequals,"&=",istrueif((integer_group&filter)=filter)—thatis,ifallbitssetinthemaskarealsosetintheinteger_group(otherbitsmightbesetintheinteger_groupbutarenotchecked).
Forpointgroups,theX,Y,andZtestscanbecombinedintoasinglestring,witheachoperatorseparatedbycommas(forexample,">,>,*").Ifanoperatorisomittedfromthestring(forexample,"=,<>"leavesouttheZtest),thenthe“anythinggoes”operator,"*",isassumed.
Directionvectors(grouptype210)canbecomparedonlywiththe
Page 590
operators"*","=",and"!="(oroneoftheequivalent“notequal”strings).
Youcannotusetherelationaloperatorswithstringgroups;usewild-cardtestsinstead.
Pleasesendusyourcommentaboutthispage
Page 591
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>SelectionSetFilterLists>
LogicalGroupingofFilterTests
YoucanalsotestgroupsbycreatingnestedBooleanexpressionsthatusethelogicalgroupingoperatorsshowninthefollowingtable:
Groupingoperatorsforselectionsetfilterlists
Starting
operatorEncloses
Ending
operator
"<AND" Oneormoreoperands
"AND>"
"<OR" Oneormoreoperands
"OR>"
"<XOR" Twooperands "XOR>"
"<NOT" Oneoperand "NOT>"
Thegroupingoperatorsarespecifiedby-4groups,liketherelationaloperators.Theyarepairedandmustbebalancedcorrectlyinthefilterlistorthessgetcallwillfail.Anexampleofgroupingoperatorsinafilterlistfollows:
(ssget"X"
'(
(-4."<OR")
(-4."<AND")
Page 592
(0."CIRCLE")
(40.1.0)
(-4."AND>")
(-4."<AND")
(0."LINE")
(8."ABC")
(-4."AND>")
(-4."OR>")
)
)
Thiscodeselectsallcircleswitharadiusof1.0plusalllinesonlayer"ABC".Thegroupingoperatorsarenotcase-sensitive;forexample,youcanspecify"and>","<or",insteadof"AND>","<OR".
Groupingoperatorsarenotallowedwithinthe-3group.Multipleapplicationnamesspecifiedina-3groupuseanimpliedANDoperator.Ifyouwanttotestforextendeddatausingothergroupingoperators,specifyseparate-3groupsandgroupthemasdesired.Toselectallcircleshavingextendeddataforeitherapplication"APP1"or"APP2"butnotboth,enterthefollowing:
(ssget"X"
'((0."CIRCLE")
(-4."<XOR")
(-3("APP1"))
(-3("APP2"))
(-4."XOR>")
)
)
Youcansimplifythecodingoffrequentlyusedgroupingoperatorsbysettingthemequaltoasymbol.Thepreviousexamplecouldberewrittenasfollows(noticethatinthisexampleyoumustexplicitlyquoteeachlist):
(setq<xor'(-4."<XOR")
xor>'(-4."XOR>"))
(ssget"X"
(list
'(0."CIRCLE")
<xor
'(-3("APP1"))
'(-3("APP2"))
xor>
)
)
Page 593
Asyoucansee,thismethodmaynotbesensibleforshortpiecesofcodebutcanbebeneficialinlargerapplications.
Pleasesendusyourcommentaboutthispage
Page 594
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>SelectionSetFilterLists>
SelectionSetManipulation
Onceaselectionsethasbeencreated,youcanaddentitiestoitorremoveentitiesfromitwiththefunctionsssaddandssdel.Youcanusethessaddfunctiontocreateanewselectionset,asshowninthefollowingexample.Thefollowingcodefragmentcreatesaselectionsetthatincludesthefirstandlastentitiesinthecurrentdrawing(entnextandentlastaredescribedlaterinthischapter).
(setqfname(entnext));Getsfirstentityinthe
;drawing.
(setqlname(entlast));Getslastentityinthe
;drawing.
(if(notfname)
(princ"\nNoentitiesindrawing.")
(progn
(setqourset(ssaddfname));Createsaselectionsetofthe
;firstentity.
(ssaddlnameourset);Addsthelastentitytothe
;selectionset.
)
)
Theexamplerunscorrectlyevenifonlyoneentityisinthedatabase(inwhichcasebothentnextandentlastsettheirargumentstothesameentityname).Ifssaddispassedthenameofanentityalreadyintheselectionset,itignorestherequestanddoesnotreportanerror.Thefollowingfunctionremovesthefirstentityfromtheselectionsetcreatedinthepreviousexample:
(ssdelfnameourset)
Ifthereismorethanoneentityinthedrawing(thatis,iffnameandlnamearenotequal),thentheselectionsetoursetcontainsonlylname,thelastentityin
Page 595
thedrawing.
Thefunctionsslengthreturnsthenumberofentitiesinaselectionset,andssmembtestswhetheraparticularentityisamemberofaselectionset.Finally,thefunctionssnamereturnsthenameofaparticularentityinaselectionset,usinganindextotheset(entitiesinaselectionsetarenumberedfrom0).
Thefollowingcodeshowscallstossname:
(setqsset(ssget));Promptstheusertocreatea
;selectionset.
(setqent1(ssnamesset0));Getsthenameofthefirst
;entityinsset.
(setqent4(ssnamesset3));Getsthenameofthefourth
;entityinsset.
(if(notent4)
(princ"\nNeedtoselectatleastfourentities.")
)
(setqilast(sslengthsset));Findsindexofthelastentity
;insset.
;Getsthenameofthe
;lastentityinsset.
(setqlastent(ssnamesset(1-ilast)))
Regardlessofhowentitiesareaddedtoaselectionset,thesetnevercontainsduplicateentities.Ifthesameentityisaddedmorethanonce,thelateradditionsareignored.Therefore,sslengthaccuratelyreturnsthenumberofdistinctentitiesinthespecifiedselectionset.
Pleasesendusyourcommentaboutthispage
Page 596
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SelectionSetHandling>
PassingSelectionSetsbetweenAutoLISPandObjectARXApplications
WhenpassingselectionsetsbetweenAutoLISPandObjectARXapplications,thefollowingshouldbeobserved:
IfaselectionsetiscreatedinAutoLISPandstoredinanAutoLISPvariable,thenoverwrittenbyavaluereturnedfromanObjectARXapplication,theoriginalselectionsetiseligibleforgarbagecollection(itisfreedatthenextautomaticorexplicitgarbagecollection).
ThisistrueevenifthevaluereturnedfromtheObjectARXapplicationwastheoriginalselectionset.Inthefollowingexample,iftheadsfuncObjectARXfunctionreturnsthesameselectionsetitwasfedasanargument,thenthisselectionsetwillbeeligibleforgarbagecollectioneventhoughitisstillassignedtothesamevariable.
(setqvar1(ssget))
(setqvar1(adsfuncvar1))
Ifyouwanttheoriginalselectionsettobeprotectedfromgarbagecollection,thenyoumustnotassignthereturnvalueoftheObjectARXapplicationtotheAutoLISPvariablethatalreadyreferencestheselectionset.Changingthepreviousexamplepreventstheselectionsetreferencedbyvar1frombeingeligibleforgarbagecollection.
(setqvar1(ssget))
(setqvar2(adsfuncvar1))
Pleasesendusyourcommentaboutthispage
Page 597
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>
ObjectHandling
AutoLISPprovidesfunctionsforhandlingobjects.Theobject-handlingfunctionsareorganizedintotwocategories:functionsthatretrievetheentitynameofaparticularobject,andfunctionsthatretrieveormodifyentitydata.SeeObject-HandlingFunctionsinAutoLISPFunctionSynopsisforacompletelistoftheobject-handlingfunctions.
EntityNameFunctionsEntityDataFunctionsEntityDataFunctionsandtheGraphicsScreenOld-StylePolylinesandLightweightPolylinesNon-GraphicObjectHandling
Pleasesendusyourcommentaboutthispage
Page 598
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>
EntityNameFunctions
Tooperateonanobject,anAutoLISPapplicationmustobtainitsentitynameforuseinsubsequentcallstotheentitydataorselectionsetfunctions.Twofunctionsdescribedinthissection,entselandnentsel,returnnotonlytheentity'snamebutadditionalinformationfortheapplication'suse.
BothfunctionsrequiretheAutoCADusertoselectanobjectinteractivelybypickingapointonthegraphicsscreen.Alltheotherentitynamefunctionscanretrieveanentityevenifitisnotvisibleonthescreenorifitisonafrozenlayer.Theentselfunctionpromptstheusertoselectanobjectbypickingapointonthegraphicsscreen,andentselreturnsboththeentitynameandthevalueofthepointselected.Someentityoperationsrequireknowledgeofthepointbywhichtheobjectwasselected.ExamplesfromthesetofexistingAutoCADcommandsinclude:BREAK,TRIM,andEXTEND.ThenentselfunctionisdescribedindetailinEntityContextandCoordinateTransformData.Thesefunctionsacceptkeywordsiftheyareprecededbyacalltoinitget.
Theentnextfunctionretrievesentitynamessequentially.Ifentnextiscalledwithnoarguments,itreturnsthenameofthefirstentityinthedrawingdatabase.Ifitsargumentisthenameofanentityinthecurrentdrawing,entnextreturnsthenameofthesucceedingentity.
Thefollowingcodefragmentillustrateshowssaddcanbeusedinconjunctionwithentnexttocreateselectionsetsandaddmemberstoanexistingset.
(setqe1(entnext))
(if(note1);Setse1tonameoffirstentity.
(princ"\nNoentitiesindrawing.")
(progn
(setqss(ssadd));Setssstoanullselectionset.
(ssadde1ss);Returnsselectionsetsswith
;e1added.
(setqe2(entnexte1));Getsentityfollowinge1.
Page 599
(ssadde2ss);Addse2toselectionsetss.
)
)
Theentlastfunctionretrievesthenameofthelastentityinthedatabase.Thelastentityisthemostrecentlycreatedmainentity,soentlastcanbecalledtoobtainthenameofanentitythathasjustbeencreatedwithacalltocommand.
Youcansettheentitynamereturnedbyentnexttothesamevariablenamepassedtothisfunction.This“walks”asingleentitynamevariablethroughthedatabase,asshowninthefollowingexample:
(setqone_ent(entnext));Getsnameoffirstentity.
(whileone_ent
.
.;Processesnewentity.
.
(setqone_ent(entnextone_ent))
);Valueofone_entisnownil.
EntityHandlesandTheirUsesEntityContextandCoordinateTransformDataEntityAccessFunctions
Pleasesendusyourcommentaboutthispage
Page 600
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityNameFunctions>
EntityHandlesandTheirUses
Thehandentfunctionretrievesthenameofanentitywithaspecifichandle.Aswithentitynames,handlesareuniquewithinadrawing.However,anentity'shandleisconstantthroughoutitslife.AutoLISPapplicationsthatmanipulateaspecificdatabasecanusehandenttoobtainthecurrentnameofanentitytheymustuse.YoucanusetheDDMODIFYcommandtogetthehandleofaselectedobject.
Thefollowingcodefragmentuseshandenttoobtainanddisplayanentityname.
(if(not(setqe1(handent"5a2")))
(princ"\nNoentitywiththathandleexists.")
(prince1)
)
Inoneparticulareditingsession,thiscodefragmentmightdisplaythefollowing:<Entityname:60004722>
Inanothereditingsessionwiththesamedrawing,thefragmentmightdisplayanentirelydifferentnumber.Butinbothcasesthecodewouldbeaccessingthesameentity.
Thehandentfunctionhasanadditionaluse.Entitiescanbedeletedfromthedatabasewithentdel(seeEntityContextandCoordinateTransformData).Theentitiesarenotpurgeduntilthecurrentdrawingends.Thismeansthathandentcanrecoverthenamesofdeletedentities,whichcanthenberestoredtothedrawingbyasecondcalltoentdel.
Note Handlesareprovidedforblockdefinitions,includingsubentities.
Entitiesindrawingsthatarecross-referencedbywayofXREFAttacharenotactuallypartofthecurrentdrawing;theirhandlesareunchangedbutcannotbe
Page 601
accessedbyhandent.However,whendrawingsarecombinedbymeansofINSERT,INSERT*,XREFBind(XBIND),orpartialDXFIN,thehandlesofentitiesintheincomingdrawingarelost,andincomingentitiesareassignednewhandlevaluestoensureeachhandleinthecurrentdrawingremainsunique.
Pleasesendusyourcommentaboutthispage
Page 602
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityNameFunctions>
EntityContextandCoordinateTransformData
Thenentselandnentselpfunctionsaresimilartoentsel,excepttheyreturntwoadditionalvaluestohandleentitiesnestedwithinblockreferences.
Anotherdifferencebetweenthesefunctionsisthatwhentheuserrespondstoanentselcallbyselectingacomplexentityoracomplexentityisselectedbynentselp,thesefunctionsreturntheentitynameoftheselectedsubentityandnotthecomplexentity'sheader,asentseldoes.
Forexample,whentheuserselectsa3Dpolyline,nentselreturnsavertexsubentityinsteadofthepolylineheader.Toretrievethepolylineheader,theapplicationmustuseentnexttostepforwardtotheseqendsubentity,andthenobtainthenameoftheheaderfromtheseqendsubentity's-2group.Thesameapplieswhentheuserselectsattributesinanestedblockreference.
Selectinganattributewithinablockreferencereturnsthenameoftheattributeandthepickpoint.Whentheselectedobjectisacomponentofablockreferenceotherthananattribute,nentselreturnsalistcontainingthefollowingelements:
Theselectedentity'sname.
Alistcontainingthecoordinatesofthepointusedtopicktheobject.
TheModeltoWorldTransformationMatrix.Thisisalistconsistingoffoursublists,eachofwhichcontainsasetofcoordinates.Thismatrixcanbeusedtotransformtheentitydefinitiondatapointsfromaninternalcoordinatesystemcalledthemodelcoordinatesystem(MCS),totheWorldCoordinateSystem(WCS).TheinsertionpointoftheblockthatcontainstheselectedentitydefinestheoriginoftheMCS.TheorientationoftheUCSwhentheblockiscreateddeterminesthedirectionoftheMCSaxes.
Page 603
Alistcontainingtheentitynameoftheblockthatcontainstheselectedobject.Iftheselectedobjectisinanestedblock(ablockwithinablock),thelistalsocontainstheentitynamesofallblocksinwhichtheselectedobjectisnested,startingwiththeinnermostblockandcontinuingoutwarduntilthenameoftheblockthatwasinsertedinthedrawingisreported.
Thelistreturnedfromselectingablockwithnentselissummarizedasfollows:
(<EntityName:ename1>;Nameofentity.
(PxPyPz);Pickpoint.
((X0Y0Z0);ModeltoWorldTransformationMatrix.
(X1Y1Z1)
(X2Y2Z2)
(X3Y3Z3)
)
(<Entityname:ename2>;Nameofmostdeeplynestedblock
.;containingselectedobject.
.
.
<Entityname:enamen>);Nameofoutermostblock
);containingselectedobject.
Inthefollowingexample,createablocktousewiththenentselfunction.Command: line
Specifyfirstpoint: 1,1
Specifynextpointor[Undo]: 3,1
Specifynextpointor[Undo]: 3,3
Specifynextpointor[Close/Undo]: 1,3
Specifynextpointor[Close/Undo]: c
Command: -block
Enterblocknameor[?]: square
Specifyinsertionbasepoint: 2,2
Selectobjects: Selectthefourlinesyoujustdrew
Selectobjects: ENTER
Then,inserttheblockinaUCSrotated45degreesabouttheZaxis:Command: ucs
Currentucsname:*WORLD*
Enteroption[New/Move/orthoGraphic/Prev/Restore/Save/Del/Apply/?/World]
Page 604
<World>: z
SpecifyrotationangleaboutZaxis<0>: 45
Command: -insert
Enterblocknameor[?]: square
Specifyinsertionpointor[Scale/X/Y/Z/Rotate/PScale/PX/PY/PZ/PRotate]:7,0
EnterXscalefactor,specifyoppositecorner,or[Corner/XYZ]<1>: ENTER
EnterYscalefactor<useXscalefactor>: ENTER
Specifyrotationangle<0>: ENTER
Usenentseltoselectthelower-leftsideofthesquare.
(setqndata(nentsel))
Thiscodesetsndataequaltoalistsimilartothefollowing:
(<EntityName:400000a0>;Entityname.
(6.46616-1.06060.0);Pickpoint.
((0.7071070.7071070.0);ModeltoWorld
(-0.7071070.7071070.0);TransformationMatrix.
(0.0-0.01.0)
(4.949754.949750.0)
)
(<Entityname:6000001c>);Nameofblockcontaining
;selectedobject.
)
OnceyouobtaintheentitynameandtheModeltoWorldTransformationMatrix,youcantransformtheentitydefinitiondatapointsfromtheMCStotheWCS.UseentgetandassocontheentitynametoobtainthedefinitionpointsexpressedinMCScoordinates.TheModeltoWorldTransformationMatrixreturnedbynentselisa4×3matrix—passedasanarrayoffourpoints—thatusestheconventionthatapointisarowratherthanacolumn.Thetransformationisdescribedbythefollowingmatrixmultiplication:
Sotheequationsforderivingthenewcoordinatesareasfollows:
Page 605
TheMij,where0le;i,jle;2,aretheModeltoWorldTransformationMatrixcoordinates;X,Y,ZistheentitydefinitiondatapointexpressedinMCScoordinates,andX',Y',Z'istheresultingentitydefinitiondatapointexpressedinWCScoordinates.
Totransformavectorratherthanapoint,donotaddthetranslationvector(M30M31M32fromthefourthcolumnofthetransformationmatrix).
Note ThisistheonlyAutoLISPfunctionthatusesamatrixofthistype.ThenentselpfunctionispreferredtonentselbecauseitreturnsamatrixsimilartothoseusedbyotherAutoLISPandObjectARXfunctions.
Usingtheentitynamepreviouslyobtainedwithnentsel,thefollowingexampleillustrateshowtoobtaintheMCSstartpointofaline(groupcode10)containedinablockdefinition:
Command:(setqedata(assoc10(entget(carndata))))
(10-1.01.00.0)
ThefollowingstatementstorestheModeltoWorldTransformationMatrixsublistinthesymbolmatrix.
Command:(setqmatrix(caddrndata))
((0.7071070.7071070.0);Xtransformation
(-0.7071070.7071070.0);Ytransformation
(0.0-0.01.0);Ztransformation
(4.949754.949750.0);DisplacementfromWCSorigin
)
ThefollowingcommandappliesthetransformationformulaforX'tochangetheXcoordinateofthestartpointofthelinefromanMCScoordinatetoaWCScoordinate:
(setqanswer
(+;add:
(*(car(nth0matrix))(cadredata));M00*X
(*(car(nth1matrix))(caddredata));M10*Y
(*(car(nth2matrix))(cadddredata));M20*Z
Page 606
(car(nth3matrix));M30
)
)
Thisstatementreturns3.53553,theWCSXcoordinateofthestartpointoftheselectedline.
Pleasesendusyourcommentaboutthispage
Page 607
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityNameFunctions>
EntityAccessFunctions
Theentityaccessfunctionsarerelativelyslow.Itisbesttogetthecontentsofaparticularentity(orsymboltableentry)onceandkeepthatinformationstoredinmemory,ratherthanrepeatedlyaskAutoCADforthesamedata.Besurethedataremainsvalid.Iftheuserhasanopportunitytoaltertheentityorsymboltableentry,youshouldreissuetheentityaccessfunctiontoensurethevalidityofthedata.
Pleasesendusyourcommentaboutthispage
Page 608
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>
EntityDataFunctions
Thefunctionsdescribedinthissectionoperateonentitydataandcanbeusedtomodifythecurrentdrawingdatabase.
DeletinganEntityObtainingEntityInformationModifyinganEntityAddinganEntitytoaDrawingCreatingComplexEntitiesWorkingwithBlocksAnonymousBlocks
Pleasesendusyourcommentaboutthispage
Page 609
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
DeletinganEntity
Theentdelfunctiondeletesaspecifiedentity.Theentityisnotpurgedfromthedatabaseuntiltheendofthecurrentdrawingsession,soiftheapplicationcallsentdelasecondtimeduringthatsessionandspecifiesthesameentity,theentityisundeleted.
Attributesandold-stylepolylineverticescannotbedeletedindependentlyoftheirparententities.Theentdelfunctionoperatesonlyonmainentities.Ifyouneedtodeleteanattributeorvertex,youcanusecommandtoinvoketheAutoCADATTEDITorPEDITcommands.
Pleasesendusyourcommentaboutthispage
Page 610
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
ObtainingEntityInformation
Theentgetfunctionreturnsthedefinitiondataofaspecifiedentity.Thedataisreturnedasalist.EachiteminthelistisspecifiedbyaDXFgroupcode.Thefirstiteminthelistcontainstheentity'scurrentname.
Inthisexample,thefollowing(default)conditionsapplytothecurrentdrawing:
Layeris0
LinetypeisCONTINUOUS
Elevationis0
Theuserhasdrawnalinewiththefollowingsequenceofcommands:Command: line
Frompoint: 1,2
Topoint: 6,6
Topoint: ENTER
AnAutoLISPapplicationcanretrieveandprintthedefinitiondataforthelinebyusingthefollowingAutoLISPfunction:
(defunC:PRINTDXF()
(setqent(entlast));Setenttolastentity.
(setqentl(entgetent));Setentltoassociationlistof
;lastentity.
(setqct0);Setct(acounter)to0.
(textpage);Switchtothetextscreen.
(princ"\nentgetoflastentity:")
(repeat(lengthentl);Repeatfornumberofmembersinlist:
(print(nthctentl));Printanewline,theneachlist
;member.
(setqct(1+ct));Incrementsthecounterbyone.
)
(princ);Exitquietly.
Page 611
)
Thiswouldprintthefollowing:entgetoflastentity:
(-1.<Entityname:1bbd1c8>)
(0."LINE")
(330.<Entityname:1bbd0c8>)
(5."69")
(100."AcDbEntity")
(67.0)
(410."Model")
(8."0")
(100."AcDbLine")
(101.02.00.0)
(116.06.00.0)
(2100.00.01.0)
The-1itematthestartofthelistcontainsthenameoftheentity.Theentmodfunction,whichisdescribedinthissection,usesthenametoidentifytheentitytobemodified.Theindividualdottedpairsthatrepresentthevaluescanbeextractedbyusingassocwiththecdrfunction.
Sublistsforpointsarenotrepresentedasdottedpairsliketherestofthevaluesreturned.Theconventionisthatthecdrofthesublististhegroup'svalue.Becauseapointisalistoftwoorthreereals,theentiregroupisathree-(orfour-)elementlist.Thecdrofthegroupisthelistrepresentingthepoint,sotheconventionthatcdralwaysreturnsthevalueispreserved.
ThecodesforthecomponentsoftheentityarethoseusedbyDXF.AswithDXF,theentityheaderitems(color,linetype,thickness,theattributes-followflag,andtheentityhandle)arereturnedonlyiftheyhavevaluesotherthanthedefault.UnlikeDXF,optionalentitydefinitionfieldsarereturnedwhetherornottheyequaltheirdefaultsandwhetherornotassociatedX,Y,andZcoordinatesarereturnedasasinglepointvariable,ratherthanasseparateX(10),Y(20),andZ(30)groups.
Allpointsassociatedwithanobjectareexpressedintermsofthatobject'sobjectcoordinatesystem(OCS).Forpoint,line,3Dline,3Dface,3Dpolyline,3Dmesh,anddimensionobjects,theOCSisequivalenttotheWCS(theobjectpointsareWorldpoints).Forallotherobjects,theOCScanbederivedfromthe
Page 612
WCSandtheobject'sextrusiondirection(its210group).WhenworkingwithobjectsthataredrawnusingcoordinatesystemsotherthantheWCS,youmayneedtoconvertthepointstotheWCSortothecurrentUCSbyusingthetransfunction.
Whenwritingfunctionstoprocessentitylists,makesurethefunctionlogicisindependentoftheorderofthesublists;useassoctoguaranteethis.Theassocfunctionsearchesalistforagroupofaspecifiedtype.Thefollowingcodereturnstheobjecttype"LINE"(0)fromthelistentl.
(cdr(assoc0entl))
IftheDXFgroupcodespecifiedisnotpresentinthelist(orifitisnotavalidDXFgroup),assocreturnsnil.
Warning Beforeperforminganentgetonvertexentities,youshouldreadorwritethepolylineentity'sheader.Ifthemostrecentlyprocessedpolylineentityisdifferentfromtheonetowhichthevertexbelongs,widthinformation(the40and41groups)canbelost.
Pleasesendusyourcommentaboutthispage
Page 613
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
ModifyinganEntity
Theentmodfunctionmodifiesanentity.Itpassesalistthathasthesameformatasalistreturnedbyentgetbutwithsomeoftheentitygroupvalues(presumably)modifiedbytheapplication.Thisfunctioncomplementsentget.TheprimarymechanismbywhichanAutoLISPapplicationupdatesthedatabaseisbyretrievinganentitywithentget,modifyingitsentitylist,andthenpassingthelistbacktothedatabasewithentmod.
ThefollowingcodefragmentretrievesthedefinitiondataofthefirstentityinthedrawingandchangesitslayerpropertytoMYLAYER.
(setqen(entnext));Setsentofirstentityname
;inthedrawing.
(setqed(entgeten));Setsedtotheentitydata
;forentitynameen.
(setqed
(subst(cons8"MYLAYER")
(assoc8ed);Changesthelayergroupined.
ed;tolayerMYLAYER.
)
)
(entmoded);Modifiesentityen'slayerin
;thedrawing.
Therearerestrictionsonthechangestothedatabasethatentmodcanmake;entmodcannotchangethefollowing:
Theentity'stypeorhandle.
Internalfields.(InternalfieldsarethevaluesthatAutoCADassignstocertaingroupcodes:-2,entitynamereference;-1,entityname;5,entityhandle.)Anyattempttochangeaninternalfield—forexample,themainentitynameinaseqendsubentity(group-2)—isignored.
Page 614
Viewportentities.Anattempttochangeaviewportentitycausesanerror.
Otherrestrictionsapplywhenmodifyingdimensionsandhatchpatterns.
AutoCADmustrecognizeallobjects(exceptlayers)thattheentitylistrefersto.Thenameofanytextstyle,linetype,shape,orblockthatappearsinanentitylistmustbedefinedinthecurrentdrawingbeforetheentitylistispassedtoentmod.Thereisoneexception:entmodacceptsnewlayernames.
Iftheentitylistreferstoalayernamethathasnotbeendefinedinthecurrentdrawing,entmodcreatesanewlayer.TheattributesofthenewlayerarethestandarddefaultvaluesusedbytheNewoptionoftheAutoCADLAYERcommand.
Theentmodfunctioncanmodifysubentitiessuchaspolylineverticesandblockattributes.
Ifyouuseentmodtomodifyanentityinablockdefinition,thisaffectsallINSERTorXREFreferencestothatblock.Also,entitiesinblockdefinitionscannotbedeletedbyentdel.
Pleasesendusyourcommentaboutthispage
Page 615
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
AddinganEntitytoaDrawing
Anapplicationcanaddanentitytothedrawingdatabasebycallingtheentmakefunction.Likethatofentmod,theargumenttoentmakeisalistwhoseformatissimilartothatreturnedbyentget.Thenewentitythatthelistdescribesisappendedtothedrawingdatabase(itbecomesthelastentityinthedrawing).Iftheentityisacomplexentity(anold-stylepolylineorablock),itisnotappendedtothedatabaseuntilitiscomplete.
ThefollowingcodefragmentcreatesacircleontheMYLAYERlayer:
(entmake'((0."CIRCLE");Objecttype
(8."MYLAYER");Layer
(105.07.00.0);Centerpoint
(40.1.0);Radius
))
Thefollowingentmakerestrictionsapplytoallentities:
Thefirstorsecondmemberinthelistmustspecifytheentitytype.ThetypemustbeavalidDXFgroupcode.Ifthefirstmemberdoesnotspecifythetype,itcanspecifyonlythenameoftheentity:group-1(thenameisnotsavedinthedatabase).
AutoCADmustrecognizeallobjectsthattheentitylistrefersto.Thereisoneexception:entmakeacceptsnewlayernames.
Anyinternalfieldspassedtoentmakeareignored.
entmakecannotcreateviewportentities.
ForentitytypesintroducedinAutoCADRelease13andlaterreleases,youmustalsospecifysubclassmarkers(DXFgroupcode100)whencreatingtheentity.AllAutoCADentitieshavetheAcDbEntitysubclassmarker,andthismustbeexplicitlyincludedintheentmakelist.Inaddition,oneormoresubclass
Page 616
markerentriesarerequiredtoidentifythespecificsub-entitytype.Theseentriesmustfollowgroupcode0andmustprecedegroupcodesthatarespecificallyusedtodefineentitypropertiesintheentmakelist.Forexample,thefollowingistheminimumcoderequiredtoentmakeanMTEXTentity:
(entmake'(
(0."MTEXT")
(100."AcDbEntity");Requiredforallpost-R12entities.
(8."ALAYER")
(100."AcDbMText");IdentifiestheentityasMTEXT.
(104.04.00.0)
(1."Some\\Ptext")
)
)
Thefollowingtableidentifiestheentitiesthatdonotrequiresubentitymarkerentriesinthelistpassedtoentmake:
DXFnamesofentitiesintroduced
priortoAutoCADRelease13
3DFACE ARC
ATTDEF ATTRIB
CIRCLE DIMENSION
INSERT LINE
POINT POLYLINE(old-style)
SEQEND SHAPE
SOLID TEXT
TRACE VERTEX
VIEWPORT
Page 617
Theentmakefunctionverifiesthatavalidlayername,linetypename,andcoloraresupplied.Ifanewlayernameisintroduced,entmakeautomaticallycreatesthenewlayer.Theentmakefunctionalsochecksforblocknames,dimensionstylenames,textstylenames,andshapenames,iftheentitytyperequiresthem.Thefunctionfailsifitcannotcreatevalidentities.Objectscreatedonafrozenlayerarenotregenerateduntilthelayeristhawed.
Pleasesendusyourcommentaboutthispage
Page 618
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
CreatingComplexEntities
Tocreateacomplexentity(anold-stylepolylineorablock),youmakemultiplecallstoentmake,usingaseparatecallforeachsubentity.Whenentmakefirstreceivesaninitialcomponentforacomplexentity,itcreatesatemporaryfileinwhichtogatherthedefinitiondataandextendeddata,ifpresent.(SeeExtendedData-xdata.)Foreachsubsequententmakecall,thefunctionchecksifthetemporaryfileexists.Ifitdoes,thenewsubentityisappendedtothefile.Whenthedefinitionofthecomplexentityiscomplete(thatis,whenentmakereceivesanappropriateseqendorendblksubentity),theentityischeckedforconsistency;ifvalid,itisaddedtothedrawing.Thefileisdeletedwhenthecomplexentityiscompleteorwhenitscreationhasbeencanceled.
Noportionofacomplexentityisdisplayedonyourdrawinguntilitsdefinitioniscomplete.Theentitydoesnotappearinthedrawingdatabaseuntilthefinalseqendorendblksubentityhasbeenpassedtoentmake.Theentlastfunctioncannotretrievethemostrecentlycreatedsubentityforacomplexentitythathasnotbeencompleted.Youcancancelthecreationofacomplexentitybyenteringentmakewithnoarguments.Thisclearsthetemporaryfileandreturnsnil.
Asthepreviousparagraphsimply,entmakecanconstructonlyonecomplexentityatatime.Ifacomplexentityisbeingcreatedandentmakereceivesinvaliddataoranentitythatisnotanappropriatesubentity,boththeinvalidentityandtheentirecomplexentityarerejected.Youcanexplicitlycancelthecreationofacomplexentitybycallingentmakewithnoarguments.
Thefollowingexamplecontainsfiveentmakefunctionsthatcreateasinglecomplexentity,anold-stylepolyline.ThepolylinehasalinetypeofDASHEDandacolorofBLUE.Ithasthreeverticeslocatedatcoordinates(1,1,0),(4,6,0),and(3,2,0).Allotheroptionaldefinitiondataassumedefaultvalues.(Forthisexampletoworkproperly,thelinetypeDASHEDmustbeloaded.)
Page 619
(entmake'((0."POLYLINE");Objecttype
(62.5);Color
(6."dashed");Linetype
(66.1);Verticesfollow
))
(entmake'((0."VERTEX");Objecttype
(101.01.00.0);Startpoint
))
(entmake'((0."VERTEX");Objecttype
(104.06.00.0);Secondpoint
))
(entmake'((0."VERTEX");Objecttype
(103.02.00.0);Thirdpoint
))
(entmake'((0."SEQEND")));Sequenceend
Whendefiningdottedpairs,asintheaboveexample,theremustbeaspaceonbothsidesofthedot.Otherwise,youwillgetaninvaliddottedpairerrormessage.
Blockdefinitionsbeginwithablockentityandendwithanendblksubentity.Newlycreatedblocksareautomaticallyenteredintothesymboltablewheretheycanbereferenced.Blockdefinitionscannotbenested,norcantheyreferencethemselves.Ablockdefinitioncancontainreferencestootherblockdefinitions.
Note Beforeyouuseentmaketocreateablock,youshouldusetblsearchtoensurethatthenameofthenewblockisunique.Theentmakefunctiondoesnotcheckfornameconflictsintheblockdefinitionstable,soitcanredefineexistingblocks.SeeSymbolTableandDictionaryAccessforinformationonusingtblsearch.
Blockreferencescanincludeanattributes-followflag(group66).Ifpresentandequalto1,aseriesofattribute(attrib)entitiesisexpectedtofollowtheinsertobject.Theattributesequenceisterminatedbyaseqendsubentity.
Old-stylepolylineentitiesalwaysincludeavertices-followflag(alsogroup66).Thevalueofthisflagmustbe1,andtheflagmustbefollowedbyasequenceofvertexentities,terminatedbyaseqendsubentity.
Applicationscanrepresentpolygonswithanarbitrarilylargenumberofsidesinpolyfacemeshes.However,theAutoCADentitystructureimposesalimitonthenumberofverticesthatagivenfaceentitycanspecify.Youcanrepresentmorecomplexpolygonsbydividingthemintotriangularwedges.AutoCADrepresentstriangularwedgesasfour-vertexfaceswheretwoadjacentvertices
Page 620
havethesamevalue.Theiredgesshouldbemadeinvisibletopreventvisibleartifactsofthissubdivisionfrombeingdrawn.ThePFACEcommandperformsthissubdivisionautomatically,butwhenapplicationsgeneratepolyfacemeshesdirectly,theapplicationsmustdothisthemselves.
Thenumberofverticesperfaceisthekeyparameterinthissubdivisionprocess.ThePFACEVMAXsystemvariableprovidesanapplicationwiththenumberofverticesperfaceentity.Thisvalueisread-onlyandissetto4.
Complexentitiescanexistineithermodelspaceorpaperspace,butnotboth.IfyouhavechangedthecurrentspacebyinvokingeitherMSPACEorPSPACE(withcommand)whileacomplexentityisbeingconstructed,asubsequentcalltoentmakecancelsthecomplexentity.Thiscanalsooccurifthesubentityhasa67groupwhosevaluedoesnotmatchthe67groupoftheentityheader.
Pleasesendusyourcommentaboutthispage
Page 621
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
WorkingwithBlocks
ThereisnodirectmethodforanapplicationtocheckwhetherablocklistedintheBLOCKtableisactuallyreferencedbyaninsertobjectinthedrawing.Youcanusethefollowingcodetoscanthedrawingforinstancesofablockreference:
(ssget"x"'((2."BLOCKNAME")))
Youmustalsoscaneachblockdefinitionforinstancesofnestedblocks.
Pleasesendusyourcommentaboutthispage
Page 622
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>EntityDataFunctions>
AnonymousBlocks
Theblockdefinitions(BLOCK)tableinadrawingcancontainanonymousblocks(alsoknownasunnamedblocks),thatAutoCADcreatestosupporthatchpatternsandassociativedimensioning.Theentmakefunctioncancreateanonymousblocksotherthan*Dnnn(dimensions)and*Xnnn(hatchpatterns).UnreferencedanonymousblocksarepurgedfromtheBLOCKdefinitiontablewhenadrawingisopened.Referencedanonymousblocks(thosethathavebeeninserted)arenotpurged.Youcanuseentmaketocreateablockreference(insertobject)toananonymousblock.(YoucannotpassananonymousblocktotheINSERTcommand.)Also,youcanuseentmaketoredefinetheblock.Youcanmodifytheentitiesinablock(butnottheblockobjectitself)withentmod.
Thename(group2)ofananonymousblockcreatedbyAutoLISPorObjectARXhastheform*Unnn,wherennnisanumbergeneratedbyAutoCAD.Also,thelow-orderbitofananonymousblock'sblocktypeflag(group70)issetto1.Whenentmakecreatesablockwhosenamebeginswith*andwhoseanonymousbitisset,AutoCADtreatsthisasananonymousblockandassignsitaname.Anycharactersfollowingthe*inthenamestringpassedtoentmakeareignored.
Note Anonymousblocknamesdonotremainconstant.Althoughareferencedanonymousblockbecomespermanent,thenumericportionofitsnamecanchangebetweendrawingsessions.
Pleasesendusyourcommentaboutthispage
Page 623
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>
EntityDataFunctionsandtheGraphicsScreen
Changestothedrawingmadebytheentitydatafunctionsarereflectedonthegraphicsscreen,providedtheentitybeingdeleted,undeleted,modified,ormadeisinanareaandonalayerthatiscurrentlyvisible.Thereisoneexception:Whenentmodmodifiesasubentity,itdoesnotupdatetheimageoftheentire(complex)entity.If,forexample,anapplicationmodifies100verticesofanold-stylepolylinewith100callstoentmod,thetimerequiredtorecalculateandredisplaytheentirepolylineisunacceptablyslow.Instead,anapplicationcanperformaseriesofsubentitymodifications,andthenredisplaytheentireentitywithasinglecalltotheentupdfunction.
Considerthefollowing:Ifthefirstentityinthecurrentdrawingisanold-stylepolylinewithseveralvertices,thefollowingcodemodifiesthesecondvertexofthepolylineandregeneratesitsscreenimage.
(setqe1(entnext));Setse1tothepolyline'sentityname.
(setqv1(entnexte1));Setsv1toitsfirstvertex.
(setqv2(entnextv1));Setsv2toitssecondvertex.
(setqv2d(entgetv2));Setsv2dtothevertexdata.
(setqv2d
(subst
'(101.02.00.0)
(assoc10v2d);Changesthevertex'slocationinv2d
v2d;topoint(1,2,0).
)
)
(entmodv2d);Movesthevertexinthedrawing.
(entupde1);Regeneratesthepolylineentitye1.
Theargumenttoentupdcanspecifyeitheramainentityorasubentity.Ineithercase,entupdregeneratestheentireentity.Althoughitsprimaryuseisforcomplexentities,entupdcanregenerateanyentityinthecurrentdrawing.
Note Toensurethatallinstancesoftheblockreferencesareupdated,youmust
Page 624
regeneratethedrawingbyinvokingtheAutoCADREGENcommand(withcommand).Theentupdfunctionisnotsufficientifthemodifiedentityisinablockdefinition.
Pleasesendusyourcommentaboutthispage
Page 625
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>
Old-StylePolylinesandLightweightPolylines
Alightweightpolyline(lwpolyline)isdefinedinthedrawingdatabaseasasinglegraphicentity.Thelwpolylinediffersfromtheold-stylepolyline,whichisdefinedasagroupofsubentities.LwpolylinesdisplayfasterandconsumelessdiskspaceandRAM.
AsofRelease14ofAutoCAD,3Dpolylinesarealwayscreatedasold-stylepolylineentities,and2Dpolylinesarecreatedaslwpolylineentities,unlesstheyarecurvedorfittedwiththePEDITcommand.WhenadrawingfromanearlierreleaseisopenedinRelease14oralaterrelease,all2Dpolylinesconverttolwpolylinesautomatically,unlesstheyhavebeencurvedorfittedorcontainxdata.
ProcessingCurve-FitandSpline-FitPolylines
Pleasesendusyourcommentaboutthispage
Page 626
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>Old-StylePolylinesandLightweightPolylines>
ProcessingCurve-FitandSpline-FitPolylines
WhenanAutoLISPapplicationusesentnexttostepthroughtheverticesofanold-stylepolyline,itmightencounterverticesthatwerenotcreatedexplicitly.AuxiliaryverticesareinsertedautomaticallybythePEDITcommand'sFitandSplineoptions.Youcansafelyignorethem,becausechangestotheseverticeswillbediscardedthenexttimetheuserappliesPEDITtofitortosplinethepolyline.
Theold-stylepolylineentity'sgroup70flagsindicatewhetherthepolylinehasbeencurve-fit(bitvalue2)orspline-fit(bitvalue4).Ifneitherbitisset,allthepolyline'sverticesareregularuser-definedvertices.However,ifthecurve-fitbit(2)isset,alternatingverticesofthepolylinehavethebitvalue1setintheir70grouptoindicatethattheywereinsertedbythecurve-fittingprocess.IfyouuseentmodtomovetheverticesofsuchapolylinewiththeintentofrefittingthecurvebymeansofPEDIT,ignorethesevertices.
Likewise,iftheold-stylepolylineentity'sspline-fitflagbit(bit4)isset,anassortmentofverticeswillbefound—somewithflagbit1(insertedbycurvefittingifsystemvariableSPLINESEGSwasnegative),somewithbitvalue8(insertedbysplinefitting),andallotherswithbitvalue16(splineframe-controlpoint).Hereagain,ifyouuseentmodtomovetheverticesandyouintendtorefitthesplineafterward,moveonlythecontrol-pointvertices.
Pleasesendusyourcommentaboutthispage
Page 627
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>
Non-GraphicObjectHandling
AutoCADusestwotypesofnon-graphicalobjects:dictionaryobjectsandsymboltableobjects.Althoughtherearesimilaritiesbetweentheseobjecttypes,theyarehandleddifferently.
Allobjecttypesaresupportedbytheentget,entmod,entdel,andentmakefunctions,althoughobjecttypesindividuallydictatetheirparticipationinthesefunctionsandmayrefuseanyorallprocessing.WithrespecttoAutoCADbuilt-inobjects,therulesapplyforsymboltablesandfordictionaryobjects.Formoreinformation,seeSymbolTableObjectsandDictionaryObjects.
Allrulesandrestrictionsthatapplytographicobjectsapplytonon-graphicobjectsaswell.Non-graphicobjectscannotbepassedtotheentupdfunction.
Whenusingentmake,theobjecttypedetermineswheretheobjectwillreside.Forexample,ifalayerobjectispassedtoentmake,itautomaticallygoestothelayersymboltable.Ifagraphicobjectispassedtoentmake,itwillresideinthecurrentspace(modelorpaper).
SymbolTableObjectsDictionaryObjects
Pleasesendusyourcommentaboutthispage
Page 628
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>Non-GraphicObjectHandling>
SymbolTableObjects
Thefollowingrulesapplytosymboltables:
Symboltableentriescanbecreatedthroughentmakewithfewrestrictions,otherthanbeingvalidrecordrepresentations,andnameconflictscanonlyoccurintheVPORTtable.*ACTIVEentriescannotbecreated.
Symboltableentriescannotbedeletedwithentdel.
Theobjectstatesofsymboltablesandsymboltableentriesmaybeaccessedwithentgetbypassingtheentityname.Thetblobjnamefunctioncanbeusedtoretrievetheentitynameofasymboltableentry.
Symboltablesthemselvescannotbecreatedwithentmake;however,symboltableentriescanbecreatedwithentmake.
Handlegroups(5,105)cannotbechangedinentmod,norspecifiedinentmake.
SymboltableentriesthatarenotintheAPPIDtablecanhavemanyoftheirfieldsmodifiedwithentmod.Tobepassedtoentmod,asymboltablerecordlistmustincludeitsentityname,whichcanbeobtainedfromentgetbutnotfromthetblsearchandtblnextfunctions.The70groupofsymboltableentriesisignoredinentmodandentmakeoperations.
Renamingsymboltableentriestoduplicatenamesisnotacceptable,exceptfortheVPORTsymboltable.Thefollowingentriescannotbemodifiedorrenamed,exceptthatmostLAYERentriescanberenamedandxdatacanbemodifiedonallsymboltableentries.
Page 629
Symboltableentriesthatcannotbemodifiedorrenamed
Table Entryname
VPORT *ACTIVE
LINETYPE CONTINUOUS
LAYER Entriescannotbemodified,exceptforxdata,butrenamingisallowed
Thefollowingentriescannotberenamed,butareotherwisemodifiable:
Symboltableentriesthatcannotberenamed
Table Entryname
STYLE STANDARD
DIMSTYLE STANDARD
BLOCKS *MODEL_SPACE
BLOCKS *PAPER_SPACE
APPID Noentriescanberenamed
Pleasesendusyourcommentaboutthispage
Page 630
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ObjectHandling>Non-GraphicObjectHandling>
DictionaryObjects
Thefollowingrulesapplytodictionaryobjects:
Dictionaryobjectscanbeexaminedwithentgetandtheirxdatamodifiedwithentmod.Theirentriescannotbealteredwithentmod.Allaccesstotheirentriesaremadethroughthedictsearchanddictnextfunctions.
Dictionaryentrycontentscannotbemodifiedthroughentmod,althoughxdatacanbemodified.
DictionaryentriesthatbeginwithACAD*cannotberenamed.
Pleasesendusyourcommentaboutthispage
Page 631
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>
ExtendedData-xdata
SeveralAutoLISPfunctionsareprovidedtohandleextendeddata(xdata),whichiscreatedbyapplicationswrittenwithObjectARXorAutoLISP.Ifanentitycontainsxdata,itfollowstheentity'sregulardefinitiondata.
Youcanretrieveanentity'sextendeddatabycallingentget.Theentgetfunctionretrievesanentity'sregulardefinitiondataandthexdataforthoseapplicationsspecifiedintheentgetcall.
Whenxdataisretrievedwithentget,thebeginningofextendeddataisindicatedbya-3code.The-3codeisinalistthatprecedesthefirst1001group.The1001groupcontainstheapplicationnameofthefirstapplicationretrieved,asshowninthetableandasdescribedinthetopicsinthissection.
Groupcodesforregularandextendeddata
Groupcode Field Typeofdata
(-1,-2(0-239)
Entityname)Regulardefinitiondatafields)...
Normalentitydefinitiondata
(-3(1001(1000,
ExtendeddatasentinelRegisteredapplicationname1)XDATAfields)
Extendeddata
Page 632
1002-1071(1001(1000,1002-1071(1001
.
.
.Registeredapplicationname2)XDATAfields)...Registeredapplicationname3)..
OrganizationofExtendedDataRegistrationofanApplicationRetrievalofExtendedDataAttachmentofExtendedDatatoanEntityManagementofExtendedDataMemoryUseHandlesinExtendedData
Pleasesendusyourcommentaboutthispage
Page 633
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
OrganizationofExtendedData
Extendeddataconsistsofoneormore1001groups,eachofwhichbeginswithauniqueapplicationname.Thexdatagroupsreturnedbyentgetfollowthedefinitiondataintheorderinwhichtheyaresavedinthedatabase.
Withineachapplication'sgroup,thecontents,meaning,andorganizationofthedataaredefinedbytheapplication.AutoCADmaintainstheinformationbutdoesnotuseit.Thetablealsoshowsthatthegroupcodesforxdataareintherange1000-1071.Manyofthesegroupcodesareforfamiliardatatypes,asfollows:
String
1000.Stringsinextendeddatacanbeupto255byteslong(withthe256thbytereservedforthenullcharacter).
ApplicationName
1001(alsoastringvalue).Applicationnamescanbeupto31byteslong(the32ndbyteisreservedforthenullcharacter)andmustadheretotherulesforsymboltablenames(suchaslayernames).Anapplicationnamecancontainletters,digits,andthespecialcharacters$(dollarsign),-(hyphen),and_(underscore).Itcannotcontainspaces.
LayerName
1003.Nameofalayerassociatedwiththexdata.
Database-Handle
1005.Handleofanentityinthedrawingdatabase.
3DPoint
1010.Threerealvalues,containedinapoint.
Page 634
Real
1040.Arealvalue.
Integer
1070.A16-bitinteger(signedorunsigned).
Long
1071.A32-bitsigned(long)integer.Ifthevaluethatappearsina1071groupisashortintegerorrealvalue,itisconvertedtoalonginteger;ifitisinvalid(forexample,astring),itisconvertedtoalongzero(0L).
Note AutoLISPmanages1071groupsasrealvalues.Ifyouuseentgettoretrieveanentity'sdefinitionlistthatcontainsa1071group,thevalueisreturnedasareal,asshowninthefollowingexample:(1071.12.0)Ifyouwanttocreatea1071groupinanentitywithentmakeorentmod,youcanuseeitherarealoranintegervalue,asshowninthefollowingexample:(entmake'((.....(1071.12)....)))
(entmake'((.....(1071.12.0)....)))
(entmake'((.....(1071.65537.0)....)))
(entmake'((.....(1071.65537)....)))
ButAutoLISPstillreturnsthegroupvalueasareal:(entmake'((.....(1071.65537)....)))
Theprecedingstatementreturnsthefollowing:(1071.65537.0)
ObjectARXalwaysmanages1071groupsaslongintegers.
Severalotherextendeddatagroupshavespecialmeaningsinthiscontext(iftheapplicationchoosestousethem):
ControlString
1002.Anxdatacontrolstringcanbeeither"{"or"}".Thesebracesenabletheapplicationtoorganizeitsdatabysubdividingitintolists.Theleftbracebeginsalist,andtherightbraceterminatesthemostrecentlist.Listscanbenested.
Page 635
Note Ifa1001groupappearswithinalist,itistreatedasastringanddoesnotbeginanewapplicationgroup.
BinaryData
1004.Binarydatathatisorganizedintovariable-lengthchunks,whichcanbehandledinObjectARXwiththeads_binarystructure.Themaximumlengthofeachchunkis127bytes.
Note AutoLISPcannotdirectlyhandlebinarychunks,sothesameprecautionsthatapplytolong(1071)groupsapplytobinarygroupsaswell.
WorldSpacePosition
1011.Unlikeasimple3Dpoint,theWCScoordinatesaremoved,scaled,rotated,andmirroredalongwiththeparententitytowhichtheextendeddatabelongs.TheWCSpositionisalsostretchedwhentheSTRETCHcommandisappliedtotheparententityandwhenthispointlieswithintheselectwindow.
WorldSpace-Displacement
1012.A3Dpointthatisscaled,rotated,ormirroredalongwiththeparent,butnotstretchedormoved.
World-Direction
1013.A3Dpointthatisrotatedormirroredalongwiththeparent,butnotscaled,stretched,ormoved.TheWCSdirectionisanormalizeddisplacementthatalwayshasaunitlength.
Distance
1041.Arealvaluethatisscaledalongwiththeparententity.
ScaleFactor
1042.Alsoarealvaluethatisscaledalongwiththeparent.
TheDXFgroupcodesforxdataarealsodescribedintheDXFReference.
Pleasesendusyourcommentaboutthispage
Page 636
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
RegistrationofanApplication
ToberecognizedbyAutoCAD,anapplicationmustregisterthenameornamesthatituses.Applicationnamesaresavedwiththeextendeddataofeachentitythatusesthem,andalsointheAPPIDtable.Registrationisdonewiththeregappfunction,whichspecifiesastringtouseasanapplicationname.IfitsuccessfullyaddsthenametoAPPID,itreturnsthenameoftheapplication;otherwiseitreturnsnil.Aresultofnilindicatesthatthenameisalreadypresentinthesymboltable.Thisisnotanactualerrorconditionbutanexpectedreturnvalue,becausetheapplicationnameneedstoberegisteredonlyonceperdrawing.
Toregisteritself,anapplicationshouldfirstcheckthatitsnameisnotalreadyintheAPPIDtable.Ifthenameisnotthere,theapplicationmustregisterit.Otherwise,itcansimplygoaheadandusethedata,asdescribedlaterinthissection.
Thefollowingfragmentshowsthetypicaluseofregapp.(ThetblsearchfunctionisdescribedinSymbolTableandDictionaryAccess.)
(setqappname"MYAPP_2356");Uniqueapplicationname.
(if(tblsearch"appid"appname);Checksifalreadyregistered.
(princ(strcat
"\n"appname"alreadyregistered."))
(if(=(regappappname)nil);Someotherproblem.
(princ(strcat
"\nCan'tregisterXDATAfor"appname"."))
)
)
Theregappfunctionprovidesameasureofsecurity,butitcannotguaranteethattwoseparateapplicationshavenotchosenthesamename.Onewayofensuringthisistoadoptanamingschemethatusesthecompanyorproductnameandauniquenumber(likeyourtelephonenumberorthecurrentdateand
Page 637
time).
Pleasesendusyourcommentaboutthispage
Page 638
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
RetrievalofExtendedData
Anapplicationcancallentgettoobtainthexdatathatithasregistered.Theentgetfunctioncanreturnboththedefinitiondataandthexdatafortheapplicationsitrequests.Itrequiresanadditionalargument,application,thatspecifiestheapplicationnames.Thenamespassedtoentgetmustcorrespondtoapplicationsregisteredbyapreviouscalltoregapp;theycanalsocontainwild-cardcharacters.
Bydefault,associativehatchpatternscontainextendeddata.Thefollowingcodeshowstheassociationlistofthisxdata.
Command: (entget(car(entsel))'("ACAD"))
Selectobject: Selectanassociativehatch
Enteringtheprecedingcodeatthecommandlinereturnsalistthatlookssomethinglikethis:
((-1.<Entityname:600000c0>)(0."INSERT")(8."0")(2."*X0")
(100.00.00.0)(41.1.0)(42.1.0)(50.0.0)(43.1.0)(70.0)(71.0)
(44.0.0)(45.0.0)(2100.00.01.0)(-3("ACAD"(1000."HATCH")
(1002."{")(1070.16)(1000."LINE")(1040.1.0)(1040.0.0)
(1002."}"))))
Thisfragmentshowsatypicalsequenceforretrievingxdatafortwospecifiedapplications.Notethattheapplicationargumentpassesapplicationnamesinlistform:
(setqworking_elist
(entgetent_name
'("MY_APP_1""SOME_OTHER");Onlyxdatafrom"MY_APP_1"
);and"SOME_OTHER"isretrieved.
)
(ifworking_elist
(progn
Page 639
...;Updatesworkingentitygroups.
(entmodworking_elist);Onlyxdatafromregistered
);applicationsstillinthe
);working_elistlistaremodified.
Asthesamplecodeshows,youcanmodifyxdataretrievedbyentgetbyusingasubsequentcalltoentmod,justasyoucanuseentmodtomodifynormaldefinitiondata.Youcanalsocreatexdatabydefiningitintheentitylistpassedtoentmake.
Returningtheextendeddataofonlythoseapplicationsspecificallyrequestedprotectsoneapplicationfromcorruptinganotherapplication'sdata.Italsocontrolstheamountofmemorythatanapplicationneedstouseandsimplifiesthexdataprocessingthatanapplicationneedstoperform.
Note Becausethestringspassedbyapplicationcanincludewild-cardcharacters,anapplicationnameof"*"willcauseentgettoreturnallextendeddataattachedtoanentity.
Pleasesendusyourcommentaboutthispage
Page 640
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
AttachmentofExtendedDatatoanEntity
Youcanusexdatatostoreanytypeofinformationyouwant.Forexample,drawanentity(suchasalineoracircle),thenenterthefollowingcodetoattachxdatatotheentity:
(setqlastent(entget(entlast)));Getstheassociation
;listofdefinitiondata
;forthelastentity.
(regapp"NEWDATA");Registersthe
;applicationname.
(setqexdata;Setsthevariable
'((-3("NEWDATA";exdataequaltothe
(1000."Thisisanewthing!");newextendeddata—
)));inthiscase,atext
);string.
(setqnewent
(appendlastentexdata));Appendsnewdatalistto
;entity'slist.
(entmodnewent);Modifiestheentitywiththenew
;definitiondata.
Toverifythatyournewxdatahasbeenattachedtotheentity,enterthefollowingcodeandselecttheobject:
(entget(car(entsel))'("NEWDATA"))
Thisexampleshowsthebasicmethodforattachingextendeddatatoanentity.
Pleasesendusyourcommentaboutthispage
Page 641
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
ManagementofExtendedDataMemoryUse
Extendeddataiscurrentlylimitedto16Kperentity.Becausethexdataofanentitycanbecreatedandmaintainedbymultipleapplications,problemscanresultwhenthesizeofthexdataapproachesitslimit.AutoLISPprovidestwofunctions,xdsizeandxdroom,toassistinmanagingthememorythatxdataoccupies.Whenxdsizeispassedalistofxdata,itreturnstheamountofmemory(inbytes)thatthedatawilloccupy.Whenxdroomispassedthenameofanentity,itreturnstheremainingnumberoffreebytesthatcanstillbeappendedtotheentity.
Thexdsizefunctionreadsanextendeddatalist,whichcanbelarge.Thisfunctioncanbeslow,soitisnotrecommendedthatyoucallitfrequently.Abetterapproachistouseit(inconjunctionwithxdroom)inanerrorhandler.Ifacalltoentmodfails,youcanusexdsizeandxdroomtofindoutwhetherthecallfailedbecausetheentitydidn'thaveenoughroomforthexdata.
Pleasesendusyourcommentaboutthispage
Page 642
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>ExtendedData-xdata>
HandlesinExtendedData
Extendeddatacancontainhandles(group1005)tosaverelationalstructureswithinadrawing.Oneentitycanreferenceanotherbysavingtheother'shandleinitsxdata.Thehandlecanberetrievedlaterfromxdataandthenpassedtohandenttoobtaintheotherentity.Becausemorethanoneentitycanreferenceanother,xdatahandlesarenotnecessarilyunique.TheAUDITcommanddoesrequirethathandlesinextendeddataeitherbeNULLorvalidentityhandles(withinthecurrentdrawing).Thebestwaytoensurethatxdataentityhandlesarevalidistoobtainareferencedentity'shandledirectlyfromitsdefinitiondatabymeansofentget.Thehandlevalueisingroup5.
Whenyoureferenceentitiesinotherdrawings(forexample,entitiesthatareattachedwithXREF),youcanavoidprotestsfromAUDITbyusingextendedentitystrings(group1000)ratherthanhandles(group1005).Thehandlesofcross-referencedentitiesareeithernotvalidinthecurrentdrawing,ortheyconflictwithvalidhandles.However,ifanXREFAttachchangestoanXREFBindoriscombinedwiththecurrentdrawinginsomeotherway,itisuptotheapplicationtorevisetheentityreferencesaccordingly.
WhendrawingsarecombinedbymeansofINSERT,INSERT*,XREFBind(XBIND),orpartialDXFIN,handlesaretranslatedsotheybecomevalidinthecurrentdrawing.(Iftheincomingdrawingdidnotemployhandles,newonesareassigned.)Extendedentityhandlesthatrefertoincomingentitiesarealsotranslatedwhenthesecommandsareinvoked.
Whenanentityisplacedinablockdefinition(withtheBLOCKcommand),theentitywithintheblockisassignednewhandles.(IftheoriginalentityisrestoredbymeansofOOPS,itretainsitsoriginalhandles.)Thevalueofanyxdatahandlesremainsunchanged.Whenablockisexploded(withtheEXPLODEcommand),xdatahandlesaretranslatedinamannersimilartothewaytheyaretranslatedwhendrawingsarecombined.Ifthexdatahandlereferstoanentity
Page 643
thatisnotwithintheblock,itisunchanged.However,ifthexdatahandlereferstoanentitythatiswithintheblock,thedatahandleisassignedthevalueofthenew(exploded)entity'shandle.
Pleasesendusyourcommentaboutthispage
Page 644
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>
XrecordObjects
Xrecordobjectsareusedtostoreandmanagearbitrarydata.TheyarecomposedofDXFgroupcodeswithnormalobjectgroups(thatis,non-xdatagroupcodes),rangingfrom1through369forsupportedranges.Theseobjectsaresimilarinconcepttoxdatabutisnotlimitedbysizeororder.
Thefollowingexamplesprovidemethodsforcreatingandlistingxrecorddata.
(defunC:MAKEXRECORD(/xrecxname)
;createthexrecord'sdatalist.
(setqxrec'((0."XRECORD")(100."AcDbXrecord")
(1."Thisisatestxrecordlist")
(101.02.00.0)(40.3.14159)(50.3.14159)
(62.1)(70.180))
)
;useentmakextocreatethexrecordwithnoowner.
(setqxname(entmakexxrec))
;addthenewxrecordtothenamedobjectdictionary.
(dictadd(namedobjdict)"XRECLIST"xname)
(princ)
)
(defunC:LISTXRECORD(/xlist)
;findthexrecordinthenamedobjectdictionary.
(setqxlist(dictsearch(namedobjdict)"XRECLIST"))
;printoutthexrecord'sdatalist.
(princxlist)
(princ)
)
Pleasesendusyourcommentaboutthispage
Page 645
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>
SymbolTableandDictionaryAccess
AutoLISPprovidesfunctionsforaccessingsymboltableanddictionaryentries.Examplesofthetblnextandtblsearchfunctionsareprovidedinthefollowingsections.Foracompletelistofthesymboltableanddictionaryaccessfunctions,seeSymbolTableandDictionary-HandlingFunctionsinAutoLISPFunctionSynopsisRefertotheAutoLISPReferenceformoredetailedinformationonthefunctionslistedintheSynopsis.
Foradditionalinformationonnon-graphicobjectssee,Non-GraphicObjectHandling.
SymbolTablesDictionaryEntries
Pleasesendusyourcommentaboutthispage
Page 646
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SymbolTableandDictionaryAccess>
SymbolTables
Symboltableentriescanalsobemanipulatedbythefollowingfunctions:
entdel
entget
entmake
entmod
handent
Thetblnextfunctionsequentiallyscanssymboltableentries,andthetblsearchfunctionretrievesspecificentries.Tablenamesarespecifiedbystrings.ThevalidnamesareLAYER,LTYPE,VIEW,STYLE,BLOCK,UCS,VPORT,DIMSTYLE,andAPPID.BothfunctionsreturnlistswithDXFgroupcodesthataresimilartotheentitydatareturnedbyentget.
Thefirstcalltotblnextreturnsthefirstentryinthespecifiedtable.Subsequentcallsthatspecifythesametablereturnsuccessiveentries,unlessthesecondargumenttotblnext(rewind)isnonzero,inwhichcasetblnextreturnsthefirstentryagain.
Inthefollowingexample,thefunctionGETBLOCKretrievesthesymboltableentryforthefirstblock(ifany)inthecurrentdrawing,andthendisplaysitinalistformat.
(defunC:GETBLOCK(/blkct)
(setqblk(tblnext"BLOCK"1));GetsthefirstBLOCKentry.
(setqct0);Setsct(acounter)to0.
(textpage);Switchestothetextscreen.
(princ"\nResultsfromGETBLOCK:")
(repeat(lengthblk);Repeatsforthenumberof
Page 647
;membersinthelist.
(print(nthctblk));Printsanewline,then
;eachlistmember.
(setqct(1+ct));Incrementsthecounterby1.
)
(princ);Exitsquietly.
)
EntriesretrievedfromtheBLOCKtablecontaina-2groupthatcontainsthenameofthefirstentityintheblockdefinition.Iftheblockisempty,thisisthenameoftheblock'sENDBLKentity,whichisneverseenonoccupiedblocks.InadrawingwithasingleblocknamedBOX,acalltoGETBLOCKdisplaysthefollowing.(Thenamevaluevariesfromsessiontosession.)
ResultsfromGETBLOCK:
(0."BLOCK")
(2."BOX")
(70.0)
(109.02.00.0)
(-2.<Entityname:40000126>)
Aswithtblnext,thefirstargumenttotblsearchisastringthatnamesatable,butthesecondargumentisastringthatnamesaparticularsymbolinthetable.Ifthesymbolisfound,tblsearchreturnsitsdata.Thisfunctionhasathirdargument,setnext,thatyoucanusetocoordinateoperationswithtblnext.Ifsetnextisnil,thetblsearchcallhasnoeffectontblnext,butifsetnextisnon-nil,thenextcalltotblnextreturnsthetableentryfollowingtheentryfoundbytblsearch.
ThesetnextoptionisusefulwhenyouarehandlingtheVPORTsymboltable,becauseallviewportsinaparticularviewportconfigurationhavethesamename(suchas*ACTIVE).
IftheVPORTsymboltableisaccessedwhenTILEMODEisturnedoff,anychangeshavenovisibleeffectuntilTILEMODEisturnedon.DonotconfuseVPORTS,whichisdescribedbytheVPORTsymboltablewithpaperspaceviewportentities.
Thefollowingprocessesallviewportsinthe4VIEWconfiguration:
(setqv(tblsearch"VPORT""4VIEW"T));FindsfirstVPORTentry.
(while(andv(=(cdr(assoc2v))"4VIEW"))
.
Page 648
.;...Processesentry...
.
(setqv(tblnext"VPORT"));GetsnextVPORTentry.
)
Pleasesendusyourcommentaboutthispage
Page 649
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SymbolTableandDictionaryAccess>
DictionaryEntries
Adictionaryisacontainerobject,similartothesymboltablesinfunctions.Dictionaryentriescanbequeriedwiththedictsearchanddictnextfunctions.Eachdictionaryentryconsistsofatextnamekeyplusahardownershiphandlereferencetotheentryobject.Dictionaryentriesmayberemovedbydirectlypassingentryobjectnamestotheentdelfunction.Thetextnamekeyusesthesamesyntaxandvalidcharactersassymboltablenames.
AccessingAutoCADGroups
Pleasesendusyourcommentaboutthispage
Page 650
AutoLISPDeveloper'sGuide>UsingtheAutoLISPLanguage>UsingAutoLISPtoManipulateAutoCADObjects>SymbolTableandDictionaryAccess>DictionaryEntries>
AccessingAutoCADGroups
Thefollowingisanexampleofonemethodforaccessingtheentitiescontainedinagroup.ThisexampleassumesagroupnamedG1existsinthecurrentdrawing.
(setqobjdict(namedobjdict))
(setqgrpdict(dictsearchobjdict"ACAD_GROUP"))
ThissetsthegrpdictvariabletotheentitydefinitionlistoftheACAD_GROUPdictionaryandreturnsthefollowing:
((-1.<Entityname:8dc10468>)(0."DICTIONARY")(5."D")
(102."{ACAD_REACTORS")(330.<Entityname:8dc10460>)
(102."}")(100."AcDbDictionary")(3."G1")
(350.<Entityname:8dc41240>))
Thefollowingcodesetsthevariablegroup1totheentitydefinitionlistoftheG1group:
(setqgroup1(dictsearch(cdargrpdict)"G1"))
Itreturnsthefollowing:((-1.<Entityname:8dc10518>)(0."GROUP")(5."23")
(102."{ACAD_REACTORS")(330.<Entityname:8dc10468>)
(102."}")(100."AcDbGroup")(300."lineandcircle")(70.0)(71.1)
(340.<Entityname:8dc10510>)(340.<Entityname:8dc10550>))
The340groupcodesaretheentitiesthatbelongtothegroup.
Pleasesendusyourcommentaboutthispage
Page 651
AutoLISPDeveloper'sGuide>
WorkingwithProgrammableDialogBoxes
DesigningDialogBoxesWithdialogcontrollanguage,youcancreatedialogboxes.ManagingDialogBoxesYoucanusedialogboxestorespondtouserinput.ProgrammableDialogBoxReferenceYoucanuseattributestoworkwithdialogboxes.
Pleasesendusyourcommentaboutthispage
Page 652
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>
DesigningDialogBoxes
Withdialogcontrollanguage,youcancreatedialogboxes.
DialogboxesaredefinedbyASCIIfileswrittenindialogcontrollanguage(DCL).Theelementsinadialogbox,suchasbuttonsandeditboxes,areknownastiles.Thesizeandfunctionalityofeachtileiscontrolledbythetile'sattributes.Thesizeofthedialogboxandthelayoutofitspartsaresetautomaticallywithaminimumofpositioninginformation.VisualLISP®providesatoolforviewingdialogboxes,andprovidesfunctionsforcontrollingdialogboxesfromapplicationprograms.
Thischapterintroducestheelementsthatmakeupdialogboxes.ItexplainsDCLfilestructureandsyntax,andpresentssampleAutoLISP®andDCLcodeforasampledialogbox.ThischapteralsoprovidessomeDCLcodingtechniquesforhandlinglayoutproblems.
DialogBoxComponentsUsingDCLtoDefineDialogBoxesDisplayingDialogBoxeswithVisualLISPAdjustingtheLayoutofDialogBoxesDesignGuidelines
Pleasesendusyourcommentaboutthispage
Page 653
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>
DialogBoxComponents
ThefollowingfigureshowsastandardAutoCAD®dialogbox,withsomeofitscomponentslabeled.Indialogboxcreationandcustomizationthesecomponentsareknownastiles.
Adialogboxconsistsoftheboxandthetileswithinit.Thebasictiletypesarepredefinedbytheprogrammabledialogbox(PDB)facility.
Youcancreatecomplextiles,calledsubassemblies,bygroupingtilesintorowsandcolumns,withorwithoutanenclosingboxorborder.Aroworcolumnoftilesisreferredtoasacluster.Subassembliesdefinegroupsoftilesorclustersthatcanbeusedinmanydialogboxes.Forexample,theOK,Cancel,andHelpbuttonsaregroupedintoasubassembly,definedasarow(cluster)ofthreebuttontilesandsomespacingseparatingthebuttons.
Subassembliesaretreatedassingletiles.Thetileswithinasubassemblyarecalledchildren.DCLfilesareorganizedinatreestructure.Atthetopofthetreeisa(dialog)tilethatdefinesthedialogboxitself.ThefollowingdiagramshowsaDCLfilestructure:
Page 654
Thelayout,appearance,andbehaviorofatileorsubassemblyarespecifiedinDCLbythetile'sattributes.Forexample,thedialogitself,andmostpredefinedtiletypes,hasalabelattributethatspecifiesthetextassociatedwiththetile.Thelabelofadialogboxdefinesthecaptionatthetopofthedialogbox,thelabelofabuttonspecifiesthetextinsidethebutton,andsoon.
DCLalsoenablesyoutodefinenewtiles,calledprototypes,thatarenotnecessarilyassociatedwithaspecificdialogbox.Thisisusefulwhenyouwanttousethesamecomponentinseveraldialogboxes.YoucanreferenceprototypetilesfromotherDCLfilesandchangetheirattributesthesamewayyouchangepredefinedtiles.
Beforeyouprogramadialogbox,planboththedialogboxandtheapplicationindetailbeforeyoucodeanddebug.Thesequenceinwhichthedataisenteredwillvarywitheachuser.Theneedtoanticipateavarietyofuseractionsimposesaprogramstructurethatislesslinearthanconventionalprogramming,butismorereflectiveofthewayuserswork.
Pleasesendusyourcommentaboutthispage
Page 655
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>
UsingDCLtoDefineDialogBoxes
YoudefinedialogboxesbyenteringDCLdescriptionsinASCIItextfiles,muchlikewritingAutoLISPcode.DCLfileshavea.dclextension.AsingleDCLfilecancontainthedescriptionofoneormoredialogboxes,oritcancontainonlyprototypetilesandsubassembliesforusebyotherDCLfiles.ADCLfileconsistsofthefollowingthreeparts,whichcanappearinanyorder.Dependingonyourapplication,onlyoneormoreofthesepartsisrequired.
ReferencestootherDCLfilesTheseconsistofincludedirectivesasdescribedinReferencingDCLFiles.
PrototypetileandsubassemblydefinitionsThesearetiledefinitionsyoucanrefertoinsubsequenttiledefinitions(includingdialogboxdefinitions).
DialogboxdefinitionsThesedefinetheattributesoftilesoroverridetheattributesdefinedinprototypetilesandsubassemblies.Thebase.dclandacad.dclFilesReferencingDCLFilesDCLSyntax
Pleasesendusyourcommentaboutthispage
Page 656
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>
Thebase.dclandacad.dclFiles
Thebase.dclandacad.dclfilesareincludedwithAutoCADandaredistributedintheUserSupportfolder.ToseethepathtotheUserSupportfolder,fromtheToolsmenu,clickOptions.OntheFilestab,thepathtotheUserSupportfolderisthefirstpathdisplayedunderSupportFileSearchPath.
Thebase.dclfileshowstheDCLdefinitionsforthebasic,predefinedtilesandtiletypes.Italsocontainsdefinitionsforcommonlyusedprototypes.ThePDBfeaturedoesnotallowyoutoredefinethepredefinedtiles.Theacad.dclfilecontainsthestandarddefinitionsofallthedialogboxesusedbyAutoCAD.
Warning Anyerrorsinbase.dclmaydisrupttheappearanceofthestandardAutoCADdialogboxesandcustomizeddialogboxesfromyourapplicationorotherapplications.
Pleasesendusyourcommentaboutthispage
Page 657
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>
ReferencingDCLFiles
Whenyoucreatedialogboxes,youmustcreateanew,application-specificDCLfile.AllDCLfilescanusethetilesdefinedinthebase.dclfile.ADCLfilecanalsousetilesdefinedinanotherDCLfilebynamingtheotherfileinwhatiscalledanincludedirective.YoucancreateyourownhierarchyofDCLfiles,asshowninthefollowingfigure:
Inthisfigure,theuser1.dclanduser2.dclfilesareindependentofeachother,butuser3.dclusestilesdefinedinuser1.dcl.Theincludedirectivehastheform:
@includefilename
wherefilenameisaquotedstringcontainingthefullnameoftheotherDCLfile.Forexample,thefollowingdirectiveincludesafilenamedusercore.dcl:
@include"usercore.dcl"
Ifyouspecifyonlythefilename,thePDBfeaturesearchesforthefilefirstinthecurrentdirectoryandtheninthesamedirectoryastheDCLfileitself(theonethatcontainstheincludedirective).Ifyouspecifyafullpathname,thePDBfeaturesearchesonlythedirectoryspecifiedinthatpath.
Note TheDCLfilesyoucreatecannotusethedialogboxesdefinedinacad.dcl.Youcannotspecify@include"acad.dcl".However,ifyouwanttocreate
Page 658
similardialogboxes,youcancutandpastethedefinitionsintoyourownDCLfile.
Pleasesendusyourcommentaboutthispage
Page 659
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>
DCLSyntax
ThissectiondescribestheDCLsyntaxforspecifyingtiles,tileattributes,andattributevalues.
Newtilesarecreatedbytiledefinitions.Ifatiledefinitionappearsoutsideadialogboxdefinition,itisaprototypeorasubassembly.Prototypesandsubassembliescanbeusedindialogboxdefinitionsbytilereferences.Eachreferencetoadefinitioninheritstheattributesoftheoriginaltile.Whenreferringtoprototypes,youcanchangethevaluesoftheinheritedattributesoraddnewattributes.Whenreferringtosubassemblies,youcannotchangeoraddattributes.
Ifyouneedmultipleinstancesofatilewithsomeattributesincommon,itiseasiesttodefineandnameaprototypethatcontainsonlythecommonattributes.Then,ineachreferencetotheprototype,youcanchangeattributesoraddnewones,butyoudonothavetolistallthecommonattributeseachtimeyoureferencethetile.Becauseattributesareinherited,youwillmoreoftenneedtocreatetilereferences—especiallyreferencestothepredefinedtiles—thantodefinenewtiles.
TileDefinitionsTileReferencesAttributesandAttributeValuesCommentsinDCLFiles
Pleasesendusyourcommentaboutthispage
Page 660
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>DCLSyntax>
TileDefinitions
Tiledefinitionshavethefollowingform:
name:item1[:item2
:item3...]{
attribute=value;
...
}
whereeachitemisapreviouslydefinedtile.Thenewtile(name)inheritstheattributesofallthespecifiedtiles(item1,item2,item3,…).Theattributedefinitionswithinthecurlybraces({})eithersupplement,or,iftheattribute'snameisidentical,replacetheinheriteddefinitions.Whenthedefinitionhasmultipleparents,attributestakeprecedenceinleft-to-rightorder.Inotherwords,ifmorethanoneitemspecifiesthesameattribute,thefirstoneencounteredistheoneused.
Ifthenewdefinitioncontainsnochildren,itisaprototype,andyoucanalteroraugmentitsattributeswhenreferringtoit.Ifitisasubassemblywithchildren,itsattributescannotbealtered.
Thenameofatileortileprototypecancontainonlyletters,numbers,ortheunderscorecharacter(_),andmustbeginwithaletter.
Note Tilenamesarecase-sensitive.Forexample,bigbuttonisnotthesameasBigButtonorBIGBUTTON.Becarefulwhenusingcapitalization.
Thisisthe(internal)definitionofabutton:
button:tile{
fixed_height=true;
is_tab_stop=true;
}
Page 661
Thebase.dclfiledefinesadefault_buttonasfollows:
default_button:button{
is_default=true;
}
Thedefault_buttoninheritsthebuttontile'svaluesforthefixed_heightandis_tab_stopattributes.Itaddsanewattribute,is_default,andsetsittotrue.
Pleasesendusyourcommentaboutthispage
Page 662
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>DCLSyntax>
TileReferences
Tilereferenceshaveoneofthefollowingforms:
name;
or
:name{
attribute=value;
...
}
wherenameisthenameofapreviouslydefinedtile.Tilenamesarecasesensitive.Inthefirstinstance,alltheattributesdefinedinnameareincorporatedintothereference.Inthesecondinstance,theattributedefinitionswithinthecurlybraceseithersupplementorreplacethedefinitionsinheritedfromname.Becausethisisatilereference,asopposedtoadefinition,theattributechangesapplyonlytothisinstanceofthetile.
Note Theformatofthesecondinstancecanreferonlytoprototypes,nottosubassemblies.
Thespacertileisusedforlayoutinadialogboxdefinition.Ithasnouniqueattributes,soreferencestoitspecifyonlyitsname:
spacer;
Theok_canceltiledefinedinbase.dclisasubassembly,soittoocanbereferencedonlybyname:
ok_cancel;
Ontheotherhand,youhavetheoptionofredefiningtheattributesofan
Page 663
individualtile.Forexample,thefollowingstatementcreatesabuttonwiththesamepropertiesasapreviouslydefinedbutton,butwithdifferenttext:
:retirement_button{
label="Goodbye";
}
Formoreinformation,seeCustomizingExitButtonText.
Pleasesendusyourcommentaboutthispage
Page 664
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>DCLSyntax>
AttributesandAttributeValues
Withinthecurlybracesofatiledefinitionorreference,youspecifyattributesandassignthemvaluesusingthefollowingform:
attribute=value;
whereattributeisavalidkeywordandvalueisthevalueassignedtotheattribute.Anequalsign(=)separatestheattributefromthevalue,andasemicolon(;)endstheassignmentstatement.Forexample,thekeyattributedefinesthenamebywhichaprogramcanrefertothetile,andthelabelattributedefinesthetextdisplayedwithinthetile.SeeSynopsisofPredefinedAttributesforacompletelistofDCLattributes.
Aswithtilenames,attributenamesandvaluesarealsocase-sensitive.Widthandwidtharenotthesamething;Trueandtruedonotproducethesameresults.
Pleasesendusyourcommentaboutthispage
Page 665
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>UsingDCLtoDefineDialogBoxes>DCLSyntax>
CommentsinDCLFiles
Astatementprecededbytwoforwardslashes(//)istreatedasacommentinaDCLfile.Anythingthatappearsbetweenthe//andtheendofthelineisignored.DCLalsoallowsClanguagestylecomments.Thesehavetheform/*commenttext*/.Thestarting/*andending*/canbeonseparatelines.
Pleasesendusyourcommentaboutthispage
Page 666
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>
DisplayingDialogBoxeswithVisualLISP
VLISPprovidesatoolforpreviewingdialogboxesdefinedwithDCL.Toseehowthisworks,copythefollowingDCLcodeintoanewfileintheVLISPtexteditor:
hello:dialog{
label="SampleDialogBox";
:text{
label="Hello,world";
}
:button{
key="accept";
label="OK";
is_default=true;
}
}
ThisDCLfiledefinesadialogboxlabeled“SampleDialogBox.”ItcontainsatexttileandanOKbutton.Savethefileashello.dcl,andspecify“DCLSourceFiles”intheSaveAsTypefieldoftheSaveAsdialogbox.
Note Youmustincludethefileextensionwhenyouspecifythefilename.VLISPdoesnotautomaticallyadda.dclfileextensionforyou.
NotehowthetexteditorcolorcodesthestatementsintheDCLfile.Thedefaultcolorcodingschemeisshowninthefollowingtable:
DCLdefaultcolorcoding
DCLelement Color
Tilesandtileattributes
Blue
Page 667
Strings Magenta
Integers Green
Realnumbers Teal
Comments Magenta,ongraybackground
Parentheses Red
Preprocessor Darkblue
Operatorsandpunctuation
Darkred
Unrecognizeditems(forexample,uservariables)
Black
ChooseTools InterfaceTools PreviewDCLinEditortodisplaythedialogboxdefinedinthetexteditorwindow.Becauseyoumayhavemorethanonedialogboxdefinedinasingle.dclfile,VLISPpromptsyoutospecifythenameofthedialogyouwanttoview:
IfyourDCLfilecontainsdefinitionsformultipledialogboxes,clickthepull-downarrowandchoosetheoneyouwanttopreview.Thereisonlyonedialogboxdefinedinhello.dcl,sochooseOKtoviewit:
Page 668
ChooseOKtocompletepreviewingthedialogbox.
Althoughbuttonsareagoodwaytodemonstratedialogboxattributes,therearestandardexitbuttonsubassembliesyoushoulduseinyourdialogboxes.Youcancreateadialogboxthatisvirtuallythesameastheoneshowninthepreviousfigurebyusingtheok_onlysubassembly.SeeDialogBoxExitButtonsandErrorTiles.
PreviewErrorHandlingSemanticAuditingofDCLFiles
Pleasesendusyourcommentaboutthispage
Page 669
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DisplayingDialogBoxeswithVisualLISP>
PreviewErrorHandling
IfyourDCLcodecontainserrors,theVLISPDCLpreviewerdisplaysmessagesindicatingtheoffendinglineandkeywordorsymbol.Forexample,introduceanerrorintohello.dclbyremovingthecolonbefore“button,”thentrypreviewingthedialogbox.You'llseethefollowingmessage:
ChooseOKtoclearthemessagefromyourscreen.VLISPmaydisplayadditionalerrormessages,likethefollowing:
Pleasesendusyourcommentaboutthispage
Page 670
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DisplayingDialogBoxeswithVisualLISP>
SemanticAuditingofDCLFiles
AutoCADprovidesachoiceoffourlevels(0-3)ofsemanticauditingforDCLfiles(seethefollowingtable).AuditingattemptstodetectcodeintheDCLfilethatislikelytobeproblematicorunnecessary.TheseauditsaredoneatDCLloadtime.TosettheauditlevelforaDCLfile,includealinesuchasthefollowinganywherewithintheDCLfile,butnotinsideanytiledefinitions:
dcl_settings:default_dcl_settings{audit_level=3;}
IfyourDCLfilereferencesotherDCLfileswithincludedirectives,youshoulddefinedcl_settingsinonlyonefile.Thedefinedauditlevelisusedinallincludedfiles.Thefollowingtabledescribeseachauditlevel:
Semanticauditinglevels
Level Description
0 Nochecking.UseonlyiftheDCLfileshavebeenauditedandhavenotbeentouchedsincetheaudit.
1 Errors.FindsDCLbugsthatmaycauseAutoCADtoterminate.Thislevelofcheckingisthedefaultandinvolvesalmostnodelay.Errorscanincludeusingundefinedtilesandcircularprototypedefinitions.
2 Warnings.FindsDCLbugsthatresultindialogboxeswithundesiredlayoutorbehavior.AmodifiedDCLfileshouldbeauditedatthislevelatleastonce.Thewarninglevelcatchesmistakessuchasmissingrequiredattributesandinappropriateattributevalues.
Page 671
3 Hints.Findsredundantattributedefinitions.
Togetthemostoutoftheauditingfacility,youshouldkeeptheaudit_levelat3duringprogramdevelopment.Remembertostripoutthedcl_settingslinebeforeshippingDCLfilestousers.
Pleasesendusyourcommentaboutthispage
Page 672
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>
AdjustingtheLayoutofDialogBoxes
Lookagainatthesampledialogboxdefinedintheprevioussection.Thereisasmallproblemwithit:
NoticehowtheOKbuttonoccupiesalmostthefullwidthofthedialogbox.Toimprovetheappearanceofthisdialogbox,youcanedittheDCLfileandaddtwoattributestothebuttontile.Topreventthebuttonfromfillingtheavailablespace,addafixed_widthattributeandsetittotrue.Thiscausesthebutton'sbordertoshrinksothatitisjustslightlywiderthanthetextinside.Tocenterthebutton,addanalignmentattributethatspecifiescentered.Tilesinacolumnareleft-justifiedbydefault.NowtheDCLdescriptionisasfollows:
hello:dialog{
label="SampleDialogBox";
:text{
label="Hello,world";
}
:button{
key="accept";
label="OK";
is_default=true;
fixed_width=true;
alignment=centered;
}
}
Thedialogboxnowappearslikethefollowing:
Page 673
Manycommonlayoutproblemscanberesolvedwiththetechniquesthataredescribedinthefollowingsubsections.Ifthedefaultlayoutisnotsuitabletothedialogboxyouarecreating,adjustthelayoutbychangingthedefaultsattheprototypeorsubassemblylevel.Adjustindividualtilesonlywhennecessary.
DistributingTilesinaClusterAdjustingtheSpacebetweenTilesAdjustingSpaceattheRightSideorBottomFixingtheSpacingAroundaBoxedRoworColumnCustomizingExitButtonText
Pleasesendusyourcommentaboutthispage
Page 674
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>AdjustingtheLayoutofDialogBoxes>
DistributingTilesinaCluster
Whenlayingouttilesinadialogbox,youneedtoarrangethemintorowsandcolumnsbasedontherelativesizeofeachtile.ThefollowingDCLdefinesarowofthreetilesthatrunsalongthetopofanothertile:
:column{
:row{
:compact_tile{
}
:compact_tile{
}
:compact_tile{
}
}
:large_tile{
}
}
Ifthecompact_tilecomponentshavefixed_widthandthelarge_tileiswiderthantheminimumspacerequiredbytherowofcompact_tilesaboveit,thedefaulthorizontalalignmentofthisassemblyappearsasfollows:
Theleadingedgeofthefirstcompact_tileintherowalignswiththeleadingedgeofthelarge_tile,andthetrailingedgeofthelastcompact_tilealignswiththetrailingedgeofthelarge_tile.Tilesinbetweenaredistributedevenly.Thesituationwithadjoiningcolumnsisanalogous.
Page 675
Youcancontrolthedefaultdistributionbyusingthespacer_0andspacer_1tiles,whicharevariantsofthespacertiledefinedinbase.dcl.SeeDCLAttributeCatalogformoreinformationonthesetiles.
Pleasesendusyourcommentaboutthispage
Page 676
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>AdjustingtheLayoutofDialogBoxes>
AdjustingtheSpacebetweenTiles
Iftwoadjoiningcolumnsdiffergreatlyintheamountofspacetheirtilesoccupy,thenthetilesintheonethatneedslessspacemayappeartobedistributedtoofarapart.Theirappearancecanbeimprovedifyousettheincongruouscolumn'sfixed_heightattributetotrue.Theresultforverticaltiledistributionisshowninthefollowingdiagram:
Pleasesendusyourcommentaboutthispage
Page 677
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>AdjustingtheLayoutofDialogBoxes>
AdjustingSpaceattheRightSideorBottom
Adialogboxmaycontainunusedspacealongitsrightside.Youcandefineatexttileandexplicitlyspecifyawidthgreaterthanthewidthrequiredbyitscurrentvalue.Forexample,thefollowingcodefragmentdefinesatilethatdoesnotdisplayanything(itsvalueisnull)untilanapplicationsetsitsvalue:
:text{
key="l_text";
width=18;
fixed_width=true;
}
Thewidthattributereservesspacefor18charactersinthedialogbox.Theapplicationcanaddtextwithastatementlikethefollowing:
(set_tile"l_text""Bylayer")
Because"Bylayer"doesn'tneedall18characters,thedialogboxhassurplusspacealongitsrightside.
Asimilarsituationoccurswhenyouuseanerrtiletodisplayerrormessages.(SeeDialogBoxExitButtonsandErrorTiles.)Unlessanerrormessageiscurrentlyshown,itlooksasifthereisextraspaceatthebottomofthedialogbox.Inthiscase,anextraspacertileatthetopofthedialogboxcanhelpbalancetheverticallayout.
Pleasesendusyourcommentaboutthispage
Page 678
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>AdjustingtheLayoutofDialogBoxes>
FixingtheSpacingAroundaBoxedRoworColumn
Ifthelabelattributeofaboxedroworcolumniseitherblank("")ornull(""),theboxenclosestheclusterbutnotextisshown.Asingleblankdoesnotappearasaspaceinthebox.However,thereisadifferenceinthewayblankandnulllabelsarelaidout:
Ifthelabelisasingleblank,anyverticalspacethetextoccupiedinsidetheboxislost,butanyverticalspacethelabeloccupiedabovetheboxisnotlost.
Ifthelabelisanullstring,allverticalspaceislost,whetherabovetheboxorinsideit.
InthefollowingDCLcode,thetoplinesoftheboxesaroundthefirsttwocolumnsareguaranteedtolineup(withthesameYlocation),andthetoplineoftheboxaroundthethirdcolumnisguaranteedtohavenospacingaboveorbelowit,exceptforthedefaultmargins:
:row{
:boxed_column{
label="SomeText";
}
:boxed_column{
label="";//singleblank:thedefault
}
:boxed_column{
label="";//nullstring
}
}
Pleasesendusyourcommentaboutthispage
Page 679
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>AdjustingtheLayoutofDialogBoxes>
CustomizingExitButtonText
Forsomedialogboxes,youmaywanttochangethetextofoneoftheexitbuttons.Forexample,ifyoucreateadialogboxcapableofdestroyingdata,it'ssafertocallthebuttonDestroyinsteadofOK.Todothis,usetheretirement_buttonprototypeasfollows:
destroy_button:retirement_button{
label="&Destroy";
key="destroy";
}
Noticetheuseoftheampersand(&)inthelabelattribute.Thisassignsamnemonictothetile.InthiscasetheletterDisunderscoredinthebuttonlabelandbecomesthemnemonic.
Note Whencustomizingexistingbuttonsubassemblies,youshouldobtaintheproperDCLcodefromyourbase.dclfileratherthanfromthemanual.
Onceyouhavedefinedacustomexitbutton,youneedtoembeditinasubassemblythatmatchestheappearanceandfunctionalityofthestandardclusters.Thefollowingexampleshowsthecurrentdefinitionofok_cancel_help:
ok_cancel_help:column{
:row{
fixed_width=true;
alignment=centered;
ok_button;
:spacer{width=2;}
cancel_button;
:spacer{width=2;}
help_button;
}
}
Page 680
Createanewsubassemblythatreplacestheok_buttonwiththenewbuttonasfollows:
destroy_cancel_help:column{
:row{
fixed_width=true;
alignment=centered;
destroy_button;
:spacer{width=2;}
cancel_button;
:spacer{width=2;}
help_button;
}
}
Inthestandardsubassembly,theOKbuttonisthedefault,butthisattributewasn'taddedtodestroy_button.Wherethedialogbox'sactioncanbedestructive(orverytime-consuming),itisstronglyrecommendedtomaketheCancelbuttonthedefault.Inthiscase,itfunctionsbothasthedefaultandastheAbortbutton:
destroy_cancel_help:column{
:row{
fixed_width=true;
alignment=centered;
destroy_button;
:spacer{width=2;}
:cancel_button{is_default=true;}
:spacer{width=2;}
help_button;
}
}
Becauseanattributehasbeenchanged,theoriginalCancelbuttonisusedasaprototype,requiringacoloninfrontofcancel_button.
Warning WhentheCancelbuttonandtheDefaultbuttonarethesame(bothis_defaultandis_cancelaretrue)andyouneglecttoassignanactionthatcallsdone_dialogtoanyotherbutton,thennootherbuttoncanexitthedialogboxanditwillalwaysbecanceled.
Pleasesendusyourcommentaboutthispage
Page 681
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>
DesignGuidelines
Todesignadialogboxwell,youmustconsidernotonlythepracticalpurposeoftheboxbutalsoitsaesthetics,theergonomicsofusingit,andtheGUIstandardsfortheWindowsenvironment.ThefollowingsubsectionsprovidesomeguidelinesforGUIdesign,dialogboxdesign,andpredefinedtilesandclusters.RefertoProgrammableDialogBoxFunctionSynopsisformoreexamplesoftilesandclusters.
AestheticsandErgonomicsConsistentDesignandClearLanguageUserControlForgivingErrorsProvidingHelpUserswithDisabilitiesUsingCapitalizationAvoidingAbbreviationsLayoutSizeandPlacementDisablingTilesNestingDialogBoxesClosingaDialogBoxforUserSelectionProvidingDefaultsHandlingKeyboardInputInternationalLanguageConsiderationsGuidelinesforPredefinedTilesandClusters
Page 682
ErrorHandlinginDialogBoxes
Pleasesendusyourcommentaboutthispage
Page 683
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
AestheticsandErgonomics
Theappearanceofadialogboxisimportant.Iftheboxistoocluttered,itisineffectiveandhardtouse.Also,tilesshouldbearrangedsotheyareeasytouse.Considerwhichtileswillbeusedmostfrequently,makethemprominentinthedesign,andarrangethemsoit'seasytomovebetweenthem,particularlywhentheyareusedinconjunctionwitheachother.
Pleasesendusyourcommentaboutthispage
Page 684
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ConsistentDesignandClearLanguage
Theuserinterfaceofanapplicationshouldbeinternallyconsistent,andconsistentwithrelatedapplications.Anunfamiliardialogboxiseasiertounderstandifitsdesignisconsistentwithotherdialogboxesintheapplication,relatedapplications,orthehostsystem.OneexampleofthisistheconsistentplacementofbuttonssuchasOKandCancel.Thetechniqueassociatedwitheachkindoftile—howyouentertextinatextboxandhowyouselectalistboxitem—shouldalsobeconsistent.Thebestwaytoachieveconsistencyistoreusetilesandthecodethatcontrolsthem.
Standardizationcontributestoconsistency.Usestandarddefinitionsfordialogboxcontrols.Thisreducesyourwork,contributestoconsistency,andmakesiteasierforuserstolearnanduseyourdialogboxes.
Uselanguagethatisclear.Althoughdialogboxesareconsideredpartofagraphicalinterface,mostofthetilesandinformationtheypresentaretextual.Thelabelingofdialogboxes,namingofbuttons,andphrasingofmessagesshouldbedirectandunambiguous.Avoidjargonandtechnicaltermsthatusersmaynotunderstand.
Pleasesendusyourcommentaboutthispage
Page 685
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
UserControl
Giveuserssomecontroloverhowtheyaccessthedialogboxtoenterinput.Oneadvantageofusingdialogboxesinsteadofacommandlineinterfaceisthatboxesdon'tconfineuserstoastrictsequenceofprompts.Inadialogbox,usersshouldbeabletoenterinputinanysequence.Someconstraintsarenecessary—whenselectingoneoptioncausesanothertobeunavailable,forexample—butbuildinonlyconstraintsthathaveunderlyingreasonsinthewayyourapplicationworks.
Forexample,thefollowingfigureshowstheObjectGroupingdialogbox.ThisdialogboxcontainsaGroupNamefield,whereusersmayenteranameforanewgrouptheyarecreating.IftheUnnamedoptionisselected,aGroupNamecannotbespecified.
Page 686
Multipledialogboxesshouldappearontopofoneanotherratherthanrequiretheusertoexitthecurrentboxbeforecallinganother.Alwaysletusersreturntothedialogboxthatwasinitiallydisplayed.Thisdesigndoesn'tcommituserstoachoicebeforetheyarereadytoleavethedialogbox.Becausethecurrentdialogboxappearsontopofthepreviousone,itremindsusersofthecontext:wheretheyhavecomefromandwherethey'llreturnto.
Wheneverusersdosomethingtochangethecurrentstatusoroptions,providethemwithimmediatefeedback.Ifusersselectsomething,showitordescribeitimmediately.Ifonechoiceexcludesotherchoices,besuretomaketheinvalidchoicesunavailableimmediately.
IntheAutoCADColorSelectiondialogbox,forexample,animagetileshowsthecolorimmediatelyaftertheuserselectsitsnumber.InthesampleBlockDefinitiondialogbox,thenumberofselectedobjectsisalwaysdisplayedinamessagebelowtheSelectObjectsbutton:
Pleasesendusyourcommentaboutthispage
Page 687
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ForgivingErrors
Makeyourdialogboxesforgiving,sousersfeelfreetoexplorewithoutfearofmakingirreversiblemistakes.Reportminorerrorsbymessagesinanerrortileatthebottomofthedialogbox.Reportmoreseriouserrorsbydisplayinganalertbox.Thealertfunctiondisplaysasimplealertbox(withasingleOKbutton).SeeintheAutoLISPReference.
Iftheuserselectsapotentiallydestructiveortime-consumingaction,thedialogboxshoulddisplayanalertboxthatgivestheuserachoiceofproceedingwiththeoperationorcancelingit.
Forexample,intheBlockDefinitiondialogbox,analertboxappearswhenusersattempttocreateablockthatalreadyexists.Userscanthenchoosetoproceedandoverwritetheoriginalblock,orcanceltheoperationwithoutmakingchanges:
Nesteddialogboxesthatalertusersshouldreturntothepreviousdialogbox.Terminatethecurrentnestofdialogboxesonlyinthecaseofseriousorpotentiallyfatalerrors.
Pleasesendusyourcommentaboutthispage
Page 688
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ProvidingHelp
YoushouldprovideaHelpfacility.HowmuchHelpyouprovidedependsonhowcomplexyourapplicationisandhowself-explanatoryyourdialogboxesare.Attheveryleast,itisrecommendedthatthemaindialogboxofyourapplicationhaveaHelpbuttonthatdisplaysasingledialogboxdescribingimportantinformation.Inmostcases,theHelpbuttonshouldcalltheHelpfacilityusingthehelpfunction.
Ifyourapplicationismoresophisticated,considerusingaHelpbuttonineachdialogbox.
Pleasesendusyourcommentaboutthispage
Page 689
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
UserswithDisabilities
Considerationsintendedforuserswithdisabilitiescanmakeaprogrameasierforanyonetouse.Whendesigningyourdialogboxes,considerthefollowing:
Color
Manypeoplecannotdistinguishbetweencertaincolors.Ifyouusecolorcodingtopresentinformation,supplementthisbypresentingthesameinformationinsomeotherway(usuallywithtext).Forexample,thestandardAutoCADColordialogboxdisplaysatextmessagethatstatesthecolor'snameornumberaswellasanimagetilethatdisplaysthecolor.
OnlineHelp
Manyusershavedifficultyeitherreadingthesmallprintinmanualsorphysicallyhandlingbooks.EvenasingleHelpbuttononthemaindialogboxcanbeuseful.
KeyboardAccess
Someusersmayhavedifficultywithorbeunabletouseapointingdevice.Trytospecifymnemonicssoyourdialogboxescanbeusedwithjustthekeyboard.
ClarityandSimplicity
Carefullydesigneddialogboxeswithclearandsimplelanguagehelpuserswithverbalorcognitiveimpairments.Don'tforceuserstoremembermanydifferentthings.Instead,useconsistentterminologyandpresentchoiceswhereverpossible.
Pleasesendusyourcommentaboutthispage
Page 691
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
UsingCapitalization
Thefollowingaresomegeneralguidelinesforcapitalizingtextwithindialogboxes:
DialogBoxes,Areas,andColumnHeadings
Useheadlinecapitalization:capitalizethefirstandlastwords,andallotherwordsexceptarticles,prepositions,andcoordinatingconjunctions.However,ifthedialogboxisinvokedfromamenu(notfromtheCommandprompt),itstitleshouldmatchthemenuitem.
ControlLabels
Useheadlinecapitalizationforlabelsofcontroltilessuchasbuttons.Donotfollowlabelswithaperiod.Followthelabelsofatextboxoradrop-downlistwithacolon(:).Youmaywanttousesentence-stylecapitalization(inwhichyoucapitalizeonlythefirstwordandpropernouns)ifthelabelislengthyorphrasedasaquestion.
PromptsandMessages
Usesentence-stylecapitalization.
Pleasesendusyourcommentaboutthispage
Page 692
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
AvoidingAbbreviations
Abbreviationscanbeambiguousanddifficulttotranslate.Ifspaceconstraintsrequireyoutoabbreviateterms,abbreviatethemconsistentlywithinagroup(suchasaboxedcolumn).Beconsistent.Don'tspellsometermsinfullandabbreviateothers.
Pleasesendusyourcommentaboutthispage
Page 693
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
Layout
Arrangesectionsofthedialogboxlogicallyintorowsorcolumnssouserscanscanthemfromlefttorightorfromtoptobottom.Alignrelatedentryfields(suchaseditboxesorlistboxes)bothverticallyandhorizontally,sothatwhenusersswitchfieldsbypressingTAB,thecursormovesinastraight,orthogonalline.
Ifthereisanaturalorderforenteringdata—suchastheX,Y,andZofcoordinates—orderthefieldsinthesameway.Alignboxedareasbothverticallyandhorizontally.Donotleavealotofwhitespacearoundorbetweenboxedareas.Extendtheirwidthtotheright,ifnecessary.
Pleasesendusyourcommentaboutthispage
Page 694
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
SizeandPlacement
Todisplayinformationclearly,makethedialogboxnolargerthannecessary.
Note Usersmayhaveascreenresolutionaslowas640×480.Ifyouaredevelopingapplicationsondisplaysusingahigherresolution,remembertoverifythatyourdialogboxesdisplayproperlyatlowerresolutions.
Bydefault,AutoCADinitiallydisplaysalldialogboxesinthecenterofthegraphicswindow.However,youcanspecifythatdialogboxesdisplayatanalternatelocation(suchasthelastlocationspecifiedbytheuser).Thenew_dialoganddone_dialogAutoLISPfunctionsprovidefordialogboxplacement.
Pleasesendusyourcommentaboutthispage
Page 695
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
DisablingTiles
Ifatileoranareaisunavailableorirrelevantgiventhecurrentoptionsettings,disableitimmediatelysothetileorareaisunavailableandtheusercan'tselectit.Trynottooverusethedisablingtilesfeature.Toomanyunavailabletilescanbedistracting.
Ifatiledisplaysavalue,disablingthetileshouldn'taffectthevalue.Thetileshoulddisplaythesamevaluewhenitisenabledagain.Valuesthatchangemagicallycreatemoreworkfortheuser,whichisannoyinganddistracting.
Pleasesendusyourcommentaboutthispage
Page 696
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
NestingDialogBoxes
AutoCADlimitsthenumberofnesteddialogboxestoeight.Forinformationonhowtohandlenesteddialogboxes,seeNestingDialogBoxes.
Insertanellipsis(…)inthelabelofabuttonthatdisplaysanesteddialogboxunlessthenesteddialogboxisanalertbox.Don'tnestdialogboxesmorethanthreedeep.Fourlevelsofnestingarereasonableifthefourth-leveldialogboxesareonlyalertboxes.Becausedialogboxesappearinitiallyinthecenterofthescreen,makethenesteddialogboxessmallerthanthemaindialogbox.
Pleasesendusyourcommentaboutthispage
Page 697
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ClosingaDialogBoxforUserSelection
Ifauserneedstomakeaselectionfromthegraphicsscreenbeforethedialogboxhasclosed,youmustclosethedialogboxmomentarilysothattheusercanseethescreenandmaketheselection.Thisisknownashidingadialogbox.Oncetheselectionismade,youneedtodisplaythedialogboxagain.
Thelabelofabuttonthatcausesthedialogboxtobehiddenshouldnotcontainanellipsis.Instead,useaspacefollowedbyaless-thansymbol(<)inthelabel.Whenthedialogboxhidesitself,apromptshouldbedisplayedthatexplainswhattheuserisexpectedtodo.
Inmostcases,youcangettheinputwithoneofthegetxxxfunctions.Thesefunctionshaveanargumentwithwhichyoucanspecifyaprompt.
Whenthedialogboxreappears,itshouldcontainfeedbackontheselectionprocess.Thiscanbenewinformationintheeditboxfields,anupdatedlistbox,atextmessagethatindicatesthestatus,oracombinationofthese.
Pleasesendusyourcommentaboutthispage
Page 698
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ProvidingDefaults
Providereasonabledefaultsforallentriesandoptions.Well-chosendefaultscanhelpuserscompleteadialogboxquicklyandeasily.
Itisrecommendedthatyouupdatethedefaultvalues—inotherwords,thatyousavetheuser'sprevioussettingsandusethemasthenewdefaults—eachtimethedialogboxisused.Eveniftheuserhastochangesomeofthese,itislessworkthanstartingfromthebeginningeachtime.
Pleasesendusyourcommentaboutthispage
Page 699
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
HandlingKeyboardInput
Whenyoucreateacustomdialogbox,youcanspecifyhowithandleskeyboardshortcuts.Somekeyboardshortcutsarecommontoalldialogboxes.Forexample,theTABkeygenerallyenablesuserstomovefromtiletotile,andtheSPACEBARallowsuserstoturntogglesofforon.Eachactivetileshouldbeatabstop(thedefault).
Twokeyscommonlyactasacceleratorkeys.Theacceptkey(usuallytheENTERkey)acceptsthedialogboxandvaluesentered.Thecancelkey(ESC),discardsthedialogboxandthevalues.WhenAutoCADfirstdisplaysadialogbox,oneofitstileshastheinitialkeyboardfocus.Whattheuserentersaffectsthistileuntiltheusermovesfocustoanothertile.
Tomovefromtiletotile,theusercanpressTAB,chooseanothertile,orenteroneofthekeyboardshortcutsknownasmnemonickeystrokes.Movingbetweentileschangesfocusbutdoesn'tmakeaselection.Toselectatilethathasfocus,usersmustpressENTER.Forsomekindsoftiles,adouble-clickisequivalenttopressingENTER.
Pleasesendusyourcommentaboutthispage
Page 700
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
InternationalLanguageConsiderations
WordsinotherlanguagesoftenrequiremorecharactersthantheirEnglishequivalents.Ifyourdialogboxesaregoingtobetranslated,leaveasmuchroomaspossibleforthemtogrow.ThefollowingtableshowssomefamiliarAutoCADtermswiththeirequivalentsinFrenchandGerman.
EquivalentAutoCADtermsinEnglish,French,andGerman
English French German
Line Ligne Linie
Arc Arc Bogen
Circle Cercle Kreis
3DPolylines Polylignes3D 3D-Polylinien
Diameterdimensioning
Cotationdediamtre
Durchmesserbemaung
Layers Calque Layer
Linetypes Typesdeligne Linientypen
Entitycreationmodes
Modesdecrationdesobjets
ModusfrObjekterzeugung
Page 701
Selectobjects Choixdesobjets Objektewhlen
OK OK OK
Cancel Annuler Abbruch
Help Aide Hilfe
Pleasesendusyourcommentaboutthispage
Page 702
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
GuidelinesforPredefinedTilesandClusters
Thissectionlistsrecommendedconventionsanddesignguidelinesassociatedwithparticularkindsofpredefinedtilesandtileclusters.
ButtonsClustersEditBoxesImageButtonsandImageTilesListBoxesRadioButtons,RadioRows,andRadioColumnsSlidersTextToggles
Pleasesendusyourcommentaboutthispage
Page 703
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
Buttons
Theactionassociatedwithabuttonshouldbevisibletotheuserandshouldtakeplaceimmediately.Thelabelofabuttonshouldbeunambiguous.Usually,itshouldbeaverbthatdescribestheeffectofpushingthebutton,thoughanotherlabel—suchasOKorOptions—isacceptableifitsmeaningisclear.Forbuttonsthatcallotherdialogboxesorhidethecurrentdialogbox,seeNestingDialogBoxesandClosingaDialogBoxforUserSelection.
Buttonsinacolumnshouldbethesamewidth.Inothercases,buttonsshouldhaveafixedwidth(eitherfixed_width=true;,orchildren_fixed_width=true;)intheircommonparentcluster.
Pleasesendusyourcommentaboutthispage
Page 704
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
Clusters
Aboxedcluster(aroworcolumn)iscalledagroupboxoranarea.Anareaprovidesavisualcuetousersbyisolatingandnamingcontrolsthatworktogether.Theareacancontainasmanytiles,rows,andcolumns(unboxed)asnecessary.Thelabelofanareashouldindicateitspurpose.
Ifcontrolsrelatetoeachother,puttheminanarea.TheBasePointclusterintheBlockDefinitionsampledialogboxdemonstratesthistechniquewithanareaformedfromaclusterwithalabelandaborder:
However,donotoveruseareas.Whitespaceisalsoaneffectivewaytogrouptiles.Donotputaboxaroundalistbox;thislookstoobusy.
Pleasesendusyourcommentaboutthispage
Page 705
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
EditBoxes
Thelengthofthetext-entryportionofaneditboxshouldroughlyequalthelengthofanaverageentry.Whenindoubt,useacharacterwidthof10forrealnumberfieldsand20fortextfields.
Thelabelofaneditboxshouldendwithacolon(:).
Iftherearerestrictionsonwhatuserscanenterintheeditbox,putatexttiletotherightoftheeditboxthatbrieflyexplainstheserestrictions.Ifusersneedtoenterafilename,forexample,there'snoneedtoexplainwhatafilenameis.Butifthestringisanumberthatcannotexceed100,areminderofthislimitisagoodidea.
Fordata,suchaspoints,providetwoorthreeeditboxesratherthanrequireuserstoremembertheCommandlinesyntaxofpointentry.Oneexceptionisaneditboxintendedspecificallyforenteringadvancedsyntax,suchasthewild-cardpatterneditboxintheAutoCADFileSearchdialogbox.
Pleasesendusyourcommentaboutthispage
Page 706
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
ImageButtonsandImageTiles
Ifyouuseanimagebuttonorimagetileasanicontoalerttheuser—forexample,awarningsignalsuchasastopsign—useitconsistentlyinalldialogboxes.
Whenyouuseimagebuttonstorepresentselections,supplementtheimagewithtextthatbrieflydescribesit,especiallyifthecoloroftheimage(orpartoftheimage)isafactorinselectingit.
Pleasesendusyourcommentaboutthispage
Page 707
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
ListBoxes
BecauseDCLlistboxescannotbescrolledhorizontally,thewidthofthelistboxshouldaccommodatethelongestiteminthelist.Providealabel(oratexttile)toexplainthecontentsofthelistbox,unlessthelistboxisthemaintileinthedialogbox.Inthatcasethedialogbox'slabelmightbesufficient—althoughyoumustgivethelistboxalabelifyouwantuserstobeabletomovetothatlistboxbyusingamnemonic.
Alphabetizetheitemsinthelistunlessyouhavealogicalreasontoorganizetheminsomeotherway.Ifthelengthofthelistisfixedandshort,considerusingaradiocolumninsteadofalistbox.
Pleasesendusyourcommentaboutthispage
Page 708
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
RadioButtons,RadioRows,andRadioColumns
Radiocolumnslookbetterandareeasiertousethanradiorows.
Radiorowsareappropriateonlywhentheycontainasmallnumberofbuttons(usually,twotofour)orifthelabelsareshort.Ifanoptionselectedelsewheremakesthechoicesintheradioroworradiocolumninvalidorirrelevant,thendisablethewholeroworcolumn.Insomesituations,anoptionselectedelsewheremaymakecertainradiobuttonsinvalidorirrelevant.Insituationslikethis,youcandisablebuttonsindividually.
Pleasesendusyourcommentaboutthispage
Page 709
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
Sliders
Thegranularityofaslidershouldnotbetoocoarse.Forexample,ifasliderisassignedonlyfourincrementalvaluesbutislaidoutinatwo-inchsectionofthedialogbox,userswouldhavetomovehalfaninchtoseeachange.Avoidjumpinesslikethisbyscalingthesizeoftheslider.
Ifusersneedtoknowthevaluecontrolledbytheslider,yourdialogboxshouldalsodisplaytheslider'scurrentvalue.Updatethisvaluewheneverthesliderismoved.Itisrecommendedyoualsodisplayaneditboxthatenablesuserstoenterthevalueratherthanusetheslider.Ifyouuseaneditboxthisway,updateitsvalue;otherwise,displaythevalueinatexttile.Thefollowingfigureshowsatypicalcombinationofsliderandeditbox:
Pleasesendusyourcommentaboutthispage
Page 710
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
Text
Whenlabelsarenotsufficient,usetexttilestoidentifythepurposeofindividualtilesordialogboxareas.Youcanalsousetexttilestodisplaystatusmessagesorreminders,includingerrormessagesandwarnings.
Textshouldbedirectandunambiguous.Describeoptionsandentryfieldsintermsyouruserswoulduse.Forexample,theerrormessage“Invalidentry”inalistboxconveyslittleinformation.Amessagesuchas“Layerdoesnotexist”ismorehelpful.
Alignmessageswiththecontroltilestheydescribe.
Puttextthatidentifiesagroupofcontroltilesorasectionofthedialogboxabovethetilesthatthetextdescribes.
Pleasesendusyourcommentaboutthispage
Page 711
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>GuidelinesforPredefinedTilesandClusters>
Toggles
Whentheoptionscontrolledbytogglesrelatetothesametopic,groupthemtogether.
Useasingletogglethatcontrolswhetherothertiles,ofteninaroworcolumn,areactive.Inthiscase,thetoggleshouldbeprominent.Whenthetogglecontrolsonlyoneothertile,youcanalsoplaceittotherightofthattile.Thetoggleinthefollowingdialogboxenablesordisablesanothertile:
Pleasesendusyourcommentaboutthispage
Page 712
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>
ErrorHandlinginDialogBoxes
Dialogboxescandisplayerrormessagesandwarningswithatexttileknownasanerrortile(errtile),orwithanestedalertbox.Thefollowingguidelinesapplytoboth:
Errormessagesshouldbecompletesentences,punctuatedassuch,withaninitialcapitalandaperiodattheend.
Errormessagesshouldexplainclearlytheproblemorpotentialproblem.
Afterreportingtheerror,shiftthedialogbox'sfocustothetilethattriggeredtheerror,ifpossible.ErrorTilesAlertBoxes
Pleasesendusyourcommentaboutthispage
Page 713
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>ErrorHandlinginDialogBoxes>
ErrorTiles
Useanerrortileforminorerrorsorwarnings,especiallythosethatarisefromtypographicalerrors.
Donotdisplayerrorsintexttilesusedforstatusmessages.Theseareeasytooverlook.
Errortilesshouldappearatthebottomofadialogbox.UsethestandarderrtiledescribedinDialogBoxExitButtonsandErrorTiles.
Pleasesendusyourcommentaboutthispage
Page 714
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>DesigningDialogBoxes>DesignGuidelines>ErrorHandlinginDialogBoxes>
AlertBoxes
YoucandisplayastandardalertboxwithasingleOKbuttonbycallingthealertfunction.Usealertboxesforseriousorpotentiallyfatalerrors,butdonotoverusethem.Alertboxesrequireuserinput.Therefore,theycanbeannoying,especiallywhentheyreportminorerrorsorobscuretheentrythatneedstobecorrected.
Usealertboxestowarnusersthattheactionabouttobegincandestroydataorcanbetimeconsuming.Alertboxesofthissortshouldgiveusersachoiceofproceedingorcancelingtheaction.Ifthealertboxoffersusersachoice,suchasProceedorCancel,youmustconstructityourself.
Ifthealertboxprovidesuserswithachoice,thetextinthealertboxshouldfirstdescribetheproblemandthenposethenextactionasaquestion.Insuchcasesitisimportantthatthebuttonforproceedingbelabeledwithaverbthatdescribeswhatwillhappen.Inthiscontext,Overwrite,forexample,islessambiguousthanOK,andisanaidtoexperienceduserswhowillglossoverthetextbecausetheyhaveseenthisalertboxmanytimes.
Unlesstheerroristrulyfatal,provideawayforuserstoreturntoaprevioussteporescapefromtheoperationthattriggeredthealertbox.
UsuallythedefaultbuttonforadialogboxisOKoritsequivalent,butwhenthesituationdescribedbythealertboxhasseriousconsequences,makeCanceloritsequivalentthedefault.
Pleasesendusyourcommentaboutthispage
Page 715
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>
ManagingDialogBoxes
Youcanusedialogboxestorespondtouserinput.
WithAutoCAD®,youcandesignandimplementdialogboxestousewithyourapplications.Theappearanceofadialogboxisdefinedbydialogcontrollanguage(DCL)files,asdescribedinDesigningDialogBoxes.YoucontrolthefunctionalityofadialogboxwithanAutoLISP®application.ThischapterdescribeshowtocontroldialogboxesusingAutoLISP.AlthoughthischaptershowssomeexamplesofDCLfiles,youmayfindithelpfultoreadDesigningDialogBoxesbeforereadingthischapter.
ControllingDialogBoxeswithAutoLISPProgramsActionExpressionsandCallbacksHandlingTilesNestingDialogBoxesFunctionsforHidingDialogBoxesListBoxesandPop-UpListsImageTilesandButtonsApplication-SpecificDataDCLErrorHandlingDialogBoxFunctionSummary
Pleasesendusyourcommentaboutthispage
Page 716
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
ControllingDialogBoxeswithAutoLISPPrograms
ThischapterbeginswithanoverviewoftheprocessyouusetodisplaydialogboxesandrespondtouserinputfromanAutoLISPprogram.
QuickOverviewFunctionsRestrictedWhenaDialogBoxIsOpen
Pleasesendusyourcommentaboutthispage
Page 717
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ControllingDialogBoxeswithAutoLISPPrograms>
QuickOverview
Thisexamplestartswithasimpledialogbox:
ThefollowingDCLdefinesthedialogbox:
hello:dialog{
label="SampleDialogBox";
:text{label="Hello,world.";}
ok_only;
}
ThisDCLdefinesadialogboxlabeledSampleDialogBoxthatcontainsatexttileandasingleOKbutton.TheDCLresidesinafilenamedhello.dcl.
TodisplaythedialogboxandrespondtotheuserpressingOK
1. Usetheload_dialogfunctiontoloadtheDCLfileintomemory.Forexample:
(setqdcl_id(load_dialog"hello.dcl"))
Theload_dialogfunctionreturnsaDCLidentificationnumber.Youneedthistoidentifythedialoginsubsequentfunctioncalls.
2. Callthenew_dialogfunctionandpassitthedialognameandDCLidentificationnumberasarguments,asfollows:
Page 718
(new_dialog"hello"dcl_id)
3. Initializethedialogboxbysettinguptilevalues,lists,andimages.TheDCLexampleaboveusesapredefinedtilenamedok_only,soyoudonothavetoinitializethetileunlessyouwanttooverrideitsdefaultvalues.Theok_onlytilealsohasanactionnameddone_dialogassignedtoit.IftheuserpressestheOKbutton,AutoCADpassesthedone_dialogcalltoyourAutoLISPapplicationandendsthedialog.
4. Callstart_dialogtopasscontrolofthedialogtoAutoCADfordisplaytotheuser:
(start_dialog)
5. Callunload_dialogtoremovethedialogfrommemoryaftertheuserresponds.Steps3,4,and5aredependentonthenew_dialogfunctionreturninganon-nilvalue.Forthesakeofsimplicity,noerrorprocessingisincludedinthisexample.
Youcanusethefollowingfunctiontocallthesampledialogbox:
(defunC:HELLO(/dcl_id)
(setqdcl_id(load_dialog"hello.dcl"));LoadtheDCLfile.
(if(not(new_dialog"hello"dcl_id));Initializethedialog.
(exit);Exitifthisdoesn't
;work.
)
(start_dialog);Displaythedialog
;box.
(unload_dialogdcl_id);UnloadtheDCLfile.
(princ)
)
EnterthiscodeintoanewVLISPtexteditorwindowandloadtheprogrambychoosingTools LoadTextinEditorfromtheVLISPmenu.Todisplaythedialogbox,enter(c:hello)attheVLISPConsoleprompt.
Notethatthestart_dialogcallremainsactiveuntiltheuserselectsatile(usuallyabutton)whoseassociatedactionexpressioncallsdone_dialog.Thedone_dialogcallcanbeissuedexplicitlybythetile.Thedone_dialogcallisalsoissuedbytheselectedtileifitsis_cancelattributeissettotrue.
Page 719
Warning Intheory,thedialogboxfacilitytakescontrolofinputatthetimeyoucallstart_dialog,butinWindowsittakescontrolwhenyoucallnew_dialog.Thishasnoeffectonwritingprograms.However,ifyouinvokethesefunctionsinteractively(attheAutoCADCommandpromptoraVLISPwindow),youmustenterthemasonestatement.Enclosethemwithinaprognoranotherfunction.Ifyoudon't,theinteractivecalltonew_dialogcanfreezethescreen.Callingnew_dialogandstart_dialoginteractivelycanbeusefulduringdebugging.(Foranexampleofusingthesefunctionsinteractively,seeDCLErrorHandling.)
Pleasesendusyourcommentaboutthispage
Page 720
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ControllingDialogBoxeswithAutoLISPPrograms>
FunctionsRestrictedWhenaDialogBoxIsOpen
Whileadialogboxisactive—thatis,duringthestart_dialogcall—youcannotcallanyfunctionthatrequiresuserinputontheAutoCADcommandline,oraffectsthedisplayoutsidethedialogbox(forexample,intheAutoCADgraphicswindow).Thisrestrictionincludesfunctionsthatwritetext,suchasprint,princ,andprin1.
Youcanissuessgetcalls,aslongasyoudonotuseanyoptionsthatrequireuserinput.
Ifyourprogramcallsoneoftherestrictedfunctionsbetweenthestart_dialoganddone_dialogcalls,AutoCADterminatesalldialogboxesanddisplaysthefollowingerrormessage:
AutoCADrejectedfunction
YoucantesttheCMDACTIVEsystemvariabletodetermineifadialogboxisactive.IfCMDACTIVEisgreaterthan7,adialogboxisactive.TheCMDACTIVEsystemvariablehasbit-codedvaluesthatindicatecommand,script,anddialogboxactivity.
Note Ifyourapplicationrequiresuserstoenterinputbasedonthegraphicsscreenratherthanonthedialogboxitself(forexample,tospecifyapointorselectanobject),youmusthidethedialogbox.Thatis,youmustcalldone_dialogsothegraphicsscreenisvisibleagain,andthenrestartthedialogboxaftertheuserhasmadetheselection.Formoreinformation,seeFunctionsforHidingDialogBoxes.
Theterm_dialogfunctionterminatesallcurrentdialogboxesasiftheuserhadcanceledeachofthem.Thisfunctioncanbeusedtocancelaseriesofnesteddialogboxes.
Page 721
Pleasesendusyourcommentaboutthispage
Page 722
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
ActionExpressionsandCallbacks
Todefinetheactiontakenwhenacertaintileinadialogboxisselected,youassociateanAutoLISPexpressionwiththattilebycallingtheaction_tilefunction.Thisisknownasanactionexpression.Withintheactionexpression,youoftenneedaccesstoattributesintheDCLfile.Theget_tileandget_attrfunctionsprovidethiscapability.Theget_attrfunctionretrievestheuser-definedattributeswithintheDCLfile.Theget_tilefunctiongetsthecurrentruntimevalueofatilebasedonuserinputtothattile.Actionexpressionsmustbedefinedfollowingthenew_dialogcallandbeforethestart_dialogcall.
Informationrelatingtohowtheuserhasselectedatileormodifiedatile'scontentsisreturnedtotheactionexpressionasacallback.Inmostcases,everyactivetilewithinadialogboxcangenerateacallback.Aswithreactors,theactionexpressionthatrespondstothecallbackisoftenreferredtoasacallbackfunction.Thisfunctionshouldperformvaliditycheckingontheassociatedtileandshouldupdateinformationinthedialogboxthatpertainstothevalueofthetile.Updatingthedialogboxcanincludeissuinganerrormessage,disablingothertiles,anddisplayingtheappropriatetextinaneditboxorlistbox.
OnlytheOKbutton(oritsequivalent)shouldquerythetilevaluestopermanentlysavethesettingsthattheuserhasfinallyselected.Inotherwords,youshouldupdatethevariablesassociatedwithtilevalueswithinthecallbackfortheOKbutton,notthecallbackforanindividualtile.Ifpermanentvariablesareupdatedwithintheindividualtilecallbacks,thereisnowaytoresetthevaluesiftheuserselectstheCancelbutton.IftheOKbutton'scallbackdetectsanerror,itshoulddisplayanerrormessageandreturnfocustothetileinerror;itshouldnotexitthedialogbox.
Whenadialogboxincludesseveraltileswhosehandlingissimilar,itcanbeconvenienttoassociatethosetileswithasinglecallbackfunction.Theprinciple
Page 723
ofnotcommittingtotheuser'schangesuntiltheuserchoosesOKstillapplies.
Therearetwowaystodefineactionsotherthancallingaction_tile.Youcandefineadefaultactionfortheentiredialogboxwhenyoucallnew_dialog,andyoucandefineanactionbyusingatile'sactionattribute.Thesealternativemeansofdefiningactions,andtheorderinwhichtheyoccur,aredescribedinDefaultandDCLActions.
ActionExpressionsCallbackReasons
Pleasesendusyourcommentaboutthispage
Page 724
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ActionExpressionsandCallbacks>
ActionExpressions
Anactionexpressioncanaccessthevariablesshowninthefollowingtable,indicatewhichtilewasselected,anddescribethetile'sstateatthetimeoftheaction.Thevariablenamesarereserved.Theirvaluesareread-onlyandhavenomeaning,unlesstheyareaccessedwithinanactionexpression.
Actionexpressionvariables
Variable Description
$key Thekeyattributeofthetilethatwasselected.Thisvariableappliestoallactions.
$value Thestringformofthecurrentvalueofthetile,suchasthestringfromaneditbox,ora"1"or"0"fromatoggle.Thisvariableappliestoallactions.Ifthetileisalistbox(orpop-uplist)andnoitemisselected,the$valuevariablewillbenil.
$data Theapplication-manageddata(ifany)thatwassetjustafternew_dialogtimebymeansofclient_data_tile.
Thisvariableappliestoallactions,but
Page 725
$datahasnomeaningunlessyourapplicationhasalreadyinitializeditbycallingclient_data_tile.SeeApplication-SpecificData.
$reason Thereasoncodethatindicateswhichuseractiontriggeredtheaction.Usedwithedit_box,list_box,image_button,andslidertiles.
Thisvariableindicateswhytheactionoccurred.Itsvalueissetforanykindofaction,butyouneedtoinspectitonlywhentheactionisassociatedwithanedit_box,list_box,image_button,orslidertile.SeeCallbackReasonsinthefollowingsectionfordetails.
Ifedit1isatextbox,theactionexpressioninthefollowingaction_tilecallisevaluatedwhentheuserexitsthetextbox:
(action_tile"edit1""(setqns$value)")
The$valuecontainsthestringthattheuserentered,andtheexpressionsavesthisinthensvariable.
Thenextexamplesavesthenameoftheselectedtilesothattheprogramcanrefertoit:
(action_tile"edit1""(setqnewtile$key)")
Thenewtilevariableissettothekeynameoftheselectedtile,inthiscase"edit1".The$keyvariableisveryusefulwithinafunctionthatservesastheactionforseveralseparatetiles.
Whenatileisnamedinmorethanoneaction_tilecall,onlythelastsuchcall(priortostart_dialog)hasanyeffect.(It'sasifyouweretoassignmultiplevaluestothesamevariable.)Theprogrammabledialogbox(PDB)
Page 726
featureallowsonlyoneactionpertile.
Pleasesendusyourcommentaboutthispage
Page 727
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ActionExpressionsandCallbacks>
CallbackReasons
Thecallbackreason,returnedinthe$reasonvariable,specifieswhytheactionoccurred.Itsvalueissetforanykindofaction,butyouneedtoinspectitonlywhentheactionisassociatedwithanedit_box,list_box,image_button,orslidertile.Thefollowingtableshowsthepossiblevalues:
Callbackreasoncodes
Code Description
1 Thisisthevalueformostactiontiles.Theuserhasselectedthetile(possiblybypressingENTER,ifthetileisthedefaultandtheplatformrecognizesacceleratorkeys).
2 Editboxes:Theuserhasexitedtheeditbox,buthasnotmadeafinalselection.
3 Sliders:Theuserhaschangedthevalueofthesliderbydraggingtheindicatorbuthasnotmadeafinalselection.
4 Listboxesandimagebuttons:Thiscallbackreasonalwaysfollowsacode1.Itusuallymeans“committothepreviousselection.”Itshouldneverundothepreviousselection;thisconfusesand
Page 728
annoystheuser.
Code1isdescribedfullyinthetable.Thefollowingtextdescribesthecodes2,3,and4ingreaterdetail.
Code2—EditBoxes
Theuserhasexitedtheeditbox—bypressingtheTABkeyorbychoosingadifferenttile—buthasnotmadeafinalselection.Ifthisisthereasonforaneditboxcallback,yourapplicationshouldnotupdatethevalueoftheassociatedvariable,butshouldcheckthevalidityofthevalueintheeditbox.
Code3—Sliders
Theuserhaschangedthevalueofthesliderbydraggingtheindicator(oranequivalentaction),buthasnotmadeafinalselection.Ifthisisthereasonforaslidercallback,yourapplicationshouldnotupdatethevalueoftheassociatedvariablebutshouldupdatethetextthatdisplaystheslider'sstatus.Formoreinformation,seeSliders.Forcodeexamples,seeHandlingSliders.
Code4—ListBoxes
Theuserhasdouble-clickedonthelistbox.Youcandefinethemeaningofadouble-clickinyourapplication.Ifthemainpurposeofthedialogboxistoselectalistitem,adouble-clickshouldmakeaselectionandthenexitthedialogbox.(Inthiscase,theis_defaultattributeofthelist_boxtileshouldbetrue.)Ifthelistboxisnottheprimarytileinthedialogbox,thenadouble-clickshouldbetreatedasequivalenttomakingaselection(code1).
Listboxesthatallowtheusertoselectmultipleitems(multiple_select=true)cannotsupportdouble-clicking.
Code4—ImageButtons
Theuserhasdouble-clickedontheimagebutton.Youcandefinethemeaningofadouble-clickinyourapplication.Inmanycasesitisappropriateforasingle-clicktoselectthebutton,butinothersitisbetterforasingle-click(orakeyboardaction)tohighlightthebutton,andthenhavetheENTERkeyora
Page 729
double-clickselectit.DefaultandDCLActions
Pleasesendusyourcommentaboutthispage
Page 730
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ActionExpressionsandCallbacks>CallbackReasons>
DefaultandDCLActions
Theaction_tilefunctionisnottheonlywaytospecifyanaction.Atile'sDCLdescriptioncanincludeanactionattributeinAutoLISP,andthenew_dialogcallcanspecifyadefaultactionforthedialogboxasawhole.Atilecanhaveonlyasingleactionatatime.IftheDCLandtheapplicationspecifymorethanoneaction,theysupersedeeachotherinthefollowingorderofpriority(lowesttohighest):
Thedefaultactionspecifiedbythenew_dialogcall(usedonlyifnoactionisexplicitlyassignedtothetile).
TheactionspecifiedbytheactionattributeintheDCLfile.
Theactionassignedbytheaction_tilecall(highestpriority).
Pleasesendusyourcommentaboutthispage
Page 731
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
HandlingTiles
Yourprogramhassomecontroloverthetilesthatareinthecurrentdialogboxatinitializationtimeandaction(callback)time.Thissectionintroducesthetile-handlingfunctionsandshowshowtoinitializeandmodifythetiles'modesandvalues.
InitializingModesandValuesChangingModesandValuesatCallbackTimeHandlingRadioClustersHandlingSlidersHandlingEditBoxes
Pleasesendusyourcommentaboutthispage
Page 732
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>HandlingTiles>
InitializingModesandValues
Initializingatilecanincludethefollowing:
Makingittheinitialkeyboardfocusofthedialogbox
Disablingorenablingit
Highlightingitscontents,ifitisaneditboxorimage
Theseoperationsareperformedbymode_tilecalls.Youcansetthevalueofatilebyusingset_tile.
Todisplayadefaultvalue—suchasasurname—inaneditboxandsetthedialogbox'sinitialfocustothatbox,usethefollowingcode:
(setqname_str"Kenobi");Default.
(set_tile"lastname"name_str);Initializesfield.
(mode_tile"lastname"2);2setsfocustotile.
Anadditionalmode_tilecallcanhighlightallthecontentsofaneditbox,sotheuserhastheoptiontotypeimmediatelyoverthedefaultcontents,asshowninthefollowingexample:
(mode_tile"lastname"3);3selectsboxcontents.
Pleasesendusyourcommentaboutthispage
Page 733
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>HandlingTiles>
ChangingModesandValuesatCallbackTime
Atcallbacktime,youcancheckthevalueofatile.Ifnecessary,youcanuseset_tileagaintomodifythisvalue.Duringcallbacks,youcanalsousemode_tiletochangethestatusofatile.Thefollowingtableshowsthevaluesofthemode_tilemodeargument:
Modecodesformode_tile
Value Description
0 Enabletile
1 Disabletile
2 Setfocustotile
3 Selecteditboxcontents
4 Flipimagehighlightingonoroff
Whenyouusemode_tiletodisableatilethathasthecurrentfocus,youmustcallmode_tileagaintosetthefocustoadifferenttile(inmostcases,thenexttabstopinthedialogbox).Otherwise,thefocuswillremainonadisabledtile,whichisillogicalandcancauseerrors.
Page 734
AgoodexampleofatiledisablingitselfisaseriesofdialogboxpagesthattheuserstepsthroughbychoosingaNextorPreviousbutton.WhentheuserchoosesNextonthenext-to-lastpage,thebuttonisdisabled.ThesamethinghappensafterchoosingPreviousonthesecondpage.Inbothcases,thecodemustdisablethebuttonthatwaschosen,andthensetfocustoadifferenttile.
Supposethetilecalledgroup_onisatogglethatcontrolsaclustercalledgroup.Whenthetoggleisturnedoff,thetilesintheclusterareinactiveandshouldnotbemodified.Inthiscase,youmightdefinethefollowingactionforthetoggle.(Noticetheuseofthe\"controlcharacter,whichallowsquotationmarkswithinanaction_tileargument.)
(action_tile"group_on""(mode_tile\"group\"(-1(atoi$value)))")
Thesubtractionandatoicallintheactionexpressionsetthemode_tilefunction'smodeargument.Becauseatoggleis0whenitisturnedoffand1whenitisturnedon,thesubtractioninvertsitsvalueandthemodecontrolswhethertheclusterisenabled.
Youcaninspectattributesotherthanatile'svaluewiththeget_attrfunction.Forexample,youmaywanttoretrievethelabelofabuttoncalled"pressme":
(get_attr"pressme""label")
Theget_attrfunctionreturnsthevalueofthespecifiedattributeasastring.
Note Ifyouuseget_attrtoretrieveavalueattribute,itgetsthevalueattributesavedintheDCLfile(theinitialvalueofthetile).Theget_tilefunction,however,getsthecurrentruntimevalueofthetile.Thetwovaluesarenotnecessarilythesame.
Pleasesendusyourcommentaboutthispage
Page 735
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>HandlingTiles>
HandlingRadioClusters
Radiobuttonsappearinradioclusters.Thevalueofeachradiobuttoniseither"1"forOnor"0"forOff.Thevalueoftheradioclusteristhekeyattributeofthecurrentlyselectedbutton.ThePDBfeaturemanagesthevaluesofradiobuttonsinaclusterandensuresthatonlyonebuttonisturnedonatatime.Youcanassignanactiontoeachradiobutton,butitismoreconvenienttoassignanactiontotheradioclusterasawholeandthentestthecluster'svaluetoseewhichradiobuttonwaschosen.
Considerthefollowingexample:Aradioclustercontrolstheviewofathree-dimensionalobjectthatisdisplayedafterauserexitsadialogbox.Thisclustercontainsfourradiobuttons:
(action_tile"view_sel""(pick_view$value)")
.
.
.
(defunpick_view(which)
(cond
((=which"front")(setqshow_which0))
((=which"top")(setqshow_which1))
((=which"left")(setqshow_which2))
((=which"right")(setqshow_which3))
)
)
Theseexamplesshoweachradiobuttonassociatedwithasinglevariablethattakesmultiplevalues.Thesevariablesmayalsocauseadditionalactions,suchasdisablingselectionsinyourdialogbox.Iftheradioclusterislarge,youcanstoretheassociatedvaluesinatable.Ifyouuseatable,structureitsoitdoesn'tdependontheorderofthebuttonswithinthecluster.ThePDBfeaturedoesnotimposethisrestriction,andtheordercanchangeiftheDCLdefinitionchanges.
Page 736
Pleasesendusyourcommentaboutthispage
Page 737
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>HandlingTiles>
HandlingSliders
Whenyouhandleactionsandcallbacksfromsliders,yourapplicationshouldcheckthereasoncodethatitreceivesalongwiththecallback.Thisisnotrequired,butitisagoodideabecauseitcanreduceprocessing.
Acallbackoccurswhenanincrementboundaryonaslideriscrossed.Forexample,ifthesliderisdefinedwithaminimumvalueof0,amaximumvalueof10,andbothsmallandbigincrementsof1,acallbackisissued10timesastheusertraversesfromoneendoftheslidertotheother.
Thefollowingfunctionshowsthebasicschemeofafunctiontohandleaslider.Itiscalledfromanactionexpressionassociatedwiththeslidertile.Theslider_infotileusedbythefunctiondisplaystheslider'scurrentvalueindecimalform.Oftensuchatileisaneditboxaswell,whichgivesusersthechoiceofeithermanipulatingthesliderorenteringitsvaluedirectly.Ifauserentersavalueinslider_info,youreditboxcallbackshouldupdatethevalueofthesliderasfollows:
(action_tile
"myslider"
"(slider_action$value$reason)"
)
(action_tile
"slider_info"
"(ebox_action$value$reason)"
)
.
.
.
(defunslider_action(valwhy)
(if(or(=why2)(=why1));Checkreasoncode.
(set_tile"slider_info"val);Showinterimresult.
)
)
Page 738
(defunebox_action(valwhy)
(if(or(=why2)(=why1));Checkreasoncode.
(set_tile"myslider"val);Showinterimresult.
)
)
Pleasesendusyourcommentaboutthispage
Page 739
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>HandlingTiles>
HandlingEditBoxes
Actionsandcallbackstohandleeditboxesaresimilartothoseforsliders.However,becausecharactersineditboxesarealreadyvisible,thereisnoneedforactiononinterimresults.Editboxesonlyreturnacallbackcodewhenthefocustothattileislost.Thefollowingcodeexamplechecksthevaluebutdoesn'tredisplayit:
(action_tile"myeditbox""(edit_action$value$reason)")
.
.
.
(defunedit_action(valwhy)
(if(or(=why2)(=why4))
.;Dorangecheckingon
.;transientvaluehere.
.
)
)
Pleasesendusyourcommentaboutthispage
Page 740
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
NestingDialogBoxes
Youcreateandmanagenesteddialogboxesbycallingnew_dialogandstart_dialogfromwithinanactionexpressionorcallbackfunction.Forexample,byincludingthefollowingstatement,afunctioncandisplaythe“Hello,world”boxwhentheuserchoosesthebuttoncalledbutton_1:
(action_tile"button_1""(c:hello)")
Theusermustexitthenesteddialogboxbeforeusingthepreviousdialogboxagain.
AutoCADimposesalimitofnomorethaneightnesteddialogboxes,buttoavoidconfusionitisrecommendedyounestdialogboxesnodeeperthanfourlevels.
Warning Ifyoudisplaynesteddialogboxesbymultiplenew_dialogcalls,becarefultobalanceeachnew_dialogcallwithacorrespondingdone_dialogcall(whethercalledfromacallbackornot).Otherwise,yourapplicationmayfail.
Theterm_dialogfunctionterminatesallcurrentdialogboxesasiftheuserhadcanceledeachofthem.Youcanusethisfunctionifyouneedtocancelaseriesofnesteddialogboxes.
Pleasesendusyourcommentaboutthispage
Page 741
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
FunctionsforHidingDialogBoxes
Ausercannotmakeaninteractiveselectionwhileadialogboxisactive.Ifyouwanttheusertomakeaselectionfromthegraphicsscreen,youmusthideyourdialogboxandthenrestoreit.Hidingtheboxisthesameasendingitwithdone_dialog,exceptyourcallbackfunctionmustusethedone_dialogstatusargumenttoindicatethatthedialogboxishidden—asopposedtoendedorcanceled.Setstatustoanapplication-definedvalue.
Thestart_dialogfunctionreturnstheapplication-definedstatuswhenthedialogboxdisappears.Yourprogrammustthenexaminethestatusreturnedbystart_dialoganddeterminewhattodonext.Forstandardandapplication-definedstatusvalues,seeintheAutoLISPReference.
Forexample,hereisasimpledialogboxthatmayrequireausertopickapointintheAutoCADgraphicswindow:
ThedialogboxisdefinedwiththefollowingDCL:
hidedcl:dialog
{label="HideExample";
:column
{:text
{key="message";
label="ClickPickMetopickapoint";
fixed_width=true;
fixed_height=true;
alignment=centered;
}
:row
Page 742
{ok_only;
:retirement_button
{label="PickMe";
key="hide";
mnemonic="H";
}}}}
ThefunctioncontrollingthedialogboxdisplaysthewindowuntiltheuserpressesOKorclosesthewindow.IftheuserchoosesPickMe,thecodehidesthedialogboxandpromptstheusertoselectapoint.ThefollowingAutoLISPcodecontrolsthedialogbox:
(defunc:hidedcl(/dcl_idwhat_nextcnt)
(setqdcl_id(load_dialog"hidedcl.dcl"));Loadthedialogbox.
(setqwhat_next2)
(setqcnt1)
(while(>=what_next2);Begindisplayloop.
(if(null(new_dialog"hidedcl"dcl_id));Initializedialog
(exit);box,exitifnil
);endif;returned.
;Setactiontotakeifabuttonispressed.Eitherbutton
;resultsinadone_dialogcalltoclosethedialogbox.
;Eachbuttonassociatesaspecificstatuscodewith
;done_dialog,andthisstatuscodeisreturnedby
;start_dialog.
(action_tile"accept""(done_dialog1)");SetactionforOK.
(action_tile"hide""(done_dialog4)");Setactionfor
;PickMe.
(setqwhat_next(start_dialog));Displaydialogbox.
;
(cond
((=what_next4);Promptuserto
(getpoint"\npickapoint");pickpt.
)
((=what_next0)
(prompt"\nusercancelleddialog")
)
)
)
(unload_dialogdcl_id)
(princ)
)
Note Theterm_dialogfunctionterminatesalldialogboxesatoncebutdoesnotreturnastatuscode,sothereisnowayforanapplicationtodistinguishbetweenhidinganestedboxandcancelingboxesduetoanerrorcondition.
RequestingaPassword
Page 743
Pleasesendusyourcommentaboutthispage
Page 744
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>FunctionsforHidingDialogBoxes>
RequestingaPassword
Thefollowingexamplesshowhowtouseasimpledialogboxtorequestapasswordfromusers.
Thegetpass.dclfiledefinesadialogboxnamedpassdlg,whichcontainstwotiles:theedit_boxtilewheretheuserentersthepassword,andtheok_canceltile.Itusesthepassword_charDCLattributetomaskthetextauserenters:
//GETPASS.DCL
//
passdlg:dialog{
label="PasswordProtected";
:edit_box{
label="Password:";
edit_width=20;
key="password";
password_char="?";
}
ok_cancel;
}
Thegetpass.lspfiledefinestheGETPASSfunction.Thisfunctionloadsthegetpass.dclfileanddisplaysthepassdlgdialogbox.Whenauserenterstextintotheeditbox,itismaskedbythepassword_charcharacterdefinedintheDCLfile.Theactionassignedtotheeditboxensuresthatthecharactersenteredbytheuseraresettothepassvariable:
;;GETPASS.LSP
;;
(defunGETPASS(/dcl_idpass)
(setqdcl_id(load_dialog"getpass.dcl"))
(if(new_dialog"passdlg"dcl_id)
(progn
(action_tile"password""(setqpass$value)")
Page 745
(start_dialog)
(unload_dialogdcl_id)
)
(princ"Error:UnabletoloadGETPASS.DCL.")
)
pass
)
TheGETPASSfunctionreturnsthestringenteredbytheuser.
Pleasesendusyourcommentaboutthispage
Page 746
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
ListBoxesandPop-UpLists
Thefollowingfunctionshandlelistboxesandpop-uplistsindialogboxes:
start_list
add_list
end_list
Yousetupthelistsdisplayedinlistboxesandpop-uplistsbyusingasequenceofcallstothesefunctions.
ListOperationsProcessingListElements
Pleasesendusyourcommentaboutthispage
Page 747
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ListBoxesandPop-UpLists>
ListOperations
Adialogboxlistoperationalwaysbeginswithastart_listfunctioncall.Thefunctionsyntaxisasfollows:
(start_listkey[operation[index]])
Thekeyargumentisastringthatidentifiesthedialogboxtile.Thekeyargumentiscase-sensitive.Theoperationargumentisanintegervaluethatindicateswhetheryouarecreatinganewlist,changingalist,orappendingtoalist.Thefollowingarevalidoperationarguments:
Operationcodesforstart_list
Value Description
1 Changeselectedlistcontents
2 Appendnewlistentry
3 Deleteoldlistandcreatenewlist(thedefault)
Theindexargumentisonlyusedinchangeoperations.Theindexindicatesthelistitemtochangebyasubsequentadd_listcall.Thefirstiteminalistisindex0.
Ifyoudon'tspecifyoperation,itdefaultsto3(createanewlist).Ifyoudo
Page 748
notspecifyanindex,theindexvaluedefaultsto0.
Youimplementthelistoperationsasfollows:
CreatingaNewList(3)
Afterthestart_listcall,calladd_listrepeatedlytoaddnewitemstothelist.Endlisthandlingbycallingend_list.
ChanginganIteminaList(1)
Aftercallingstart_list,calladd_listoncetoreplacetheitemwhoseindexwasspecifiedinthestart_listcall.(Ifyoucalladd_listmorethanonce,itreplacesthesameitemagain.)Endlisthandlingbycallingend_list.
AppendinganItemtoaList(2)
Aftercallingstart_list,calladd_listtoappendanitemtotheendofthelist.Ifyoucontinuetocalladd_list,moreitemsareappendeduntilyoucallend_list.
Regardlessofwhichlistoperationyouaredoing,youmustcallthethreefunctionsinsequence:start_list,thenadd_list(possiblymorethanonce),andthenend_list.
Themapcarfunctionisusefulforturninga“raw”AutoLISPlistintoalistboxdisplay.Inthefollowingexample,theappnameslistcontainsstringsthatyouwanttoappearinalistboxcalledselections.Youcanusethiscodefragmenttosetupthelistanddisplayitasfollows:
(start_list"selections");Specifythenameofthelistbox.
(mapcar'add_listappnames);SpecifytheAutoLISPlist.
(end_list)
Becauselistcreation(3)isthedefault,thisexampledoesn'tspecifyit.
Thevalueofalist_boxtileistheindexoftheselecteditem(ortheindexesofselecteditems,ifmultipleselectionsareallowed).Ifyourprogramneedstoknowtheactualtextassociatedwithanindex,itmustsavetheoriginallist.Itmustalsotrackchangestothelist.
Appendinglistitemsissimilartocreatinganewlist.If,forexample,appnameshas12itemsinit,andyouwanttoappendanotherlist,called
Page 749
newnames,youcouldusethefollowingcode:
(start_list"selections"2)
(mapcar'add_listnewnames)
(end_list)
Changingasingleitemrequiresonlyoneadd_listcall.Inthiscase,youspecifytheindexoftheitemtochange:
(start_list"selections"15);Changethesixthiteminthelist.
(add_list"SURPRISE!");Rememberthatthefirstindexis0.
(end_list)
Youcannotdeletealistitemorinsertanitemwithoutrebuildingthelistfromscratch.
Pleasesendusyourcommentaboutthispage
Page 750
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ListBoxesandPop-UpLists>
ProcessingListElements
Becausethevalueofalist_boxtilecancontainleadingspaces(especiallyifyouareretrievingmultipleitems),donottestthevalueasastringcomparison.Convertlist_boxvaluetoanintegerfirstwiththeatoifunction,beforeprocessingthelistbox.Youcanalsousethereadfunction,whichconvertsatokentoanintegerautomatically.Forexample,foralistnamedjustonethatacceptsonlyasingleselection,thefollowingcodefragmentcheckstoseeifthethirditeminthelistwasselected:
(setqindex(get_tile"justone"))
(cond
((/=index"");Seeifstringisempty.
(=2(atoiindex))
;Processthethirdentry.
...
)
)
Itisnecessarytofirstcheckifthestringisempty,becausetheatoifunctionsreturn0foranemptystringaswellasthestring"0".
Thevalueofapop-uplistneverhasaleadingspace,soyoudon'thavetoconvertthevalue.Pop-uplistsdonotallowformultipleselection.
Ifthelistboxsupportsmultipleselection,yourprogrammustdotheconversionandstepthroughthemultiplevaluesinthevaluestring.ThefollowingdefinitionofMK_LISTreturnsalistcontainingonlyitemstheuserhasselectedfromtheoriginaldisplist.(Inthisexample,thedisplaylistdisplistismaintainedasaglobalvariable.)TheMK_LISTfunctionexpectstobecalledwiththecurrent$valueofthelistbox:
(defunMK_LIST(readlist/countitemretlist)
(setqcount1)
Page 751
(while(setqitem(readreadlist))
(setqretlist(cons(nthitemdisplist)retlist))
(while(and(/=""(substrreadlistcount1))
(/=""(substrreadlistcount1)))
(setqcount(1+count))
)
(setqreadlist(substrreadlistcount))
)
(reverseretlist)
)
Bothprecedingexamplesalsoworkforthecaseofasingleselection.
Pleasesendusyourcommentaboutthispage
Page 752
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
ImageTilesandButtons
AutoLISPprovidesfunctionsforhandlingimagetilesandimagebuttons.Examplesforhowtousethesefunctionsareprovidedinthissection.
CreatingImagesHandlingImageButtons
Pleasesendusyourcommentaboutthispage
Page 753
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ImageTilesandButtons>
CreatingImages
Thecallingsequencetocreateimagesforimagetilesandimagebuttonsissimilartothelist-handlingsequence.Thestart_imagefunctionbeginsthecreationofanimage,andend_imageendsit.However,thetypeofimagetodrawisspecifiedinseparatefunctioncalls,insteadofarguments:
vector_image
Drawsavector(asingle,straightline)inthecurrentimage.
fill_image
Drawsafilledrectangleinthecurrentimage.
slide_image
DrawsanAutoCADslideintheimage.
Vectorsandfilledrectanglesareusefulforsimpleimages,suchasthecolorswatches(filledrectangles)thattheAutoCADSelectColordialogboxusestodisplaytheuser'schoiceofcolor.Forcomplicatedimages,slidesaremoreconvenient.However,displayingslidescanbetime-consuming.Ifyouuseslides,keepthemsimple.
Note Ifyouuseslideswithfilledobjects(suchaswidepolylines,solids,and3Dfaces)inimagetiles,theimageswillappearasoutlinesunlessyoumaketheslidesfromanimagecreatedwiththeSHADEMODEcommand.
Thevector_imagefunctionrequiresthatyouspecifyabsolutecoordinates,whilefill_imageandslide_imagerequirethatyouspecifyastartingcoordinatealongwitharelativewidthandheight.Todothiscorrectlyyoumustknowtheexactdimensionsoftheimagetileorimagebutton.Becausethesedimensionsareusuallyassignedwhenthedialogboxislaidout,thePDBfeatureprovidesfunctionsthatreturnthewidthandheightofaparticulartile.These
Page 754
dimensionfunctionsaredimx_tileanddimy_tile.Youshouldcallthembeforeyoubegincreatinganimage.Theoriginofatile,(0,0),isalwaystheupper-leftcorner.
ColorscanbespecifiedasAutoCADcolornumbersorasoneofthelogicalcolornumbersshowninthefollowingtable.(ThevaluesandmnemonicsaredefinedbytheAutodeskDeviceInterface[ADI].)
Dialogboxcolorattribute
Colornumber
ADImnemonic Meaning
-2 BGLCOLOR CurrentbackgroundoftheAutoCADgraphicsscreen
-15 DBGLCOLOR Currentdialogboxbackgroundcolor
-16 DFGLCOLOR Currentdialogboxforegroundcolor(fortext)
-18 LINELCOLOR Currentdialogboxlinecolor
Inthefollowingexample,"cur_color"isanimagetileyouwanttofillentirelywithapatchofredasfollows:
(setqwidth(dimx_tile"cur_color")
height(dimy_tile"cur_color"))
(start_image"cur_color")
(fill_image00widthheight1);1=AutoCADred.
(end_image)
Youcanusetheimage-drawingfunctionsinconjunctionwitheachother.Thefollowingcodefillsanimageandthendrawsaverticalstripeoverit:
Page 755
(setqwidth(dimx_tile"stripe")
height(dimy_tile"stripe"))
(start_image"stripe")
(fill_image00widthheight3);3=AutoCADgreen.
(setqx(/width2));Centerthevectorvertically.
(vector_imagex0xheight4);4=AutoCADcyan.
(end_image)
Theslidesyoudisplaywithslide_imagecanbestandaloneslide(SLD)files,orpartofaslidelibrary(SLB)file.IftheslideisinanSLDfile,youspecifyitsnamewithoutthe.sldextension(forexample,"frntview").Iftheslideisinaslidelibrary,youspecifythenameofthelibrary,followedbythenameoftheslideenclosedinparentheses.Notethatthelibraryandslidenamesarealsospecifiedwithoutextensions—forexample,"allviews(frntview)".Theslide_imagefunctionsearchesfortheslideorslidelibraryfileaccordingtothecurrentAutoCADlibrarysearchpath.(SeeintheAutoLISPReference.)
Inthefollowingexample,theslideisinasinglefilecalledtopview.sld:
(setqx(dimx_tile"view")
y(dimy_tile"view"))
(start_image"view")
(slide_image00xy"topview")
(end_image)
Vectorsinslidesareoftendrawninwhite(colornumber7),whichisthedefaultbackgroundcolorofanimage.Ifyourimagetileisblankwhenyoufirstdisplayaslide,trychangingitscolorattributetographics_background.(Youcanalsochangethebackgroundoftheimagebyprecedingtheslide_imagecallwithafill_imagecall.)
Pleasesendusyourcommentaboutthispage
Page 756
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>ImageTilesandButtons>
HandlingImageButtons
Youcanhandleanimagebuttonsimplyasabutton—thatis,youcanuseittotriggerasingleaction.However,youcanalsousethePDBfeaturetodefineregionsofthebutton.Withregionsdefined,theactiontakendependsonthepartoftheimagebuttontheuserselects.Themechanismforthisisstraightforward:animagebutton'sactionorcallbackreturnsthe(X,Y)locationthattheuserselected.Thecoordinatesarewithintherangeoftheparticularimagebuttontile(asreturnedbythedimensionfunctions).Yourapplicationmustassignameaningtoselectlocationsbyimplicitlydefiningregionsoftheimage.TheDDVPOINTdialogboxmakesgooduseofthisfeature.Youcanviewthisbyloadingandrunningtheddvpoint.lspfileintheAutoCADSupportdirectory.
Inthefollowingexample,yourimagebuttonhastwocolorswatchescreatedbyfill_image.Youwanttoselecteitheroneortheother,dependingonwhichregiontheuserselects.Iftheimagebuttonisdividedhorizontally(darkaboveandlightbelow),youractionneedstotestonlytheonedimension:
(action_tile"image_sel""(pick_shade$key$value$y)")
...
(defunpick_shade(keyvaly)
(setqthreshold
(/(dimy_tilekey)2));Imageisdividedhorizontally.
(if(>ythreshold);Rememberthattheoriginisat
(setqresult"Light");upperleft.
(setqresult"Dark"))
)
Pleasesendusyourcommentaboutthispage
Page 757
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
Application-SpecificData
Theclient_data_tilefunctionassignsapplication-specificdatatoatile.Thedataisavailableatcallbacktimeasthe$datavariableandmustbeastring.ClientdataisnotrepresentedinDCL;itisvalidonlywhileyourapplicationisrunning.Usingclientdataiscomparabletousinguser-definedattributes.Themaindifferenceisthatuser-definedattributesareread-only,whileclientdatacanchangeatruntime.Also,end-userscaninspectuser-definedattributesintheapplication'sDCLfile,butclientdataisinvisibletothem.
Becauseyourprogrammustmaintainthelistdisplayedbyalistbox(orpop-uplist),clientdataisgoodforhandlingthisinformation.ThefollowingmodificationtotheMK_LISTfunction(showninProcessingListElements)makesthelistanargument:
(defunMK_LIST(readlistdisplist/)
Thiscodeeliminatestheneedforagloballistvariable.Thefollowingcallsinthemainpartofthedialogboxhandlerassociateashortlistwiththetilebycallingclient_data_tile,andthenpassthatlisttoMK_LISTbymeansofanactionexpressionasfollows:
(client_data_tile
"colorsyslist"
"Red-Green-BlueCyan-Magenta-YellowHue-Saturation-Value"
)
(action_tile
"colorsyslist"
"(setqusrchoice(mk_list$value$data))"
)
Pleasesendusyourcommentaboutthispage
Page 758
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
DCLErrorHandling
ThePDBfeaturechecksaDCLfileforerrorsthefirsttimeyouloadit.IfAutoCADencountersasyntaxerror,amisuseofattributes,oranyothererror(suchasfailuretospecifyakeyattributeforanactivetile),thePDBdoesnotloadtheDCLfile.Instead,AutoCADeitherdisplaysoneormoredialogboxesalertingyoutotheerror,orwritesalistoferrorstoatextfilecalledacad.dce.IfAutoCADwritestheerrormessagestoacad.dce,italertsyoutothiswithamessagesimilartothefollowing:
Youcaninspectthecontentsofacad.dcetofindtheproblem.AutoCADplacestheacad.dcefileinthecurrentworkingdirectory.WhenAutoCADreadsaDCLfilesuccessfully,itdeletestheacad.dcefile.
IfyourapplicationusesmultipleDCLfiles,theacad.dcefileisoverwritten(ordeletedifnoerrorsoccur)wheneachnewfileisloaded.Whenyoutesttheprogram,acad.dceshowserrors(ifany)fromonlytheDCLfilemostrecentlyread.ItisrecommendedthatyouusetheVLISPDCLPreviewfeaturetodebugyourDCLfiles(seeDisplayingDialogBoxeswithVisualLISP).YoucanalsoloadanddebugeachfilemanuallyinAutoCADwiththeload_dialogfunction.Thefollowingload_dialogfunctionloadstheDCLfilehellofile.dcl:
Command: (load_dialog"hellofile")
3
Ifthedialogboxloadssuccessfully,load_dialogreturnsapositiveinteger
Page 759
thatidentifiestheDCLfile.Youpassthisvaluetothenew_dialogfunctiontoinitializeindividualdialogboxesinthefile.
Thenew_dialogfunctionreturnsTifitsucceeds;otherwiseitreturnsnil.Ifnew_dialogreturnsT,callthestart_dialogfunctiontodisplaythedialogbox.
Onceyou'vedebuggedeachDCLfile,youcanloadyourprogramandtestthedialogboxesincombination.Ifyourprogramcallsarestrictedfunctionbetweenthestart_dialoganddone_dialogcalls,AutoCADterminatesalldialogboxesanddisplaysthefollowingerrormessage:
AutoCADrejectedfunction
SeeFunctionsRestrictedWhenaDialogBoxIsOpenforinformationonwhichfunctionsarerestricted.
SettingtheAuditingLeveltoAffectErrorMessages
Pleasesendusyourcommentaboutthispage
Page 760
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>DCLErrorHandling>
SettingtheAuditingLeveltoAffectErrorMessages
ThelevelofsemanticauditingaffectswhichmessagesAutoCADissuesforaDCLfile(seeSemanticAuditingofDCLFiles).Forexample,thehidedcldialogboxdefinedinFunctionsforHidingDialogBoxesisdisplayedwithoutanywarnings,ifyouusethedefaultauditlevel.Ifyousettheauditlevelto3,though,AutoCADdisplaysanalertdialogboxwithawarningmessage.Youcanseethisforyourselfbyinsertingthefollowinglineatthebeginningofhidedcl:
dcl_settings:default_dcl_settings{audit_level=3;}
TryusingtheVLISPDCLPreviewfeaturetoviewthedialogboxdefinedinhidedcl.Youwillbealertedtoviewtheacad.dcefile,whichcontainsthefollowingmessages:
===DCLsemanticauditofC:/PROGRA~1/AUTOCA~1/VLISP/$vld$.dcl===
Hintin"hidedcl".(widgettype=text,key="message")
fixed_height=trueisprobablyredundant.
Atlower(lessdiscriminating)levelsofsemanticauditing,AutoCADdoesnotlookforredundantattributedefinitionsandthedialogboxdisplaysnormally.
Removethefixed_height=truestatementfromtheDCLtocorrectthesituationAutoCADiswarningyouabout.
Pleasesendusyourcommentaboutthispage
Page 761
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>
DialogBoxFunctionSummary
Thissectionsummarizesthestepsrequiredinatypicaldialogboxhandlingfunction.Italsodescribesasampleapplicationyoucanrefertowhendesigningandimplementingyourowndialogboxfunctions.
FunctionSequenceTheSampleBlockDefinitionDialogBox
Pleasesendusyourcommentaboutthispage
Page 762
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>DialogBoxFunctionSummary>
FunctionSequence
Thefollowingdemonstratesthetypicalfunctionsequence:
1. LoadtheDCLfilewithaload_dialogcall.
2. Callnew_dialogtodisplayaparticulardialogbox.Besuretocheckthevaluereturnedbynew_dialog.Callingstart_dialogwhenthenew_dialogcallhasfailedcanhaveunpredictableresults.
3. Initializethedialogboxbysettinguptilevalues,lists,andimages.Initializealsowhenyoucallaction_tiletosetupactionexpressionsorcallbackfunctions.Otherfunctionstypicallycalledatthistimeareset_tileandmode_tileforgeneraltilevaluesandstates,start_list,add_list,andend_listforlistboxes,andthedimensionfunctionswithstart_image,vector_image,fill_image,slide_image,andend_imageforimages.Atthistimeyoucanalsocallclient_data_tiletoassociateapplication-specificdatawiththedialogboxanditscomponents.
4. Callstart_dialogtoturncontrolovertothedialogbox,sothattheusercanenterinput.
5. Processuserinputfromwithinyouractions(callbacks).Processinputwhenyouaremostlikelytouseget_tile,get_attr,set_tile,andmode_tile.Theuserpressesanexitbutton,causinganactiontocalldone_dialog,whichcausesstart_dialogtoreturnavalue.Atthispoint,unloadtheDCLfilebycallingunload_dialog.ThisschemehandlesonlyonedialogboxandoneDCLfileatatime.Applicationsusuallyhavemultipledialogboxes.Theeasiestand
Page 763
quickestwaytohandlethesedialogboxesistosavealloftheminasingleDCLfile.Theload_dialogcallthenloadsalldialogboxesatonce,andyoucancallnew_dialogforanydialogbox.Ifmemoryislimited,however,youmayneedtocreatemultipleDCLfilesanduseunload_dialogtoremoveonesetofdialogboxesfrommemorybeforeyouloadanotherset.
Pleasesendusyourcommentaboutthispage
Page 764
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ManagingDialogBoxes>DialogBoxFunctionSummary>
TheSampleBlockDefinitionDialogBox
Thesampleapplicationbmake.lspanditsassociatedbmake.dclfileillustrateanumberofusefuldialogboxtechniques.ThesefilesareintheAutoCADSupportdirectory.Thebmakeapplicationisessentiallyaninteractiveinterfacetotheentmakefunction.Youcanuseittodefinenewblocksandtoviewthenamesofexistingblocks.Someofthetechniquesillustratedbybmakeare
Hidingdialogboxesbydefiningspecialstatuscodesfordone_dialogtopasstostart_dialog.SeethemainloopoftheC:BMAKEfunction(followingtheload_dialogandaction_tilecalls).
Usingatoggletoenableordisableanothertile.SeethedefinitionoftheDO_UNNAMEDfunction.
Buildingalistforalistbox.SeethePAT_MATCHandSORTfunctions.
DisplayingthestandardAutoCADHelpdialogbox.SeetheDO_HELPfunction.
Asidefromdemonstratingdialogboxtechniques,bmakeillustratesgooddesign.
Pleasesendusyourcommentaboutthispage
Page 765
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>
ProgrammableDialogBoxReference
Youcanuseattributestoworkwithdialogboxes.
Thischapterlistsanddescribesallthedialogcontrollanguage(DCL)tilesandtheirassociatedattributes,andsummarizestheVisualLISP®functionsavailableforworkingwithprogrammabledialogboxes.
TileAttributesSynopsisofPredefinedAttributesDCLAttributeCatalogactionalignmentallow_acceptaspect_ratiobig_incrementchildren_alignmentchildren_fixed_heightchildren_fixed_widthcoloredit_limitedit_widthfixed_heightfixed_widthfixed_width_fontheightinitial_focus
Page 766
is_boldis_cancelis_defaultis_enabledis_tab_stopkeylabellayoutlistmax_valuemin_valuemnemonicmultiple_selectpassword_charsmall_incrementtabstab_truncatevaluewidthFunctionalSynopsisofDCLTilesDCLTileCatalogboxed_columnboxed_radio_columnboxed_radio_rowboxed_rowbuttoncolumnconcatenationdialog
Page 767
edit_boxerrtileimageimage_buttonlist_boxok_onlyok_cancelok_cancel_helpok_cancel_help_errtileok_cancel_help_infoparagraphpopup_listradio_buttonradio_columnradio_rowrowslidertexttext_parttogglespacerspacer_0spacer_1ProgrammableDialogBoxFunctionSynopsis
Pleasesendusyourcommentaboutthispage
Page 768
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
TileAttributes
Atile'sattributesdefineitslayoutandfunctionality.Anattributeissimilartoaprogramminglanguagevariable:itconsistsofanameandavalue.
AttributeTypesRestrictedAttributesUser-DefinedAttributes
Pleasesendusyourcommentaboutthispage
Page 769
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>TileAttributes>
AttributeTypes
Thevalueofanattributemustbeoneofthefollowingdatatypes:
Integer
Numericvalues(bothintegersandrealnumbers)thatrepresentdistances,suchasthewidthorheightofatile,areexpressedincharacter-widthorcharacter-heightunits.
RealNumber
Afractionalrealnumbermusthavealeadingdigit:forexample,0.1,not.1.
QuotedString
Aquotedstringconsistsoftextenclosedinquotationmarks("").Attributevaluesarecase-sensitive:B1isnotthesameasb1.Ifthestringmustcontainaquotationmark,precedethequotationmarkcharacterwithabackslash(\").Quotedstringscancontainothercontrolcharactersaswell.ThecharactersrecognizedbyDCLareshowninthefollowingtable:
ControlcharactersallowedinDCLstrings
Controlcharacter Meaning
\" quote(embedded)
\\ backslash
\n newline
Page 770
\t horizontaltab
ReservedWord
Areservedwordisanidentifiermadeupofalphanumericcharacters,beginningwithaletter.Forexample,manyattributesrequireavalueofeithertrueorfalse.Reservedwordsarealsocase-sensitive:Truedoesnotequaltrue.
Likereservedwordsandstrings,attributenamesarecase-sensitive;forexample,youcannotassignawidthbycallingitWidth.
Applicationprogramsalwaysretrieveattributesasstrings.Ifyourapplicationusesnumericvalues,itmustconvertthemtoandfromstringvalues.FormoreinformationonhandlingtilevalueswithinanAutoLISP®program,seeHandlingTiles.
Someattributes,suchaswidthandheight,arecommontoalltiles.Attributespecificationsareoptional.Manyattributeshavedefaultvaluesthatareusediftheattributeisnotspecified.Otherattributesarespecificallymeantforcertainkindsoftiles—forexample,thebackgroundcolorofanimage.Ifyouattempttoassignthisattributetoadifferentkindoftile,AutoCAD®mayreportanerror.Usually,itignorestheattribute.
Pleasesendusyourcommentaboutthispage
Page 771
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>TileAttributes>
RestrictedAttributes
Thefollowingtileattributesarerestricted.DonotusetheminyourDCLfiles:
horizontal_margin
vertical_margin
type
Pleasesendusyourcommentaboutthispage
Page 772
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>TileAttributes>
User-DefinedAttributes
Whendefiningtiles,youcanassignyourownattributes.Thenameoftheattributecanbeanyvalidnamethatdoesnotconflictwiththestandard,predefinedattributesdescribedinRestrictedAttributesandsummarizedinSynopsisofPredefinedAttributes.Anattributename,likeakeyword,cancontainletters,numbers,ortheunderscore(_),andmustbeginwithaletter.
Ifauser-definedattributenameconflictswithapredefinedattribute,thePDBfeaturedoesnotrecognizetheattributeasanewone,andattemptstousethevalueyouassignitwiththestandardattribute.Thiscanbeveryhardtodebug.
Thevaluesyouassigntotheattribute,andtheirmeanings,aredefinedbyyourapplication.Valuesforuser-definedattributesmustconformtothetypesdescribedinTileAttributes.
Definingattributesiscomparabletodefiningapplication-specificclientdata.BothtechniquesenablethePDBfeaturetomanagedatayousupply.User-definedattributesareread-only,thatis,theyarestaticwhilethedialogboxisactive.Ifyouneedtochangethevaluesdynamically,youmustuseclientdataatruntime.Also,enduserscaninspectthevalueofuser-definedattributesintheapplication'sDCLfile,butclientdataremainsinvisible.
ThedefinitionoftheAutoCADDrawingAidsdialogboxdefinesitsownattribute,errmsg,whichhasauniquestringvalueforeachtile.Acommonerrorhandlerusesthevalueoferrmsgwhenitdisplaysawarning.Forexample,thetilecouldassignthefollowingvaluetoerrmsg:
errmsg="GridYSpacing";
Iftheuserentersanunusablevalue,suchasanegativenumber,AutoCADdisplaysthefollowingerrormessage:
InvalidGridYSpacing.
Page 773
ThewordInvalidandthetrailingperiod(.)aresuppliedbytheerrorhandler.
User-definedattributescanalsobeusedforlimitsonthevalueofatileandthenameofasubdialogboxthatthetileactivates(seeNestingDialogBoxes).
Pleasesendusyourcommentaboutthispage
Page 774
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
SynopsisofPredefinedAttributes
ThissectionliststheattributesdefinedbythePDBfeature.Thefollowingtablesummarizesthepredefinedattributesinalphabeticalorder.TheattributesaredescribedindetailinUser-DefinedAttributes.
Predefinedattributes
Attributename AssociatedwithMeaning(ifspecifiedortrue)
action Allactivetiles AutoLISPactionexpression
alignment Alltiles Horizontalorverticalpositioninacluster
allow_accept edit_box,image_button,
list_box
Activatesis_defaultbuttonwhenthistileisselected
aspect_ratio image,image_button Aspectratioofanimage
Page 775
big_increment slider Incrementaldistancetomove
children_alignment row,column,radio_row,radio_column,boxed_row,boxed_column,boxed_radio_row,boxed_radio_column
Alignmentofacluster'schildren
children_fixed_height
row,column,radio_row,radio_column,boxed_row,boxed_column,boxed_radio_row,boxed_radio_column
Heightofacluster'schildrendoesn'tgrowduringlayout
children_fixed_width
row,column,radio_row,radio_column,boxed_row,boxed_column,boxed_radio_row,boxed_radio_column
Widthofacluster'schildrendoesn'tgrowduringlayout
color image,image_button Background(fill)colorofanimage
edit_limit edit_box Maximumnumberofcharactersuserscanenter
edit_width edit_box,popup_list Widthoftheedit(input)portionofthetile
Page 776
fixed_height Alltiles Heightdoesn'tgrowduringlayout
fixed_width Alltiles Widthdoesn'tgrowduringlayout
fixed_width_font list_box,popup_list Displaystextinafixedpitchfont
height Alltiles Heightofthetile
initial_focus Dialog Keyofthetilewithinitialfocus
is_bold Text Displaysasbold
is_cancel Button Buttonisactivatedwhenthecancelkey—usuallyESC—ispressed
is_default Button Buttonisactivatedwhentheacceptkey—usuallyENTER—ispressed
is_enabled Allactivetiles Tileisinitiallyenabled
Page 777
is_tab_stop Allactivetiles Tileisatabstop
key Allactivetiles Tilenameusedbytheapplication
label boxed_row,boxed_column,boxed_radio_row,boxed_radio_column,button,dialog,edit_box,list_box,popup_list,radio_button,text,toggle
Displayedlabelofthetile
layout slider Whetherthesliderishorizontalorvertical
list list_box,popup_list Initialvaluestodisplayinlist
max_value slider Maximumvalueofaslider
min_value slider Minimumvalueofaslider
mnemonic allactivetiles Mnemoniccharacterforthetile
multiple_select list_box Listboxallowsmultipleitemstobeselected
Page 778
password_char edit_box Maskscharactersenteredinedit_box
small_increment slider Incrementaldistancetomove
tabs list_box,popup_list Tabstopsforlistdisplay
tab_truncate list_box,popup_list Truncatestextthatislargerthantheassociatedtabstop
value Text,activetiles(exceptbuttonsandimagebuttons)
Tile'sinitialvalue
width Alltiles Widthofthetile
Pleasesendusyourcommentaboutthispage
Page 779
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
DCLAttributeCatalog
DCLtileattributesaredescribedindetailinthissection.Theattributesarelistedalphabetically.
Pleasesendusyourcommentaboutthispage
Page 780
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
action
action="(function)";
SpecifiesanAutoLISPexpressiontoperformanactionwhenthistileisselected.Alsoknownasacallback.Forsomekindsoftiles,anactioncanalsooccurwhentheuserswitchesfocustoadifferenttile.
ThepossiblevalueisaquotedstringthatisavalidAutoLISP®expression.Atilecanhaveonlyoneaction.Iftheapplicationassignsitanaction(withaction_tile),thisoverridestheactionattribute.
Note YoucannotcalltheAutoLISPcommandfunctionfromtheactionattribute.
Pleasesendusyourcommentaboutthispage
Page 781
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
alignment
alignment=position;
Specifiesthehorizontalorverticalpositioning(justification)ofatilewithinitscluster.
Foratilethatisachildofacolumn,thepossiblevaluesareleft,right,orcentered(defaultisleft).
Foratilethatisachildofarow,thepossiblevaluesaretop,bottom,orcentered(defaultiscentered).
Youcannotspecifythealignmentalongthelongaxisofacluster.Thefirstandlasttilesintheclusteralwaysalignthemselveswiththeendsofthecolumnorrow.Othertilesintheclusteraredistributedevenlyunlessyouadjustthedistributionbyusingpaddinginsertionpoints(seespacer_0).
Pleasesendusyourcommentaboutthispage
Page 782
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
allow_accept
allow_accept=true-false;
Specifieswhetherthetileisactivatedwhentheuserpressestheacceptkey(usuallyENTER).Iftrueandtheuserpressestheacceptkey,thedefaultbutton(ifany)ispressed.Thedefaultbuttonisthebuttontilewhoseis_defaultattributeissettotrue.Theallow_acceptattributedefaultstofalse.
Pleasesendusyourcommentaboutthispage
Page 783
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
aspect_ratio
aspect_ratio=real;
Specifiestheratioofthewidthoftheimagetoitsheight(widthdividedbyheight).Ifzero(0.0),thetileisfittedtothesizeoftheimage.
Possiblevaluesarefloating-pointvalues(default:none).
Pleasesendusyourcommentaboutthispage
Page 784
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
big_increment
big_increment=integer;
Specifiesthevalueusedbytheslider'sincrementalcontrols.Thedefaultvalueofbig_incrementisone-tenthofthetotalrange.Thevaluemustbewithintherangespecifiedbymin_valueandmax_value.
Pleasesendusyourcommentaboutthispage
Page 785
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
children_alignment
children_alignment=position;
Specifiesthedefaultalignment(similartoalignment)foralltilesinacluster.Doesnotoverrideachild'salignmentattribute,ifalignmentisspecifiedexplicitly.
Forcolumns,possiblevaluesareleft,right,orcentered(default:left).
Forrows,possiblevaluesaretop,bottom,orcentered(default:centered).
Pleasesendusyourcommentaboutthispage
Page 786
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
children_fixed_height
children_fixed_height=true-false;
Specifiesthedefaultheight(similartoheight)foralltilesinacluster.Doesnotoverrideachild'sheightattribute,ifitisspecifiedexplicitly.
Possiblevaluesaretrueorfalse(default:false).
Note Usethefixed_attributeswithdiscretion.Inconsistentoverridingofdefaultsresultsininconsistentlayouts.
Pleasesendusyourcommentaboutthispage
Page 787
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
children_fixed_width
children_fixed_width=true-false;
Specifiesthedefaultwidth(similartowidth)foralltilesinacluster.Doesnotoverrideachild'swidthattribute,ifitisspecifiedexplicitly.
Possiblevaluesaretrueorfalse(default:false).
Note Usethefixed_attributeswithdiscretion.Inconsistentoverridingofdefaultsresultsininconsistentlayouts.
Pleasesendusyourcommentaboutthispage
Page 788
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
color
color=colorname;
Specifiesthebackground(fill)coloroftheimage.Possiblevaluesareanintegerorreservedword(default:7)specifiedasanAutoCADcolornumberorasoneofthesymbolicnamesshowninthefollowingtable:
Symbolicnamesforcolors
Symbolicname Meaning
dialog_line Currentdialogboxlinecolor
dialog_foreground Currentdialogboxforegroundcolor(fortext)
dialog_background Currentdialogboxbackgroundcolor
graphics_background CurrentbackgroundoftheAutoCADgraphicsscreen(usuallyequivalentto0)
black AutoCADcolor=0(black)(appearslightonablackbackground)
red AutoCADcolor=1(red)
Page 789
yellow AutoCADcolor=2(yellow)
green AutoCADcolor=3(green)
cyan AutoCADcolor=4(cyan)
blue AutoCADcolor=5(blue)
magenta AutoCADcolor=6(magenta)
whitegraphics_foreground
AutoCADcolor=7(white)(appearsblackonalightbackground)
Thesymbolicnamesgraphics_backgroundandgraphics_foregroundareprovidedasalternativestothenamesblackandwhite.TheuseofaspecificcolorcanbeconfusingbecausethecolorthatisactuallydisplayedvariesdependingonthecurrentAutoCADconfiguration.Also,vectorsinslidesthatyoudisplayinanimageareoftendrawninblackorwhite.Ifyourimagetileisblankwhenyoufirstdisplayit,trychangingitscolortographics_backgroundorgraphics_foreground.
Pleasesendusyourcommentaboutthispage
Page 790
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
edit_limit
edit_limit=integer;
Specifiesthemaximumnumberofcharactersauserisallowedtoenterintheeditbox.Apossiblevalueisaninteger(default:132).Whentheuserreachesthislimit,AutoCADrejectsadditionalcharacters(exceptforBACKSPACEorDEL).Themaximumeditlimitallowedis256characters.
Pleasesendusyourcommentaboutthispage
Page 791
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
edit_width
edit_width=number;
Specifiesthewidthincharacter-widthunitsoftheedit(input)portionofthebox—theactualboxedportionoftheedit_boxtile.Possiblevaluesareanintegerorarealnumber.Ifedit_widthisnotspecifiedoriszero,andthewidthofthetileisnotfixed,theboxexpandstofilltheavailablespace.Ifedit_widthisnonzero,thentheboxisright-justifiedwithinthespaceoccupiedbythetile.Ifit'snecessarytostretchthetileforlayoutpurposes,thePDBfeatureinsertswhitespacebetweenthelabelandtheeditportionofthebox.
Pleasesendusyourcommentaboutthispage
Page 792
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
fixed_height
fixed_height=true-false;
Specifiesifatile'sheightisallowedtofilltheavailablespace.Ifthisattributeistrue,thetiledoesnotfilltheextraspacethatbecomesavailableinthelayout/alignmentprocess.
Possiblevaluesaretrueorfalse(default:false).
Pleasesendusyourcommentaboutthispage
Page 793
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
fixed_width
fixed_width=true-false;
Specifiesifatile'swidthisallowedtofilltheavailablespace.Ifthisattributeistrue,thetiledoesnotfilltheextraspacethatbecomesavailableinthelayout/alignmentprocess.
Possiblevaluesaretrueorfalse(default:false).
Pleasesendusyourcommentaboutthispage
Page 794
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
fixed_width_font
fixed_width_font=true-false;
Specifieswhetheralistboxorpop-uplistwilldisplaytextinafixedpitchfont.Thisallowsforeasierspacingandtabalignmentof-columns.
Possiblevaluesaretrueorfalse(default:false).
Pleasesendusyourcommentaboutthispage
Page 795
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
height
height=number;
Specifiestheheightofatile.Possiblevaluesareanintegerorarealnumberrepresentingthedistanceincharacterheightunits.Donotspecifythisvalueunlesstheassigneddefaultsdonothaveanacceptableappearance.Youmustspecify,however,theheightofimagetilesandimagebuttons.
Theheightattributespecifiestheminimumheightofatile.Thisdimensioncanbeexpandedwhenthetileislaidout,unlesstheheightisfixedbyoneofthefixed_attributes.Defaultsaredynamicallyassignedbasedonlayoutconstraints.
Character-heightunitsaredefinedasthemaximumheightofscreencharacters(includinglinespacing).
Pleasesendusyourcommentaboutthispage
Page 796
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
initial_focus
initial_focus="string";
Specifiesthekeyofthetilewithinthedialogboxthatreceivestheinitialkeyboardfocus.Possiblevalueisaquotedstring(nodefault).
Pleasesendusyourcommentaboutthispage
Page 797
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
is_bold
is_bold=true-false;
Specifieswhetherthetextisdisplayedinboldcharacters.Possiblevaluesaretrueorfalse(default:false).Iftrue,thetextisdisplayedinboldcharacters.
Pleasesendusyourcommentaboutthispage
Page 798
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
is_cancel
is_cancel=true-false;
SpecifieswhetherthebuttonisselectedwhentheuserpressestheESCkey.Possiblevaluesaretrueorfalse(default:false).
Iftheactionexpressionforbuttonswiththeis_cancelattributesettotruedoesnotexitthedialogbox(doesnotcalldone_dialog),thedialogboxisautomaticallyterminatedaftertheactionexpressionhasbeencarriedout,andtheDIASTATsystemvariableissetto0.
Onlyonebuttoninadialogboxcanhavetheis_cancelattributesettotrue.
Pleasesendusyourcommentaboutthispage
Page 799
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
is_default
is_default=true-false;
Specifieswhetherthebuttonisthedefaultbuttonselected(“pushed”)whentheuserpressestheacceptkey.Possiblevaluesaretrueorfalse(default:false).Iftheuserisinanedit_box,list_box,orimage_buttonthathastheallow_acceptattributesettotrue,thedefaultbuttonisalsoselectediftheuserpressestheacceptkeyor(forlistboxesandimagebuttons)double-clicks.Thedefaultbuttonisnotselectedbytheacceptkeyifanotherbuttonhasfocus.Inthiscase,thebuttonthathasfocusistheoneselected.
Onlyonebuttoninadialogboxcanhavetheis_defaultattributesettotrue.
Pleasesendusyourcommentaboutthispage
Page 800
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
is_enabled
is_enabled=true-false;
Specifieswhetherornotthetileisinitiallyavailable.Possiblevaluesaretrueorfalse(default:true).Iffalse,thetileisunavailableandappearsgrayedout.
Pleasesendusyourcommentaboutthispage
Page 801
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
is_tab_stop
is_tab_stop=true-false;
SpecifieswhetherthetilereceiveskeyboardfocuswhentheusermovesbetweentilesbypressingtheTABkey.Possiblevaluesaretrueorfalse(default:true).Ifthetileisdisabled,itisnotatabstopevenifthisattributeistrue.Iffalse,thetileisnotatabstop.
Pleasesendusyourcommentaboutthispage
Page 802
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
key
key="string";
Specifiesanamethattheprogramusestorefertothisspecifictile.Possiblevalueisaquotedstring(nodefault).Withinaparticulardialogbox,eachkeyvaluemustbeunique.Thisstringiscase-sensitive:ifyouspecifythekeyasBigTile,youcannotreferenceitasbigtile.
Becausethevalueofakeyisnotvisibletotheuser,itsnamecanbewhateveryouchoose(aslongasitisuniquetothedialogbox).Forthesamereason,keyattributesdonotneedtobetranslatedforapplicationsofferedinmultiplelanguages.
Pleasesendusyourcommentaboutthispage
Page 803
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
label
label="string";
Specifiesthetextdisplayedwithinthetile.Possiblevalueisaquotedstring(default:ablankstring,"").Theplacementoflabeltextistile-specific.
Thelabelattributecanspecifyamnemoniccharacterforthetile.Themnemonicisunderlinedinthetile'slabel.
Anycharacterinalabelstringthatisprecededbyanampersand(&)becomesthemnemonic.Thecharacterdoesn'thavetobeuniquetothedialogbox.Ifmorethanonetilehasthesamemnemonic,theuserpressesthatkeytocyclethroughthetilessequentially.
Mnemonicschangefocusbutdonotselectatile.Iftheuserspecifiesamnemonickeyforatilethatcontainsagroupofitems,suchasaclusteroralistbox,thefocusisputonthefirstiteminthetilethatisatabstop.Anyactivetileisatabstopunlessitsis_tab_stopattributeissettofalse.
Note Themnemonicattributealsospecifiesamnemoniccharacter.
Pleasesendusyourcommentaboutthispage
Page 804
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
layout
layout=position;
Specifiestheorientationofaslider.Possiblevaluesarehorizontalorvertical(default:horizontal).Forhorizontalsliders,thevalueincreasesfromlefttoright.Forverticalsliders,thevalueincreasesfrombottomtotop.
Pleasesendusyourcommentaboutthispage
Page 805
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
list
list="string";
Specifiestheinitialsetoflines(choices)tobeplacedinthepopup_listorlist_box.Possiblevalueisaquotedstring(nodefault).Linesareseparatedbyanewlinesymbol(\n).Tabcharacters(\t)canoccurwithineachline.
Pleasesendusyourcommentaboutthispage
Page 806
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
max_value
max_value=integer;
Specifiestheupperrangeofvaluesthatasliderreturns.Defaultmaximumvalueis10000.Thisvaluemustbeasigned,16-bitintegernogreaterthan32767.
Pleasesendusyourcommentaboutthispage
Page 807
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
min_value
min_value=integer;
Specifiesthelowerrangeofvaluesthatasliderreturns.Defaultminimumvalueis0.Thisvaluemustbeasigned,16-bitintegernolessthan-32768.Themin_valuecanbegreaterthanthemax_value.
Pleasesendusyourcommentaboutthispage
Page 808
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
mnemonic
mnemonic="char";
Specifiesakeyboardmnemoniccharacterforthetile.Themnemonicisunderlinedinthetile'slabel.Apossiblevalueisaquotedstringofasinglecharacter(nodefault).Thecharactermustbeoneofthelettersinthetile'slabel.Thecharacterdoesn'thavetobeuniquetothedialogbox.Ifmorethanonetilehasthesamemnemonic,theuserpressesthatkeytocyclethroughthetilessequentially.
Fromtheuser'spointofview,mnemonicsaren'tcase-sensitive.Forexample,ifabutton'smnemoniccharacterisA,enteringeitheraorAgivestheAbuttonfocus.However,intheDCLfilethemnemonicmustbeoneofthecharactersinthetile'slabel,anditmustbecapitalizedasitappearsinthelabelstring.
Mnemonicschangefocus.Iftheuserspecifiesamnemonickeyforatilethatcontainsagroupofitems,suchasaclusteroralistbox,thefocusisputonthefirstiteminthetilethatisatabstop.Anyactivetileisatabstopunlessitsis_tab_stopattributeissettofalse.
Note Thelabelattributecanalsospecifyamnemoniccharacter.
Pleasesendusyourcommentaboutthispage
Page 809
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
multiple_select
multiple_select=true-false;
Specifieswhethermultipleitemsinthelist_boxcanbeselected(highlighted)atthesametime.Possiblevaluesaretrueorfalse(default:false).Iftrue,multipleitemscanbeselectedatatime.
Pleasesendusyourcommentaboutthispage
Page 810
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
password_char
password_char="char";
Specifiesthecharactertobeusedtomaskuserinput.Ifpassword_charisspecifiedandisnotnull,thatcharacterisdisplayedintheeditboxinsteadofthecharactersenteredbytheuser.Theuseofthisattributehasnoeffectonyourapplication'sretrievalofthevalueenteredbytheuser;italtersonlythedisplayofthecharactersintheeditbox.
Foranexampleofusingthepassword_charattributeinanapplication,seeRequestingaPassword.
Pleasesendusyourcommentaboutthispage
Page 811
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
small_increment
small_increment=integer;
Specifiesthevalueusedbytheslider'sincrementalcontrols.Defaultvalueofsmall_incrementisoneone-hundredththetotalrange.Thevaluemustbewithintherangespecifiedbymin_valueandmax_value.Thisattributeisoptional.
Pleasesendusyourcommentaboutthispage
Page 812
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
tabs
tabs="string";
Specifiestheplacementoftabsincharacterwidthunits.Possiblevalueisaquotedstringcontainingintegersorfloating-pointnumbers,separatedbyspaces(nodefault).Thesevaluesareusedforverticallyaligningcolumnsoftextinapopup_listorlist_box.
Forexample,thefollowingcodespecifiesatabstopatevery8characters.
tabs="8162432";
Pleasesendusyourcommentaboutthispage
Page 813
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
tab_truncate
tab_truncate=true-false;
Specifieswhetherthetextinalistboxorpop-uplististruncatedifitislargerthantheassociatedtabstop.Possiblevaluesaretrueorfalse(default:false).
Pleasesendusyourcommentaboutthispage
Page 814
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
value
value="string";
Specifiestheinitialvalueofatile.Possiblevalueisaquotedstring.Themeaningofatile'svaluevariesdependingonthekindoftile.Thevalueofatilecanchangeatruntimethroughuserinputorset_tilecalls.
Thevalueattributeofatileisnotconsideredwhenthedialogboxislaidout.Afterthelayoutisfinishedandthedialogboxhasbeendisplayed,new_dialogusesthevalueattributestoinitializeeachtileinthedialogbox.Atile'svalueattributehasnoeffectonthesizeorspacingoftilesinthedialogbox.
Pleasesendusyourcommentaboutthispage
Page 815
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
width
width=number;
Specifiesthewidthofatile.Possiblevaluesareanintegerorarealnumberrepresentingthedistanceincharacter-widthunits.Donotspecifythisvalueunlesstheassigneddefaultsdon'tprovideacceptableappearance.Youmustspecify,however,thewidthofimagetilesandimagebuttons.
Thewidthofatilespecifiesaminimumwidth.Thisdimensioncanbeexpandedwhenthetileislaidoutunlessthewidthisfixedbyoneofthefixed_attributes.Defaultsaredynamicallyassignedbasedonlayoutconstraints.
Characterwidthunitsaredefinedastheaveragewidthofalluppercaseandlowercasealphabeticcharacters,orthescreenwidthdividedby80,whicheverisless(averagewidthis(width(A..Z)+width(a..z)))/52).
Pleasesendusyourcommentaboutthispage
Page 816
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
FunctionalSynopsisofDCLTiles
ThissectionpresentstheDCLtilesinfunctionalgroupings.PredefinedActiveTilesTileClustersDecorativeandInformativeTilesTextClustersDialogBoxExitButtonsandErrorTilesRestrictedTiles
Pleasesendusyourcommentaboutthispage
Page 817
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
PredefinedActiveTiles
TheAutoCADPDBfeaturehasasetofbuilt-in,orpredefined,tilesthatcanbeusedbythemselvesorasthebasisformorecomplextiles.Theirdefinitionsappearascommentswithinthebase.dclfile.(SeeThebase.dclandacad.dclFiles.)
Whentheuserchoosesanactivetile—abutton,forexample—thedialogboxrespondsbynotifyingtheapplicationcontrollingthedialogbox.Anypredefinedactivetilecanhaveanassociatedaction.Theeffectofanactioncanbevisibletotheuserorcanbepurelyinternal(forexample,astatusupdate).Actionsareaccompaniedbyareasoncodethatindicateswhattriggeredtheaction.Themeaningofthereasondependsonwhichkindoftiletriggeredit.Thefollowingtilesareselectable,activetiles:
button popup_list
edit_box radio_button
image_button slider
list_box toggle
Pleasesendusyourcommentaboutthispage
Page 818
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
TileClusters
Youcangrouptilesintocompositerowsorcolumns(knowncollectivelyasclusters).Forlayoutpurposes,aclusteristreatedasasingletile.Theroworcolumncanbeboxed,withanoptionallabel(aclusterwithoutaboxcannotbelabeled).
Userscannotselectacluster,onlyindividualtileswithinthecluster.Clusterscannothaveactionsassignedtothem,withtheexceptionofradiorowsandradiocolumns.Thefollowingtilesdefineclusters:
boxed_column dialog
boxed_radio_column radio_column
boxed_radio_row radio_row
boxed_row row
column
Pleasesendusyourcommentaboutthispage
Page 819
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
DecorativeandInformativeTiles
Thetileslistedbelowdonotcauseactionsandcannotbeselected.Theyareprovidedtodisplayinformationorforvisualemphasis,ortoassistyouinlayingoutthedialogbox.
image spacer_0
text spacer_1
spacer
Pleasesendusyourcommentaboutthispage
Page 820
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
TextClusters
Atexttileissurroundedbymarginspace(likeanyotherkindoftile),whichpresentsaproblemwhenyouwanttocombinepiecesoftext.Forexample,assumeyouwanttodisplaythefollowingmessage:
Thetimeisnow0800hoursand37seconds.
Theactualvalues(0800and37)aresuppliedbyyourprogram.Youcandothisbycreatingaconcatenatedlineoftextbuiltoutoftext_parttiles.Youcanalsousetextpartsverticallytocreateaparagraphthatdoesn'thavetoomuchspacebetweenthelines.
Thefollowingtextclustertilesareprototypesdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 821
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
DialogBoxExitButtonsandErrorTiles
Thebase.dclfileprovidesstandardbuttonsubassembliesforexiting(or“retiring”)adialogbox.Usethesestandardversionstomaintainaconsistentappearanceacrossapplications.
Youcancustomizethetextinthesebuttonsbyusingtheprototyperetirement_buttonasdescribedinCustomizingExitButtonText.
Pleasesendusyourcommentaboutthispage
Page 822
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>FunctionalSynopsisofDCLTiles>
RestrictedTiles
YourDCLfilesshouldnotusethetilesclusterortile.Also,donotusethebasicexitbuttontypes(cancel_button,help_button,info_button,andok_button)unlessyouredefinethestandardexitbuttonsubassembliesasdescribedinDialogBoxExitButtonsandErrorTiles.
Pleasesendusyourcommentaboutthispage
Page 823
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
DCLTileCatalog
ThissectiondescribesallthepredefinedDCLtiles.Thesyntaxstatement,whichfollowsthetilename,listsalltheattributesassociatedwiththattile.Anyspecificattributefunctionalityisnotedfollowingthetile'sdescription.
Pleasesendusyourcommentaboutthispage
Page 824
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
boxed_column
:boxed_column{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aboxedcolumnhasaborderaroundit.Adialogboxislaidoutlikeaboxedcolumn.Ifaboxedcolumnisassignedalabel,thelabelappearsembeddedinthetopborder.Ifthelabelisabsent,blank(""),ornull(""),onlytheboxisdisplayed.
label
Appearsasatitle.Spacingbetweenablankandanulllabelmightbedifferent.(SeeFixingtheSpacingAroundaBoxedRoworColumn.)
Pleasesendusyourcommentaboutthispage
Page 825
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
boxed_radio_column
:boxed_radio_column{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aboxedradiocolumnhasaborderaroundit.Treatthelabelthesamewaythatyouwouldtreatthelabelofaboxedcolumn.
label
Appearsasatitle.Ifthelabelisabsent,blank(thedefault),ornull(""),onlytheboxappears.Spacingbetweenablankandanulllabelmightbedifferent.(SeeFixingtheSpacingAroundaBoxedRoworColumn.)
value
Specifiesthekeyofthecurrentlyselectedradiobutton(theonewhosevalueis"1").
Pleasesendusyourcommentaboutthispage
Page 826
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
boxed_radio_row
:boxed_radio_row{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aboxedradiorowhasaborderaroundit.Youtreatthelabelthesamewaythatyouwouldtreatthelabelofaboxedrow.
label
Appearsasatitle.Ifthelabelisabsent,blank(thedefault),ornull(""),onlytheboxappears.Spacingbetweenablankandanulllabelmightbedifferent.(SeeFixingtheSpacingAroundaBoxedRoworColumn.)
value
Specifiesthekeyofthecurrentlyselectedradiobutton(theonewhosevalueis"1").
Pleasesendusyourcommentaboutthispage
Page 827
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
boxed_row
:boxed_row{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aboxedrowhasaborderaroundit.Ifaboxedrowhasalabel,thelabelappearsembeddedinit.
label
Appearsasatitle.Ifthelabelisabsent,blank(thedefault),ornull(""),onlytheboxappears.Spacingbetweenablankandanulllabelmightbedifferent.(SeeFixingtheSpacingAroundaBoxedRoworColumn.)
Pleasesendusyourcommentaboutthispage
Page 828
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
button
:button{
action alignment fixed_height fixed_widthheight is_cancel is_default is_enabledis_tab_stop key label mnemonic width}
Abuttontileresemblesapushbutton.Thebutton'slabelspecifiestextthatappearsinsidethebutton.Buttonsareappropriateforactionsthatareimmediatelyvisibletotheusersuchasleavingthedialogbox,orgoingintoasubdialogbox.
DialogboxesmustincludeanOKbutton(oritsequivalent)fortheusertopressafterusing(orreading)thebox.ManydialogboxesalsoincludeaCancelbuttonthatenablestheusertoleavethedialogboxwithoutmakinganychanges.
DialogboxesshouldusethestandardexitbuttonsubassembliesdescribedinDialogBoxExitButtonsandErrorTiles.Thesesubassembliesguaranteethattheattributesdescribedinthissectionarecorrectlyassigned.
Note Ifyoumakethedefaultbuttonandthecancelbuttonthesame,youmustmakesureatleastoneotherexitbuttonisassociatedwithanactionthatcallsdone_dialog.Otherwise,thedialogboxisalwayscanceled.
label
Specifiesthetextthatappearsinthebutton.
Pleasesendusyourcommentaboutthispage
Page 829
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
column
:column{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
TilesinacolumnarelaidoutverticallyintheorderinwhichtheyappearintheDCLfile.Acolumncancontainanykindoftile(exceptforsolitaryradiobuttons),includingrowsandothercolumns.
Acolumnwithoutaboxhasnoadditionalattributesbeyondthestandardlayoutattributes.
Pleasesendusyourcommentaboutthispage
Page 830
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
concatenation
:concatenation{
}
Aconcatenationisalineoftextmadeupofmultiple,concatenatedtext_parttiles.Thisisusefulwhenyouwanttoinserttextthatcanchangeatruntimeintoastandardmessage.Thereisamarginaroundtheconcatenationasawhole.
Theconcatenationtileisdefinedinthebase.dclfile.Seeparagraphforanexamplethatusesconcatenation.
Pleasesendusyourcommentaboutthispage
Page 831
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
dialog
:dialog{
initial_focus label value}
Adialogisthetilethatdefinesthedialogbox.Youshouldnotspecifybothalabelandvalueattribute:thevalueattributeoverridesthelabelattribute.
label
Specifiestheoptionaltitledisplayedinthetitlebarofthedialogbox.
value
Specifiesastringtodisplayastheoptionaldialogboxtitle.However,thevalueisn'tinspectedatlayouttime,soifyouassignthetitlethisway,makesurethedialogboxiswideenoughorthetextmightbetruncated.Foradialog,thelabelandvalueareequivalentexceptforlayoutconsiderations.Tochangethetitle(seeinatruntime,usetheset_tilefunctiontheAutoLISPReference).
initial_focus
Specifiesthekeyofthetilethatreceivestheinitialkeyboardfocus.
Pleasesendusyourcommentaboutthispage
Page 832
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
edit_box
:edit_box{
action alignment allow_accept edit_limit edit_width fixed_height fixed_width height is_enabled is_tab_stop key label mnemonic value width password_char}
Aneditboxisafieldthatenablestheusertoenteroreditasinglelineoftext.Anoptionallabelcanappeartotheleftofthebox.Iftheenteredtextislongerthanthelengthoftheeditbox,theeditboxscrollshorizontally.
Left-justifyingthelabelandright-justifyingtheeditboxmakesiteasiertoalignedit_boxtilesvertically.
label
Appearsasatitle.Ifspecified,thelabelisleft-justifiedwithinthewidthoftheedit_boxtile.
value
TheinitialASCIIvalueplacedinthebox.Itisdisplayedleft-justifiedwithintheedit(input)partofthebox.Thevalueofaneditboxisterminatedbythenullcharacter.Iftheuserentersmorecharactersthantheedit_limitandthestringistruncated,thenullcharacterisappended.
Pleasesendusyourcommentaboutthispage
Page 833
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
errtile
errtile;
Anerrortileisatexttilethatappearsatthebottomofadialogbox.Bydefaultitisblank,butprogramscandisplaymessagesinitbysettingthevalueofthetilewhosekeyis"error".Forexample:
(set_tile"error""Youcanonlyselectoneoption")
Theerrtiletileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 834
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
image
:image{
action alignment aspect_ratio color fixed_height fixed_width height is_enabled is_tab_stop key mnemonic value width}
Animageisarectangleinwhichavectorgraphicpictureisdisplayed.Imagesareusedtodisplayicons,linetypes,textfonts,andcolorpatchesinAutoCADdialogboxes.SeeCreatingImagesforinstructionsonhowtogenerateimagesforimagetiles.
Youmustassignanimagetileeitheranexplicitwidthandheightattribute,oroneofthoseattributesplusanaspect_ratio.
Pleasesendusyourcommentaboutthispage
Page 835
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
image_button
:image_button{
action alignment allow_accept aspect_ratio color fixed_height fixed_width height is_enabled is_tab_stop key mnemonic width}
Theimagebuttontileisabuttonthatdisplaysagraphicimageratherthanalabel.
Whentheuserselectsanimagebutton,theprogramobtainsthecoordinatesofthepointthatwasselected.Thisisusefulifyouwanttodisplayaminiaturedrawingandassigndifferentmeaningstoselectingdifferentregionsinit.
SeeCreatingImagesforinstructionsonhowtogenerateimagesforimagebuttons.
Youmustassignanimagebuttoneitheranexplicitwidthandheightattribute,oroneofthoseattributesplusanaspect_ratio.
Pleasesendusyourcommentaboutthispage
Page 836
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
list_box
:list_box{
action alignment allow_accept fixed_height fixed_width height is_enabled is_tab_stop key label list mnemonic multiple_selecttabsvalue width}
Alistboxcontainsalistoftextstrings,arrangedinrows.Usuallythelistisofvariablelength,butlistboxescanbeusedforfixed-lengthlistswhenadifferentkindoftile,suchasasetofradiobuttons,takesuptoomuchspaceinthedialogbox.Whenusersselectarow,itishighlighted.Alistboxcancontainmorerowsthancanfitinthebox,soascrollbaralwaysappearstotherightofthelistbox.(Thescrollbarisenabledonlyifthelisthasmoreitemsthancanappearatonce.)Bydraggingthescrollbarcursororclickingonitsarrows,userscanscrollthroughthelistboxitems.Someapplicationsmayallowuserstoselectmultiplerows.
SeeListBoxesandPop-UpListsforinstructionsonhowtomanagelistsforlistboxesandpop-uplists.
Note Thelist_listtileislimitedto32,768entrieswiththefirstelementbeinganindexof0andthelastbeing32,767.Oncethelimitisreached,thevalueofany
Page 837
entrythathasanindexgreaterthan32,767isnotaccuratelyreported.
label
Textdisplayedabovethelistbox.
value
Aquotedstringcontainingzero("")ormoreintegers,separatedbyspaces(nodefault).Eachintegerisazero-basedindexthatindicatesalistitemthatisinitiallyselected.Ifmultiple_selectisfalse,valuecannotcontainmorethanoneinteger.Ifthevaluestringisempty(""),thennoitemsinthelistareinitiallyselected.Inthiscase,youdon'tneedtospecifythevalueattributeatall.
Pleasesendusyourcommentaboutthispage
Page 838
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ok_only
ok_only;
Theok_onlytileisasolitaryOKbutton,suchasthekindthatalertboxesuse.ThekeyoftheOKbuttonis"accept".
Theok_onlytileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 839
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ok_cancel
ok_cancel;
Theok_canceltileisacombinationoftheOKandCancelbuttons,andisthestandardcombinationfordialogboxesthatcanoriginatechangestodata.ThekeyoftheCancelbuttonis"cancel".
Theok_canceltileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 840
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ok_cancel_help
ok_cancel_help;
Thistileistheok_cancelclustercombinedwiththeHelpbutton.ThekeyoftheHelpbuttonis"help".Helpbuttonsarerecommendedforthemaindialogboxofanapplicationandforcomplexdialogboxes.ThefunctionthathandlestheHelpbuttoncandisplaythestandardAutoCADHelpdialogboxbyinvokingtheAutoLISPhelpfunction.
Theok_cancel_helptileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 841
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ok_cancel_help_errtile
ok_cancel_help_errtile;
Theok_cancel_help_errtiletileprovidesaconvenientwaytospecifytheexitbuttonsanderrortileallatonce.
Theok_cancel_help_errtiletileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 842
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ok_cancel_help_info
ok_cancel_help_info;
Theok_cancel_help_infotiledoeseverythingthattheok_cancel_helptiledoes,butitalsoincludesaninformationbuttonfordisplayingadditionalmaterial.Itmightdisplaythenameofyourapplication,thelogoofyourfirm,theapplication'sversionnumber,howtoobtainsupport,andsoon.ThekeyoftheInfobuttonis"info".
Theok_cancel_help_infotileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 843
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
paragraph
:paragraph{
}
Aparagraphisaclusteroftext_partorconcatenationtilesthatarearrangedvertically.Youcanconstructparagraphsofrunningtexteitherstaticallyoratruntime.Thereisamarginaroundtheparagraphasawhole.
Theparagraphtileisdefinedinthebase.dclfile.
TheillustrationabovewasgeneratedwiththefollowingDCL:
:paragraph
{
:concatenation
{
:text_part
{
label="One";
}
:text_part
{
label="goodturn";
}
}
:text_part{
label="Deservesanother";
}
}
Pleasesendusyourcommentaboutthispage
Page 844
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
popup_list
:popup_list{
action alignment edit_width fixed_height fixed_width height is_enabled is_tab_stop key label list mnemonictabs value width}
Apop-uplist,orsimplypop-up,isfunctionallyequivalenttoalistbox.Whenadialogboxisfirstdisplayed,thepop-upisinacollapsedstateandlookslikeabuttonexceptforthedownward-pointingarrowontheright.Whentheuserselectsthetextorthearrow,thelistpopsupanddisplaysmoreselections.Apop-uplisthasascrollbarontherightthatworkslikethescrollbarofalistbox.Whenapop-uplistiscollapsed,thecurrentselectionappearsinitsdisplayfield.Pop-uplistsdonotallowmultipleselection.
SeeListBoxesandPop-UpListsforinstructionsonhowtomanagelistsforlistboxesandpop-uplists.
Note Thepopup_listtileislimitedto32,768entrieswiththefirstelementbeinganindexof0andthelastbeing32,767.Oncethelimitisreached,thevalueof
Page 845
anyentrythathasanindexgreaterthan32,767isnotaccuratelyreported.
label
Appearsasatitletotheleftofthepop-uplist.Ifspecified,thelabelisleftjustifiedwithinthewidthofthepopup_listtile.
edit_width
Specifiesthewidthofthetextportionofthelistincharacter-widthunits.Itdoesn'tincludetheoptionallabelontheleftorthepop-uparrow(orscrollbar)ontheright.Ifedit_widthisn'tspecifiedoriszero,andthewidthofthetileisn'tfixed,theboxexpandstofilltheavailablespace.Possiblevalueisanintegerorarealnumber.Ifedit_widthisnonzero,thentheboxisright-justifiedwithinthespaceoccupiedbythetile.Ifitisnecessarytostretchthetileforlayoutpurposes,thePDBfeatureinsertswhitespacebetweenthelabelandtheeditportionofthebox.
value
Aquotedstringcontaininganinteger(default:"0").Theintegerisazero-basedindexthatindicatesthecurrentlyselectediteminthelist(theonethatisdisplayedwhenthelistisn'tpoppedup).
Pleasesendusyourcommentaboutthispage
Page 846
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
radio_button
:radio_button{
action alignment fixed_height fixed_width height is_enabled is_tab_stop key label mnemonic value width}
Aradiobuttonisoneofagroupofbuttonscomposingaradiocolumnorradiorow.Theseworklikethebuttonsonacarradio:onlyonecanbeselectedatatime,andwhenoneispressed,anyotherbuttoninthecolumn(orrow)thatisonisturnedoff.Anoptionallabelappearstotherightoftheradiobutton.ThePDBfeaturereportsanerrorifyouattempttoplacearadiobuttonoutsidearadiocolumnorradiorow.
label
Thetextdisplayedtotherightoftheradiobutton.
value
Aquotedstring(nodefault).Ifthevalueis"1",theradio_buttonison;ifitis"0",theradio_buttonisoff;allothervaluesareequivalentto"0".Ifbysomechancemorethanoneradio_buttoninaradioclusterhasvalue="1",onlythelastoneisturnedon.(ThiscanhappeninaDCLfile.Oncethedialogboxstarts,thePDBfeaturemanagesradiobuttonsandensuresthatonlyoneperclusteristurnedonatatime.)
Pleasesendusyourcommentaboutthispage
Page 847
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
radio_column
:radio_column{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aradiocolumncontainsradiobuttontiles,onlyoneofwhichcanbeselectedatatime.Radiocolumnspresenttheuserwithafixedsetofmutuallyexclusivechoices.Radiocolumns,unlikeordinarycolumns,canbeassignedanaction.
value
Aquotedstringcontainingthekeyofthecurrentlyselectedradiobutton(theonewhosevalueis"1").
Pleasesendusyourcommentaboutthispage
Page 848
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
radio_row
:radio_row{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
Aradiorow,likearadiocolumn,containsradiobuttontiles,onlyoneofwhichcanbeselectedatatime.Radiorowscanbeassignedanaction.
value
Aquotedstringcontainingthekeyofthecurrentlyselectedradiobutton(theonewhosevalueis"1").
Note Radiorowsarenotaseasytouseasradiocolumns,becausethemousehastotravelfarther.Useradiorowsonlyiftheyspecifytwotofouroptions,orifthelabelsareshort.
Pleasesendusyourcommentaboutthispage
Page 849
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
row
:row{
alignment children_alignment children_fixed_height children_fixed_width fixed_height fixed_width height label width}
TilesinarowarelaidouthorizontallyintheorderinwhichtheyappearintheDCLfile.Arowcancontainanykindoftile.
Arowwithoutaboxhasnoadditionalattributesbeyondthestandardlayoutattributes.
Pleasesendusyourcommentaboutthispage
Page 850
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
slider
:slider{
action alignment big_increment fixed_height fixed_width height key label layout max_value min_value mnemonic small_increment value width}
Asliderobtainsanumericvalue.Theusercandragtheslider'sindicatortotheleftorright(orupordown)toobtainavaluewhosemeaningdependsontheapplication.Thisvalueisreturnedasastringcontainingasignedintegerwithinaspecifiedrange(theintegerisa16-bitvalue,sothemaximumrangeis-32,768to32,767).Theapplicationcanscalethisvalueasrequired.
value
Aquotedstringthatcontainsthecurrent(integer)valueoftheslider(default:min_value).
Pleasesendusyourcommentaboutthispage
Page 851
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
text
:text{
alignment fixed_height fixed_width height is_bold key label value width}
Atexttiledisplaysatextstringfortitlingorinformationalpurposes.
Becausemosttileshavetheirownlabelattributefortitlingpurposes,youdon'talwaysneedtousetexttiles.Butatexttilethatyouusuallykeepblankisausefulwaytodisplayfeedbackaboutuseractions,errormessages,orwarnings.
AlertboxesanderrortilesarediscussedinDialogBoxExitButtonsandErrorTilesandDCLErrorHandling.
Ifyouintendthemessagetobestatic,specifyitinthelabelattributeanddon'tspecifyawidthorvalue.Ifyouintendthemessagetochangeatrun-time,specifyitinthevalueattributeandassignawidthlongenoughtocontainanystringsthatyouplantoassignthevalue.Oncethedialogboxislaidout,thesizeofitstilescan'tchange,soifyouuseset_tiletoassignastringlongerthanthewidth,thedisplayedtextistruncated.
label
Thedisplayedtext.Whenatexttileislaidout,itswidthisthelargerofeitheritswidthattribute,ifthatisspecifiedintheDCL,orthewidthrequiredbyitslabelattribute,ifspecified.Atleastoneoftheseattributesmustbespecified.
value
Likelabel,thevalueattributespecifiesastringtodisplayinthetexttile.However,ithasnoeffectonthetile'slayout.
Page 852
Pleasesendusyourcommentaboutthispage
Page 853
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
text_part
:text_part{
label
}
Atextpartisatexttilethatispartofalargerpieceoftext.Themarginsofatext_partaresuppressed,soitcanbecombinedwithothertext_partsintoaconcatenationorparagraphtile.
Thetext_parttileisdefinedinthebase.dclfile.Seeparagraphforanexamplethatusestext_part.
Pleasesendusyourcommentaboutthispage
Page 854
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
toggle
:toggle{
action alignment fixed_height fixed_width height is_enabled is_tab_stop label width}
AtogglecontrolsaBooleanvalue("0"or"1").Atoggleappearsasasmallboxwithanoptionallabeltotherightofthebox.AcheckmarkorXappears(ordisappears)whentheuserselectsthebox.Togglesenabletheusertovieworchangethestateofon/offoptions.Togglesarealsoknownascheckboxes.
label
Thetextdisplayedtotherightofthetogglebox.
value
Aquotedstringcontaininganinteger(default:"0")andspecifyingtheinitialstateofthetoggle.Ifthestringis"0",thetoggleboxisblank(withoutacheckmark).Ifitis"1",theboxcontainsacheckmark(oranX).
Pleasesendusyourcommentaboutthispage
Page 855
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
spacer
:spacer{
alignment fixed_height fixed_width height width}
Aspacerisablanktile.Itisusedonlyforlayoutpurposestoaffectthesizeandlayoutofadjacenttiles.Toensureconsistencywithotherdialogboxes,usespacertilesonlyinspecialcases,becausethePDBfeaturehandlesspacingautomatically.SeeAdjustingtheLayoutofDialogBoxes.
Thespacertilehasnoadditionalattributesbeyondthestandardlayoutattributes.
Pleasesendusyourcommentaboutthispage
Page 856
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
spacer_0
spacer_0;
Aspacer_0,demonstratedinthefollowingfigure,isaspacerthatnormallyhasnowidth.However,itindicatesapointinatilegroupwhereyouwantspacetobeinserted,ifthegrouphastobestretchedduringlayout.Ifthespacer_0tilesinagroupareassignedapositivewidth,allofthemareassignedanequalshareofthespacing.
Thespacer_0tileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 857
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
spacer_1
spacer_1;
Thespacer_1tile,demonstratedinthefollowingfigure,isaspacerwhosewidthandheightbothequalone.Itisusedforthesmallestkindofspacerthatwillstillbeobvioustotheuser.
Thespacer_1tileisdefinedinthebase.dclfile.
Pleasesendusyourcommentaboutthispage
Page 858
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>
ProgrammableDialogBoxFunctionSynopsis
Theprogrammabledialogboxfunctionsperformdialogboxopeningandclosing,tileandattributehandling,listboxandpop-uplisthandling,imagetilehandling,andapplication-specificdatahandling.ThissectionlistseachPDBfunctionavailableinVisualLISP,groupingthembythetypeoftaskeachperforms.Fordetailedinformationonthesefunctions,seetheAutoLISPReference.
DialogBoxOpeningandClosingFunctionsTile-andAttribute-HandlingFunctionsListBoxandPop-UpList-HandlingFunctionsImageTile-HandlingFunctionsApplication-SpecificData-HandlingFunction
Pleasesendusyourcommentaboutthispage
Page 859
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>ProgrammableDialogBoxFunctionSynopsis>
DialogBoxOpeningandClosingFunctions
ThefollowingtableprovidessummarydescriptionsoftheDCLopeningandclosingfunctions.
Dialogboxopeningandclosingfunctions
Functionname Description
(done_dialog[status]) Terminatesadialogbox
(load_dialogdclfile) LoadsaDCLfile
(new_dialogdlgnamedcl_id[action[screen-pt]])
Beginsanewdialogboxanddisplaysit,andcanalsospecifyadefaultaction
(start_dialog) Displaysadialogboxandbeginsacceptinguserinput
(term_dialog) Terminatesallcurrentdialogboxesasiftheusercancelseachofthem
(unload_dialogdcl_id) UnloadsaDCLfile
Page 860
Pleasesendusyourcommentaboutthispage
Page 861
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>ProgrammableDialogBoxFunctionSynopsis>
Tile-andAttribute-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheDCLtile-andattribute-handlingfunctions.
Tile-andattribute-handlingfunctions
Functionname Description
(action_tilekeyaction-expression) Assignsanactiontoevaluatewhentheuserselectsthespecifiedtileinadialogbox
(get_attrkeyattribute) RetrievestheDCLvalueofadialogboxattribute
(get_tilekey) Retrievesthecurrentruntimevalueofadialogboxtile
(mode_tilekeymode) Setsthemodeofadialogboxtile
(set_tilekeyvalue) Setsthevalueofadialogboxtile
Pleasesendusyourcommentaboutthispage
Page 862
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>ProgrammableDialogBoxFunctionSynopsis>
ListBoxandPop-UpList-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheDCLlistboxandpop-uplist-handlingfunctions.
Listboxandpop-uplist-handlingfunctions
Functionname Description
(add_liststring) Addsormodifiesastringinthecurrentlyactivedialogboxlist
(end_list) Endsprocessingofthecurrentlyactivedialogboxlist
(start_listkey[operation[index]])
Startstheprocessingofalistinthelistboxorinthepop-uplistdialogboxtile
Pleasesendusyourcommentaboutthispage
Page 863
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>ProgrammableDialogBoxFunctionSynopsis>
ImageTile-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheDCLimagetile-handlingfunctions.
Imagetile-handlingfunctions
Functionname Description
(dimx_tilekey)and(dimy_tilekey)
Retrievesthedimensionsofatileindialogboxunits
(end_image) Endscreationofthecurrentlyactivedialogboximage
(fill_imagex1y1widhgtcolor) Drawsafilledrectangleinthecurrentlyactivedialogboximagetile
(slide_imagex1y1widhgtsldname)
DisplaysanAutoCADslideinthecurrentlyactivedialogboximagetile
(start_imagekey) Startsthecreationofanimageinthedialogboxtile
(vector_imagex1y1x2y2color) Drawsavectorinthecurrentlyactivedialogboximage
Page 864
Pleasesendusyourcommentaboutthispage
Page 865
AutoLISPDeveloper'sGuide>WorkingwithProgrammableDialogBoxes>ProgrammableDialogBoxReference>ProgrammableDialogBoxFunctionSynopsis>
Application-SpecificData-HandlingFunction
ThefollowingtableprovidesasummarydescriptionoftheDCLapplication-specificdata-handlingfunction.
Application-specificdata-handlingfunction
Functionname Description
(client_data_tilekeyclientdata) Associatesapplication-manageddatawithadialogboxtile
Pleasesendusyourcommentaboutthispage
Page 866
AutoLISPDeveloper'sGuide>
Appendixes
AutoLISPFunctionSynopsisFunctionsarecategorizedanddescribed.VisualLISPEnvironmentandFormattingOptionsColor-codingoptions,diagnosticoptions,andpagelayoutoptionsaredescribed.AutoLISPErrorCodesTheerrorcodesgeneratedbyAutoLISParedescribed.
Pleasesendusyourcommentaboutthispage
Page 867
AutoLISPDeveloper'sGuide>Appendixes>
AutoLISPFunctionSynopsis
Functionsarecategorizedanddescribed.
Tofindafunctionwithoutknowingitsname,usethelistingsinthisappendix.TheAutoLISP®functionsinthissynopsisareorganizedintofunctionalgroups,andlistedalphabeticallywithineachfunctiongroup.Eachfunctionisbrieflydescribedbyitssignatureandasinglesentenceindicatingthefunction'spurpose.
CategorySummaryBasicFunctionsUtilityFunctionsSelectionSet,Object,andSymbolTableFunctionsMemoryManagementFunctionsVisualLISPExtensionstoAutoLISPReactorFunctionsVLXNamespaceFunctionsNamespaceCommunicationFunctionsWindowsRegistryFunctions
Pleasesendusyourcommentaboutthispage
Page 868
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
CategorySummary
Functionsinthissynopsisareorganizedintothefollowingcategories:
Basic:Application-handling,arithmetic,equalityandconditional,error-handling,function-handling,listmanipulation,string-handling,andsymbol-handlingfunctions
Utility:Conversion,deviceaccess,displaycontrol,file-handling,geometric,queryandcommand,anduserinputfunctions
SelectionSet,Object,andSymbolTable:Extendeddata-handling,object-handling,selectionsetmanipulation,andsymboltable-handlingfunctions
MemoryManagement
VisualLISPExtensionstoAutoLISP:Collectionmanipulation,curvemeasurement,dataconversion,dictionary-handling,object-handling,andproperty-handlingfunctions
Reactor
VLXNamespace:Functionexposure,documentnamespacevariableaccess,anderror-handlingfunctions
NamespaceCommunication:Blackboard-addressingandmulti-documentloadingfunctions
WindowsRegistryHandling
NotethatprogrammabledialogboxfunctionsarelistedintheProgrammableDialogBoxFunctionSynopsissectionofthismanual.
Functionsaregroupedbydatatypeandbytheactiontheyperform.DetailedinformationoneachVisualLISP®functionisprovidedinthealphabeticallistingsintheAutoLISPReference.
Page 869
Notethatanyfunctionsnotdescribedhereorinotherpartsofthedocumentationarenotofficiallysupportedandaresubjecttochangeinfuturereleases.
BasicFunctions
Application-HandlingFunctions
Application-HandlingFunctions
ArithmeticFunctions ArithmeticFunctions
EqualityandConditionalFunctions
EqualityandConditionalFunctions
Error-HandlingFunctions Error-HandlingFunctions
Function-HandlingFunctions Function-HandlingFunctions
ListManipulationFunctions ListManipulationFunctions
String-HandlingFunctions String-HandlingFunctions
Symbol-HandlingFunctions Symbol-HandlingFunctions
UtilityFunctions
ConversionFunctions Conversion
Page 870
Functions
DeviceAccessFunctions DeviceAccessFunctions
DisplayControlFunctions DisplayControlFunctions
File-HandlingFunctions File-HandlingFunctions
GeometricFunctions GeometricFunctions
QueryandCommandFunctions
QueryandCommandFunctions
UserInputFunctions UserInputFunctions
SelectionSet,Object,andSymbolTableFunctions
ExtendedData-HandlingFunctions
ExtendedData-HandlingFunctions
Object-HandlingFunctions Object-HandlingFunctions
SelectionSetManipulationFunctions
SelectionSetManipulationFunctions
SymbolTableandDictionary-HandlingFunctions
SymbolTableandDictionary-
Page 871
HandlingFunctions
MemoryManagementFunctions
MemoryManagementFunctions
VisualLISPAutoLISPExtensions
ActiveXCollectionManipulationFunctions
ActiveXCollectionManipulationFunctions
ActiveXDataConversionFunctions
ActiveXDataConversionFunctions
ActiveXMethodInvocationFunctions
ActiveXMethodInvocationFunctions
ActiveXObject-HandlingFunctions
ActiveXObject-HandlingFunctions
ActiveXProperty-HandlingFunctions
ActiveXProperty-HandlingFunctions
CurveMeasurementFunctions CurveMeasurementFunctions
DictionaryFunctions Dictionary
Page 872
Functions
FunctionsforHandlingDrawingObjects
FunctionsforHandlingDrawingObjects
ReactorFunctions ReactorFunctions
VLXNamespaceFunctions VLXNamespaceFunctions
NamespaceCommunicationFunctions
NamespaceCommunicationFunctions
WindowsRegistryFunctions WindowsRegistryFunctions
Pleasesendusyourcommentaboutthispage
Page 873
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
BasicFunctions
Thebasicfunctionsconsistofthearithmetic,string-handling,equalityandconditional,listmanipulation,symbol-handling,function-handling,error-handling,andapplication-handlingfunctions.
Application-HandlingFunctionsArithmeticFunctionsEqualityandConditionalFunctionsError-HandlingFunctionsFunction-HandlingFunctionsListManipulationFunctionsString-HandlingFunctionsSymbol-HandlingFunctions
Pleasesendusyourcommentaboutthispage
Page 874
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
Application-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPapplication-handlingfunctions.
Application-handlingfunctions
Function Description
(arx) ReturnsalistofthecurrentlyloadedObjectARXapplications
(arxloadapplication[onfailure])
LoadsanObjectARXapplication
(arxunloadapplication[onfailure])
UnloadsanObjectARXapplication
(autoarxloadfilenamecmdlist)
PredefinescommandnamestoloadanassociatedObjectARXfile
(autoloadfilenamecmdlist)
PredefinescommandnamestoloadanassociatedAutoLISPfile
(initdia[dialogflag]) Forcesthedisplayofthenextcommand'sdialogbox
Page 875
(loadfilename[onfailure])
EvaluatestheAutoLISPexpressionsinafile
(startappappcmdfile) StartsaWindowsapplication
(vl-load-allfilename) LoadsafileintoallopenAutoCADdocuments
(vl-vbaload“filename”)
LoadsaVBAproject
(vl-vbarun“macroname”)
RunsaVBAmacro
(vlax-add-cmd“global-name”'func-sym[“local-name”cmd-flags])
AddscommandstotheAutoCADbuilt-incommandset
Note VLISPextension:requiresvl-load-com
Pleasesendusyourcommentaboutthispage
Page 876
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
ArithmeticFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISParithmeticfunctions.
Arithmeticfunctions
Function Description
(+(add)[numbernumber]...)
Returnsthesumofallnumbers
(-(subtract)[numbernumber]...)
Subtractsthesecondandfollowingnumbersfromthefirstandreturnsthedifference
(*(multiply)[numbernumber]...)
Returnstheproductofallnumbers
(/(divide)[numbernumber]...)
Dividesthefirstnumberbytheproductoftheremainingnumbersandreturnsthequotient
(~(bitwiseNOT)int)
ReturnsthebitwiseNOT(1'scomplement)oftheargument
Page 877
(1+(increment)number)
Returnstheargumentincreasedby1(incremented)
(1-(decrement)number)
Returnstheargumentreducedby1(decremented)
(absnumber) Returnstheabsolutevalueoftheargument
(atannum1[num2]) Returnsthearctangentofanumberinradians
(cosang) Returnsthecosineofanangleexpressedinradians
(expnumber) Returnstheconstante(areal)raisedtoaspecifiedpower(thenaturalantilog)
(exptbasepower) Returnsanumberraisedtoaspecifiedpower
(fixnumber) Returnstheconversionofarealintothenearestsmallerinteger
(floatnumber) Returnstheconversionofanumberintoareal
(gcdint1int2) Returnsthegreatestcommondenominatoroftwointegers
(lognumber) Returnsthenaturallogof
Page 878
anumberasareal
(logand[intint...]) ReturnstheresultofthelogicalbitwiseANDofalistofintegers
(logior[intint...]) ReturnstheresultofthelogicalbitwiseinclusiveORofalistofintegers
(lsh[intnumbits]) Returnsthelogicalbitwiseshiftofanintegerbyaspecifiednumberofbits
(max[numbernumber...])
Returnsthelargestofthenumbersgiven
(min[numbernumber...])
Returnsthesmallestofthenumbersgiven
(minuspnumber) Verifiesthatanumberisnegative
(rem[num1num2...])
Dividesthefirstnumberbythesecond,andreturnstheremainder
(sinang) Returnsthesineofanangleasarealexpressedinradians
(sqrtnumber) Returnsthesquarerootofanumberasareal
(zeropnumber) Verifiesthatanumberevaluatestozero
Page 879
Pleasesendusyourcommentaboutthispage
Page 880
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
EqualityandConditionalFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPequalityandconditionalfunctions.
Equalityandconditionalfunctions
Function Description
(=(equalto)numstr[numstr]...)
ReturnsTifallargumentsarenumericallyequal,andreturnsnilotherwise
(/=(notequalto)numstr[numstr]...)
ReturnsTiftheargumentsarenotnumericallyequal,andniliftheargumentsarenumericallyequal
(<(lessthan)numstr[numstr]...)
ReturnsTifeachargumentisnumericallylessthantheargumenttoitsright,andreturnsnilotherwise
(<=(lessthanorequalto)numstr[numstr]...)
ReturnsTifeachargumentisnumericallylessthanorequaltotheargumenttoitsright,and
Page 881
returnsnilotherwise
(>(greaterthan)numstr[numstr]...)
ReturnsTifeachargumentisnumericallygreaterthantheargumenttoitsright,andreturnsnilotherwise
(>=(greaterthanorequalto)numstr[numstr]...)
ReturnsTifeachargumentisnumericallygreaterthanorequaltotheargumenttoitsright,andreturnsnilotherwise
(and[expr...]) ReturnsthelogicalANDofalistofexpressions
(Boolefuncint1[int2...])
ServesasageneralbitwiseBooleanfunction
(cond[(testresult...)...])
ServesastheprimaryconditionalfunctionforAutoLISP
(eqexpr1expr2) Determineswhethertwoexpressionsareidentical
(equalexpr1expr2[fuzz])
Determineswhethertwoexpressionsareequal
(iftestexprthenexpr[elseexpr])
Conditionallyevaluatesexpressions
(or[expr...]) ReturnsthelogicalORofalistofexpressions
(repeatint[expr...]) Evaluateseachexpressionaspecified
Page 882
numberoftimes,andreturnsthevalueofthelastexpression
(whiletestexpr[expr...])
Evaluatesatestexpression,andifitisnotnil,evaluatesotherexpressions;repeatsthisprocessuntilthetestexpressionevaluatestonil
Pleasesendusyourcommentaboutthispage
Page 883
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
Error-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPerror-handlingfunctions.
Error-handlingfunctions
Function Description
(alertstring) Displaysanalertdialogboxwiththeerrororwarningmessagepassedasastring
(*error*string) Auser-definableerror-handlingfunction
(exit) Forcesthecurrentapplicationtoquit
(quit) Forcesthecurrentapplicationtoquit
(vl-catch-all-apply'functionlist)
Passesalistofargumentstoaspecifiedfunctionandtrapsanyexceptions
(vl-catch-all-error-messageerror-obj)
Returnsastringfromanerrorobject
Page 884
(vl-catch-all-error-parg)
Determineswhetheranargumentisanerrorobjectreturnedfromvl-catch-all-apply
Pleasesendusyourcommentaboutthispage
Page 885
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
Function-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPfunction-handlingfunctions.
Function-handlingfunctions
Function Description
(applyfunctionlst) Passesalistofargumentstoaspecifiedfunction
(defunsym([arguments][/variables...])expr...)
Definesafunction
(defun-qsym([arguments][/variables...])expr...)
Definesafunctionasalist(intendedforbackward-compatibilityonly)
(defun-q-list-ref'function)
Displaystheliststructureofafunctiondefinedwithdefun-q
(defun-q-list-set'symlist)
Definesafunctionasalist(intendedforbackward-compatibilityonly)
Page 886
(evalexpr) ReturnstheresultofevaluatinganAutoLISPexpression
(lambdaargumentsexpr...)
Definesananonymousfunction
(progn[expr]...) Evaluateseachexpressionsequentially,andreturnsthevalueofthelastexpression
(tracefunction...) AidsinAutoLISPdebugging
(untracefunction...)
Clearsthetraceflagforthespecifiedfunctions
Pleasesendusyourcommentaboutthispage
Page 887
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
ListManipulationFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPlistmanipulationfunctions.
Listmanipulationfunctions
Function Description
(acad_strlsortlst) Sortsalistofstringsbyalphabeticalorder
(appendlst...) Takesanynumberoflistsandrunsthemtogetherasonelist
(associtemalist) Searchesanassociationlistforanelementandreturnsthatassociationlistentry
(carlst) Returnsthefirstelementofalist
(cdrlst) Returnsthespecifiedlist,exceptforthefirstelementofthelist
Page 888
(consnew-first-elementlst)
Thebasiclistconstructor
(foreachnamelst[expr...])
Evaluatesexpressionsforallmembersofalist
(lastlst) Returnsthelastelementinalist
(lengthlst) Returnsanintegerindicatingthenumberofelementsinalist
(list[expr...]) Takesanynumberofexpressionsandcombinesthemintoonelist
(listpitem) Verifiesthatanitemisalist
(mapcarfunctionlist1...listn)
Returnsalistoftheresultofexecutingafunctionwiththeindividualelementsofalistorlistssuppliedasargumentstothefunction
(memberexprlst) Searchesalistforanoccurrenceofanexpressionandreturnstheremainderofthelist,startingwiththefirstoccurrenceoftheexpression
Page 889
(nthnlst) Returnsthenthelementofalist
(reverselst) Returnsalistwithitselementsreversed
(substnewitemolditemlst)
Searchesalistforanolditemandreturnsacopyofthelistwithanewitemsubstitutedinplaceofeveryoccurrenceoftheolditem
(vl-consplist-variable) Determineswhetherornotalistisnil
(vl-everypredicate-functionlist[more-lists]...)
Checkswhetherthepredicateistrueforeveryelementcombination
(vl-list*object[more-objects]...)
Constructsandreturnsalist
(vl-list->stringchar-codes-list)
Combinesthecharactersassociatedwithalistofintegersintoastring
(vl-list-lengthlist-or-cons-object)
Calculateslistlengthofatruelist
(vl-member-ifpredicate-functionlist)
Determineswhetherthepredicateistrueforoneofthelistmembers
Page 890
(vl-member-if-notpredicate-functionlist)
Determineswhetherthepredicateisnilforoneofthelistmembers
(vl-positionsymbollist) Returnstheindexofthespecifiedlistitem
(vl-removeelement-to-removelist)
Removeselementsfromalist
(vl-remove-ifpredicate-functionlist)
Returnsallelementsofthesuppliedlistthatfailthetestfunction
(vl-remove-if-notpredicate-functionlist)
Returnsallelementsofthesuppliedlistthatpassthetestfunction
(vl-somepredicate-functionlist[more-lists]...)
Checkswhetherthepredicateisnotnilforoneelementcombination
(vl-sortlistless?-function)
Sortstheelementsinalistaccordingtoagivencomparefunction
(vl-sort-ilistless?-function)
Sortstheelementsinalistaccordingtoagivencomparefunction,andreturnstheelementindex
Page 891
numbers
(vl-string->liststring) Convertsastringintoalistofcharactercodes
Pleasesendusyourcommentaboutthispage
Page 892
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
String-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPstring-handlingfunctions.
String-handlingfunctions
Function Description
(read[string]) Returnsthefirstlistoratomobtainedfromastring
(strcasestring[which]) Returnsastringwhereallalphabeticcharactershavebeenconvertedtouppercaseorlowercase
(strcat[string1[string2]...)
Returnsastringthatistheconcatenationofmultiplestrings
(strlen[string]...) Returnsanintegerthatisthenumberofcharactersinastring
(substrstringstart[length])
Returnsasubstringofastring
Page 893
(vl-prin1-to-stringobject)
ReturnsthestringrepresentationofanyLISPobjectasifitwereoutputbytheprin1function
(vl-princ-to-stringobject)
ReturnsthestringrepresentationofanyLISPobjectasifitwereoutputbytheprincfunction
(vl-string->liststring) Convertsastringintoalistofcharactercodes
(vl-string-eltstringposition)
ReturnstheASCIIrepresentationofthecharacterataspecifiedpositioninastring
(vl-string-left-trimcharacter-setstring)
Removesthespecifiedcharactersfromthebeginningofastring
(vl-string-mismatchstr1str2[pos1pos2ignore-case-p])
Returnsthelengthofthelongestcommonprefixfortwostrings,startingatspecifiedpositions
(vl-string-positionchar-codestr[start-pos[from-end-p]])
LooksforacharacterwiththespecifiedASCIIcodeinastring
(vl-string-right-trim Removesthespecified
Page 894
character-setstring) charactersfromtheendofastring
(vl-string-searchpatternstring[start-pos])
Searchesforthespecifiedpatterninastring
(vl-string-substnew-strpatternstring[start-pos])
Substitutesonestringforanother,withinastring
(vl-string-translatesource-setdest-setstr)
Replacescharactersinastringwithaspecifiedsetofcharacters
(vl-string-trimchar-setstr)
Removesthespecifiedcharactersfromthebeginningandendofastring
(wcmatchstringpattern)
Performsawild-cardpatternmatchonastring
Pleasesendusyourcommentaboutthispage
Page 895
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>BasicFunctions>
Symbol-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPsymbol-handlingfunctions.
Symbol-handlingfunctions
Function Description
(atomitem) Verifiesthatanitemisanatom
(atoms-familyformat[symlist])
Returnsalistofthecurrentlydefinedsymbols
(boundpsym) Verifieswhetheravalueisboundtoasymbol
(notitem) Verifiesthatanitemevaluatestonil
(nullitem) Verifiesthatanitemisboundtonil
(numberpitem) Verifiesthatanitemisarealoraninteger
(quoteexpr) Returnsanexpressionwithoutevaluatingit
Page 896
(setsymexpr) Setsthevalueofaquotedsymbolnametoanexpression
(setqsym1expr1[sym2expr2]...)
Setsthevalueofasymbolorsymbolstoassociatedexpressions
(typeitem) Returnsthetypeofaspecifieditem
(vl-symbol-namesymbol)
Returnsastringcontainingthenameofasymbol
(vl-symbol-valuesymbol)
Returnsthecurrentvalueboundtoasymbol
(vl-symbolpobject) Identifieswhetherornotaspecifiedobjectisasymbol
Pleasesendusyourcommentaboutthispage
Page 897
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
UtilityFunctions
Theutilityfunctionsconsistofqueryandcommand,displaycontrol,userinput,geometric,conversion,file-handling,anddeviceaccessfunctions.
ConversionFunctionsDeviceAccessFunctionsDisplayControlFunctionsFile-HandlingFunctionsGeometricFunctionsQueryandCommandFunctionsUserInputFunctions
Pleasesendusyourcommentaboutthispage
Page 898
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
ConversionFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPconversionfunctions.
Conversionfunctions
Function Description
(angtofstring[mode])
Convertsastringrepresentinganangleintoareal(floating-point)valueinradians
(angtosangle[mode[precision]])
Convertsanangularvalueinradiansintoastring
(asciistring) ReturnstheconversionofthefirstcharacterofastringintoitsASCIIcharactercode(aninteger)
(atofstring) Returnstheconversionofastringintoareal
(atoistring) Returnstheconversionofastringintoaninteger
(chrinteger) Returnstheconversionof
Page 899
anintegerrepresentinganASCIIcharactercodeintoasingle-characterstring
(cvunitvaluefromto)
Convertsavaluefromoneunitofmeasurementtoanother
(distofstring[mode])
Convertsastringthatrepresentsareal(floating-point)valueintoarealvalue
(itoaint) Returnstheconversionofanintegerintoastring
(rtosnumber[mode[precision]])
Convertsanumberintoastring
(transptfromto[disp])
Translatesapoint(oradisplacement)fromonecoordinatesystemtoanother
Pleasesendusyourcommentaboutthispage
Page 900
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
DeviceAccessFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPdeviceaccessfunctions.
Deviceaccessfunctions
Function Description
(grread[track][allkeys[curtype]])
ReadsvaluesfromanyoftheAutoCADinputdevices
(tabletcode[row1row2row3direction])
Retrievesandsetsdigitizer(tablet)calibrations
Pleasesendusyourcommentaboutthispage
Page 901
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
DisplayControlFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPdisplaycontrolfunctions.
Displaycontrolfunctions
Function Description
(graphscr) DisplaystheAutoCADgraphicsscreen
(grdrawfromtocolor[highlight])
Drawsavectorbetweentwopoints,inthecurrentviewport
(grtext[boxtext[highlight]])
Writestexttothestatuslineortoscreenmenuareas
(grvecsvlist[trans]) Drawsmultiplevectorsonthegraphicsscreen
(menucmdstring) Issuesmenucommands,orsetsandretrievesmenuitemstatus
(menugroupgroupname) Verifiesthatamenugroupisloaded
Page 902
(prin1[expr[file-desc]])
Printsanexpressiontothecommandlineorwritesanexpressiontoanopenfile
(princ[expr[file-desc]])
Printsanexpressiontothecommandline,orwritesanexpressiontoanopenfile
(print[expr[file-desc]])
Printsanexpressiontothecommandline,orwritesanexpressiontoanopenfile
(promptmsg) Displaysastringonyourscreen'spromptarea
(redraw[ename[mode]])
Redrawsthecurrentviewportoraspecifiedobject(entity)inthecurrentviewport
(terpri) PrintsanewlinetotheCommandline
(textpage) Switchesfromthegraphicsscreentothetextscreen
(textscr) Switchesfromthegraphicsscreentothetextscreen(liketheAutoCADFlipScreenfunctionkey)
(vports) Returnsalistofviewportdescriptorsforthecurrentviewportconfiguration
Page 903
Pleasesendusyourcommentaboutthispage
Page 904
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
File-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPfile-handlingfunctions.
File-handlingfunctions
Function Description
(closefile-desc) Closesanopenfile
(findfilefilename) SearchestheAutoCADlibrarypathforthespecifiedfile
(openfilenamemode)
OpensafileforaccessbytheAutoLISPI/Ofunctions
(read-char[file-desc])
ReturnsthedecimalASCIIcoderepresentingthecharacterreadfromthekeyboardinputbufferorfromanopenfile
(read-line[file-desc]) Readsastringfromthekeyboardorfromanopenfile
Page 905
(vl-directory-files[directorypatterndirectories])
Listsallfilesinagivendirectory
(vl-file-copy"source-filename""destination-filename"[append?])
Copiesorappendsthecontentsofonefiletoanotherfile
(vl-file-delete"filename")
Deletesafile
(vl-file-directory-p"filename")
Determinesifafilenamereferstoadirectory
(vl-file-rename"old-filename""new-filename")
Renamesafile
(vl-file-size"filename")
Determinesthesizeofafile,inbytes
(vl-file-systime"filename")
Returnslastmodificationtimeofthespecifiedfile
(vl-filename-base"filename")
Returnsthenameofafile,afterstrippingoutthedirectorypathandextension
(vl-filename-directory"filename")
Returnsthedirectorypathofafile,afterstrippingoutthenameandextension
Page 906
(vl-filename-extension"filename")
Returnstheextensionfromafilename,afterstrippingouttherestofthename
(vl-filename-mktemp["pattern""directory""extension"])
Calculatesauniquefilenametobeusedforatemporaryfile
(write-charnum[file-desc])
Writesonecharactertothescreenortoanopenfile
(write-linestring[file-desc])
Writesastringtothescreenortoanopenfile
Pleasesendusyourcommentaboutthispage
Page 907
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
GeometricFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPgeometricfunctions.
Geometricfunctions
Function Description
(anglept1pt2) Returnsanangleinradiansofalinedefinedbytwoendpoints
(distancept1pt2) Returnsthe3Ddistancebetweentwopoints
(interspt1pt2pt3pt4[onseg])
Findstheintersectionoftwolines
(osnapptmode) Returnsa3DpointthatistheresultofapplyinganObjectSnapmodetoaspecifiedpoint
(polarptangdist) ReturnstheUCS3Dpointataspecifiedangleanddistancefromapoint
(textboxelist) Measuresaspecifiedtextobject,andreturnsthe
Page 908
diagonalcoordinatesofaboxthatenclosesthetext
Pleasesendusyourcommentaboutthispage
Page 909
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
QueryandCommandFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPqueryandcommandfunctions.
Queryandcommandfunctions
Function Description
(acad_colordlgcolornum[flag])
DisplaysthestandardAutoCADColorSelectiondialogbox
(acad_helpdlghelpfiletopic)
InvokestheHelpfacility(obsolete)
(command[arguments]...)
ExecutesanAutoCADcommand
(getcfgcfgname) RetrievesapplicationdatafromtheAppDatasectionoftheacad*.cfgfile
(getcnamecname) RetrievesthelocalizedorEnglishnameofanAutoCADcommand
(getenv"variable-name")
Returnsthestringvalueassignedtoanenvironmentvariable
Page 910
(getvarvarname) RetrievesthevalueofanAutoCADsystemvariable
(help[helpfile[topic[command]]])
InvokestheHelpfacility
(setcfgcfgnamecfgval) WritesapplicationdatatotheAppDatasectionoftheacad*.cfgfile
(setenv"varname""value")
Setsanenvironmentvariabletoaspecifiedvalue
(setfunhelp"c:fname"["helpfile"["topic"["command"]]])
Registersauser-definedcommandwiththeHelpfacilitysotheappropriatehelpfileandtopicarecalledwhentheuserrequestshelponthatcommand
(setvarvarnamevalue) SetsanAutoCADsystemvariabletoaspecifiedvalue
(ver) ReturnsastringthatcontainsthecurrentAutoLISPversionnumber
(vl-cmdf[arguments]...)
ExecutesanAutoCADcommandafterevaluatingarguments
(vlax-add-cmdglobal-name
Addscommandstoagroup
Page 911
func-sym[local-namecmd-flags])
Note VLISPextension:requiresvl-load-com
(vlax-remove-cmdglobal-name)
Removesasinglecommandorcommandgroup
Note VLISPextension:requiresvl-load-com
Pleasesendusyourcommentaboutthispage
Page 912
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>UtilityFunctions>
UserInputFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPuserinputfunctions.
Userinputfunctions
Function Description
(entsel[msg]) Promptstheusertoselectasingleobject(entity)byspecifyingapoint
(getangle[pt][msg])
Pausesforuserinputofanangle,andreturnsthatangleinradians
(getcornerpt[msg])
Pausesforuserinputofarectangle'ssecondcorner
(getdist[pt][msg]) Pausesforuserinputofadistance
(getfiledtitledefaultextflags)
PromptstheuserforafilenamewiththestandardAutoCADfiledialogbox,andreturnsthatfilename
(getint[msg]) Pausesforuserinputofaninteger,andreturnsthat
Page 913
integer
(getkword[msg]) Pausesforuserinputofakeyword,andreturnsthatkeyword
(getorient[pt][msg])
Pausesforuserinputofanangle,andreturnsthatangleinradians
(getpoint[pt][msg])
Pausesforuserinputofapoint,andreturnsthatpoint
(getreal[msg]) Pausesforuserinputofarealnumber,andreturnsthatrealnumber
(getstring[cr][msg])
Pausesforuserinputofastring,andreturnsthatstring
(initget[bits][string])
Establisheskeywordsforusebythenextuserinputfunctioncall
(nentsel[msg]) Promptstheusertoselectanobject(entity)byspecifyingapoint,andprovidesaccesstothedefinitiondatacontainedwithinacomplexobject
(nentselp[msg][pt])
Providessimilarfunctionalitytothatofthenentselfunctionwithouttheneedforuserinput
Page 914
Pleasesendusyourcommentaboutthispage
Page 915
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
SelectionSet,Object,andSymbolTableFunctions
Theselectionset,object,andsymboltablefunctionsconsistofselectionsetmanipulation,object-handling,extendeddata-handling,andsymboltable-handlingfunctions.
ExtendedData-HandlingFunctionsObject-HandlingFunctionsSelectionSetManipulationFunctionsSymbolTableandDictionary-HandlingFunctions
Pleasesendusyourcommentaboutthispage
Page 916
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>SelectionSet,Object,andSymbolTableFunctions>
ExtendedData-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPextendeddata-handlingfunctions.
Extendeddata-handlingfunctions
Function Description
(regappapplication)
RegistersanapplicationnamewiththecurrentAutoCADdrawinginpreparationforusingextendedobjectdata
(xdroomename) Returnstheamountofextendeddata(xdata)spacethatisavailableforanobject(entity)
(xdsizelst) Returnsthesize(inbytes)thatalistoccupieswhenitislinkedtoanobject(entity)asextendeddata
Pleasesendusyourcommentaboutthispage
Page 917
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>SelectionSet,Object,andSymbolTableFunctions>
Object-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPobject-handlingfunctions.
Object-handlingfunctions
Function Description
(entdelename) Deletesobjects(entities)orrestorespreviouslydeletedobjects
(entgetename[applist])
Retrievesanobject'sdefinitiondata
(entlast) Returnsthenameofthelastnondeletedmainobjectinthedrawing
(entmake[elist]) Createsanewentity(graphicalobject)inthedrawing
(entmakex[elist]) Makesanewobject,givesitahandleandentityname(butdoesnotassignanowner),andthenreturnsthenewentityname
Page 918
(entmodelist) Modifiesthedefinitiondataofanobject
(entnext[ename]) Returnsthenameofthenextobjectinthedrawing
(entupdename) Updatesthescreenimageofanobject
(handenthandle) Returnsanobjectnamebasedonitshandle
(vlax-dump-objectobj)
Listsanobject'smethodsandproperties
Note VLISPextension:requiresvl-load-com
(vlax-erased-pobj)
Determineswhetheranobjectwaserased
Note VLISPextension:requiresvl-load-com
(vlax-get-acad-object)
Retrievesthetop-levelAutoCADapplicationobjectforthecurrentAutoCADsession
Note VLISPextension:requiresvl-load-com
(vlax-method-applicable-pobjmethod)
Determineswhetheranobjectsupportsaparticularmethod
Note VLISPextension:requiresvl-load-com
(vlax-object-released-pobj)
Determineswhetheranobjecthasbeenreleased
Page 919
Note VLISPextension:requiresvl-load-com
(vlax-read-enabled-pobj)
Determineswhetheranobjectcanberead
Note VLISPextension:requiresvl-load-com
(vlax-release-objectobj)
Releasesadrawingobject
Note VLISPextension:requiresvl-load-com
(vlax-typeinfo-available-pobj)
Determineswhethertypelibraryinformationispresentforthespecifiedtypeofobject
Note VLISPextension:requiresvl-load-com
(vlax-write-enabled-pobj)
DetermineswhetheranAutoCADdrawingobjectcanbemodified
Note VLISPextension:requiresvl-load-com
Pleasesendusyourcommentaboutthispage
Page 920
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>SelectionSet,Object,andSymbolTableFunctions>
SelectionSetManipulationFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPselectionsetmanipulationfunctions.
Selectionsetmanipulationfunctions
Function Description
(ssadd[ename[ss]]) Addsanobject(entity)toaselectionset,orcreatesanewselectionset
(ssdelenamess) Deletesanobject(entity)fromaselectionset
(ssget[mode][pt1[pt2]][pt-list][filter-list])
Promptstheusertoselectobjects(entities),andreturnsaselectionset
(ssgetfirst) Determineswhichobjectsareselectedandgripped
(sslengthss) Returnsanintegercontainingthenumberofobjects(entities)inaselectionset
(ssmembenamess) Testswhetheranobject(entity)isamemberofa
Page 921
selectionset
(ssnamessindex) Returnstheobject(entity)nameoftheindexedelementofaselectionset
(ssnamexssindex) Retrievesinformationabouthowaselectionsetwascreated
(sssetfirstgripset[pickset])
Setswhichobjectsareselectedandgripped
Pleasesendusyourcommentaboutthispage
Page 922
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>SelectionSet,Object,andSymbolTableFunctions>
SymbolTableandDictionary-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPsymboltableanddictionary-handlingfunctions.
Symboltableanddictionary-handlingfunctions
Function Description
(dictaddenamesymbolnewobj)
Addsanon-graphicalobjecttothespecifieddictionary
(dictnextenamesymbol[rewind])
Findsthenextiteminadictionary
(dictremoveenamesymbol)
Removesanentryfromthespecifieddictionary
(dictrenameenameoldsymnewsym)
Renamesadictionaryentry
(dictsearchenamesymbol[setnext])
Searchesadictionaryforanitem
(layoutlist) Returnsalistofallpaperspacelayoutsinthecurrentdrawing
Page 923
(namedobjdict) Returnstheentitynameofthecurrentdrawing'snamedobjectdictionary,whichistherootofallnon-graphicalobjectsinthedrawing
(setviewview_description[vport_id])
Establishesaviewforaspecifiedviewport
(snvalidsym_name) Checksthesymboltablenameforvalidcharacters
(tblnexttable-name[rewind])
Findsthenextiteminasymboltable
(tblobjnametable-namesymbol)
Returnstheentitynameofaspecifiedsymboltableentry
(tblsearchtable-namesymbol[setnext])
Searchesasymboltableforasymbolname
(vlax-ldata-listdictkey) ErasesAutoLISPdatafromadrawingdictionary
Note VLISPextension:requiresvl-load-com
(vlax-ldata-getdictkey[default-data])
RetrievesAutoLISPdatafromadrawingdictionary
Note VLISPextension:requiresvl-load-com
Page 924
(vlax-ldata-listdict) ListsAutoLISPdatainadrawingdictionary
Note VLISPextension:requiresvl-load-com
(vlax-ldata-putdictkeydata)
StoresAutoLISPdatainadrawingdictionary
Note VLISPextension:requiresvl-load-com
(vlax-ldata-testdata) Determineswhetherdatacanbesavedoverasessionboundary
Note VLISPextension:requiresvl-load-com
Pleasesendusyourcommentaboutthispage
Page 925
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
MemoryManagementFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPmemorymanagementfunctions.
Memorymanagementfunctions
Function Description
(allocint) Setsthesegmentsizetoagivennumberofnodes
(expandnumber)
Allocatesnodespacebyrequestingaspecifiednumberofsegments
(gc) Forcesagarbagecollection,whichfreesupunusedmemory
(mem) DisplaysthecurrentstateofmemoryinAutoLISP
Pleasesendusyourcommentaboutthispage
Page 926
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
VisualLISPExtensionstoAutoLISP
TheextendedAutoLISPfunctionsprovidedwithVLISPconsistofcurvemeasurement,dataconversion,object-handling,property-handling,collectionmanipulation,anddictionary-handlingfunctions.Thefunctionnamesareprefixedwithvlax-.ThesefunctionsareinadditiontotheActiveX®methodsprovidedthroughvla-*functions.
Note BeforeyoucanusetheAutoLISPextensions,youmustissuethefollowingcommand:
(vl-load-com)
Thevl-load-comfunctionalsoinitializesActiveXsupportforAutoLISP.ActiveXCollectionManipulationFunctionsActiveXDataConversionFunctionsActiveXMethodInvocationFunctionsActiveXObject-HandlingFunctionsActiveXProperty-HandlingFunctionsCurveMeasurementFunctionsDictionaryFunctionsFunctionsforHandlingDrawingObjects
Pleasesendusyourcommentaboutthispage
Page 927
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
ActiveXCollectionManipulationFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPActiveXcollectionmanipulationfunctions.
Collectionmanipulationfunctions
Function Description
(vlax-forsymbolcollection[expression1[expression2...]])
Iteratesthroughacollectionofobjects,evaluatingeachexpression(VLISPFunction)
(vlax-map-collectionobjfunction)
Appliesafunctiontoallobjectsinacollection
Pleasesendusyourcommentaboutthispage
Page 928
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
ActiveXDataConversionFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPActiveXdataconversionfunctions.
Dataconversionfunctions
Function Description
(vlax-3D-pointlist) CreatesanActiveX-compatible3Dpointstructure
(vlax-ename->vla-objectentname)
TransformsentitytoVLA-object
(vlax-make-safearraytype'(l-bound.u-bound)['(l-bound.u-bound)...)]
Createsasafearray
(vlax-make-variantvaluetype)
Createsavariantdatatype
(vlax-safearray-fillvar'element-values)
Storeselementsinasafearray
Page 929
(vlax-safearray-get-dimvar)
Returnsthenumberofdimensionsinasafearrayobject
(vlax-safearray-get-elementvarelement)
Returnsanelementfromanarray
(vlax-safearray-get-l-boundvardim)
Returnsthelowerboundary(startingindex)ofadimensionofanarray
(vlax-safearray-get-u-boundvardim)
Returnstheupperboundary(endindex)ofadimensionofanarray
(vlax-safearray-put-elementvarelementvalue)
Addsorupdatesanelementinanarray
(vlax-safearray-typevar)
Returnsthedatatypeofasafearray
(vlax-safearray->listvar)
Returnstheelementsofasafearrayinlistform
(vlax-tmatrixlist) Returnsasuitablerepresentationfora4x4transformationmatrixtobeusedinVLAmethods
(vlax-variant-change-typevartype)
Returnsthevalueofavariantafterchangingitfromonedatatype
Page 930
toanother
(vlax-variant-typevar) Returnsthedatatypeofavariant
(vlax-variant-valuevar) Returnsthevalueofavariant
(vlax-vla-object->enameobj)
TransformsaVLA-objecttoanAutoLISPentity
Pleasesendusyourcommentaboutthispage
Page 931
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
ActiveXMethodInvocationFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPActiveXmethodinvocationfunctions.
Methodinvocationfunctions
Function Description
(vlax-invoke-methodobjmethodlist)
Callsthespecifiedmethodofanobject
(vlax-method-applicable-pobjmethod)
Determinesifanobjectsupportsaparticularmethod
Pleasesendusyourcommentaboutthispage
Page 932
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
ActiveXObject-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPActiveXobject-handlingfunctions.
ActiveXObject-handlingfunctions
Function Description
(vlax-dump-objectobj)
Listsanobject'smethodsandproperties
(vlax-erased-pobj) Determineswhetheranobjectwaserased
(vlax-get-acad-object)
Retrievesthetop-levelAutoCADapplicationobjectforthecurrentAutoCADsession
(vlax-method-applicable-pobjmethod)
Determinesifanobjectsupportsaparticularmethod
(vlax-object-released-pobj)
Determinesifanobjecthasbeenreleased
(vlax-read-enabled-pobj)
Determineswhetheranobjectcanberead
Page 933
(vlax-release-objectobj)
Releasesagraphicalobject
(vlax-typeinfo-available-pobj)
Determineswhethertypelibraryinformationispresentforthespecifiedtypeofobject
(vlax-write-enabled-pobj)
DetermineswhetheranAutoCADdrawingobjectcanbemodified
Pleasesendusyourcommentaboutthispage
Page 934
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
ActiveXProperty-HandlingFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPproperty-handlingfunctions.
Property-handlingfunctions
Function Description
(vlax-get-propertyobjproperty)
Low-levelpropertygetfunction.MaybeusedforcustomActiveXobject
(vlax-property-available-pobjprop[T])
Determineswhetheranobjecthasaspecifiedproperty
(vlax-put-propertyobjpropertyarg)
Low-levelpropertysetfunction
Pleasesendusyourcommentaboutthispage
Page 935
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
CurveMeasurementFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPcurvemeasurementfunctions.
Curvemeasurementfunctions
Function Description
(vlax-curve-getAreacurve-obj) Returnstheareainsidethecurve
(vlax-curve-getDistAtParamcurve-objparam)
Returnsthelengthofthecurve'ssegmentfromthecurve'sbeginningtothespecifiedpoint
(vlax-curve-getDistAtPointcurve-objpoint)
Returnsthelengthofthecurve'ssegmentbetweenthecurve'sstartpointandthespecifiedpoint
(vlax-curve-getEndParamcurve-obj)
Returnstheparameteroftheendpointofthecurve
(vlax-curve-getEndPointcurve-obj)
Returnstheendpoint(inWCScoordinates)
Page 936
ofthecurve
(vlax-curve-getParamAtPointcurve-objparam)
Returnsthedistancealongthecurvefromthebeginningofthecurvetothelocationofthespecifiedparameter
(vlax-curve-getParamAtPointcurve-objpoint)
Returnstheparameterofthecurveatthepoint
(vlax-curve-getPointAtDistcurve-objdist)
Returnsthepoint(inWCScoordinates)alongacurveatthedistancespecifiedbytheuser
(vlax-curve-getPointAtParamcurve-objparam)
Determinesthepointonthecurvethatcorrespondstotheparamparameterandreturnsthepoint
(vlax-curve-getStartParamcurve-obj)
Returnsthestartparameteronthecurve
(vlax-curve-getStartPointcurve-obj)
Returnsthestartpoint(inWCScoordinates)ofthecurve
(vlax-curve-isClosedcurve-obj)
Determinesifthespecifiedcurveisclosed(i.e.,startpointissameasendpoint)
(vlax-curve-isPeriodiccurve-obj) Determinesifthe
Page 937
specifiedcurvehasaninfiniterangeinbothdirectionsandthereisaperiodvaluedT,suchthatthereisapointoncurveat(u+dT)=pointoncurve(u),foranyparameteru
(vlax-curve-isPlanarcurve-obj) Determinesifthereisaplanethatcontainsthecurve
(vlax-curve-getClosestPointTocurve-objgivenPnt[extend])
Returnsthepoint(inWCScoordinates)onacurvethatisnearesttothespecifiedpoint
(vlax-curve-getClosestPointToProjectioncurve-objgivenPntnormal[extend])
Returnsthepoint(inWCScoordinates)onacurvethatisnearesttothespecifiedpoint
(vlax-curve-getFirstDerivcurve-objparam)
Returnsthefirstderivative(inWCScoordinates)ofacurveatthespecifiedlocation
(vlax-curve-getSecondDerivcurve-objparam)
Returnsthesecondderivative(inWCScoordinates)ofacurveatthespecifiedlocation
Pleasesendusyourcommentaboutthispage
Page 939
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
DictionaryFunctions
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPdictionaryfunctions.
Dictionaryfunctions
Function Description
(vlax-ldata-deletedictkey)
ErasesAutoLISPdatafromadrawingdictionary
(vlax-ldata-getdictkey[default-data])
RetrievesAutoLISPdatafromadrawingdictionary
(vlax-ldata-listdict) ListsAutoLISPdatainadrawingdictionary
(vlax-ldata-putdictkeydata)
StoresAutoLISPdatainadrawingdictionary
(vlax-ldata-testdata)
Determineswhetherdatacanbesavedoverasessionboundary
Pleasesendusyourcommentaboutthispage
Page 940
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>VisualLISPExtensionstoAutoLISP>
FunctionsforHandlingDrawingObjects
ThefollowingtableprovidessummarydescriptionsoftheAutoLISPfunctionsforhandlingdrawingobjects.
Functionsforhandlingdrawingobjects
Function Description
(vlax-create-object“prog-id”)
CreatesanewinstanceofanActiveXobject
(vlax-dump-objectobj)
Listsanobject'smethodsandproperties
(vlax-erased-pobj) Determineswhetheranobjectwaserased
(vlax-get-acad-object)
Retrievesthetop-levelAutoCADapplicationobjectforthecurrentAutoCADsession
(vlax-get-object“prog-id”)
ReturnsarunninginstanceofanActiveXobject
(vlax-get-or-create-object“prog-id”)
ReturnsarunninginstanceofanActiveXobject,ifoneexists,otherwisestartsanewinstanceof
Page 941
theobject
(vlax-import-type-library:tlb-filenamefilename[:methods-prefixmprefix:properties-prefixpprefix:constants-prefixcprefix])
Importsinformationfromatypelibrary
(vlax-method-applicable-pobjmethod)
Determineswhetheranobjectsupportsaparticularmethod
(vlax-object-released-pobj)
Determineswhetheranobjecthasbeenreleased
(vlax-read-enabled-pobj)
Determineswhetheranobjectcanberead
(vlax-release-objectobj)
Releasesadrawingobject
(vlax-typeinfo-available-pobj)
Determineswhethertypelibraryinformationispresentforthespecifiedtypeofobject
(vlax-write-enabled-pobj)
DetermineswhetheranAutoCADdrawingobjectcanbemodified
Page 942
Pleasesendusyourcommentaboutthispage
Page 943
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
ReactorFunctions
Reactorfunctionsdefine,query,anddeletereactorsandreactorproperties.
Note Beforeyoucanusethesefunctions,youmustloadAutoLISPreactorsupportbyissuingthefollowingcommand:
(vl-load-com)
Thevl-load-comfunctioninitializesreactorsupportandanumberofotherAutoLISPextensions.
Reactorfunctions
Function Description
(vl-load-com) LoadsAutoLISPreactorsupportfunctionsandotherAutoLISPextensions
(vlr-acdb-reactordatacallbacks)
Constructsadatabase(global)reactorobject
(vlr-addobj) Enablesadisabledreactorobject
(vlr-added-pobj) Teststodeterminewhetherareactorobjectisenabled
(vlr-beep-reaction[args])
Producesabeepsound
Page 944
(vlr-current-reaction-name)
Returnsthename(symbol)ofthecurrentevent,ifcalledfromwithinareactor'scallback
(vlr-dataobj) Returnsapplication-specificdataassociatedwithareactor
(vlr-data-setobjdata) Overwritesapplication-specificdataassociatedwithareactor
(vlr-deepclone-reactorobjdata)
Constructsaneditorreactorobjectthatprovidesnotificationofdeepcloneevents
(vlr-docmanager-reactorobjdata)
ConstructsareactorobjectthatprovidesnotificationofMDI-relatedevents
(vlr-dwg-reactorobjdata)
Constructsaneditorreactorobjectthatprovidesnotificationofadrawingevent(forexample,openingorclosingadrawingfile)
(vlr-dxf-reactorobjdata) ConstructsaneditorreactorobjectthatnotifiesofaneventrelatedtoreadingorwritingofaDXFfile
(vlr-editor-reactordatacallbacks)
Constructsaneditor(global)reactorobject
(vlr-linker-reactordatacallbacks)
Constructsalinker(global)reactorobject
Page 945
(vlr-miscellaneous-reactordatacallbacks)
Constructsaneditorreactorobjectthatdoesnotfallunderanyoftheothereditorreactortypes
(vlr-mouse-reactordatacallbacks)
Constructsaneditorreactorobjectthatprovidesnotificationofamouseevent(forexample,adouble-click)
(vlr-notificationreactor) Determineswhetherornotareactor'scallbackfunctionwillexecuteifitsassociatednamespaceisnotactive
(vlr-object-reactorownersdatacallbacks)
Constructsanobjectreactorobject
(vlr-owner-addreactorowner)
Addsanobjecttothelistofownersofanobjectreactor
(vlr-owner-removereactorowner)
Removesanobjectfromthelistofownersofanobjectreactor
(vlr-ownersreactor) Returnsthelistofownersofanobjectreactor
(vlr-persreactor) Makesareactorpersistent
(vlr-pers-list[reactor]) Returnsalistofpersistentreactorsinthecurrentdrawing
(vlr-pers-preactor) Determineswhetherornotareactorispersistent
Page 946
(vlr-pers-releasereactor)
Makesareactortransient
(vlr-reaction-namereactor-type)
Returnsalistofallcallbackconditionsforthisreactortype
(vlr-reaction-setreactoreventfunction)
Addsorreplacesacallbackfunctioninareactor
(vlr-reactionsreactor) Returnsalistofpairs(event-name.callback_function)forthereactor
(vlr-reactors[reactor-type...])
Returnsalistofreactorsofthespecifiedtypes
(vlr-removereactor) Disablesareactor
(vlr-remove-allreactor-type)
Disablesallreactorsofthespecifiedtype
(vlr-set-notificationreactor'range)
Defineswhetherornotareactor'scallbackfunctionwillexecuteifitsassociatednamespaceisnotactive
(vlr-sysvar-reactordatacallbacks)
Constructsaneditorreactorobjectthatprovidesnotificationofachangetoasystemvariable
(vlr-toolbar-reactordatacallbacks)
Constructsaneditorreactorobjectthatprovidesnotificationofachangetothebitmapsinatoolbar
Page 947
(vlr-trace-reaction) Apre-definedcallbackfunctionthatprintsoneormorecallbackargumentsintheTracewindow
(vlr-typereactor) Returnsasymbolrepresentingthereactortype
(vlr-types) Returnsalistofallreactortypes
(vlr-undo-reactordatacallbacks)
Constructsaneditorreactorobjectthatprovidesnotificationofanundoevent
(vlr-wblock-reactordatacallbacks)
Constructsaneditorreactorobjectthatprovidesnotificationofaneventrelatedtowritingablock
(vlr-window-reactordatacallbacks)
ConstructsaneditorreactorobjectthatnotifiesofaneventrelatedtomovingorsizinganAutoCADwindow
(vlr-xref-reactordatacallbacks)
ConstructsaneditorreactorobjectthatprovidesnotificationofaneventrelatedtoattachingormodifyingXREF
Pleasesendusyourcommentaboutthispage
Page 948
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
VLXNamespaceFunctions
TheVLXnamespacefunctionslistedbelowapplytoseparate-namespaceVLXapplications.Thesefunctionsallowseparate-namespaceVLXfunctionstobeaccessiblefromadocumentnamespace,enabletheretrievalandupdatingofvariablesintheassociateddocumentnamespace,andprovideerror-handlingroutinesforseparate-namespaceVLXfunctions.
VLXnamespacefunctions
Function Description
(vl-arx-import[function|application]
ImportsADS-DEFUNfunctionsintoaseparate-namespaceVLX
(vl-doc-export'function)
MakesafunctionloadedinaVLXnamespaceavailabletothecurrentdocument
(vl-doc-import['function|application])
Importsafunctionthatwaspreviouslyexportedfromanotherseparate-namespaceVLX
(vl-doc-refsymbol)
Retrievesthevalueofavariablefromthenamespaceoftheassociateddocument
(vl-doc-setsymbolvalue)
Setsthevalueofavariableintheassociateddocument's
Page 949
namespace
(vl-exit-with-error“msg”)
PassescontrolfromaVLXerrorhandlertothe*error*functionoftheassociateddocumentnamespace
(vl-exit-with-valuevalue)
ReturnsavaluetothedocumentnamespacefromwhichtheVLXwasinvoked
(vl-list-exported-functions[“appname”])
Listsallfunctionsexportedbythespecifiedapplication,orallexportedfunctionsifnoapplicationisspecified
(vl-list-loaded-vlx)
Returnsalistofallseparate-namespaceVLXfilesassociatedwiththecurrentdocument
(vl-unload-vlx“appname”)
UnloadsaVLXthatisloadedinitsownnamespace(aseparate-namespaceVLX)
(vl-vlx-loaded-p“appname”)
DetermineswhetheraVLXisloadedinitsownnamespace
Pleasesendusyourcommentaboutthispage
Page 950
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
NamespaceCommunicationFunctions
Thenamespacecommunicationfunctionsconsistofblackboardaddressingandmulti-document-loadingfunctions.
Namespacecommunicationfunctions
Function Description
(vl-bb-ref'variable)
Returnsthevalueofavariablefromtheblackboardnamespace
(vl-bb-set'variablevalue)
Setsthevalueofavariableintheblackboardnamespace
(vl-load-all“filename”)
LoadsafileintoallopenAutoCADdocuments,andintoanydocumentsubsequentlyopenedduringthecurrentAutoCADsession
(vl-propagate'variable)
CopiesthevalueofavariableintoallopenAutoCADdocuments,andintoanydocumentsubsequentlyopenedduringthecurrentAutoCADsession
Page 951
Pleasesendusyourcommentaboutthispage
Page 952
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPFunctionSynopsis>
WindowsRegistryFunctions
WindowsRegistryfunctionsqueryandupdatetheWindowsRegistry.
WindowsRegistryfunctions
Function Description
(vl-registry-deletereg-key[val-name])
DeletesthespecifiedkeyorvaluefromtheWindowsRegistry
(vl-registry-descendentsreg-key[val-names])
ReturnsalistofsubkeysorvaluenamesforthespecifiedRegistrykey
(vl-registry-readreg-key[val-name])
ReturnsdatastoredintheWindowsRegistryforthespecifiedkey/valuepair
(vl-registry-writereg-key[val-nameval-data])
CreatesakeyintheWindowsRegistry
(vlax-product-key) ReturnstheAutoCADregistrypath
Note Thisisanextendedfunctionprovidedby
Page 953
VLISP.Youmustissuevl-load-combeforeyoucanusethefunction.
Pleasesendusyourcommentaboutthispage
Page 954
AutoLISPDeveloper'sGuide>Appendixes>
VisualLISPEnvironmentandFormattingOptions
Color-codingoptions,diagnosticoptions,andpagelayoutoptionsaredescribed.
ThischapterdescribestheconfigurationoptionsavailableontheVisualLISP®Toolsmenu.TheWindowAttributesoptionssetcolor-codingfortheVLISPtexteditorwindows.UsingEnvironmentOptionsontheToolsmenu,youcansetsession-wideVLISPoptions(forexample,whetherornottocreateautomaticbackupfiles,orhowtotreatprotectedsymbols),diagnosticoptions(suchaswhatstatisticstoreportduringsyntaxchecking,orwhatlevelofdetailtodisplaywheninspectingdrawingobjects),formattingoptionsforAutoLISP®code,andpagelayoutoptionsforprintedoutput.
WindowAttributesOptionsEnvironmentOptionsSaveSettings(ToolsMenu)
Pleasesendusyourcommentaboutthispage
Page 955
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>
WindowAttributesOptions
OntheVisualLISPToolsmenu,theWindowAttributessubmenuincludesoptionsforcustomizingtheVLISPwindowingenvironment,controllingattributessuchascolors,fonts,andcodeformatting.TheSyntaxColoring,CurrenttoPrototype,andAlltoPrototypeoptionsareavailableonlyfortexteditorwindows.
VLISPallowsyoutodefineprototypeconfigurationsfortexteditorwindows.Theprototypebecomesthedefaultconfigurationforthesewindows.Forexample,whenyouopenanewfileintheVLISPtexteditor,theeditorwindowassumestheattributesandpropertiesoftheprototypeeditorconfiguration.Thewindowprototypeincludes
Colorscheme
Lexicalcoloringflag
Tabsize
Leftmarginindent
Everytimeyouchangeandsaveanytexteditorwindowattributesettings,VLISPwillaskyouifthemodifiedsettingshouldbeusedasaprototypeforthewindowtype.
SyntaxColoringConfigureCurrentSetCurrentWindowtoPrototypeSetAllWindowstoPrototypeFont
Page 956
Pleasesendusyourcommentaboutthispage
Page 957
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>WindowAttributesOptions>
SyntaxColoring
OntheVisualLISPToolsmenu,ontheWindowAttributessubmenu,theSyntaxColoringoptiondeterminesthetypeofsyntaxcoloringthatwillbeusedforthecurrentfilebeingedited.Thisoptionisavailablewhenyoueditafilewhosefiletypeisnot.lsp.Whenchosen,SyntaxColoringdisplaystheColorStyledialogbox,whichprovidesthefollowingoptions:
None
Nocolorcoding.
AutoLISP
UseAutoLISPsyntaxcolorcoding.Thiscolorcodingschemeisusedforallfilesoftype.lsp.
C++
UseC++syntaxcolorcoding.Thisisthedefaultforallfilesoftype.cpp,.c++,.c,.hpp,.h++,and.h.
DCL
UseDCLsyntaxcolorcoding.Thisisthedefaultforallfilesoftype.dcl.
SQL
UseSQLsyntaxcolorcoding.Thisisthedefaultforallfilesoftype.sql.
Ifafiletypedoesnothaveadefaultcoloringstyle,theuserisaskedwhethertousetheselectedcoloringstyleforallfilesofthesametype.
Note Allformattingand“smart”indentationfeaturesrequiretheAutoLISPlexicalcoloringstyle.
Page 958
Pleasesendusyourcommentaboutthispage
Page 959
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>WindowAttributesOptions>
ConfigureCurrent
OntheVisualLISPToolsmenu,ontheWindowAttributessubmenu,theConfigureCurrentoptionallowsyoutoconfiguretheattributesofthecurrentwindow.ItisapplicabletotheVLISPtexteditorandConsolewindows.TheConfigureCurrentoptiondisplaystheWindowAttributesdialogbox:
Thisdialogboxletsyoucustomizethetabwidthandleftmarginsizes,customizevarioustextcolorsdefinedforthecurrentwindowtype,andcontrolthelexicalcoloringforthatwindow(ifapplicable).Toselectthecolorwiththeaidofthecolorselectioncontrol,clickthemousebuttonintherectanglethatispaintedwiththecoloryouwanttoset.
TextColors
Theupperrowofrectanglesindicatesforegroundcolor;thelowerrowindicatesbackgroundcolor.Whenyouselectacolor,thecolorpalettechangesitscolorwithrespecttoyourchoice.Usethepull-downlisttoselecttheattributeofthewindowwhosecolorsyouwanttochange.Theavailable
Page 960
choicesdependonwhichwindowiscurrent.Thefollowingarepossiblewindowattributes:
:Input-Zone.TheinputareafollowingtheConsolewindowprompt.
:Window-Text.Textdisplayedinthewindow(otherthaninputzone).
:Window-Selection.Selectedtext.
:Error-Highlight.ErrormessagesintheBuildOutputwindow.
:Console-Message.Noeffect(reservedforfutureuse).
:BPT-Active.Activebreakpoint.
:BPT-Disable.Disabledbreakpoint.Thepull-downlistmayalsoprovideoptionsforchangingthelexicalcoloringofthefollowingAutoLISPcodecomponents:
:LEX-SPACE.Spaces.
:LEX-STR.Strings.
:LEX-SYM.Symbols.
:LEX-NUM.Reservedforfutureuse.
:LEX-INT.Integers.
:LEX-REAL.Realnumbers.
:LEX-COMM.Reservedforfutureuse.
:LEX-COMM1.Commentsthatbeginwithoneormoresemicolons.
:LEX-COMM2.Inlineandmulti-linecomments(commentsthatbeginwith;|andendwith|;).
:LEX-PAREN.Parentheses.
:LEX-SPEC.Reservedforfutureuse.
:LEX-SPEC1.Reservedforfutureuse.
:LEX-UNKN.Unknownitems.
TransparentFG
Page 961
Transparentforeground.
TransparentBG
Transparentbackground.
LexicalColors
Ifthisoptionisselected,VLISPappliestheselectedcolorcodingoptions.IfyouwanttousetheVLISPformatterbutdonotwantlexicalcoloring,turnthisoptionoff.
TabWidth
Setstabspacinginthecurrentwindow.
LeftMargin
Setstheleftmarginofthecurrentwindow.
WhenyouchangeandsavetheconfigurationofaVLISPeditorwindow,youwillbeaskedwhetherornotyouwanttheconfigurationtobecometheprototypeforalltexteditorwindows.IfyouchooseYes,theconfigurationofthecurrentwindowbecomesthenewprototypeforVLISPtexteditorwindows,andallopentexteditorwindowsassumetheattributesoftheprototype.
Pleasesendusyourcommentaboutthispage
Page 962
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>WindowAttributesOptions>
SetCurrentWindowtoPrototype
OntheVisualLISPToolsmenu,ontheWindowAttributessubmenu,theSetCurrentWindowtoPrototypeoptionconfiguresthecurrentactivewindowwiththeattributesoftheprototypewindow.
Pleasesendusyourcommentaboutthispage
Page 963
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>WindowAttributesOptions>
SetAllWindowstoPrototype
OntheVisualLISPToolsmenu,ontheWindowAttributessubmenu,theSetAllWindowstoPrototypeoptionsetsallopenwindowswiththeattributesoftheprototype.
Pleasesendusyourcommentaboutthispage
Page 964
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>WindowAttributesOptions>
Font
OntheVisualLISPToolsmenu,ontheWindowAttributessubmenu,thefontoptionopensastandardWindowsFontdialogboxwhereyoucanselectthefonttobeusedinVLISPwindows.
Notethatforcodeformattingtoworkcorrectly,youmustuseafixed(non-proportional)font.
Pleasesendusyourcommentaboutthispage
Page 965
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>
EnvironmentOptions
OntheVisualLISPToolsmenu,theEnvironmentOptionssubmenuallowsyoutosetsession-wideVLISPoptions.Forexample,youcantellVLISPwhethertosavetexteditorfilesatsetintervalsautomatically,whethertocreateautomaticbackupfiles,andhowyouwanttotreatattemptstomodifyprotectedsymbols.EnvironmentOptionsisalsowhereyousetdiagnosticoptions,suchaswhatstatisticstoreportduringsyntaxchecking,andwhatlevelofdetailtodisplaywheninspectingdrawingobjects.YoucanalsosetformattingoptionsforAutoLISPcode,andpagelayoutoptionsforprintedoutput.
GeneralOptionsDialogBoxVisualLISPFormatOptionsPageFormatOptionsinthePageSetupDialogBox
Pleasesendusyourcommentaboutthispage
Page 966
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>
GeneralOptionsDialogBox
OntheVisualLISPToolsmenu,ontheEnvironmentOptionssubmenu,theGeneralOptionsoptiondisplaystheGeneralOptionsdialogboxcontainingtheGeneralandDiagnostictabs.
GeneralTab(GeneralOptionsDialogBox)DiagnosticTab(GeneralOptionsDialogBox)
Pleasesendusyourcommentaboutthispage
Page 967
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>GeneralOptionsDialogBox>
GeneralTab(GeneralOptionsDialogBox)
OntheVisualLISPToolsmenu,ontheEnvironmentOptionssubmenu,theGeneralOptionsoptiondisplaystheGeneralOptionsdialogbox.IntheGeneralOptionsdialogbox,ontheGeneraltab,therearethreegroupsofoptions:EditorOptions,Desktop,andSETQtoProtectedSymbols.
TheEditorOptionsgroupcontainsthefollowingoptions:
BackuptheFileEditedonFirstSave
Whenthisoptionisselected,VLISPcreatesabackupcopyofthefilethefirsttimeyousaveit.
MakeBackupbyCopy,NotRename
VLISPcreatesacopyoftheoriginalfile.Whenthisoptionisnotselected,the
Page 968
backupfileisarenamedversionoftheoriginalfile.
GroupTypingforUndo/Redo
VLISPgroupskeystrokesfortheUndoandRedoEditcommands.Ifthisoptionisnotselected,UndoandRedoproceedonecharacteratatime.
TheDesktopgroupcontainsthefollowingoptions:
SaveEditorWindowsSettings
TheVLISPtexteditorwindowsettings(toolbarplacementandtext/backgroundcolor)willbesavedalongwithwindowsizes,placements,andeditorconfigurationswhenyouusetheSaveSettingsoptionontheToolsmenu.WhentheSaveEditorWindowsSettingoptionisoff,VLISPeditorwindowsettingsarenotsaved.
AutosaveSettingonExitApplication
IfSaveEditorWindowsSettingsisturnedon,thenwhenyouexitVLISP,theVLISPtexteditorwindowsettings(toolbarplacementandtext/backgroundcolor)aresavedalongwithwindowsizes,placements,andeditorconfiguration.
TheSETQtoProtectedSymbolsgroupcontrolshowVLISPrespondstoattemptstoredefineprotectedsymbols.(SeeProtectedSymbols.)Theoptionsareasfollows:
Transparent
Whenthisoptionisselected,protectedsymbolsaretreatedlikeanyothersymbol.
PrintMessage
Whenthisoptionisselected,AutoLISPissuesawarningmessagewhenyoumodifyaprotectedsymbolbutcarriesoutthemodification.
PrompttoEnterBreakLoop
Whenthisoptionisselected,AutoLISPdisplaysamessageboxaskingwhetherornottoenterabreakloopwhenyouattempttomodifyaprotectedsymbol.Thisoptionisthedefault.IfyouchooseNo,thesymbol'svalueismodifiedandprocessingcontinuesnormally.IfyouchooseYes,processingisinterruptedandyouenteraVLISPbreak
Page 969
loop.Inabreakloop,controlswitchestotheVLISPConsolewindow.YoucansetthesymbolandcontinueprocessingbypressingtheContinuebuttonontheVLISPtoolbar,oryoucanabortmodificationbypressingReset.
Error
Whenthisoptionisselected,modificationofprotectedsymbolsisprohibited.Anyattempttomodifyaprotectedsymbolresultsinanerror.
Pleasesendusyourcommentaboutthispage
Page 970
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>GeneralOptionsDialogBox>
DiagnosticTab(GeneralOptionsDialogBox)
OntheVisualLISPToolsmenu,ontheEnvironmentOptionssubmenu,theGeneralOptionsoptiondisplaystheGeneralOptionsdialogbox.IntheGeneralOptionsdialogbox,ontheDiagnostictab,theoptionscontrolhowVLISPprovidesinformationaboutAutoLISPsyntax.
TheDiagnostictab'soptionsareasfollows:
ReportStatisticsDuringSyntaxChecking
Ifthisoptionisselected,thesyntaxcheckerandthefilecompilerreportthestatisticsaftercheckingorcompilingeachtop-levelformandaftereachfile.
PrintTopLevelResultsOnLoad
Ifthisoptionisselected,top-levelexpressionsareevaluatedandprintedin
Page 971
theConsolewindowwhentheexpressionsareloaded.Atop-levelexpressionisonethatappearsoutsideanyotherexpression(forexample,anexpressionthatappearsoutsideofdefun).Forexample,thefollowingcalltolistisatop-levelexpression:(list123)
(defunfoo(x)x)
LoadingafilecontainingthiscoderesultsinthefollowingbeingprintedintheConsolewindow,ifPrintTopLevelResultsonLoadisselected:(123)
FOO
PrintNotificationMessageAfterLoad
Ifthisoptionisselected,eachcalltotheloadfunctionresultsinmessagesprintedtotheVLISPConsolewindow.
EchoPRINxOutputtoACAD
Ifthisoptionisselected,thedefaultoutputoffunctionsprint,princandprin1isechoedtotheAutoCADCommandwindowandtheVLISPConsolewindowinsteadofonlytotheVLISPConsolewindow.
InspectDrawingObjectsVerbosely
Ifthisoptionisselected,theelementsofanobjectareincludedintheInspectwindowforadrawingdatabaseobject.Iftheoptionisnotselected,onlytheobjectline(containingtheentityname)appearsindrawingobjectInspectwindows.
DoNotDebugTop-Level
IfthisoptionisselectedandStopOncemodeisset,thebreakwillnotoccurbeforeevaluatingeverytop-levelform(suchasdefun)duringthefileloadprocess.
AnimationDelay
DeterminesthepauselengthbetweenprogramstepsinAnimatemode,measuredinmilliseconds.Thedefaultis100.
Pleasesendusyourcommentaboutthispage
Page 973
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>
VisualLISPFormatOptions
OntheVisualLISPToolsmenu,ontheEnvironmentOptionssubmenu,theVisualLISPFormatOptionsoptiondisplaystheFormatOptionsdialogbox,whichisusedtosetformattingandindentationoptions.
AdditionalformattingoptionsareavailablebypressingtheMoreOptionsbutton.TheseoptionsarecoveredinAdditionalFormattingOptionsintheFormatOptionsDialogBox.
PressingReverttoDefaultrevertstheoptionsettingstotheprevioussavedsetting,ortothesystemdefault,iftheuserhasnotpreviouslychangedandsavedsettings.
Page 974
Notethatthecodeformatterassumesthatyouareusingafixedfonttodisplayorprintformattedtext.
BaseFormattingOptionsintheFormatOptionsDialogBoxAdditionalFormattingOptionsintheFormatOptionsDialogBox
Pleasesendusyourcommentaboutthispage
Page 975
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>VisualLISPFormatOptions>
BaseFormattingOptionsintheFormatOptionsDialogBox
ThefollowingoptionsareshownatthetopoftheFormatOptionsdialogbox.
RightTextMargin
Rightmarginfortext.Anexpressionprintsonasinglelineifitslastcharacterpositiondoesnotexceedtherightmargin.
NarrowStyleIndentation
SetsthestandardindentationvalueusedintheNarrowFormattingStyleforfunctionarguments.
MaximumWide-StyleCarLength
MaximumlengthforfunctionexpressionsinWideFormattingStyle.Forlongerexpressions,theformatteralwaysusesNarrowFormattingStyle.
Single-SemicolonCommentIndentation
Identifiestheleftmarginalignmentforsingle-semicoloncomments.
TheClosingParenStylegroupofoptionscontrolsthepositionofclosingparenthesesformulti-lineformattingstyles.Theeffectofeachoptionisdemonstratedbyformattingthefollowingcode,whereRightTextMarginissetto40andPreserveExistingLineBreaksisnotselected:
(cond
((/=(logandmaskflg)0)
(list(listtxton)))
)
VLISPformatstheprecedingcodeasfollows:
CloseattheSameLine
Page 976
(cond((/=(logandmaskflg)0)
(list(listtxton))))
CloseattheNewLinewithInnerIndentation
(cond((/=(logandmaskflg)0)
(list(listtxton))
)
)
CloseatTheNewLinewithOuterIndentation
(cond((/=(logandmaskflg)0)
(list(listtxton))
)
)
Theremainingitemsinthisdialogboxconcerntabs,savingthecurrentsetting,andthesettingofseveralcommentoptions.
InsertTabs
TheVLISPformatterinsertstabcharactersinsteadofmultiplespacecharacterswheneverpossible.
SaveFormattingOptionsinSourceFile
TheVLISPformatterappendscommentscontainingthecurrentformattingsettingstotheendofthetextintheVLISPtexteditorwindow.Ifyousavethesecomments(anddonotmodifythem),VLISPappliesthesavedformattingoptionstothetexteditorthenexttimeyouopenthefile.
InsertForm-ClosingComment
ThisoptioncausesVLISPtoaddaclosingcommenttoanexpressionwhenCloseattheNewLinewithInnerIndentationorCloseattheNewLinewithOuterIndentationisselected.Thecommenttakesthefollowingformattheendofamulti-linefunction:;_endof<functionname>
VLISPdoesnotaddthecommentifthelinealreadycontainsacomment.
Form-ClosingCommentPrefix
Page 977
DeterminesthetexttobeincludedwhenInsertForm-ClosingCommentisselected.
Pleasesendusyourcommentaboutthispage
Page 978
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>VisualLISPFormatOptions>
AdditionalFormattingOptionsintheFormatOptionsDialogBox
AdditionalformattingoptionsappearwhenyoupresstheMoreOptionsbuttonintheFormatOptionsdialogbox.
ApproximateLineLength
TheVLISPformatterchecksthisvaluewhenitchoosestheformattingstyle.Ifthenumberofcharactersinanexpressionisgreaterthanthisvalue,theformatterprintstheexpressionasmulti-line.
PreserveExistingLineBreaks
Whenthisoptionisselected,theVLISPformatterinsertsnewlineswheneveranewlineisdetectedinthetextbeingformatted.Whentheoptionisoff,theformattercansqueezeamultiple-lineexpressiontotheplanestyle,ifitfitswithintherightmargin.
Note SelectingthisoptioncausesVLISPtoignoreotherformattingoptionswhenthoseoptionswouldresultinalossofexistinglinebreaks.Thisisoftenthesourceofunexpectedformattingresults.
SplitComments
Whenthisoptionisselected,theVLISPformattersplitscommentsthatexceedtherightmargin.
CasingforSymbols
TheseoptionscontrolwhetherornottheVLISPformatterconvertsthecaseofalphabetictextinanAutoLISPsymbolname.Theprotectedsymbolssubgroupcontrolsthecaseconversionofprotectedsymbols(thatis,symbolswiththeASSIGN-PROTECTflagset).TheunprotectedoptionssubgroupcontrolsthecaseconversionofunprotectedAutoLISPsymbols.The
Page 979
followingoptionsareavailable:None:Nocaseconversion.Downcase:Theformatterconvertsallcharactersinasymbolnametolowercase.Upcase:Theformatterconvertsallcharactersinasymbolnametouppercase.
TheLongListformatstyleoptioncontrolstheformattingoflonglists.Longlistsarelistsofformalargumentsindefunandlambdaexpressions,orinquotedlistsofatomswithmorethanfiveelements.Thestyleoptionappliestolongliststhatdonotfitonasingleline(thatis,withintheRightTextMargin).LongListformatstyleoptionsareillustratedbyformattingthefollowingstatementwithRightTextMarginsetto45:
(setqlista'("abc""def""ghi""jkl""mno""pqr"))
Theoptionsareasfollows
Single-ColumnFormatting
(setqlista'("abc"
"def"
"ghi"
"jkl"
"mno"
"pqr"
)
)
2-ColumnFormatting
(setqlistall'("abc""def"
"ghi""jkl"
"mno""pqr"
)
)
Multi-ColumnFormatting
(setqlistall'("abc""def""ghi"
Page 980
"jkl""mno""pqr"
)
)
Fill-to-MarginFormatting
(setqlistall'("abc""def""ghi""jkl"“mno”
"pqr"
)
)
Pleasesendusyourcommentaboutthispage
Page 981
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>
PageFormatOptionsinthePageSetupDialogBox
PageformatoptionsareshowninthePageSetupDialogBox.
ThefollowingoptionscontroltheappearanceofprintedoutputfromVLISP:
HeaderandFooter
Fieldsforspecifyingthecontentofthepageheaderandfooter.Thefirstinputfieldcontainstheheaderlinetoprintatthetopofthepage;thesecondinputfieldcontainsthefooterlinetoprintatthebottomofthepage.Headersandfootersmaycontaintextstringsandvariables.SeeJustificationandSubstitutionCodesinthePageSetupDialogBoxformoreinformationonspecifyingheadersandfooters.
PrintPageMargins
Selecteitherinchesormillimetersasthemeasuringunit,thenspecifyTop,Left,Bottom,andRightmargins.
FontButton
ChoosetheFontbuttontoopentheFontdialogboxforspecifyingtheoutputfont.
JustificationandSubstitutionCodesinthePageSetupDialogBox
Pleasesendusyourcommentaboutthispage
Page 982
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>EnvironmentOptions>PageFormatOptionsinthePageSetupDialogBox>
JustificationandSubstitutionCodesinthePageSetupDialogBox
WhenyouspecifyaheaderandfooterinthePageSetupdialogbox,onlytheampersandcharacter(&)isconsideredasanescapecharacter.Boththeampersandandthecharacterthatfollowsarenotcopiedtotheoutputline.Instead,theyeitherjustifythefollowingtext,orVLISPreplacesthemwithvariableinformation.
InthePageSetupdialogbox,justificationcodesindicatehowheadertextisjustifiedontheprintedpage.Youcanspecifyanyofthefollowing:
&l
Left-justified(thedefault).
&c
Centeredwithinthepagemargins.
&r
Right-justified.
InthePageSetupdialogbox,replacecodesarevariablesforwhichVLISPsubstitutesvalues.Specifyanyofthefollowing:
&f
VLISPreplacesthiscodewiththetitleoftheactiveVLISPwindow.WheninvokedfromaVLISPtexteditorwindow,&fisthenameofthefilebeingedited,includingdirectoryandextension.
&d
Page 983
Currentsystemdate.Toselectadateformat,chooseEdit ExtraCommandsFormatDate/TimefromtheVLISPmenu.
&t
Currentsystemtime.Toselectatimeformat,chooseEdit ExtraCommandsFormatDate/TimefromtheVLISPmenu.
&p
Currentpagenumber.
Toincludeanampersandcharacterinyourheadingtext,entertwoinsuccession.
Thedefaultheadingissettothefollowing:
&cFile:&f&r&dt
Thedefaultfootingissetasfollows:
&r&p
ThefollowingisasampleprintedpagefromanAutoLISPsourcefileusingthedefaultpagelayoutsettings:
File:REACTORSTUFF.LSP12/11/98
(defunsaveDrawingInfo(calling-reactorcommandInfo/dwgnamefilesize)
(setqdwgname(cadrcommandInfo)
filesize(vl-file-sizedwgname)
)
(alert(strcat"Thefilesizeof“dwgname“is“))
.
.
.
(princ)
)
2
Pleasesendusyourcommentaboutthispage
Page 984
AutoLISPDeveloper'sGuide>Appendixes>VisualLISPEnvironmentandFormattingOptions>
SaveSettings(ToolsMenu)
TheSaveSettingsoptionontheVisualLISPToolsmenusavesthedesktopconfigurationandoptionssettings.Notethatthedesktopconfigurationforthechildwindowsattributes(theirpresenceonthescreen,color,position,filesloaded)issavedonlywhentheSaveEditorWindowsSettingsoptionintheGeneralOptionsdialogboxisturnedon.
Pleasesendusyourcommentaboutthispage
Page 985
AutoLISPDeveloper'sGuide>Appendixes>
AutoLISPErrorCodes
TheerrorcodesgeneratedbyAutoLISParedescribed.
ThisappendixliststheAutoLISP®errorcodes.ErrorCodes
Pleasesendusyourcommentaboutthispage
Page 986
AutoLISPDeveloper'sGuide>Appendixes>AutoLISPErrorCodes>
ErrorCodes
ThefollowingtableshowsthevaluesoferrorcodesgeneratedbyAutoLISP.TheERRNOsystemvariableissettooneofthesevalueswhenanAutoLISPfunctioncallcausesanerrorthatAutoCADdetects.AutoLISPapplicationscaninspectthecurrentvalueofERRNOwith(getvar"errno").
TheERRNOsystemvariableisnotalwaysclearedtozero.UnlessitisinspectedimmediatelyafteranAutoLISPfunctionhasreportedanerror,theerrorthatitsvalueindicatesmaybemisleading.Thisvariableisalwaysclearedwhenstartingoropeningadrawing.
Note ThepossiblevaluesofERRNO,andtheirmeanings,aresubjecttochange.
Onlineprogramerrorcodes
Value Meaning
0 Noerror
1 Invalidsymboltablename
2 Invalidentityorselectionsetname
3 Exceededmaximumnumberofselectionsets
4 Invalidselectionset
5 Improperuseofblockdefinition
6 Improperuseofxref
Page 987
7 Objectselection:pickfailed
8 Endofentityfile
9 Endofblockdefinitionfile
10 Failedtofindlastentity
11 Illegalattempttodeleteviewportobject
12 OperationnotallowedduringPLINE
13 Invalidhandle
14 Handlesnotenabled
15 Invalidargumentsincoordinatetransformrequest
16 Invalidspaceincoordinatetransformrequest
17 Invaliduseofdeletedentity
18 Invalidtablename
19 Invalidtablefunctionargument
20 Attempttosetaread-onlyvariable
21 Zerovaluenotallowed
22 Valueoutofrange
23 ComplexREGENinprogress
24 Attempttochangeentitytype
Page 988
25 Badlayername
26 Badlinetypename
27 Badcolorname
28 Badtextstylename
29 Badshapename
30 Badfieldforentitytype
31 Attempttomodifydeletedentity
32 Attempttomodifyseqendsubentity
33 Attempttochangehandle
34 Attempttomodifyviewportvisibility
35 Entityonlockedlayer
36 Badentitytype
37 Badpolylineentity
38 Incompletecomplexentityinblock
39 Invalidblocknamefield
40 Duplicateblockflagfields
41 Duplicateblocknamefields
42 Badnormalvector
43 Missingblockname
44 Missingblockflags
Page 989
45 Invalidanonymousblock
46 Invalidblockdefinition
47 Mandatoryfieldmissing
48 Unrecognizedextendeddata(XDATA)type
49 ImpropernestingoflistinXDATA
50 ImproperlocationofAPPIDfield
51 ExceededmaximumXDATAsize
52 Entityselection:nullresponse
53 DuplicateAPPID
54 Attempttomakeormodifyviewportentity
55 Attempttomakeormodifyanxref,xdef,orxdep
56 ssgetfilter:unexpectedendoflist
57 ssgetfilter:missingtestoperand
58 ssgetfilter:invalidopcode(-4)string
59 ssgetfilter:impropernestingoremptyconditionalclause
60 ssgetfilter:mismatchedbeginandendofconditionalclause
61 ssgetfilter:wrongnumberofarguments
Page 990
inconditionalclause(forNOTorXOR)
62 ssgetfilter:exceededmaximumnestinglimit
63 ssgetfilter:invalidgroupcode
64 ssgetfilter:invalidstringtest
65 ssgetfilter:invalidvectortest
66 ssgetfilter:invalidrealtest
67 ssgetfilter:invalidintegertest
68 Digitizerisnotatablet
69 Tabletisnotcalibrated
70 Invalidtabletarguments
71 ADSerror:Unabletoallocatenewresultbuffer
72 ADSerror:Nullpointerdetected
73 Cannotopenexecutablefile
74 Applicationisalreadyloaded
75 Maximumnumberofapplicationsalreadyloaded
76 Unabletoexecuteapplication
77 Incompatibleversionnumber
78 Unabletounloadnestedapplication
Page 991
79 Applicationrefusedtounload
80 Applicationisnotcurrentlyloaded
81 Notenoughmemorytoloadapplication
82 ADSerror:Invalidtransformationmatrix
83 ADSerror:Invalidsymbolname
84 ADSerror:Invalidsymbolvalue
85 AutoLISP/ADSoperationprohibitedwhileadialogboxwasdisplayed
Pleasesendusyourcommentaboutthispage