Files
cadcraft/docs/autolisp.md
T
code-compliantandClaude Fable 5.2 5f751ee30d AutoLISP: entnext reaches an INSERT's ATTRIBs and SEQEND (#1660) (#3396)
* AutoLISP: entnext reaches an INSERT's ATTRIBs and SEQEND (#1660)

- lisp: name an INSERT's ATTRIB and SEQEND records; entnext walks them, then the next main
  entity, and entget lists a record with its owner in group -2 (#1660)
- lisp: entmod of an ATTRIB takes its value (group 1) only, as one undo step; another property,
  a SEQEND, entdel and entmake of one return nil and change nothing (#1660)
- doc: the handles LISP named, shared with the drawing's snapshots and never given out by
  new_handle; 65,536 names, 1,024 probes past taken handles (#1660)
- io: entity_sub_record, one record of an INSERT at a time, never its other records (#1660)
- engine: an optional host hook for that record, so EntityCodec is unchanged (#1660)
- cli, web, app: install the hook; CLI tests for the walk, the value edit, the name bounds and
  the refusals (#1660)
- docs: autolisp.md on the records, their names, when a name ends, and the value-only edit (#1660)
- reused from #1753 (closed), with thanks: the entity_list extraction with the -2 owner, the
  writer's record splitting, and the entnext_walks_an_inserts_attribs test skeleton

* Keep AutoLISP's attribute names within their drawing

- Hold an INSERT's attribute names in the session's LISP state, not in
  cadcraft_doc::Drawing: comparing drawings is plain data again and takes no
  lock. The session reserves the handles in the drawing before any change, so
  new_handle still never gives one out, also after a drawing swap.
- End the names when the Block Editor closes: its drawing starts from the
  host's handles, so a name given there must never resolve to a host record.
- End only the erased reference's names on ERASE. Erasing another object
  leaves an attribute name holding, and OOPS still revives none.
- Go on to the next entity when an INSERT has no record provider installed.
- Refuse an ATTRIB edit whose outer list ends in an atom.

* Keep issued attribute names out of the drawing.

A copied drawing could reuse a name, and storing the names in the drawing marked a saved drawing changed.

* Name an INSERT's ATTRIBs and SEQEND apart from drawing handles

An ATTRIB or SEQEND has no handle of its own in the drawing, so the
name AutoLISP gives it is now a value of its own (an entity name for
`type`), numbered from one count for the whole process that never
gives a number twice. No handle of any drawing, of a copy of one, of
another session or of another thread can be such a name, so nothing
is reserved in the handle space any more: cadcraft-doc, `new_handle`
and the copy-then-install paths are as on main, and naming or reading
a record changes neither the drawing nor its saved state.

What a name stands for (reference, place, tag) stays in the engine's
LISP state, by document. Names end on Undo, Redo, ATTSYNC,
-BLOCKREPLACE, on opening and closing the Block Editor, and when a
change is taken back; erasing a reference ends only its names, and
OOPS or `entdel` bringing it back revives none. `entupd` of a record
answers its name; selection sets and `command` take no record.

Tests cover other sessions, documents and threads giving out handles
in a drawing copy, the copy paths (INSERT from a file, XATTACH, AUDIT,
REFCLOSE), and the AutoLISP behaviour of the names.

* Keep one ATTDEF index per state of a block's entities

EntityStore gets a content token: a clone has its store's, and every
edit gives the store one that no store has had. The DXF writer keys
its ATTDEF index on that token and keeps the indexes of several
blocks, up to a fixed number of tags in all. Two copies edited apart,
or a different edit after Undo, never read each other's definition
properties, in AutoLISP reads or in a saved file, and reads that
alternate between references of different blocks examine each
definition once.

* End record names when a command puts an earlier drawing back.

MOCORO Undo restored its history drawing, handle seed included, so the next Copy could reuse the removed reference's handle. That restore now advances the name epoch. An ATTDEF index that would pass the tag budget is not stored.

* Match an oversized ATTDEF definition in full and remember it is too large to index

* Count record names with try_update, not the deprecated fetch_update

Rust 1.100 deprecates fetch_update and names try_update in its place, so
clippy with -D warnings stopped the gate at RecordName::fresh. It is the
same operation: the checked increment and the None once the count runs
out are unchanged. try_update compiles on Rust 1.95, the workspace's
minimum.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* Record tests check the objects they rely on

Five tests could pass without the state they are about.

The two ATTDEF index tests changed only a layer, so both states of the
block gave T the same handle, and an index kept for the wrong state
still read the right layer. One state now keeps T on the first ATTDEF
and the other passes T to the second, on another layer. With one index
shared by every store, the old tests passed and these fail.

The MOCORO and grip Copy tests did not check that a copy was made, or
that the copy after the Undo took the removed copy's handle. They now
check both, and that the name read the first copy before the Undo.

The walk at the top of the handle range compared two values that are
both nil when the line at FFFFFFFFFFFFFFFF is not in the drawing. It
now reads that line first.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* Test that entdel preserves unrelated ATTRIB names

* Fix AutoLISP record lifetime and REFEDIT edits

* Run attribute name cases in engine integration suite

* Fix text fixtures after main merge

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 00:34:42 +01:00

177 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AutoLISP
CADCraft runs AutoLISP routines (`.lsp` files). What is here and what is not yet:
[gaps.md](gaps.md) (E1).
## Loading and running
- **APPLOAD** (Tools > Load Application…, alias `AP`) opens a file browser filtered to `.lsp`
files, starting in the folder the last one came from (kept in the preferences), and runs the
chosen file. Cancelling the browser does nothing. A picked file loads as a typed name does, so a
routine it starts that asks for a point waits for it. A desktop without a file browser asks for
the name on the command line; the web has no file system, so it says to drop the `.lsp` file on
the window and loads it from its contents. Only `.lsp` files are loaded; anything else is
refused.
- **`(load "name")`** loads a file by path, with `.lsp` added when the name has none. A file
APPLOAD loaded is found again by its name, also on the web where there is no file system.
- **`(defun c:NAME …)`** defines a command: type `NAME` at the command line. Built-in commands
keep their names.
- **At the command line**, `(expression)` evaluates and shows the value, and `!variable` shows a
variable. Space types a space while a `(...)` expression is open, and Space or Enter after its
closing parenthesis evaluates it. Typed at a command's prompt (not a free-text one), an
expression's value answers it: `CIRCLE 0,0 (* 2 r)`. The prompt waits for that value, so the
window doesn't redraw and Esc doesn't reach the expression until it ends: one that takes more
than 20 million steps (its callbacks included) stops with an error. Run long routines at
`Command:` instead.
- **Programmatically** (scripts, the control channel, MCP, the CLI): `lisp {code, inputs?}` and
`appload {path} | {name, text | data}` run to the end and return `{value, output, error?}`.
`appload` also returns `commands`, the `c:` commands the file defined, and a JSON call never
opens a file dialog. `inputs` answer `get…` calls in order (numbers, strings, `[x, y]` points);
a call with none left gets nil.
### At startup
CADCraft loads LISP from its **support folder**, `support` in the settings folder (on Windows
`%APPDATA%\CADCraft\support`, on macOS `~/Library/Application Support/CADCraft/support`, on
Linux `~/.config/cadcraft/support`; created at first start):
- `acad.lsp` once per session, into the first drawing; with `ACADLSPASDOC` set to 1, into every
drawing;
- `acaddoc.lsp` into every drawing opened or created;
- then `S::STARTUP`, when they define it.
`(autoload "file" '("CMD1" "CMD2"))` in a startup file makes `CMD1` and `CMD2` commands that load
`file` (from the support folder too) the first time they are typed. Startup files run to the end
without asking for input. A drawing's own folder is never searched: an `acaddoc.lsp` that came
with a downloaded drawing does not run.
Each drawing has its own variables and functions. A routine is one undo step, whatever commands
it runs. A routine that waits for input (`getpoint`, `pause`) lets the window work meanwhile;
Esc stops it with "Function cancelled", which `*error*` receives. A long loop runs a slice per
frame, so the window stays live and Esc stops it too.
A script (SCRIPT, `cadcraft-cli run --script`, the control channel's and MCP's `script`) lets a
routine it starts or answers run on to its end, or to the input it waits for, before it gives its
next input, since that input answers the routine or comes after it. The headless MCP server
(`cadcraft-cli mcp`), which has no frames, runs a routine typed at its command line on the same
way. Nothing can stop such a routine by hand, so one that takes more than 500 million steps stops
with an error, as a programmatic call does. In the window, a script holds the window until it
ends, its routines included.
## The language
Integers are 32-bit and wrap as AutoLISP's do; any real makes arithmetic real. A whole number
past that range read from text (source, `read`, `atoi`) or JSON, or made by `fix` or `gcd`, is a
real instead. Variables are dynamically scoped: a function's arguments and its locals (after `/`)
are bound while it runs. Symbols are case-insensitive. Reals print with six significant digits.
Nothing a routine does can crash the program: deep recursion is the error "internal stack limit
reached", malformed source is a reader error, and every built-in checks its arguments.
## Built-in functions
- **Forms:** `quote` `'` `function` `setq` `set` `if` `cond` `while` `repeat` `foreach` `progn`
`and` `or` `defun` `defun-q` `lambda` `eval` `apply` `mapcar` `load` `autoload` `exit` `quit`
- **Numbers:** `+ - * / rem 1+ 1- abs min max sqrt exp log sin cos atan expt fix float gcd
logand logior lsh ~ = /= < > <= >= zerop minusp numberp`
- **Lists:** `car cdr` and the `c…r` combinations up to four levels, `cons list append reverse
length nth last member assoc subst acad_strlsort`, `vl-position vl-remove vl-sort
vl-remove-if vl-remove-if-not vl-member-if vl-every vl-some vl-list-length vl-consp`
- **Predicates:** `atom listp null not type eq equal boundp vl-symbolp`
- **Strings:** `strcat strlen substr strcase itoa atoi atof chr ascii read wcmatch`,
`vl-string-search vl-string-subst vl-string-trim vl-string-left-trim vl-string-right-trim
vl-string-translate vl-string->list vl-list->string vl-prin1-to-string vl-princ-to-string
vl-symbol-name vl-symbol-value vl-filename-base vl-filename-extension vl-filename-directory`
- **Geometry:** `polar distance angle inters trans` (`trans` between the WCS (0), the current UCS (1), display coordinates (2, 3: the WCS in a plan view) and an object's OCS (an entity name or an extrusion direction); `getpoint` and friends answer in the current UCS and `command` takes UCS points, while entity lists stay in world coordinates)
- **Output and files:** `princ prin1 print prompt terpri alert open close read-line write-line
findfile`
- **Errors:** `*error*`, `vl-catch-all-apply vl-catch-all-error-p vl-catch-all-error-message`
- **Drawing:** `command` (also `command-s`, `vl-cmdf`) with `pause`, entity names and `entsel`
lists at prompts picking one object (a bare name picks at its DXF group 10 point, as in AutoCAD),
a command left open for the next call, and `(command)` to cancel; `getvar setvar`; `entget entmake entmod entdel entlast
entnext entupd handent regapp`; `ssget` (modes X, L, P, I, W, C, F, WP, CP, a point, or the user
selecting; filters with wildcards and `-4` operators) `ssadd ssdel sslength ssname ssmemb
sssetfirst ssgetfirst`; `tblsearch tblnext` (LAYER, LTYPE, STYLE, BLOCK, DIMSTYLE, APPID);
`namedobjdict dictsearch dictnext tblobjname`, with `entget` and `handent` of the non-graphic
objects they reach (table records, dictionaries, layouts and their plot settings)
- **Input:** `initget getpoint getcorner getdist getangle getorient getreal getint getstring
getkword entsel nentsel`
- **Units:** `rtos angtos distof angtof`
- **Angle variables:** `getvar` and `setvar` give and take ANGBASE, SNAPANG, POLARANG, HPANG,
CHAMFERD and DIMJOGANG in radians, as in AutoCAD; the SETVAR command shows them in degrees.
- **No-ops:** `vl-load-com gc redraw`; `ver`
Entity lists use the DXF group codes of CADCraft's DXF files: what `entget` returns is what a
DXF file holds for the object, plus `-1` (its name) and `410` (its layout). Angles (groups 50–58)
are in radians, as in AutoCAD, where the file holds degrees; `entmake`, `entmod` and `ssget`
filters take radians too. A block reference's list doesn't hold its attributes, and `entmod` of
it keeps them and their values. `entlast` and `entnext` see every change a routine makes, its
own `entmake`, `entmod` and `entdel` included. `(getvar "HANDSEED")` is the next handle the
drawing gives out, in hex.
Extended data (xdata) is the `-3` group, as in AutoCAD. `(entget ename '("APP" "PE_*"))` adds
`(-3 ("APP" (1000 . "text") (1070 . 3) (1040 . 2.5) (1010 x y z) (1005 . "2A") …) …)` for the
applications whose names match (any case, `wcmatch` wildcards; `'("*")` lists every
application); without the second argument the list holds no xdata. `entmake` puts a list's `-3`
group on the new entity. `entmod` keeps an entity's xdata unless the list has a `-3` group,
which replaces the data of the applications it names and removes one listed with no groups
(`(-3 ("APP"))`); other applications stay. Group codes, values and brace nesting are checked as
in a file (`entmod` and `entmake` answer nil to a bad `-3`). `(regapp "APP")` returns the name
when it is new and nil when the drawing already has that application's xdata (or `regapp`
registered it); saving writes an APPID record for every application with xdata anyway, and
`tblsearch "APPID"` lists them.
Block definitions can be read: `(tblsearch "BLOCK" name)` gives the block's first entity in group
-2, `entnext` goes from one entity of a definition to the next (nil after the last) and `entget`
lists them (without a layout, group 410). So a routine can read what a block stores, such as the
text of a dimension's `*D` block. `entmod` and `entdel` don't change a definition's entities.
`entmake` defines blocks: a BLOCK list (2 name, 70 flags, 10 base point, 4 description) begins a
definition, the entities made after it go into the block instead of the drawing, and an ENDBLK
list adds the block (redefining one of the same name) and returns its name. Flag 1 with a `*U`
name makes an anonymous block, named when it ends. A BLOCK while a definition is open, an
xref (flag 4), an invalid name, a block that inserts itself and a block being edited in place
(REFEDIT) return nil. A definition stays open across routines until ENDBLK, but a routine that
fails drops the one it began.
An INSERT in the drawing (not one inside a block definition) has its attributes as records
after it, and `entnext` reaches them: from the block reference to its first ATTRIB, from an
ATTRIB to the next, and from the last one to the SEQEND (group `-2`, its reference's name), then
on to the next main entity or nil. `entget` of an ATTRIB lists its groups with `-2` (its
reference) beside its name (group `-1`). CADCraft keeps no handle of its own for these records (a
DXF file's are the writer's), so their names are not handles: such a name is an entity name
(`type` gives `ENAME`) that no object of any drawing can ever have, printed as the reference's
handle, a dot and a number (`<Entity name: 2a.5>`). `handent` never returns one, and its list has
no group 5. `entmod` of an ATTRIB takes its value (group 1) only, as one undo step, and leaves its
tag, place, flags and properties as they are; any other edit, including one of the layout, owner,
handle or other groups the entity can't set, a `SEQEND` list, `entdel` and `entmake` of one
return nil and change nothing. `entupd` of one returns its name while it holds. A selection set
holds objects of the drawing only: `ssadd`, `ssdel` and `ssmemb` of such a name return nil, and
`command` given one picks nothing. `trans` does not take a record name: the coordinate system
has to be a number, an entity name or an extrusion direction, and a record name is an argument
error. `eq` and `equal` are true only for the same record name, the one a later walk returns
while that record holds, and they are false for another record and for an entity name. A fuzz
distance does not change that result. A name holds while its reference keeps that record in its
place with that tag: erasing the reference (also when OOPS or `entdel` brings it back), ATTSYNC,
-BLOCKREPLACE, opening and closing the Block Editor, Undo, Redo, a change taken back (a
refused or failed command) and a command that puts an earlier drawing back (MOCORO's Undo, a
grip copy's Undo, and the other restores of a saved drawing) end it (erasing another object
does not), and a name that ended names nothing (nil), never another record. A drawing holds at
most 65,536 such names at once; at the limit `entnext` gives no new one (nil) until names end
and make room.
Non-graphic objects (the named object dictionary and its dictionaries, layouts, table records)
are listed as a DXF file of the drawing holds them, pointers as entity names and group 5 (105 for a DIMSTYLE) as the
object's own name. An object read from a file keeps that file's handle as its name, so
`(handent "112C")` with a layer's handle from the file finds it; one the file didn't have gets a
name of its own (from `7F00000000000000` up). The names of table records, blocks, the named
object dictionary and its dictionaries' entries stay the same while the drawing is open, also
when it changes; an object deeper down (an entry of a dictionary inside those) keeps its name
only until the drawing changes, after which the old name finds nothing. These lists are read-only for now: `entmod` and `entmake` don't take them.
## Testing against the corpus
The AutoLISP conformance corpus (#648) lives in its own repository. Point `CADCRAFT_LISP_CORPUS`
at it and run `cargo test -p cadcraft-engine --test it lisp_corpus::`; without the variable the test
says it was skipped.