Back


Newsgroup comp.cad.autocad 61841

Directory

comp.cad.autocad AutoLISP FAQ (part 2/2) - samples, code -- rurban@xarch.tu-graz.ac.at (Reini Urban)
comp.cad.autocad AutoLISP FAQ (part 1/2) - general -- rurban@xarch.tu-graz.ac.at (Reini Urban)
Plotter for Autocad 13/14 -- Koh Choon Ngee
"Digitizer analogue failure" - what does this mean? -- Alexander Murahidy
Re: ? Autolisp: turn on snap for extend then restore it? -- Christoph Candido
Re: DWG and DXF viewers -- rhl@cadmandu.com (Robert H. Lieberman)
AutoCad 14 run on 16MB -- silver@mail.netvision.net.il
AutoCAD tutor needed in Marin County -- Brandon Davis
Re: WHIP driver/plugin -- "Lars Lindbjerg"
AutoLISP - done dirt cheap!!! -- Christopher Herd

Articles

comp.cad.autocad AutoLISP FAQ (part 2/2) - samples, code
rurban@xarch.tu-graz.ac.at (Reini Urban)
14 Jun 1997 14:02:00 GMT
Posted-By: auto-faq 3.2.1.4a
Archive-name: CAD/autolisp-faq/part2
URL: http://xarch.tu-graz.ac.at/autocad/news/faq/autolisp.html
Version: 1.8
Last-modified: 21.May 1997
Posting-Frequency: bi-weekly (every 2nd saturday)
Copyright: see Appendix [A]
        Welcome to the comp.cad.autocad AutoLISP FAQ!
          by Reini Urban 
AutoLISP is a scripting language for AutoCAD, a wellknown CAD package.
This AutoLISP FAQ is posted to comp.cad.autocad, alt.cad.autocad and
the *.answers groups bi-weekly. The (incomplete) AutoCAD FAQ is at
http://www.cadence-mag.com/library/FAQ and not posted to
comp.cad.autocad yet. The contents and the samples apply to all
releases of AutoLISP since Release 10, including the third-party
versions ACOMP and Vital Lisp. There's no special AutoLISP newsgroup.
Source code of all functions in this FAQ is in FAQ-CODE.LSP
(location see [A.1]), there's also a winhelp file.
Thanks to all who have contributed. Corrections and contributions
always welcome.
This is part 2/2 of the AutoLISP FAQ, which consists of:
    AutoLISP FAQ (part 1/2) - general
    AutoLISP FAQ (part 2/2) - samples, code
| changes, + new in items from this version to the last posted version,
intermediate personal comments and uncertainties in {..}
  -----------------
  Table of Contents
  -----------------
  part 1:
     [0] The Future of AutoLISP? Should I learn it or VB instead?
     [1] Where can I find AutoLISP routines on the
         Internet?
       [1.1] Are the comp.cad.autocad articles stored
             somewhere?
       [1.2] AutoDESK's SDK
     [2] What are the best books to learn AutoLISP?
       [2.1] Online AutoLISP documents, Winhelp
       [2.2] AutoLISP Coding Style
     [3] How do I debug AutoLISP programs?"
        [3.1] Native AutoLISP debuggers
        [3.2] Modular style, TRACE
        [3.3] break function, debug print
     [4] How can I protect my AutoLISP programs?
       [4.1] Kelvinate
       [4.2] Protect
       [4.3] Kelvinate and Protect
       [4.4] Decrypt 2.0 / Convert 3.2
       [4.5] acomp
       [4.6] Vital Lisp Pro
       [4.7] Lisp2C
     [5] AutoLISP compiler?
       [5.1] acomp
       [5.2] Vital Lisp Pro
     [6] AutoLISP editors and other tools?
       [6.1] AutoLISP editors
       [6.2] Parenthesis checkers
       [6.3] Pretty Printers
     [7] AutoLisp problems and bugs (esp. with R13)
     [8] Sorting with AutoLISP
     [9] Recursion
     [10] Iteration with mapcar,...
     [11] My Lisp doesn't load at startup anymore
     [12] How to Autoload my programs?
     [13] How can I pass a variable number of
          arguments to a lisp function?
     [14] How can I avoid stack overflows?
     [15] (command "ROTATE3D") does not work! Why?
     --
     [A] Disclaimer, Notes from the author
       [A.1] FAQ Locations
  part 2:
     [20] General helper functions
       [20.1] List manipulation
       [20.2] string manipulation
+      [20.3] symbol->string
       [20.4] AutoCAD entity access
     [21] Sample Lisp programs:
       [21.1] Globally change texts, polylines, layer utils, datestamp
       [21.2] Plot dialog from within Lisp
       [21.3] (entmod),(entmake) Layers, without (command "_LAYER"...)
       [21.4] How to select multiple files in Lisp? (as in FILES-Unlock)
       [21.5] Replace multiple blocks
       [21.6] (vports), VIEWPORT entity, pixel conversion
       [21.7] Select all visible objects: zoom coordinates
       [21.8] How to write XYZ data of selected objects to a file?
     [22] Block Attributes
       [22.1] How to access block attributes?
       [22.2] How to MODIFY block attributes? DATESTAMP.LSP
       [22.3] How to UPDATE block attributes?
       [22.4] How to ENTMAKE a Block Complex Entity in AutoLISP
     [23] Polylines
       [23.1] How to access polyline VERTICES?
       [23.2] How to JOIN multiple lines to polylines?
       [23.3] Change WIDTH of multiple polylines
       [23.4] Create a polyline or spline: with (ENTMAKE) or (COMMAND)
       [23.5] How to calculate the LENGTH of polylines?
     [24] Circle/Arc Geometry:  BULGE conversion, some trigonometry
     [25] DCL: listboxes with tabs or monotext font
     [26] EED Extended Entity Data: Get and Store
       [26.1] Select objects on their EED with (ssget "X")
       [26.2] Get EED from an object
     [27] How to break a command in Lisp?
     [28] How to decode ACIS internal geometry with Lisp?
     --
     [A] Disclaimer, Notes from the author
       [A.1] FAQ Locations
     [B] Acknowledgements
     [C] Recent Changes
----------------------------------------------------------------------
Subject: [20] General helper functions
  There doesn't yet exist free libraries for i.e. basic list and string
  manipulation as for any other lisp. You have to collect these by your
  own. Some code is available at some AutoLISP sites [1] or included in
  the SDK's by AutoDESK [1.2]
  I included here some very useful helper functions for shorter
  samples in answers on the net.
  You could rely on the fact that these functions are in common
  knowledge such as the famous dxf function, which is defined as
  (defun dxf (grp ele) (cdr (assoc grp ele))) and the specific
  counterpart of (getval) which works with every entity type.
[20.1] List manipulation
  Useful sample functions for *list manipulation* are:
  ;;; CONSP  - a not empty lisp
  (defun consp (x) (and x (listp x)))
  ;;; POSITION - returns the index of the first element in the list,
  ;;; base 0, or nil if not found
  ;;;   (position x '(a b c)) -> nil, (position b '(a b c d)) -> 1
  (defun position (x lst / ret)
    (if (not (zerop (setq ret (length (member x lst)))))
      (- (length lst) ret)))
  ;;; REMOVE - Removes an item from a list (double elements allowed)
  ;;;   (remove 0 '(0 1 2 3 0)) -> (1 2 3)
  (defun remove (ele lst)      ; by Serge Volkov
    (apply 'append (subst nil (list ele) (mapcar 'list lst))))
  ;;; REMOVE-IF - Conditional remove from flat list,
  ;;; pred requires exactly 1 arg
  ;;;   (remove-if 'zerop '(0 1 2 3 0)) -> (1 2 3)
  ;;;   (remove-if 'numberp '(0 (0 1) "")) -> ((0 1) "")
  (defun remove-if (pred from)
    (cond
      ((atom from) from)       ;nil or symbol (return that)
      ((apply pred (list (car from))) (remove-if pred (cdr from)))
      (t (cons (car from) (remove-if pred (cdr from))))
    )
  )
  ;;; REMOVE-IF-NOT  - keeps all elements to which the predicate applies
  ;;; say: "keep if", it need not be defined recursively, also like this
  (defun remove-if-not (pred lst)        ; by Vladimir Nesterowsky
    (apply 'append (mapcar '(lambda(e) (if(pred e)(list e))) lst)))
  ;;; ADJOIN - conses ele to list if not already in list
  ;;; trick: accepts quoted lists too, such as
  ;;;   (setq l '(1 2 3) (adjoin 0 'l)
  ;;;    -> !l (0 1 2 3)
  (defun adjoin (ele lst / tmp)
    (if (= (type lst) 'SYM) (setq tmp lst lst (eval tmp)))
    (setq lst (cond ((member ele lst) lst)
                    (t (cons ele lst))))
    (if tmp (set tmp lst) lst)
  )
[20.2] string manipulation
  Some useful *string functions* would be:
  predicates:
    (stringp expr)          - string predicate, is expr a string?
      (defun stringp (s) (= (type s) 'STR))
    (string-not-emptyp str) - is str a not empty string?
      (defun string-not-emptyp (s) (and (stringp s) (/= s "")))
  trimming:
    (str-trim string)       - str without any whitespace, to the right
                           and left, defined in AI_UTILS.LSP as well as
    (str-left-trim string), (str-right-trim string)
    (str-left-trim-bag string bag), (str-right-trim-bag string bag)
                            - remove all chars in bag (=STR)
  string access:
    (strpos string substr)  - position of substring in string (1 based)
  parsing and gathering functions, (list<->string) such as:
    (strtok str tokens)     - string -> list delimited by tokens (SDK2)
    (strlcat lst delim)     - concat list -> string seperated by delim
    (string->list str)      - string -> list of chars
    (list->string lst)      - list of chars -> string
  Some are at http://xarch.tu-graz.ac.at/autocad/code/vnestr/strtok.lsp
  or in your AI_UTILS.LSP. You'll need them esp. for DCL functions.
[20.3] symbol->string
  The inverse function to (read) would be (symbol-name). Don't ask
  why, but the following is the only general way:
  ;;; SYMBOL-NAME - returns the name of a symbol as string
  ;;; converts any valid lisp expression to its printed representation
  ;;; (symbol-name a) -> "a",  (symbol-name '(0 1 2 a)) -> "(0 1 2 A)"
  (defun symbol-name (sym / f str tmp)
    (setq tmp "$sym.tmp")      ;temp. filename, should be deleted
    (setq f (open tmp "w"))(princ sym f) (close f)
    (setq f (open tmp "r") str (read-line f) f (close f))
    str
  )
  For plain symbols exists a better trick explained by Christoph 
  Candido at http://xarch.tu-graz.ac.at/autocad/news/symbol-string.txt
[20.4] AutoCAD entity access
  ;;; returns the first group value of an entity.
  ;;; like the wellknown (dxf) function but accepts all kinds of
  ;;; entity representations (ename, entget list, entsel list)
  ;;; NOTE: For getting 10 groups in LWPOLYLINE's not usable!
  (defun GETVAL (grp ele)                 ;"dxf value" of any ent...
    (cond ((= (type ele) 'ENAME)          ;ENAME
            (cdr (assoc grp (entget ele))))
          ((not ele) nil)                 ;empty value
          ((not (listp ele)) nil)         ;invalid ele
          ((= (type (car ele)) 'ENAME)    ;entsel-list
            (cdr (assoc grp (entget (car ele)))))
          (T (cdr (assoc grp ele)))))     ;entget-list
  ;;; Ex: (gettyp pline) => "POLYLINE"
  (defun GETTYP (ele)                     ;return type
    (getval 0 ele))
  ;;; assure ENAME
  ;;; convert the entity to type ENAME (to write shorter code)
  (defun ENTITY (ele)                     ;convert to element name
    (cond				  ;accepts the following types:
      ((= (type ele) 'ENAME) ele)             ; ENAME
      ((not (listp ele)) nil)                 ; error: no list
      ((= (type (car ele)) 'ENAME) (car ele)) ; entsel-list
      ((cdr (assoc -1 ele)))                  ; entget-list or nil
    )
  )
  ;and now just: (defun getval (grp ele) (cdr (assoc grp (entity ele))))
  ;;; Ex: (istypep ele "TEXT")
  ;;; is element a "SOLID"?
  (defun istypep (ele typ)                   ;check type
    (= (gettyp ele) typ))
  ;;; Ex: (istypep ele '("TEXT" "ATTDEF"))
  ;;; is element a "TEXT" or a "ATTDEF"?
  (defun ISTYPEP (ele typ) ;better implementation to accept lists too
    (cond
      ((listp typ)   (member (gettyp b) typ))
      ((stringp typ) (= (gettyp b) typ))  ;assume typ uppercase
      (T nil)))
  ;;; Ex: (getpt (entsel))  => ( 0.1 10.0 24)
  (defun GETPT (ele)    ;return the startpoint of any element
    (getval 10 ele))    ;group 10
  ;;; Ex: (getflag pline)  => 1 if closed
  (defun GETFLAG (ele) (getval 70 ele)) ;same with the entity flag
  ;;; bitvalue val in flag of element set?
  ;;; Ex: (flagsetp 1 pline)   => T if closed
  ;;; Ex: (flagsetp 16 vertex) => T if spline control point
  (defun FLAGSETP (val ele)
    (bitsetp val (getflag ele)))
  ;;; Ex: (bitsetp 4 12) => T   ;bitvalue 4 (=2.Bit) in 12 (=4+8) is set
  (defun BITSETP (val flag)
    (= (logand val flag) val))
  ;;; convert selection set to list,
  ;;; Note: it's also wise to use ai_ssget, because some ents could be
  ;;;       on locked layers
  ;;; Ex: (sslist (ai_ssget (ssget))) => list of selected unlocked ents
  ;;; or  (mapcar 'entupd (sslist (ssget "X" '((8 . "TEMP")))))
  ;;;       - regens all entities on layer TEMP
  (defun SSLIST (ss / n lst)
    (if (= (type ss) 'PICKSET)
      (repeat (setq n (sslength ss))
        (setq n (1- n)
              lst (cons (ssname ss n) lst)))))
  ;;; apply a function to each ent in ss, in reversed order
  ;;; Faster, but not so easy to understand. see [22.2]
  ;;; Ex: (ssapply 'entupd (ssget))   ; regenerate only some entities
  (defun SSAPPLY (fun ss / n)
    (if (= 'PICKSET (type ss))
      (repeat (setq n (sslength ss))
        (apply fun (list (ssname ss (setq n (1- n))))))))
------------------------------
Subject: [21] Sample Lisp Programs:
[21.1] Globally change texts, polylines, layer utils, datestamp
  For globally changing text attributes use CHTEXT.LSP in your
  sample directory.
  For globally changing polyline attributes, freeze layers by pick
  and other similar tasks search for free lisp tools at any AutoLISP
  site. See "[1]" and some code at "[22]","[23]","[24]"
  For putting a datestamp and others onto your plots automatically
  first check out if your plotter supports HPGL/2. Then use the
  internal HPGL/2 driver and configure the datestamp in HPCONFIG.
  DATESTAMP.LSP: Change the plot header attributes by yourself
  as in [22.2]. A profi plotstamp routine is here:
  http://ourworld.compuserve.com/homepages/tonyt/plotstmp.htm
------------------------------
[21.2] Plot dialog from within Lisp
  Calling the PLOT dialogbox from AutoLISP is possible only under
  Windows i.e. with LISPPLOT by Mike Dickason. This feeds
  the keyboard buffer with keystrokes.
    http://www.cadalog.com/cadalog/cadalog/files/lispd-l/lspplw.zip
  or also: ftp://ftp.mcwi.com/pub/mcwi/lisp/winplt.lsp
  Otherwise create a script and call this at the end of your lisp, but
  this will not show up the dialogbox.
------------------------------
[21.3] (entmod) and (entmake) Layers, without (command "_LAYER"...)
  ENTMOD a layer
  I try to change a layer property without calling COMMAND function
  inside a lisp routine.
  Under r13, using the following lisp
    (setq tbl_lst (entget (tblobjname "LAYER" "ANY_LAYER"))
          clr_grp (assoc 62 tbl_lst)
    )
    (entmod (subst (cons 62 (- (cdr clr_grp))) clr_grp tbl_lst))
  you can toggle "ANY_LAYER" On or Off, even it is the current layer.
  But AutoCAD doesn't know a table entry has been changed until you
  click the Layer Control on the toolbar or something similar.
  Besides, you can issue 'DDLMODES to see On/OFf property of
  "ANY_LAYER" changed.
  Doing the same way to freeze a layer, you will still see entities on
  that layer shown on screen, but you can not select them, until you do
  something related to layer settings, and AutoCAD will hide those
  entities.
  ENTMAKE a layer
  You must get your pattern with entget, using the table object name as
  argument. This table object name can be retrieved with the TBLOBJNAME
  function:
	(entget (tblobjname "LAYER" "ANY_LAYER_NAME"))
  ;;; This routine will create a layer with any name you type:
  (defun c:mlay ()	; by Reinaldo Togores 
    (setq laynam (getstring "\nLayer name: "))
      (entmake
        (list
          '(0 . "LAYER")
          '(5 . "28")
          '(100 . "AcDbSymbolTableRecord")
          '(100 . "AcDbLayerTableRecord")
          (cons 2 laynam)
          '(70 . 64)
          '(62 . 7)
          '(6 . "CONTINUOUS")
      )
    )
  )
------------------------------
[21.4] How to select multiple files in Lisp? (as in FILES - Unlock)
  At http://xarch.tu-graz.ac.at/autocad/progs/MGETFILD.ZIP
  is a lisp helper routine to select multiple files with DCL.
  You will also need DOSLIB from McNeel to access the dos specific
  directory functions. http://www.mcneel.com/mcneel/doslib.html
------------------------------
[21.5] Replace multiple blocks
  A search at the lisp archives yielded those hits:
   Cadalyst: http://www.cadonline.com/search.phtml
  => 97code.htm and a question for your username which can be obtained
   free and automatically
  or xarch: http://xarch.tu-graz.ac.at/autocad/code and search for
   "BLOCK;REPLACE"
  => http://xarch.tu-graz.ac.at/autocad/code/cadalyst/94-02/replace.lsp
  also at the Cadalog:
   http://www.cadalog.com/find.htm  Keyword "Block Replace"
  => http://www.cadalog.com/cadalog/cadalog/files/lispr-z/replace.zip
   (this one is the best)
------------------------------
[21.6] (vports), VIEWPORT entity, pixel conversion
  VIEWPORT entity:
  The answer to "I can do an (entget) on a VIEWPORT and get its lower
  left (DXF group 10) and upper right (DXF group 11) corner.  But it
  appears that these coordinates are in the paper space system.  What
  I'm interested in finding out is what portion of the "real" drawing
  (the model space drawing) are currently shown in that viewport."
  is at http://xarch.tu-graz.ac.at/autocad/news/vports.lsp
  How to change viewports in AutoLISP?
  with (setvar "CVPORT" vport-id)
  see http://xarch.tu-graz.ac.at/autocad/news/change_vports.html
  With the following functions you convert pixel<->drawing units:
  ;;; Conversion pixel to drawing units
  (defun PIX2UNITS (pix)
    (* pix (/ (getvar "VIEWSIZE") (cadr (getvar "SCREENSIZE")))))
  ;;; Conversion drawing units to pixel
  (defun UNITS2PIX (units)
    (* units (/ (cadr (getvar "SCREENSIZE"))(getvar "VIEWSIZE"))))
------------------------------
[21.7] Select all visible objects: zoom coordinates
  Beware that with (ssget) you will only get visible objects, because
  all interface functions (entsel,ssget,osnap) work with pixel, only
  (ssget "X") will select not visible objects.
  ;;; returns a list of the actual viewport corners in WCS
  (defun zoompts ( / ctr h screen ratio size size_2)
    (setq ctr (xy-of (getvar "VIEWCTR")) ;3D -> 2D
          h   (getvar "VIEWSIZE")        ;real
          screen (getvar "SCREENSIZE")   ;2D: Pixel x,y
          ratio (/ (float (car screen))  ;aspect ratio
                   (cadr screen))
          size (list (* h ratio) h)      ;screensize in coords
          size_2 (mapcar '/ size '(2.0 2.0)))
      (list (mapcar '- ctr size_2)
            (mapcar '+ ctr size_2)))
  (defun xy-of (pt) (list (car pt)(cadr pt)))   ;assure 2D coords
  Note: The points returned are in WCS but this is ok, because the
    "CP" "WP" and "P" options of ssget expect WCS points.
    "W" and "C" require UCS points - why the difference I don't know.
  ;;; one way to define this function
  (defun ssall-visible (/ l)
    (ssget "C" (car (setq l (maptrans0-1 (zoompts)))) (cadr l)))
  ;;; or another
  (defun ssall-visible-1 ()      ;combine "C" and (p1 p2) to one list
    (apply 'ssget (append '("C") (maptrans0-1 (zoompts)))))
  ;;; map some pts from UCS to WCS, easier with just one argument
  (defun maptrans0-1 (pts)(mapcar '(lambda (pt)(trans pt 0 1)) pts))
------------------------------
Subject: [21.8] How to write XYZ data of selected objects to a file?
  ;;; CDF - comma delimited string
  (defun cdf-point (pt)
    (strcat (car pt) ", " (cadr pt) ", " (caddr pt)))
  ;;; SDF - space delimited, may easier be read back in to AutoCAD
  (defun sdf-point (pt)
    (strcat (car pt) " " (cadr pt) " " (caddr pt)))
  ;;; convert this SDF format back to a point with
  (defun str->point (s)
    (eval (read (strcat "(" s ")"))))
  ;;; Write a XYZ file of all selected objects (SDF see below)
  (defun C:XYZ (/ ss fname f)
    (if (and (setq ss (ssget))
          (setq fname (getfiled "Write XYZ to file"
                  (strcat (getvar "DWGNAME") ".XYZ") "XYZ" 7))
          (setq f (open fname "w")))
      (foreach ele (sslist ss)          ; -> [20.4]
        (foreach pt (getpts ele)        ; -> [23.1]
          (write-line (cdf-point pt) f)
        )
      )
    )
    (if f (close f))
  )
  ;;; => .xyz
  ;;; 0.45, 12.3, -34.0
  For a ASC file (SDF-format) simply change all XYZ to ASC
  and cdf-point to sdf-point above.
  For the other way 'round, creating PLINES from a ascii x,y file
  best convert the file to a script like:
  PLINE
  300.2,10
  350.4,10.4
------------------------------
Subject: [22] Block Attributes
[22.1] How to access block attributes?
  Check all subentities after the INSERT until the attribute is found.
  See also http://www.autodesk.com/support/techdocs/acadcdi/td300518.htm
  -> "Retrieving Complex Entities and Sub-entities with AutoLISP"
  ;;; returns entget-list of attribute attname (STRING) in element ele
  ;;; or nil if not found
  (defun attele (ele attname / rslt)
    (if (and (istypep ele "INSERT")
             (= (getval 66 ele) 1))
      (progn
        (setq ele (entnext (entity ele)))
        (while (istypep ele "ATTRIB")
          (if (= (strcase (getval 2 ele)) (strcase attname))
            (setq rslt (entget ele) ele nil)      ;break the loop
            (setq ele (entnext ele))
          )
        )
      )
    )
    rslt
  )
  ;;;Example:
  (attele (entsel) "TEST")   ; returns entget-list of
                             ; attribute "TEST" if the block has it
  BTW: Even trickier functions to get entities DXF group codes are
       GET and EDLGETENT by Vladimir Nesterowsky.
  ;;;Sample calls:
  ;;; return list of 2,1 and -1 group values
  (defun get-attribs-look-up( block-ename )
    (get '(2 1 -1) (cdr(edlgetent block-ename))))
  (defun all-verticies-and-bulges( pline-ename )
    (get '(10 42)  (cdr(edlgetent pline-ename))))
  available at http://xarch.tu-graz.ac.at/autocad/code/vnestr/
[22.2] How to MODIFY block attributes? DATESTAMP
  Simply entmod the entget-list retrieved from (attele) as above.
  ;;; change the attribute value of INSERT ele to new (group 1)
  (defun ATTCHG (ele attname new / b)
    (if (setq b (attele ele attname))
      (entmod (subst (cons 1 new) (getval 1 b) b))))
  ;;; Change all DATESTAMP attributes in all inserted PLOT* blocks
  (defun C:DATESTAMP ()
    (ssapply (ssget "X" '((0 . "INSERT")(2 . "PLOT*")))
     '(lambda (ele)
        (attchg ele "DATESTAMP" (today))
        (entupd ele)
      )))
  ;;;return todays date, could be a DIESEL or this string conversion
  (defun today (/ s)
    (setq s (rtos (getvar "CDATE") 2))  ;gets the julian date
    (strcat (substr s 5 2) "-" (substr s 7 2)"-"(substr s 3 2)))
[22.3] How to UPDATE block attributes?
  There exists a SUPPORT\ATTREDEF.LSP to update attribute properties
  (position, layer, ...) for already inserted blocks.
  On complex entities you must (entupd) the header entity, to see
  the update on the screen (forces an element REGEN).
  ;;; Example:
  (setq s (getstring "Change Attribute to: "))
  (attchg (attele (setq b (entsel "of block: ")) s)))
  (entupd (car b))        ; the block, not the attribute
  ;;; some more helper funcs to get the main entity of any attribute
  ;;; or vertex
  (defun main-entity (ele)
    (setq b (entity b))   ;force ENAME
    (while (istypep b '("ATTRIB" "ATTDEF" "VERTEX"))
      (setq b (entnext b)))               ;loop until no more sub-ents
    (if (istypep b '("SEQEND" "ENDBLK"))
      (getval -2 b)                       ;complex entity -> header
      b                                   ;normal entity
    )
  )
[22.4] How to ENTMAKE a Block Complex Entity in AutoLISP
   see http://www.autodesk.com/support/techdocs/acadcdi/td300515.htm
   There is an example how to use multiple calls to (entmake) to create
   the block header, the entities, closes the block and finally
   (entmake) the INSERT.
     For anonymous blocks beware that only
   (setq bn (entmake '((0 . "ENDBLK")))) returns the blockname for
   (entmake (list '(0 . "INSERT")(cons 2 bn) ...))
------------------------------
Subject: [23] Polylines
R14 LWPOLYLINE's store the vertices in one entity as multiple 10
groups.
[23.1] How to access polyline VERTICES?
  A polyline VERTEX is a subentity of a POLYLINE (same as an ATTRIBUTE
  is a subentity of an INSERT element or a ATTDEF of a BLOCK).
  Therefore the same functions as in [22.1]-[22.3] can be used.
  ;;; return the vertex list of a polyline or of any other element
  ;;; Note that with edlgetent mentioned in [22.1] it's a one-liner
  (defun getpts (ele / pts)
    (cond
      ((istypep ele "POLYLINE")
        (while (not (istypep (setq ele (entnext ele)) "SEQEND"))
          ;;omit fit and spline points  (conservative style)
          (if (not (or (flagsetp 1 ele) (flagsetp 8 ele))) ;bugfix!
            (setq pts (cons (getpt ele) pts))
          )
          pts
        )
      )
      ;; special case: you have to map it, assoc finds only the first
      ((istypep ele "LWPOLYLINE")
        (apply 'append (mapcar
         '(lambda (x) (if (= (car x) 10) (cdr x))) ;group 10 only
         (entget (entity ele)))))
      ;; insert here possible other types, such as
      ((istypep ele '("TEXT" "CIRCLE")) (list (getpt ele)))
      ;; more like this (serge's style)
      (T (apply 'append (mapcar
        '(lambda (n / p) (if (setq p (getval n ele)) (list p)))
        '(10 11 12 13)))
      )
      ;; or like this (conservative style)
      ;;(T (foreach n '(10 11 12 13)
      ;;     (if (setq p (getval n ele)) (setq pts (cons p pts))))
      ;;  pts
      ;;)
    )
  )
  Suggestions by Vladimir Nesteroswky for a different vertex structure:
  (defun vertices-and-bulges (pline-ename)
    (mapcar 'cdr
      (remove-if-not '(lambda (ele) (bitsetp 9 x))
        (get '(70 10 42) (cdr (edlgetent pline-ename))
  => list of (10 42) pairs of the pline
  see also [23.5] for a different edge structure (segments) of plines.
[23.2] How to JOIN multiple lines to polylines?
  Simply try to join each element with all selected, but beware that
  an entity already joined cannot be entget'ed anymore, because it's
  deleted.
  ;;; This sample converts all selected elements to polylines and
  ;;;  tries to join as much as possible.
  (defun C:JOINPOLY (/ ele ss)
    (foreach ele (sslist (setq ss (ssget)))     ;better process lists
      (if (entget ele)                          ;not already joined
        (cond                                   ;(then it would be nil)
          ((istypep ele '("ARC" "LINE"))
            ;; in fact you should check Z of lines and UCS here too
            (command "_PEDIT" ele "_Y" "_J" ss "" ""); convert and JOIN
          )
          ((and (istypep b '("POLYLINE" "LWPOLYLINE"))
                (not (flagsetp 1 ele))           ;not closed
                (< (rem (getflag ele) 128) 8))  ;ignore meshes and such
            (command "_PEDIT" ele "_J" ss "" "");ucs check omitted
          )
        )
      )
    )
  )
[23.3] Change WIDTH of multiple polylines
  With the help of the above defined helper function it's a short one:
  (defun C:POLYWID (/ wid ele)
    (initget 5)(setq wid (getdist "New Polyline Width: ")) ;not negative
    (foreach ele (sslist (ssget '((0 . "*POLYLINE"))))     ;only PLINES
      (command "_PEDIT" ele "_W" wid "")))
[23.4] Create a polyline or spline: with (ENTMAKE) or (COMMAND)
  1. You can create a script-file with a LISP-program and then run it.
  It seems to be the simpliest way, but I/O errors may occur when
  reading/writing the script. If your soft is commercial, it must handle
  such errors.
  2. The second way is to create the entities list and use ENTMAKE.
  Advantage: fast, in WCS, independent of actual osnaps.
  see http://www.autodesk.com/support/techdocs/acadcdi/td300510.htm
  3. The third solution is based on command and mapcar. It works with
  Polylines, Splines or Lines. Disadvantage: UCS, Osnaps
  ;;; Draws a POLYLINE entity from a list of points (same with SPLINE,
  ;;;  or LINE), on the actual UCS, with actual OSNAP settings
  (defun DRAW-PLINE (pts)
    (command "_PLINE")
    (mapcar 'command pts)
    (command ""))
  (defun DRAW-SPLINE (pts)
    (command "_SPLINE")
    (mapcar 'command pts)   ; the pts must be the fitpoints then
    (command "" "" ""))
[23.5] How to calculate the LENGTH of polylines?
  There are two ways:
  1. the obvious, using the AREA command which is quite "noisy"
    (prints the result), but works even with splines.
  ;;; add up the LENGTH of all selected objects, NOISY, you can do the
  ;;; same with AREAs: simply change the last line to (getvar "AREA")
  (defun C:LEN-OF ()
    (command "_AREA" "_A" "_E")           ;add up objects (for R12+13)
    (ssapply 'command (ssget))            ;pass all elements to AutoCAD
    (command "" "")                       ;two returns
    (getvar "PERIMETER"))                 ;this is the length
  2. Doing some math, but only for simple entities. Here it is best to
    define some helper functions again. This is also an introduction for
    the next chapter [24], some bulge trigonometry for curved segments.
  ;;; calculates length of a pline, quiet
  (defun poly-length (poly / seg)
    (apply '+             ; the sum of all single segment lengths
      (mapcar
       '(lambda (seg)                         ;length of one segment
          (if (zerop (car seg))               ;is it straight?
            (distance (cadr seg) (caddr seg)) ; line segment or
            (abs (arclen seg))                ; curved: -> [24]
          )
        )
        (pline-segs poly))))        ;segment list (bulge p1 p2)
  ;;; creates a segment list for the polyline pname
  ;;;   as a list of '(bulge p1 p2). a straight line has bulge 0.0
  ;;; compute pts in ECS of pname.
  ;;; Does NOT work with the new LWPOLYLINE yet!
  (defun pline-segs (pname / b line segs first)
    (setq b (entity pname))                   ; for type-safety
    (while (not (istypep (setq b (entnext b)) "SEQEND"))
      (if (not (flagsetp 16 b))               ; ignore this
        (if first
          (setq segs (cons             ;lineseg: list of '(bulge p1 p2)
             (reverse (cons (trans (getpt b) 0 pname) line))
                       segs)
                line (list (trans (getpt b) 0 pname) (getval 42 b))
          )
          (setq first (trans (getpt b) 0 pname) ;only called once
                line (list first (getval 42 b))
          )
        )
      )
    )
    (if (flagsetp 1 pname)              ; closed polyline?
      (setq segs (reverse (cons (reverse (cons first line)) segs)))
      (setq segs (reverse segs))
    )
    segs
  )
  ;;; Example:   (a bit optimized for brevity :)
  ;;; Add up all the lengths of all selected polylines, quiet
  ;;; To accept also other entities, add those to pline-segs
  (defun C:POLYLEN ()
    (apply '+ (ssapply 'poly-length (ssget '((0 . "POLYLINE"))))))
For the sum of areas use either the noisy AREA command or implement
heron's formula for polygon areas (just for simple closed polygons).
------------------------------
Subject: [24] Circle/Arc Geometry: BULGE conversion, some trigonometry
  What is the *BULGE* in a polyline?
  The bulge is the tangent of one forth of the included angle of a
  curved segment. A bulge 0.0 means a straight segment.
  Together with the start- and endpoint it is sufficient information to
  quickly calculate all other required information of a curved segment.
    arclength = radius*angle
    bulge     = tan(ang/4)            (ccw: +, cw: -)
    angle     = 4*atan(bulge)
    bulge     = (2*altitude) / chord  (ccw: +, cw: -)
  see also http://www.autodesk.com/support/techdocs/lisp/fax797.htm
  for a sample program or the book "Maximizing AutoLISP" [2]
  ;;; SEG2CIR - converts a bulged segment (bulge pt1 pt2) of a polyline
  ;;;   to a circle (ctr rad), the start- and endpoints are known
  ;;;   therefore the angles too: (angle ctr pt1)(angle ctr pt2)
  ;;; returns nil on a straight segment!
  ;;; (bugfixed version. Thanks to Sergei Komarov)
  (defun seg2cir (seg / bulge p1 p2 cot x y rad dummy)
    (if (zerop (car seg))  ;straight line => invalid circle
      nil
      (setq bulge (car seg) p1 (cadr seg) p2 (caddr seg)
        cot (* 0.5 (- (/ 1.0 bulge) bulge))
        x (/ (- (+ (car  p1) (car  p2))
                (* (- (cadr p2) (cadr p1)) cot)) 2.0)
        y (/ (+ (+ (cadr p1) (cadr p2))
                (* (- (car  p2) (car  p1)) cot)) 2.0)
        rad (distance (list (car p1) (cadr p1)) (list x y))
        dummy (list (list x y) rad))))   ; return this, I hate progn's
  ;;; ARC2SEG   - inverse conversion
  ;;; calculates segment (bulge p1 p2) of arc
  ;;;   with given circle (ctr rad), start-angle, end-angle
  (defun arc2seg (cir ang1 ang2 / p1 p2)
    (setq p1 (polar (car cir) ang1 (cadr cir))
          p2 (polar (car cir) ang2 (cadr cir)))
    (list (arc2bul p1 p2 cir) p1 p2))
  ;;; ARC2BUL - calculates bulge of arc given the arc points and the
  ;;;   circle (ctr rad)
  (defun arc2bul (p1 p2 circle / ang)
    (tan (/ (- (angle (car cir) p2) (angle (car cir) p1)) 4.0)))
  ;;; BUL2ANG - returns angle of arc (bulge)
  (defun bul2ang (seg / ctr)
    (- (angle (setq ctr (car (seg2cir seg))) (cadr seg))
       (angle ctr (caddr seg))))
  ;;; ARC2ANG
  ;;; calculates angle of arc given the chord distance and radius
  (defun arc2ang (chord rad)
    (* 2.0 (atan
             (/ chord 2.0
               (sqrt (- (expt rad 2)
                        (expt (/ chord 2.0) 2)
  ) )      ) ) )     )  ;another way in the paren's world
  ;;; ARCLEN   - length of arc   = radius*angle,
  ;;; Note: +-, you'll need (abs (arclen seg)) for the distance
  (defun arclen (seg)
    (* (cadr (seg2cir seg))                 ;radius
       4.0 (atan (car seg))))               ;angle = 4*atan(bulge)
  (defun tan (x) (/ (sin x)(cos x)))
  (defun dtr (ang)(* pi (/ ang 180.0)))     ;degree to radian
  (defun rtd (ang)(/ (* ang 180.0) pi))     ;radian to degree
------------------------------
Subject: [25] DCL: listboxes with tabs or monotext font
  In Windows it's difficult to layout texts because of non-monospaced
  fonts. Try it with the tabs attribute in the list_box tile,
  such as:
    tabs = "0 20 40";
  and (set_tile "listbox" "Layer:\t0\twhite")
  try the following to use monospaced characters:
      : list_box {
          label = "Drawing";
          key = "dwglist";
          width = 50;
          fixed_width_font = true;   // <- monotext
      }
  Also have a look at the detab routine at
    http://xarch.tu-graz.ac.at/autocad/news/detab.lsp {not yet}
------------------------------
Subject: [26] EED Extended Entity Data: Select, Get and Store
[26.1] Select objects on their EED with (ssget "X")
  ;;; defines your appname header and delimiter (4 char regapp name
  ;;; according AAIG, AutoDESK Application Interoperation Guidelines)
  (setq appname "HUBU-")
  ;;; defines * for all sub types
  (setq allappnames (strcat appname "*"))
  ;;; eg: HUBU-LIST1, HUBU-LIST2
  ;;; here is how to get the first eed list from one element
  (defun get-eed-1st (ele)
    (cdadr (assoc -3 (entget (entity ele) (list allappnames)))))
  ;;; this gets all elements of appnames typ (wildcards allowed)
  (defun ssget-app (typ)  ;fast
    (ssget "X" (list (list -3 (list typ))))
  ;;; this gets only your elements
  (defun ssget-hubu (typ)  ;fast
    (ssget "X" (list (list -3 (list (strcat appname typ)))))
  (ssget-hubu "*")  ; will get all your elements
[26.2] Get EED from an object
  Check any XDATA with:   (entget (car (entsel)) '("*"))
  ;;; GETXDATA - get all XDATA lists from an element
  ;;; i.e with XDATA:
  ;;; (-3  ("HUBU-1" (1000 ."ASSHATCH")(1002 ."{")
  ;;;                (1070 . 1)(1002 ."}")))
  ;;; =>(("HUBU-1" (1000 ."ASSHATCH")(1002 ."{")(1070 . 1)(1002 ."}")))
  (defun getxdata (e apnlst)
    (cdr (assoc -3 (entget e apnlst))))
  ;;; GETXDATA-ALL - all lists without the regapp name
  ;;; => ((1000 ."ASSHATCH")(1002 ."{")(1070 . 1)(1002 ."}"))
  (defun getxdata-all (e apnlst)
    (apply 'append (mapcar 'cdr (getxdata e apnlst))))
  The regapp name is stripped here, because it's only used for fast
  ssget access. The different apps are divided by different
  (1000 . name) groups.
  For storing XDATA in an element see XDATA.LSP or XED.LSP though those
  examples are a bit disturbing.
  For advanced EED tricks, esp. converting the "{" "}" ADS resbuf style
  to Lisp lists and back, see
  http://xarch.tu-graz.ac.at/autocad/news/eed_retrieval.txt
------------------------------
Subject: [27] How to break a command in Lisp?
Also: "How do I press Break in AutoLISP?"
(command) without parameters works just like hitting Ctrl-C in R12 or
Esc in R13 at the command prompt. But it does not mimic Esc in a dialog
box. And it does not work within SCRIPTS. (command nil) is the same as
(command).
(command) breaks only the command functions, e.g. if you use the command
"DIM" inside AutoLISP, you must interrupt it by (command) after
dimensioning.
But it doesn't work, if you try to interrupt a lisp loop. There is
another function (exit) or (quit) -they do the same-, which
immediately break a Lisp program.
Example:
  (while T ; do         ; a never ending loop
    (princ "\nEnter a=")
    (setq a (getint))
    (if (zerop a)(exit)) ; Breaks Lisp and returns to the command mode.
  )
In this example (command) doesn't work. (exit) works exactly as
Ctrl-C. It prints "error: quit / exit abort" and outputs all
nested functions. To provide "silent" break you must include this
error message to an error handling function, e.g.:
  (setq olderr *error* *error* my_error)
  (defun my_error (s)
    (if (not (member s            ; msgs of the english version:
       '("Function cancelled" "console break" "quit / exit abort")))
      (princ (strcat "\nError: " s))
    )
    (setq *error* olderr)
  )
For scripts use this workaround by defining (cancel) in lisp, simply
  (defun cancel()
    (command)
    (command "resume")
  )
and SCRIPT.SCR:
..
[