EIEIO
EIEIO (“Enhanced Implementation of Emacs Interpreted Objects”) provides an Object Oriented layer for Emacs Lisp, following the basic concepts of the Common Lisp Object System (CLOS). It provides a framework for writing object-oriented applications in Emacs.
This manual documents EIEIO, an object framework for Emacs Lisp.
Copyright © 2007–2024 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover Texts being “A GNU Manual,” and with the Back-Cover Texts as in (a) below. A copy of the license is included in the section entitled “GNU Free Documentation License.”
(a) The FSF’s Back-Cover Text is: “You have the freedom to copy and modify this GNU manual.”
Table of Contents
- 1 Quick Start
- 2 Introduction
- 3 Building Classes
- 4 Making New Objects
- 5 Accessing Slots
- 6 Writing Methods
- 7 Method Invocation
- 8 Predicates and Utilities
- 9 Association Lists
- 10 Customizing Objects
- 11 Introspection
- 12 Base Classes
- 13 Browsing class trees
- 14 Class Values
- 15 Default Superclass
- 16 Signals
- 17 Naming Conventions
- 18 CLOS compatibility
- 19 Wish List
- Appendix A GNU Free Documentation License
- Function Index
Next: Introduction, Previous: EIEIO, Up: EIEIO [Contents][Index]
1 Quick Start
EIEIO provides an Object Oriented layer for Emacs Lisp. You can use EIEIO to create classes, methods for those classes, and instances of classes.
Here is a simple example of a class named person
, containing
three slots named name
, birthday
, and phone
:
(defclass person () ; No superclasses ((name :initarg :name :initform "" :type string :custom string :documentation "The name of a person.") (birthday :initarg :birthday :initform "Jan 1, 1970" :custom string :type string :documentation "The person's birthday.") (phone :initarg :phone :initform "" :documentation "Phone number.")) "A class for tracking people I know.")
Each class can have methods, which are defined like this:
(cl-defmethod call-person ((pers person) &optional scriptname) "Dial the phone for the person PERS. Execute the program SCRIPTNAME to dial the phone." (message "Dialing the phone for %s" (slot-value pers 'name)) (shell-command (concat (or scriptname "dialphone.sh") " " (slot-value pers 'phone))))
In this example, the first argument to call-person
is a list,
of the form (varname classname). varname is the
name of the variable used for the first argument; classname is
the name of the class that is expected as the first argument for this
method.
EIEIO dispatches methods based on the type of the first argument.
You can have multiple methods with the same name for different classes
of object. When the call-person
method is called, the first
argument is examined to determine the class of that argument, and the
method matching the input type is then executed.
Once the behavior of a class is defined, you can create a new
object of type person
. Objects are created by calling the
constructor. The constructor is a function with the same name as your
class which returns a new instance of that class. Here is an example:
(setq pers (person :name "Eric" :birthday "June" :phone "555-5555"))
For backward compatibility reasons, the first argument can be a string (a name given to this instance). Each instance used to be given a name, so different instances could be easily distinguished when debugging.
It can be a bit repetitive to also have a :name slot. To avoid doing
this, it is sometimes handy to use the base class eieio-named
.
See eieio-named
.
Calling methods on an object is a lot like calling any function. The first argument should be an object of a class which has had this method defined for it. In this example it would look like this:
(call-person pers)
or
(call-person pers "my-call-script")
In these examples, EIEIO automatically examines the class of
pers
, and ensures that the method defined above is called. If
pers
is some other class lacking a call-person
method, or
some other data type, Emacs signals a cl-no-applicable-method
error. Signals.
Next: Building Classes, Previous: Quick Start, Up: EIEIO [Contents][Index]
2 Introduction
First off, please note that this manual cannot serve as a complete introduction to object oriented programming and generic functions in LISP. Although EIEIO is not a complete implementation of the Common Lisp Object System (CLOS) and also differs from it in several aspects, it follows the same basic concepts. Therefore, it is highly recommended to learn those from a textbook or tutorial first, especially if you only know OOP from languages like C++ or Java. If on the other hand you are already familiar with CLOS, you should be aware that EIEIO does not implement the full CLOS specification and also differs in some other aspects which are mentioned below (also see CLOS compatibility).
EIEIO supports the following features:
- A structured framework for the creation of basic classes with attributes and methods using inheritance similar to CLOS.
- Type checking, and slot unbinding.
- Method definitions similar to CLOS.
- Simple and complex class browsers.
- Edebug support for methods.
- Imenu updates.
- Byte compilation support of methods.
- Help system extensions for classes and methods.
- Several base classes for interesting tasks.
- Simple test suite.
- Public and private classifications for slots (extensions to CLOS)
- Customization support in a class (extension to CLOS)
Due to restrictions in the Emacs Lisp language, CLOS cannot be completely supported, and a few functions have been added in place of setf. Here are some important CLOS features that EIEIO presently lacks:
- Support for metaclasses
There is just one default metaclass,
eieio-default-superclass
, and you cannot define your own. The:metaclass
tag indefclass
is ignored. Also, functions likefind-class
, which should return instances of the metaclass, behave differently in EIEIO in that they return symbols or plain structures instead.- EQL specialization
EIEIO does not support it.
:around
method tagThis CLOS method tag is non-functional.
- :default-initargs in
defclass
Each slot can have an
:initform
tag, so this is not really necessary.- Mock object initializers
Each class contains a mock object used for fast initialization of instantiated objects. Using functions with side effects on object slot values can potentially cause modifications in the mock object. EIEIO should use a deep copy but currently does not.
Next: Making New Objects, Previous: Introduction, Up: EIEIO [Contents][Index]
3 Building Classes
A class is a definition for organizing data and methods together. An EIEIO class has structures similar to the classes found in other object-oriented (OO) languages.
To create a new class, use the defclass
macro:
- Macro: defclass class-name superclass-list slot-list &rest options-and-doc ¶
-
Create a new class named class-name. The class is represented by a symbol with the name class-name. EIEIO stores the structure of the class as a symbol property of class-name (see Symbol Components in GNU Emacs Lisp Reference Manual).
When defining a class, EIEIO overwrites any preexisting variable or function bindings for the symbol class-name, which may lead to undesired consequences. Before naming a new class, you should check for name conflicts. To help avoid cross-package conflicts you should choose a name with the same prefix you chose for the rest of your package’s functions and variables (see Coding Conventions in GNU Emacs Lisp Reference Manual).
The class-name symbol’s variable documentation string is a modified version of the doc string found in options-and-doc. Each time a method is defined, the symbol’s documentation string is updated to include the method’s documentation as well.
The parent classes for class-name is superclass-list. Each element of superclass-list must be a class. These classes are the parents of the class being created. Every slot that appears in each parent class is replicated in the new class.
If two parents share the same slot name, the parent which appears in the superclass-list first sets the tags for that slot. If the new class has a slot with the same name as the parent, the new slot overrides the parent’s slot.
When overriding a slot, some slot attributes cannot be overridden because they break basic OO rules. You cannot override
:type
or:protection
.
Whenever defclass is used to create a new class, a predicate is
created for it, named CLASS-NAME-p
:
- Function: CLASS-NAME-p object ¶
Return non-
nil
if and only if OBJECT is of the class CLASS-NAME.
If non-
nil
,defclass
signals an error if a tag in a slot specifier is unsupported.This option is here to support programs written with older versions of EIEIO, which did not produce such errors.
Next: Slot Options, Up: Building Classes [Contents][Index]
3.1 Inheritance
Inheritance is a basic feature of an object-oriented language.
In EIEIO, a defined class specifies the super classes from which it
inherits by using the second argument to defclass
. Here is an
example:
(defclass my-baseclass () ((slot-A :initarg :slot-A) (slot-B :initarg :slot-B)) "My Baseclass.")
To subclass from my-baseclass
, we specify it in the superclass
list:
(defclass my-subclass (my-baseclass) ((specific-slot-A :initarg specific-slot-A) ) "My subclass of my-baseclass")
Instances of my-subclass
will inherit slot-A
and
slot-B
, in addition to having specific-slot-A
from the
declaration of my-subclass
.
EIEIO also supports multiple inheritance. Suppose we define a second baseclass, perhaps an “interface” class, like this:
(defclass my-interface () ((interface-slot :initarg :interface-slot)) "An interface to special behavior." :abstract t)
The interface class defines a special interface-slot
, and also
specifies itself as abstract. Abstract classes cannot be
instantiated. It is not required to make interfaces abstract, but it
is a good programming practice.
We can now modify our definition of my-subclass
to use this
interface class, together with our original base class:
(defclass my-subclass (my-baseclass my-interface) ((specific-slot-A :initarg specific-slot-A) ) "My subclass of my-baseclass")
With this, my-subclass
also has interface-slot
.
If my-baseclass
and my-interface
had slots with the same
name, then the superclass showing up in the list first defines the
slot attributes.
Inheritance in EIEIO is more than just combining different slots. It is also important in method invocation. Methods.
If a method is called on an instance of my-subclass
, and that
method only has an implementation on my-baseclass
, or perhaps
my-interface
, then the implementation for the baseclass is
called.
If there is a method implementation for my-subclass
, and
another in my-baseclass
, the implementation for
my-subclass
can call up to the superclass as well.
Next: Class Options, Previous: Inheritance, Up: Building Classes [Contents][Index]
3.2 Slot Options
The slot-list argument to defclass
is a list of elements
where each element defines one slot. Each slot is a list of the form
(SLOT-NAME :TAG1 ATTRIB-VALUE1 :TAG2 ATTRIB-VALUE2 :TAGN ATTRIB-VALUEN)
where SLOT-NAME is a symbol that will be used to refer to the slot. :TAG is a symbol that describes a feature to be set on the slot. ATTRIB-VALUE is a lisp expression that will be used for :TAG.
Valid tags are:
:initarg
A symbol that can be used in the argument list of the constructor to specify a value for this slot of the new instance being created.
A good symbol to use for initarg is one that starts with a colon
:
.The slot specified like this:
(myslot :initarg :myslot)
could then be initialized to the number 1 like this:
(myobject :myslot 1)
See Making New Objects.
:initform
An expression used as the default value for this slot.
If
:initform
is left out, that slot defaults to being unbound. It is an error to reference an unbound slot, so if you need slots to always be in a bound state, you should always use an:initform
specifier.Use
slot-boundp
to test if a slot is unbound (see Predicates and Utilities). Useslot-makeunbound
to set a slot to being unbound after giving it a value (see Accessing Slots).The value passed to initform used to be automatically quoted. Thus,
:initform (1 2 3)
will use the list as a value. This is incompatible with CLOS (which would signal an error since 1 is not a valid function) and will likely change in the future, so better quote your initforms if they’re just values.
:type
An unquoted type specifier used to validate data set into this slot. See Type Predicates in Common Lisp Extensions. Here are some examples:
symbol
A symbol.
number
A number type
my-class-name
An object of your class type.
(or null symbol)
A symbol, or
nil
.
:allocation
Either :class or :instance (defaults to :instance) used to specify how data is stored. Slots stored per instance have unique values for each object. Slots stored per class have shared values for each object. If one object changes a :class allocated slot, then all objects for that class gain the new value.
:documentation
Documentation detailing the use of this slot. This documentation is exposed when the user describes a class, and during customization of an object.
:accessor
Name of a generic function which can be used to fetch the value of this slot. You can call this function later on your object and retrieve the value of the slot.
This option is in the CLOS spec, but is not fully compliant in EIEIO.
:writer
Name of a generic function which will write this slot.
This option is in the CLOS spec, but is not fully compliant in EIEIO.
:reader
Name of a generic function which will read this slot.
This option is in the CLOS spec, but is not fully compliant in EIEIO.
:custom
A custom :type specifier used when editing an object of this type. See documentation for
defcustom
for details. This specifier is equivalent to the :type spec of adefcustom
call.This option is specific to Emacs, and is not in the CLOS spec.
:label
When customizing an object, the value of :label will be used instead of the slot name. This enables better descriptions of the data than would usually be afforded.
This option is specific to Emacs, and is not in the CLOS spec.
:group
Similar to
defcustom
’s :group command, this organizes different slots in an object into groups. When customizing an object, only the slots belonging to a specific group need be worked with, simplifying the size of the display.This option is specific to Emacs, and is not in the CLOS spec.
:printer
This routine takes a symbol which is a function name. The function should accept one argument. The argument is the value from the slot to be printed. The function in
object-write
will write the slot value out to a printable form onstandard-output
.The output format MUST be something that could in turn be interpreted with
read
such that the object can be brought back in from the output stream. Thus, if you wanted to output a symbol, you would need to quote the symbol. If you wanted to run a function on load, you can output the code to do the construction of the value.:protection
This is an old option that is not supported any more.
When using a slot referencing function such as
slot-value
, and the value behind slot is private or protected, then the current scope of operation must be within a method of the calling object.This protection is not enforced by the code any more, so it’s only useful as documentation.
Valid values are:
:public
Access this slot from any scope.
:protected
Access this slot only from methods of the same class or a child class.
:private
Access this slot only from methods of the same class.
This option is specific to Emacs, and is not in the CLOS spec.
Previous: Slot Options, Up: Building Classes [Contents][Index]
3.3 Class Options
In the options-and-doc arguments to defclass
, the
following class options may be specified:
:documentation
A documentation string for this class.
If an Emacs-style documentation string is also provided, then this option is ignored. An Emacs-style documentation string is not prefixed by the
:documentation
tag, and appears after the list of slots, and before the options.:allow-nil-initform
If this option is non-
nil
, and the:initform
isnil
, but the:type
is specifies something such asstring
then allow this to pass. The default is to have this option be off. This is implemented as an alternative to unbound slots.This option is specific to Emacs, and is not in the CLOS spec.
:abstract
A class which is
:abstract
cannot be instantiated, and instead is used to define an interface which subclasses should implement.This option is specific to Emacs, and is not in the CLOS spec.
:custom-groups
This is a list of groups that can be customized within this class. This slot is auto-generated when a class is created and need not be specified. It can be retrieved with the
class-option
command, however, to see what groups are available.This option is specific to Emacs, and is not in the CLOS spec.
:method-invocation-order
This controls the order in which method resolution occurs for methods in cases of multiple inheritance. The order affects which method is called first in a tree, and if
cl-call-next-method
is used, it controls the order in which the stack of methods are run.Valid values are:
:breadth-first
Search for methods in the class hierarchy in breadth first order. This is the default.
:depth-first
Search for methods in the class hierarchy in a depth first order.
:c3
Searches for methods in a linearized way that most closely matches what CLOS does when a monotonic class structure is defined.
See Method Invocation, for more on method invocation order.
:metaclass
Unsupported CLOS option. Enables the use of a different base class other than
standard-class
.:default-initargs
Unsupported CLOS option. Specifies a list of initargs to be used when creating new objects. As far as I can tell, this duplicates the function of
:initform
.
See CLOS compatibility, for more details on CLOS tags versus EIEIO-specific tags.
Next: Accessing Slots, Previous: Building Classes, Up: EIEIO [Contents][Index]
4 Making New Objects
Suppose we have defined a simple class, such as:
(defclass my-class () ( ) "Doc String")
It is now possible to create objects of that class type.
Calling defclass
has defined two new functions. One is the
constructor my-class, and the other is the predicate,
my-class-p.
- Function: my-class object-name &rest slots ¶
-
This creates and returns a new object. This object is not assigned to anything, and will be garbage collected if not saved. This object will be given the string name object-name. There can be multiple objects of the same name, but the name slot provides a handy way to keep track of your objects. slots is just all the slots you wish to preset. Any slot set as such will not get its default value, and any side effects from a slot’s
:initform
that may be a function will not occur.An example pair would appear simply as
:value 1
. Of course you can do any valid Lispy thing you want with it, such as:value (if (boundp 'special-symbol) special-symbol nil)
Example of creating an object from a class:
(my-class :value 3 :reference nil)
To create an object from a class symbol, use make-instance
.
- Function: make-instance class &rest initargs ¶
Make a new instance of class based on initargs. class is a class symbol. For example:
(make-instance 'foo)
initargs is a property list with keywords based on the
:initarg
for each slot. For example:(make-instance
'foo
:slot1
value1:slotN
valueN)
Next: Writing Methods, Previous: Making New Objects, Up: EIEIO [Contents][Index]
5 Accessing Slots
There are several ways to access slot values in an object. The following accessors are defined by CLOS to reference or modify slot values, and use the previously mentioned set/ref routines.
- Function: slot-value object slot ¶
This function retrieves the value of slot from object. It can also be used on objects defined by
cl-defstruct
.This is a generalized variable that can be used with
setf
to modify the value stored in slot. See Generalized Variables in GNU Emacs Lisp Reference Manual.
- Function: set-slot-value object slot value ¶
This function sets the value of slot from object.
This is not a CLOS function. It is therefore recommended to use
(setf (slot-value object slot) value)
instead.
- Function: slot-makeunbound object slot ¶
This function unbinds slot in object. Referencing an unbound slot can signal an error.
The following accessors follow a naming and argument-order conventions are similar to those used for referencing vectors (see Vectors in GNU Emacs Lisp Reference Manual).
- Macro: oref obj slot ¶
This macro retrieves the value stored in obj in the named slot. Unlike
slot-value
, the symbol for slot must not be quoted.This is a generalized variable that can be used with
setf
to modify the value stored in slot. See Generalized Variables in GNU Emacs Lisp Reference Manual.
- Macro: oref-default class slot ¶
This macro returns the value of the class-allocated slot from class.
This is a generalized variable that can be used with
setf
to modify the value stored in slot. See Generalized Variables in GNU Emacs Lisp Reference Manual.
- Macro: oset object slot value ¶
This macro sets the value behind slot to value in object. It returns value.
- Macro: oset-default class slot value ¶
This macro sets the value for the class-allocated slot in class to value.
For example, if a user wanted all
data-objects
(see Building Classes) to inform a special object of his own devising when they changed, this can be arranged by simply executing this bit of code:(oset-default data-object reference (list my-special-object))
- Function: object-add-to-list object slot item &optional append ¶
In OBJECT’s slot, add item to the list of elements. Optional argument append indicates we need to append to the list. If item already exists in the list in slot, then it is not added. Comparison is done with equal through the member function call. If slot is unbound, bind it to the list containing item.
- Function: object-remove-from-list object slot item ¶
In OBJECT’s slot, remove occurrences of item. Deletion is done with delete, which deletes by side effect and comparisons are done with equal. If slot is unbound, do nothing.
- Function: with-slots spec-list object &rest body ¶
Bind spec-list lexically to slot values in object, and execute body. This establishes a lexical environment for referring to the slots in the instance named by the given slot-names as though they were variables. Within such a context the value of the slot can be specified by using its slot name, as if it were a lexically bound variable. Both
setf
andsetq
can be used to set the value of the slot.spec-list is of a form similar to let. For example:
((VAR1 SLOT1) SLOT2 SLOTN (VARN+1 SLOTN+1))
Where each var is the local variable given to the associated slot. A slot specified without a variable name is given a variable name of the same name as the slot.
(defclass myclass () ((x :initform 1))) (setq mc (make-instance 'myclass)) (with-slots (x) mc x) => 1 (with-slots ((something x)) mc something) => 1
Next: Method Invocation, Previous: Accessing Slots, Up: EIEIO [Contents][Index]
6 Writing Methods
Writing a method in EIEIO is similar to writing a function. The differences are that there are some extra options and there can be multiple definitions under the same function symbol.
Where a method defines an implementation for a particular data type, a generic method accepts any argument, but contains no code. It is used to provide the dispatching to the defined methods. A generic method has no body, and is merely a symbol upon which methods are attached. It also provides the base documentation for what methods with that name do.
Next: Methods, Up: Writing Methods [Contents][Index]
6.1 Generics
Each EIEIO method has one corresponding generic. This generic provides a function binding and the base documentation for the method symbol (see Symbol Components in GNU Emacs Lisp Reference Manual).
- Macro: cl-defgeneric method arglist [doc-string] ¶
This macro turns the (unquoted) symbol method into a function. arglist is the default list of arguments to use (not implemented yet). doc-string is the documentation used for this symbol.
A generic function acts as a placeholder for methods. There is no need to call
cl-defgeneric
yourself, ascl-defmethod
will call it if necessary. Currently the argument list is unused.cl-defgeneric
signals an error if you attempt to turn an existing Emacs Lisp function into a generic function.You can also create a generic method with
cl-defmethod
(see Methods). When a method is created and there is no generic method in place with that name, then a new generic will be created, and the new method will use it.
Next: Static Methods, Previous: Generics, Up: Writing Methods [Contents][Index]
6.2 Methods
A method is a function that is executed if the arguments passed to it matches the method’s specializers. Different EIEIO classes may share the same method names.
Methods are created with the cl-defmethod
macro, which is similar
to defun
.
- Macro: cl-defmethod method [:before | :around | :after ] arglist [doc-string] forms ¶
-
method is the name of the function to create.
:before
,:around
, and:after
specify execution order (i.e., when this form is called). If none of these symbols are present, the method is said to be a primary.arglist is the list of arguments to this method. The mandatory arguments in this list may have a type specializer (see the example below) which means that the method will only apply when those arguments match the given type specializer. An argument with no type specializer means that the method applies regardless of its value.
doc-string is the documentation attached to the implementation. All method doc-strings are incorporated into the generic method’s function documentation.
forms is the body of the function.
In the following example, we create a method mymethod
for the
classname
class:
(cl-defmethod mymethod ((obj classname) secondarg) "Doc string" )
This method only executes if the obj argument passed to it is an
EIEIO object of class classname
.
A method with no type specializer is a default method. If a given class has no implementation, then the default method is called when that method is used on a given object of that class.
Only one method per combination of specializers and qualifiers (:before
,
:around
, or :after
) is kept. If two cl-defmethod
s appear
with the same specializers and the same qualifiers, then the second
implementation replaces the first.
When a method is called on an object, but there is no method specified
for that object, but there is a method specified for object’s parent
class, the parent class’s method is called. If there is a method
defined for both, only the child’s method is called. A child method
may call a parent’s method using cl-call-next-method
, described
below.
If multiple methods and default methods are defined for the same method and class, they are executed in this order:
- :around methods
The most specific
:around
method is called first, which may invoke the less specific ones viacl-call-next-method
. If it doesn’t invokecl-call-next-method
, then no other methods will be executed. When there are no more:around
methods to call, falls through to run the other (non-:around
) methods. - :before methods Called in sequence from most specific to least specific.
- primary methods
The most specific method is called, which may invoke the less specific
ones via
cl-call-next-method
. - :after methods Called in sequence from least specific to most specific.
If no methods exist, Emacs signals a cl-no-applicable-method
error.
See Signals. If methods exist but none of them are primary, Emacs
signals a cl-no-primary-method
error. See Signals.
- Function: cl-call-next-method &rest replacement-args ¶
-
This function calls the superclass method from a subclass method. This is the “next method” specified in the current method list.
If replacement-args is non-
nil
, then use them instead of the arguments originally provided to the method.Can only be used from within the lexical body of a primary or around method.
- Function: cl-next-method-p ¶
Non-
nil
if there is a next method.Can only be used from within the lexical body of a primary or around method.
Previous: Methods, Up: Writing Methods [Contents][Index]
6.3 Static Methods
Static methods do not depend on an object instance, but instead
operate on a class. You can create a static method by using
the subclass
specializer with cl-defmethod
:
(cl-defmethod make-instance ((class (subclass mychild)) &rest args) (let ((new (cl-call-next-method))) (push new all-my-children) new))
The argument of a static method will be a class rather than an object.
Use the functions oref-default
or oset-default
which
will work on a class.
A class’s make-instance
method is defined as a static
method.
Note: The subclass
specializer is unique to EIEIO.
Next: Predicates and Utilities, Previous: Writing Methods, Up: EIEIO [Contents][Index]
7 Method Invocation
When classes are defined, you can specify the
:method-invocation-order
. This is a feature specific to EIEIO.
This controls the order in which method resolution occurs for
methods in cases of multiple inheritance. The order
affects which method is called first in a tree, and if
cl-call-next-method
is used, it controls the order in which the
stack of methods are run.
The original EIEIO order turned out to be broken for multiple inheritance, but some programs depended on it. As such this option was added when the default invocation order was fixed to something that made more sense in that case.
Valid values are:
:breadth-first
Search for methods in the class hierarchy in breadth first order. This is the default.
:depth-first
Search for methods in the class hierarchy in a depth first order.
:c3
Searches for methods in a linearized way that most closely matches what CLOS does when a monotonic class structure is defined.
This is derived from the Dylan language documents by Kim Barrett et al.: A Monotonic Superclass Linearization for Dylan Retrieved from: https://doi.org/10.1145/236338.236343
Next: Association Lists, Previous: Method Invocation, Up: EIEIO [Contents][Index]
8 Predicates and Utilities
Now that we know how to create classes, access slots, and define methods, it might be useful to verify that everything is doing ok. To help with this a plethora of predicates have been created.
- Function: find-class symbol &optional errorp ¶
Return the class that symbol represents. If there is no class,
nil
is returned if errorp isnil
. If errorp is non-nil
,wrong-argument-type
is signaled.
- Function: class-p class ¶
Return
t
if class is a valid class object. class is a symbol.
- Function: slot-exists-p object-or-class slot ¶
Non-
nil
if object-or-class has slot.
- Function: slot-boundp object slot ¶
Non-
nil
if OBJECT’s slot is bound. Setting a slot’s value makes it bound. Calling slot-makeunbound will make a slot unbound. object can be an instance or a class.
- Function: eieio-class-name class ¶
Return the class name as a symbol.
- Function: class-option class option ¶
Return the value in CLASS of a given OPTION. For example:
(class-option eieio-default-superclass :documentation)
Will fetch the documentation string for
eieio-default-superclass
.
- Function: eieio-object-name obj ¶
Return a string of the form ‘#<object-class myobjname>’ for obj. This should look like Lisp symbols from other parts of Emacs such as buffers and processes, and is shorter and cleaner than printing the object’s record. It is more useful to use
object-print
to get an object’s print form, as this allows the object to add extra display information into the symbol.
- Function: eieio-object-class obj ¶
Returns the class symbol from obj.
- Function: eieio-object-class-name obj ¶
Returns the symbol of obj’s class.
- Function: eieio-class-parents class ¶
Returns the direct parents class of class. Returns
nil
if it is a superclass.
- Function: eieio-class-parents-fast class ¶
Just like
eieio-class-parents
except it is a macro and no type checking is performed.
- Function: eieio-class-parent class ¶
Deprecated function which returns the first parent of class.
- Function: eieio-class-children class ¶
Return the list of classes inheriting from class.
- Function: eieio-class-children-fast class ¶
Just like
eieio-class-children
, but with no checks.
- Function: same-class-p obj class ¶
Returns
t
if obj’s class is the same as class.
- Function: object-of-class-p obj class ¶
Returns
t
if obj inherits anything from class. This is different fromsame-class-p
because it checks for inheritance.
- Function: child-of-class-p child class ¶
Returns
t
if child is a subclass of class.
- Function: generic-p method-symbol ¶
Returns
t
ifmethod-symbol
is a generic function, as opposed to a regular Emacs Lisp function.
Next: Customizing Objects, Previous: Predicates and Utilities, Up: EIEIO [Contents][Index]
9 Association Lists
Lisp offers the concept of association lists, with primitives such as
assoc
used to access them. The following functions can be used
to manage association lists of EIEIO objects:
- Function: object-assoc key slot list ¶
Return an object if key is equal to SLOT’s value of an object in list. list is a list of objects whose slots are searched. Objects in list do not need to have a slot named slot, nor does slot need to be bound. If these errors occur, those objects will be ignored.
- Function: object-assoc-list slot list ¶
Return an association list generated by extracting slot from all objects in list. For each element of list the
car
is the value of slot, and thecdr
is the object it was extracted from. This is useful for generating completion tables.
- Function: eieio-build-class-alist &optional base-class ¶
Returns an alist of all currently defined classes. This alist is suitable for completion lists used by interactive functions to select a class. The optional argument base-class allows the programmer to select only a subset of classes which includes base-class and all its subclasses.
Next: Introspection, Previous: Association Lists, Up: EIEIO [Contents][Index]
10 Customizing Objects
EIEIO supports the Custom facility through two new widget types.
If a variable is declared as type object
, then full editing of
slots via the widgets is made possible. This should be used
carefully, however, because modified objects are cloned, so if there
are other references to these objects, they will no longer be linked
together.
If you want in place editing of objects, use the following methods:
- Function: eieio-customize-object object ¶
Create a custom buffer and insert a widget for editing object. At the end, an
Apply
andReset
button are available. This will edit the object "in place" so references to it are also changed. There is no effort to prevent multiple edits of a singular object, so care must be taken by the user of this function.
- Function: eieio-custom-widget-insert object flags ¶
This method inserts an edit object into the current buffer in place. It is implemented as
(widget-create 'object-edit :value object)
. This method is provided as a locale for adding tracking, or specializing the widget insert procedure for any object.
To define a slot with an object in it, use the object
tag. This
widget type will be automatically converted to object-edit
if you
do in place editing of you object.
If you want to have additional actions taken when a user clicks on the
Apply
button, then overload the method eieio-done-customizing
.
This method does nothing by default, but that may change in the future.
This would be the best way to make your objects persistent when using
in-place editing.
10.1 Widget extension
When widgets are being created, one new widget extension has been added,
called the :slotofchoices
. When this occurs in a widget
definition, all elements after it are removed, and the slot is specifies
is queried and converted into a series of constants.
(choice (const :tag "None" nil) :slotofchoices morestuff)
and if the slot morestuff
contains (sym1 sym2 sym3)
, the
above example is converted into:
(choice (const :tag "None" nil) (const sym1) (const sym2) (const sym3))
This is useful when a given item needs to be selected from a list of items defined in this second slot.
Next: Base Classes, Previous: Customizing Objects, Up: EIEIO [Contents][Index]
11 Introspection
Introspection permits a programmer to peek at the contents of a class without any previous knowledge of that class. While EIEIO implements objects on top of records, and thus everything is technically visible, some functions have been provided. None of these functions are a part of CLOS.
- Function: eieio-class-slots obj ¶
Return the list of public slots for obj.
Next: Browsing class trees, Previous: Introspection, Up: EIEIO [Contents][Index]
12 Base Classes
All defined classes, if created with no specified parent class,
inherit from a special class called eieio-default-superclass
.
See Default Superclass.
Often, it is more convenient to inherit from one of the other base classes provided by EIEIO, which have useful pre-defined properties. (Since EIEIO supports multiple inheritance, you can even inherit from more than one of these classes at once.)
eieio-instance-inheritor
eieio-instance-tracker
eieio-singleton
eieio-persistent
eieio-named
eieio-speedbar
Next: eieio-instance-tracker
, Up: Base Classes [Contents][Index]
12.1 eieio-instance-inheritor
This class is defined in the package eieio-base.
Instance inheritance is a mechanism whereby the value of a slot in object instance can reference the parent instance. If the parent’s slot value is changed, then the child instance is also changed. If the child’s slot is set, then the parent’s slot is not modified.
- Class: eieio-instance-inheritor parent-instance ¶
A class whose instances are enabled with instance inheritance. The parent-instance slot indicates the instance which is considered the parent of the current instance. Default is
nil
.
To use this class, inherit from it with your own class.
To make a new instance that inherits from and existing instance of your
class, use the clone
method with additional parameters
to specify local values.
The eieio-instance-inheritor
class works by causing cloned
objects to have all slots unbound. This class’ slot-unbound
method will cause references to unbound slots to be redirected to the
parent instance. If the parent slot is also unbound, then
slot-unbound
will signal an error named slot-unbound
.
Next: eieio-singleton
, Previous: eieio-instance-inheritor
, Up: Base Classes [Contents][Index]
12.2 eieio-instance-tracker
This class is defined in the package eieio-base.
Sometimes it is useful to keep a master list of all instances of a given
class. The class eieio-instance-tracker
performs this task.
- Class: eieio-instance-tracker tracking-symbol ¶
Enable instance tracking for this class. The slot tracking-symbol should be initialized in inheritors of this class to a symbol created with
defvar
. This symbol will serve as the variable used as a master list of all objects of the given class.
- Method on eieio-instance-tracker: initialize-instance obj slot ¶
This method is defined as an
:after
method. It adds new instances to the master list.
- Method on eieio-instance-tracker: delete-instance obj ¶
Remove obj from the master list of instances of this class. This may let the garbage collector nab this instance.
- eieio-instance-tracker-find: key slot list-symbol ¶
This convenience function lets you find instances. key is the value to search for. slot is the slot to compare KEY against. The function
equal
is used for comparison. The parameter list-symbol is the variable symbol which contains the list of objects to be searched.
Next: eieio-persistent
, Previous: eieio-instance-tracker
, Up: Base Classes [Contents][Index]
12.3 eieio-singleton
This class is defined in the package eieio-base.
- Class: eieio-singleton ¶
Inheriting from the singleton class will guarantee that there will only ever be one instance of this class. Multiple calls to
make-instance
will always return the same object.
Next: eieio-named
, Previous: eieio-singleton
, Up: Base Classes [Contents][Index]
12.4 eieio-persistent
This class is defined in the package eieio-base.
If you want an object, or set of objects to be persistent, meaning the
slot values are important to keep saved between sessions, then you will
want your top level object to inherit from eieio-persistent
.
To make sure your persistent object can be moved, make sure all file
names stored to disk are made relative with
eieio-persistent-path-relative
.
- Class: eieio-persistent file file-header-line ¶
Enables persistence for instances of this class. Slot file with initarg
:file
is the file name in which this object will be saved. Class allocated slot file-header-line is used with methodobject-write
as a header comment.
All objects can write themselves to a file, but persistent objects have several additional methods that aid in maintaining them.
- Method on eieio-persistent: eieio-persistent-save obj &optional file ¶
Write the object obj to its file. If optional argument file is specified, use that file name instead.
- Method on eieio-persistent: eieio-persistent-path-relative obj file ¶
Return a file name derived from file which is relative to the stored location of OBJ. This method should be used to convert file names so that they are relative to the save file, making any system of files movable from one location to another.
- Method on eieio-persistent: object-write obj &optional comment ¶
Like
object-write
forstandard-object
, but will derive a header line comment from the class allocated slot if one is not provided.
- Function: eieio-persistent-read filename &optional class allow-subclass ¶
Read a persistent object from filename, and return it. Signal an error if the object in FILENAME is not a constructor for CLASS. Optional allow-subclass says that it is ok for
eieio-persistent-read
to load in subclasses of class instead of being pedantic.
Next: eieio-speedbar
, Previous: eieio-persistent
, Up: Base Classes [Contents][Index]
12.5 eieio-named
This class is defined in the package eieio-base.
- Class: eieio-named ¶
Object with a name. Name storage already occurs in an object. This object provides get/set access to it.
Previous: eieio-named
, Up: Base Classes [Contents][Index]
12.6 eieio-speedbar
This class is in package eieio-speedbar.
If a series of class instances map to a tree structure, it is possible to cause your classes to be displayable in Speedbar. See (speedbar)Top. Inheriting from these classes will enable a speedbar major display mode with a minimum of effort.
- Class: eieio-speedbar buttontype buttonface ¶
Enables base speedbar display for a class. The slot buttontype is any of the symbols allowed by the function
speedbar-make-tag-line
for the exp-button-type argument See (speedbar)Extending. The slot buttonface is the face to use for the text of the string displayed in speedbar. The slots buttontype and buttonface are class allocated slots, and do not take up space in your instances.
This class inherits from
eieio-speedbar
and initializes buttontype and buttonface to appear as directory level lines.
This class inherits from
eieio-speedbar
and initializes buttontype and buttonface to appear as file level lines.
To use these classes, inherit from one of them in you class. You can use multiple inheritance with them safely. To customize your class for speedbar display, override the default values for buttontype and buttonface to get the desired effects.
Useful methods to define for your new class include:
- Method on eieio-speedbar: eieio-speedbar-derive-line-path obj depth ¶
Return a string representing a directory associated with an instance of obj. depth can be used to index how many levels of indentation have been opened by the user where obj is shown.
- Method on eieio-speedbar: eieio-speedbar-description obj ¶
Return a string description of OBJ. This is shown in the minibuffer or tooltip when the mouse hovers over this instance in speedbar.
- Method on eieio-speedbar: eieio-speedbar-child-description obj ¶
Return a string representing a description of a child node of obj when that child is not an object. It is often useful to just use item info helper functions such as
speedbar-item-info-file-helper
.
Return a string which is the text displayed in speedbar for obj.
- Method on eieio-speedbar: eieio-speedbar-object-children obj ¶
Return a list of children of obj.
- Method on eieio-speedbar: eieio-speedbar-child-make-tag-lines obj depth ¶
This method inserts a list of speedbar tag lines for obj to represent its children. Implement this method for your class if your children are not objects themselves. You still need to implement
eieio-speedbar-object-children
.In this method, use techniques specified in the Speedbar manual. See (speedbar)Extending.
Some other functions you will need to learn to use are:
- eieio-speedbar-create: make-map key-map menu name toplevelfn ¶
Register your object display mode with speedbar. make-map is a function which initialized you keymap. key-map is a symbol you keymap is installed into. menu is an easy menu vector representing menu items specific to your object display. name is a short string to use as a name identifying you mode. toplevelfn is a function called which must return a list of objects representing those in the instance system you wish to browse in speedbar.
Read the Extending chapter in the speedbar manual for more information on how speedbar modes work See (speedbar)Extending.
Next: Class Values, Previous: Base Classes, Up: EIEIO [Contents][Index]
13 Browsing class trees
The command M-x eieio-browse displays a buffer listing all the
currently loaded classes in Emacs. The classes are listed in an
indented tree structure, starting from eieio-default-superclass
(see Default Superclass).
With a prefix argument, this command prompts for a class name; it then lists only that class and its subclasses.
Here is a sample tree from our current example:
eieio-default-superclass +--data-object +--data-object-symbol
Note: new classes are consed into the inheritance lists, so the tree comes out upside-down.
Next: Default Superclass, Previous: Browsing class trees, Up: EIEIO [Contents][Index]
14 Class Values
You can use the normal describe-function
command to retrieve
information about a class. Running it on constructors will show a
full description of the generated class. If you call it on a generic
function, all implementations of that generic function will be listed,
together with links through which you can directly jump to the source.
Next: Signals, Previous: Class Values, Up: EIEIO [Contents][Index]
15 Default Superclass
All defined classes, if created with no specified parent class, will
inherit from a special class stored in
eieio-default-superclass
. This superclass is quite simple, but
with it, certain default methods or attributes can be added to all
objects. In CLOS, this would be named STANDARD-CLASS
, and that
symbol is an alias to eieio-default-superclass
.
Currently, the default superclass is defined as follows:
(defclass eieio-default-superclass nil nil "Default parent class for classes with no specified parent class. Its slots are automatically adopted by classes with no specified parents. This class is not stored in the `parent' slot of a class object." :abstract t)
The default superclass implements several methods providing a default behavior for all objects created by EIEIO.
Next: Basic Methods, Up: Default Superclass [Contents][Index]
15.1 Initialization
When creating an object of any type, you can use its constructor, or
make-instance
. This, in turns calls the method
initialize-instance
, which then calls the method
shared-initialize
.
These methods are all implemented on the default superclass so you do not need to write them yourself, unless you need to override one of their behaviors.
Users should not need to call initialize-instance
or
shared-initialize
, as these are used by make-instance
to
initialize the object. They are instead provided so that users can
augment these behaviors.
- Function: initialize-instance obj &rest slots ¶
Initialize obj. Sets slots of obj with slots which is a list of name/value pairs. These are actually just passed to
shared-initialize
.
Sets slots of obj with slots which is a list of name/value pairs.
This is called from the default constructor.
Next: Signal Handling, Previous: Initialization, Up: Default Superclass [Contents][Index]
15.2 Basic Methods
Additional useful methods defined on the base subclass are:
- Function: clone obj &rest params ¶
Make a copy of obj, and then apply params. params is a parameter list of the same form as initialize-instance which are applied to change the object. When overloading clone, be sure to call cl-call-next-method first and modify the returned object.
- Function: object-print this &rest strings ¶
Pretty printer for object this. Call function eieio-object-name with strings. The default method for printing object this is to use the function eieio-object-name.
It is sometimes useful to put a summary of the object into the default #<notation> string when using eieio browsing tools.
Implement this function and specify strings in a call to cl-call-next-method to provide additional summary information. When passing in extra strings from child classes, always remember to prepend a space.
(defclass data-object () (value) "Object containing one data slot.") (cl-defmethod object-print ((this data-object) &optional strings) "Return a string with a summary of the data object as part of the name." (apply #'cl-call-next-method this (format " value: %s" (render this)) strings))
Here is what some output could look like:
(object-print test-object) => #<data-object test-object value: 3>
- Function: object-write obj &optional comment ¶
Write obj onto a stream in a readable fashion. The resulting output will be Lisp code which can be used with
read
andeval
to recover the object. Only slots with:initarg
s are written to the stream.
Previous: Basic Methods, Up: Default Superclass [Contents][Index]
15.3 Signal Handling
The default superclass defines methods for managing error conditions. These methods all throw a signal for a particular error condition.
By implementing one of these methods for a class, you can change the behavior that occurs during one of these error cases, or even ignore the error by providing some behavior.
- Function: slot-missing object slot-name operation &optional new-value ¶
Method invoked when an attempt to access a slot in object fails. slot-name is the name of the failed slot, operation is the type of access that was requested, and optional new-value is the value that was desired to be set.
This method is called from
slot-value
,set-slot-value
, and other functions which directly reference slots in EIEIO objects.The default method signals an error of type
invalid-slot-name
. See Signals.You may override this behavior, but it is not expected to return in the current implementation.
This function takes arguments in a different order than in CLOS.
- Function: slot-unbound object class slot-name fn ¶
Slot unbound is invoked during an attempt to reference an unbound slot. object is the instance of the object being reference. class is the class of object, and slot-name is the offending slot. This function throws the signal
unbound-slot
. You can overload this function and return the value to use in place of the unbound value. Argument fn is the function signaling this error. Use slot-boundp to determine if a slot is bound or not.In clos, the argument list is (class object slot-name), but eieio can only dispatch on the first argument, so the first two are swapped.
- Function: cl-no-applicable-method generic &rest args ¶
Called if there are no methods applicable for args in the generic function generic. args are the arguments that were passed to generic.
Implement this for a class to block this signal. The return value becomes the return value of the original method call.
- Function: cl-no-primary-method generic &rest args ¶
Called if there are methods applicable for args in the generic function generic but they are all qualified. args are the arguments that were passed to generic.
Implement this for a class to block this signal. The return value becomes the return value of the original method call.
- Function: cl-no-next-method generic method &rest args ¶
Called from cl-call-next-method when no additional methods are available. generic is the generic function being called on cl-call-next-method, method is the method where cl-call-next-method was called, and args are the arguments it is called by. This method signals cl-no-next-method by default. Override this method to not throw an error, and its return value becomes the return value of cl-call-next-method.
Next: Naming Conventions, Previous: Default Superclass, Up: EIEIO [Contents][Index]
16 Signals
There are new condition names (signals) that can be caught when using EIEIO.
- Signal: invalid-slot-name obj-or-class slot ¶
This signal is called when an attempt to reference a slot in an obj-or-class is made, and the slot is not defined for it.
- Signal: cl-no-applicable-method generic arguments ¶
This signal is called when generic is called, with arguments and nothing is resolved. This occurs when generic has been defined, but the arguments make it impossible for EIEIO to determine which method body to run.
To prevent this signal from occurring in your class, implement the method
cl-no-applicable-method
for your class. This method is called when to throw this signal, so implementing this for your class allows you block the signal, and perform some work.
- Signal: cl-no-primary-method generic arguments ¶
Like
cl-no-applicable-method
but applies when there are some applicable methods, but none of them are primary. You can similarly block it by implementing acl-no-primary-method
method.
- Signal: cl-no-next-method class arguments ¶
This signal is called if the function
cl-call-next-method
is called and there is no next method to be called.Overload the method
cl-no-next-method
to protect against this signal.
- Signal: invalid-slot-type slot spec value ¶
This signal is called when an attempt to set slot is made, and value doesn’t match the specified type spec.
In EIEIO, this is also used if a slot specifier has an invalid value during a
defclass
.
- Signal: unbound-slot object class slot ¶
This signal is called when an attempt to reference slot in object is made, and that instance is currently unbound.
Next: CLOS compatibility, Previous: Signals, Up: EIEIO [Contents][Index]
17 Naming Conventions
See Tips and Conventions in GNU Emacs Lisp Reference Manual, for a description of Emacs Lisp programming conventions. These conventions help ensure that Emacs packages work nicely one another, so an EIEIO-based program should follow them. Here are some conventions that apply specifically to EIEIO-based programs:
Jump to: | C D E F G I K M O S U W |
---|
Jump to: | C D E F G I K M O S U W |
---|