Python API

Emacs interface

Interface with Emacs and run commands.

exception emacs.emacs.ElispException[source]

Bases: Exception

An exception caught in Emacs while evaluating an expression.

message

Error message, from error-message-string.

Type

str

symbol

Error symbol, the car of the caught error object.

Type

str

data

Error data, the cdr of the caught error object.

Type

Any

expr

The expression that was being evaluated.

Type

emacs.elisp.ast.Expr

proc

Completed process object.

Type

subprocess.CompletedProcess

__init__(message, symbol, data, expr, proc)[source]
Parameters
class emacs.emacs.EmacsBase[source]

Bases: abc.ABC

Abstract base class for an interface to GNU Emacs.

cmd

Command to run with each invocation.

Type

Tuple[str]

logger

Logger instance (not yet implemented).

Type

logging.Logger

__init__(cmd, logger=None)[source]
Parameters
eval(src, *, catch_errors=True, ret='value', is_json=False, extra_args=None, tmpfile=False, **kw)[source]

Evaluate Elisp source code.

Parameters
  • src (Union[str, emacs.elisp.ast.Expr, Sequence[Union[str, emacs.elisp.ast.Expr]]]) – Elisp code. If a list of strings/expressions will be enclosed in progn.

  • catch_errors (bool) – Catch errors evaluating the expression in Emacs and raise an ElispException in Python.

  • ret (Optional[str]) – What to return. 'value' returns the value of the evaluated expression (must be something that can be JSON-encoded using (json-encode). 'subprocess' returns the subprocess.CompletedProcess` of the command that was run (can be used to get the raw output). 'both' returns a tuple (value, process). 'none' or None returns nothing. Use subprocess or none to avoid processing a potentially large amount of output you don’t care about.

  • extra_args (Optional[Iterable[str]]) – Additional arguments to pass to command.

  • tmpfile (bool) – Read result through temporary file instead of stdout. This may avoid certain issues emacsclient has when printing large amounts of output, or if the expression also has the side effect of printing to stdout.

  • is_json (bool) – If the result of evaluating src is already a json-encoded string that should be decoded.

  • kw – Passed to run().

Raises
Returns

See the ret argument.

Return type

Any

run(args, *, check=True, run_kw=None)[source]

Run the Emacs command with a list of arguments.

Parameters
  • args (Sequence[str]) – Arguments to run command with.

  • check (bool) – Check the return code is zero.

  • run_kw – Keyword arguments to pass to subprocess.run().

Raises

subprocess.CalledProcessError – If check=True and return code is nonzero.

Returns

Completed process object.

Return type

subprocess.CompletedProcess

class emacs.emacs.EmacsBatch[source]

Bases: emacs.emacs.EmacsBase

Interface to Emacs program using emacs --batch.

Parameters
  • cmd (Tuple[str]) – Base command to run. Name or path of emacs executable.

  • args – Additional arguments to add to cmd.

__init__(cmd='emacs', *, args=None, logger=None)[source]
Parameters
class emacs.emacs.EmacsClient[source]

Bases: emacs.emacs.EmacsBase

Interface to running Emacs server using emacsclient.

Parameters
  • cmd (Tuple[str]) – Base command to run. Name or path of emacsclient executable.

  • args – Additional arguments to add to cmd.

  • server – Name of server to connect to.

__init__(cmd='emacsclient', *, args=None, server=None, logger=None)[source]
Parameters
  • cmd (str) –

  • args (Optional[Sequence[str]]) –

  • server (Optional[str]) –

  • logger (Optional[logging.Logger]) –

emacs.emacs.el_catch_err_json(expr, encoded=False)[source]

Elisp snippet to catch errors and return the error message as encoded JSON.

Parameters
Return type

emacs.elisp.ast.Expr

emacs.emacs.el_encode_json(expr)[source]

Elisp snippet to encode value as JSON.

Parameters

expr (emacs.elisp.ast.Expr) –

Return type

emacs.elisp.ast.Expr

emacs.emacs.make_cmd(*parts)[source]

Concatenate arguments or lists of arguments to make command.

Parameters

parts (Optional[Union[str, Sequence[str]]]) –

Return type

List[str]

Elisp Expressions

Build and print Emacs Lisp abstract syntax trees in Python.

AST Classes

Base classes for Emacs Lisp abstract syntax trees.

class emacs.elisp.ast.Cons[source]

Bases: emacs.elisp.ast.Expr

A cons cell.

__init__(car, cdr)[source]
Parameters
class emacs.elisp.ast.Expr[source]

Bases: object

Base for classes which represent Elisp expressions.

quote()[source]

Return a quoted form of this expression.

Return type

emacs.elisp.ast.Expr

property q

Shortcut for self.quote().

class emacs.elisp.ast.List[source]

Bases: emacs.elisp.ast.Expr

An Elisp list expression.

items

Items in the list.

Type

Tuple[emacs.elisp.ast.Expr, …]

__init__(items)[source]
Parameters

items (Iterable[emacs.elisp.ast.Expr]) –

class emacs.elisp.ast.Literal[source]

Bases: emacs.elisp.ast.Expr

Basic self-evaluating expressions like strings, numbers, etc.

pyvalue

The Python value of the literal.

Type

Union[str, int, float]

__init__(pyvalue)[source]
Parameters

pyvalue (Union[str, int, float]) –

class emacs.elisp.ast.Quote[source]

Bases: emacs.elisp.ast.Expr

A quoted Elisp expression.

expr

The quoted Elisp expression.

__init__(expr)[source]
Parameters

expr (emacs.elisp.ast.Expr) –

class emacs.elisp.ast.Raw[source]

Bases: emacs.elisp.ast.Expr

Just raw Elisp code to be pasted in at this point.

src

Raw Elisp source code.

Type

str

__init__(src)[source]
Parameters

src (str) –

class emacs.elisp.ast.Symbol[source]

Bases: emacs.elisp.ast.Expr

An Elisp symbol.

__init__(name)[source]
Parameters

name (str) –

Creating expressions

Functions to build Elisp expressions (more) easily.

emacs.elisp.exprs.cons(car, cdr, *, convert_kw=None)[source]

Create a cons cell expression, converting both arguments first.

Parameters
  • car

  • cdr

  • convert_kw – Keyword arguments to to_elisp().

Return type

emacs.elisp.ast.Cons

emacs.elisp.exprs.el_bool(value)[source]

Convert a Python boolean to the standard Elisp representation.

Parameters

value (bool) –

Return type

emacs.elisp.ast.Expr

emacs.elisp.exprs.el_list(items, *, convert_kw=None)[source]

Create an Elisp list expression, converting items to Elisp expressions if needed.

Parameters
  • items (Iterable) – Contents of list.

  • convert_kw – Keyword arguments to to_elisp().

Return type

emacs.elisp.ast.List

emacs.elisp.exprs.funccall(f, *args, **kw)[source]

Create a function call expression.

Parameters
  • f (Union[str, emacs.elisp.ast.Symbol]) – Function name or symbol

  • args – Function arguments. Will be converted to Elisp expressions if necessary.

  • kw – Keyword arguments. Argument names are converted like my_num=1 -> :my-num 1.

emacs.elisp.exprs.get_src(src)[source]

Get Elisp source code as Expr instance.

Parameters

src (Union[str, emacs.elisp.ast.Expr, Sequence[Union[str, emacs.elisp.ast.Expr]]]) – Elisp expression(s) as either a string containing raw Elisp code, a single Expr, or a list of these.

Returns

Source code as single expression. If the input was a list it will be enclosed in a progn block.

Return type

Expr

emacs.elisp.exprs.let(assignments, *body)[source]

Make a “let” expression.

Parameters
  • assignments – Mapping from variable names (as symbols or strings) to values.

  • body – Expressions to add to body.

Return type

emacs.elisp.ast.List

emacs.elisp.exprs.make_alist(pairs, **kw)[source]

Create an alist expression from a set of key-value pairs.

Parameters
  • pairs (Union[collections.abc.Mapping, Iterable[Tuple]]) – Key-value pairs as a dict or collections of 2-tuples.

  • quote – Quote the resulting expression.

  • kw – Keyword arguments passed to to_elisp() to convert mapping values.

Return type

emacs.elisp.ast.Expr

emacs.elisp.exprs.make_plist(pairs, **kw)[source]

Create a plist expression from a set of key-value pairs.

Parameters
  • pairs (Union[collections.abc.Mapping, Tuple[Any, Any]]) – Key-value pairs as a dict or collections of 2-tuples.

  • kw – Keyword arguments passed to to_elisp() to convert mapping values.

Return type

emacs.elisp.ast.Expr

emacs.elisp.exprs.symbol(name, kebab=False, keyword=False)[source]

Convert argument to symbol.

Parameters
  • name (Union[str, emacs.elisp.ast.Symbol]) – Symbol name as string. Alternatively, an existing symbol instance which will be returned unchanged.

  • kebab (bool) – Convert name from snake_case to kebab-case.

  • keyword (bool) – Prefix name with “:” character if it doesn’t start with it already.

Return type

emacs.elisp.ast.Symbol

emacs.elisp.exprs.symbols(*names)[source]

Create an Elisp list of symbols.

Parameters

names (Union[str, emacs.elisp.ast.Symbol]) – Symbol names.

Return type

emacs.elisp.ast.Expr

emacs.elisp.exprs.to_elisp(value, **kw)[source]
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(v, **kw)
emacs.elisp.exprs.to_elisp(value, **kw)

Convert a Python value to an Elisp expression.

The following conversions are supported:

  • True to t symbol.

  • False and None to nil symbol.

  • int, float, and str to literals.

  • tuple to unquoted elisp list.

  • list to quoted elisp list.

  • dict and other mapping types to either alist or plist, see the dict_format argument.

  • Expr instances are returned unchanged.

For compound types, their contents are recursively converted as well.

Parameters
  • value – Python value to convert.

  • dict_format (str) – Elisp format to convert dicts/mappings to. Either 'alist' (default) or 'plist'.

Returns

Return type

Expr

emacs.elisp.exprs.el_true = <el t>

The standard Elisp representation of True

Return type

List

emacs.elisp.exprs.nil = <el nil>

The nil symbol

Return type

List

DSL

A DSL for writing Elisp in Python.

God help us all.

class emacs.elisp.dsl.ElispDSL[source]

Bases: object

Implements the Elisp DSL.

R

alias of emacs.elisp.ast.Raw

static C(car, cdr, *, convert_kw=None)

Create a cons cell expression, converting both arguments first.

Parameters
  • car

  • cdr

  • convert_kw – Keyword arguments to to_elisp().

Return type

emacs.elisp.ast.Cons

static S(*names)

Create an Elisp list of symbols.

Parameters

names (Union[str, emacs.elisp.ast.Symbol]) – Symbol names.

Return type

emacs.elisp.ast.Expr

emacs.elisp.dsl.E = <emacs.elisp.dsl.ElispDSL object>

Instance of ElispDSL for easy importing.

Return type

emacs.elisp.ast.Expr

Misc

Other utility code relating to Elisp.

emacs.elisp.util.escape_emacs_char(c)[source]

Escape character for use in Elisp string literal.

Parameters

c (Union[int, str]) –

Return type

str

emacs.elisp.util.escape_emacs_string(s, quotes=False)[source]

Escape non-printable characters in a way that can be read by Emacs.

If quotes=True this returns a valid Elisp string literal that evaluates to s and can be read by the read function.

Parameters
  • s (str) – String to escape.

  • quotes (bool) – Surround output with double quote characters.

Return type

str

emacs.elisp.util.snake_to_kebab(name)[source]

Convert a symbol name from 'snake_case' to 'kebab-case'.

Parameters

name (str) –

Return type

str

emacs.elisp.util.unescape_emacs_string(s, quotes=False)[source]

Unescape the representation of a string printed by Emacs.

This can be used to parse string printed using prin1, for example.

Important: this requires the Emacs variables print-escape-newlines and print-escape-control-characters be set to t for certain control and whitespace characters to be escaped properly. See here for more information.

Parameters
  • s (str) – String to escape.

  • quotes (bool) – Expect contents of s to be surrounded by double quote characters.

Return type

str