Merge branch 'master' into 38-fixing-testing

This commit is contained in:
John Miller 2016-09-24 12:26:24 -05:00
commit b242519fa5
51 changed files with 2628 additions and 189 deletions

1
.gitignore vendored
View file

@ -1,6 +1,7 @@
doc/build/
env
log
.gitmodules
*.stackdump
*.elc
*.el#

40
.gitmodules vendored
View file

@ -1,40 +0,0 @@
[submodule "tests/mocker"]
path = tests/mocker
url = https://github.com/sigma/mocker.el.git
[submodule "doc/eldomain"]
path = doc/eldomain
url = https://github.com/millejoh/sphinx-eldomain.git
[submodule "lib/websocket"]
path = lib/websocket
url = https://github.com/ahyatt/emacs-websocket.git
[submodule "lib/auto-complete"]
path = lib/auto-complete
url = https://github.com/auto-complete/auto-complete.git
[submodule "lib/fuzzy"]
path = lib/fuzzy
url = https://github.com/auto-complete/fuzzy-el.git
[submodule "lib/popup"]
path = lib/popup
url = https://github.com/auto-complete/popup-el.git
[submodule "lib/pos-tip"]
path = lib/pos-tip
url = https://github.com/emacsmirror/pos-tip.git
[submodule "lib/smartrep"]
path = lib/smartrep
url = https://github.com/myuhe/smartrep.el.git
[submodule "lib/python"]
path = lib/python
url = https://github.com/fgallina/python.el.git
[submodule "lib/markdown-mode"]
path = lib/markdown-mode
url = https://github.com/defunkt/markdown-mode.git
[submodule "lib/ert"]
path = lib/ert
url = https://github.com/ohler/ert.git
[submodule "lib/request"]
path = lib/request
url = https://github.com/tkf/emacs-request
branch = master
[submodule "lib/ein-mumamo"]
path = lib/ein-mumamo
url = https://github.com/millejoh/ein-mumamo

View file

@ -27,6 +27,9 @@ There are a number of helper functions for returning the struct for an opened no
** Notebooklist Buffer
** Kernel communication
The [[https://jupyter-client.readthedocs.io/en/latest/messaging.html#messaging][messaging protocol]].
** Contents API
Documented at the IPython Github [[https://github.com/ipython/ipython/wiki/IPEP-27%253A-Contents-Service][wiki.]]
@ -86,6 +89,66 @@ For both Travis CI and local testing.
- ~conda install ipython=x.x~ to install pre-jupyter ipython notebook versions.
* Enhancements/Fixes
** Run dynamic javascript
The development [[ipynb:(:url-or-port%208888%20:name%20"emacs-ipython-notebook/Embedding%20Altair%20Graphs.ipynb")][notebook]].
Emacs is not a web browser, hence does not know how to execute javascript.
Maybe we can get around this using [[https://github.com/skeeto/skewer-mode][skewer-mode]] or [[http://js-comint-el.sourceforge.net/][js-comint.el]].
Skewer-mode uses JS client provided by a web browser, while js-comint depends on
nodejs (you understand this difference, right? Right?).
Another thought is to get python to do this for us. The packages [[][naked]] (an
unfortunate name given my corporate firewall) and [[https://github.com/doloopwhile/PyExecJs][PyExecJs]].
** Embedding [[https://github.com/ellisonbg/altair][Altair]] plots
First get [[*Run dynamic javascript][dynamic javascript]] working...
Relevant [[https://github.com/vega/ipyvega/issues/31][issue]], [[https://github.com/vega/ipyvega/pull/32][pull request]] and [[https://github.com/ellisonbg/ipyvega/blob/be19059068557c44cbdcbcf5ad509c3312b25763/src/index.js][code]].
Appears the code has capability of returning javascript and png output. When
calling from ein all that gets returned is javascript, which
`ein:cell-append-mime-type` chokes on.
Somehow, when running [[https://nbconvert.readthedocs.io/en/latest/][nbconvert]], the javascript gets turned into a png. How to trigger
that when normally executing cells?
** Mike DeCandia's Wish and Bug List
*** Wishlist
- switch kernel
- getting a true Python mode when editing code in cells, without messing up the
other formatting
- If one cuts and pastes read-only text into a cell it cant be edited
- A full undo history
- Command history / autocomplete like one gets in regular ipython
- Image resizing
*** Bugs
- emacs ipython notebook fails to follow redirects properly - This is mainly due
to the fact that it holds on the original site name internally.
- cookie expiration for long running notebooks - On long running notebooks
tornado's default cookie expiration is 30 days. After the cookie expires emacs
will continue to attempt autosave, but the notebook will not save. The
workaround is to run ein:notebooklist-open to generate a new GET request
against /login to get another cookie.
** Switch kernel in running notebook
How? Probably by restarting kernel using a new kernelspec.
** Support company-mode
** Inline latex
See issue [[https://github.com/millejoh/emacs-ipython-notebook/issues/88][#88]].

@ -1 +0,0 @@
Subproject commit 523f8d52b41cba43f21b43718123947eea438f77

1
doc/eldomain/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
example/build

60
doc/eldomain/README.rst Normal file
View file

@ -0,0 +1,60 @@
======================================================
Emacs Lisp domain -- Sphinx extension for Emacs Lisp
======================================================
Example usage (Emacs IPython Notebook documentation):
http://tkf.github.com/emacs-ipython-notebook/
Setup
=====
You need to have something like this in ``conf.py``::
# Dictionary maps package name to package prefix.
elisp_packages = {
'YOUR-PACKAGE': 'YOUR-PACKAGE-PREFIX-',
'ANOTHER-PACKAGE': 'ANOTHER-PACKAGE-PREFIX:',
}
# These are optional:
emacs_executable = 'emacs'
elisp_pre_load = 'conf.el'
You need to load functions and variables you want to load in ``conf.el``::
(add-to-list 'load-path "PATH/TO/YOUR/PACKAGE/")
(require 'YOUR-PACKAGE)
See the setup for Emacs IPython Notebook:
https://github.com/tkf/emacs-ipython-notebook/tree/master/doc/source
Directives and roles
====================
First of all, you need to specify package to use before using any
other directives.::
.. el:package:: PACKAGE-NAME
Then, you can automatically document function/macro/variables.::
.. el:function:: FUNCTION-NAME
.. el:macro:: MACRO-NAME
.. el:variable:: VARIABLE-NAME
.. TODO: document options for these directives.
You can get well-formatted keybind list using::
.. el:keymap:: KEYMAP-NAME
Finally, you can use ``el:symbol`` role to refer symbols.
For exmaple::
:el:symbol:`FUNCTION-NAME`

105
doc/eldomain/eldomain.el Normal file
View file

@ -0,0 +1,105 @@
;;; eldomain.el --- Generate data for eldomain
;; Copyright (C) 2012- Takafumi Arakaki
;; Author: Takafumi Arakaki
;; This file is NOT part of GNU Emacs.
;; eldomain is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; eldomain is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with eldomain. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(eval-when-compile (require 'cl))
(require 'help-fns)
(require 'json)
(defvar eldomain-prefix nil)
(defun eldomain-get-symbols (predicate)
(loop for x being the symbols
with regexp = (format "^%s" eldomain-prefix)
if (and (funcall predicate x)
(string-match regexp (format "%S" x)))
collect x))
(defun eldomain-get-function-data ()
(loop for x in (eldomain-get-symbols #'fboundp)
for name = (format "%S" x)
for arg = (help-function-arglist x)
for doc = (documentation x)
collect `((name . ,name) (arg . ,arg) (doc . ,doc))))
(defun eldomain-get-variable-data ()
(loop for x in (eldomain-get-symbols #'boundp)
for name = (format "%S" x)
for doc = (documentation-property x 'variable-documentation t)
collect `((name . ,name) (doc . ,doc))))
(defun eldomain-get-face-data ()
(loop for x in (eldomain-get-symbols #'facep)
for name = (format "%S" x)
for doc = (documentation-property x 'face-documentation t)
collect `((name . ,name) (doc . ,doc))))
(defun eldomain-keymap-to-data (keymap)
(let* (data
eldomain-keymap-parent
(eldomain-prefix-regexp (format "^%s" eldomain-prefix))
eldomain-describe-keymap ; to shut up compiler...
(eldomain-describe-keymap
(lambda (event value)
(let* ((parent eldomain-keymap-parent)
(eldomain-keymap-parent (append parent (list event))))
(cond
((keymapp value)
(map-keymap eldomain-describe-keymap value))
((and (listp value) (eq (car value) 'menu-item))
nil) ; ignore menu
(value ; do not record when func is not set
(push (list :key (key-description eldomain-keymap-parent)
:func value
:doc (when (string-match eldomain-prefix-regexp
(format "%S" value))
(documentation value)))
data)))))))
(map-keymap eldomain-describe-keymap keymap)
data))
(defun eldomain-get-keymap-data ()
(loop for x in (eldomain-get-symbols
(lambda (v) (and (boundp v) (keymapp (eval v)))))
for name = (format "%S" x)
for doc = (documentation-property x 'variable-documentation t)
for data = (apply #'vector (eldomain-keymap-to-data (eval x)))
collect `((name . ,name) (doc . ,doc) (data . ,data))))
(defun eldomain-get-data ()
`((function . ,(apply #'vector (eldomain-get-function-data)))
(variable . ,(apply #'vector (eldomain-get-variable-data)))
(face . ,(apply #'vector (eldomain-get-face-data)))
(keymap . ,(apply #'vector (eldomain-get-keymap-data)))))
(defun eldomain-main ()
(assert eldomain-prefix nil "`eldomain-prefix' must be set.")
(princ (json-encode (eldomain-get-data)))
(kill-emacs))
(eldomain-main)
;;; eldomain.el ends here

458
doc/eldomain/eldomain.py Normal file
View file

@ -0,0 +1,458 @@
# eldomain is a Emacs Lisp domain for the Sphinx documentation tool.
# Copyright (C) 2012 Takafumi Arakaki
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
The Emacs Lisp domain
~~~~~~~~~~~~~~~~~~~~~
This Sphinx extension provides directives and roles under the domain
``el`` for documenting Emacs Lisp program. It also provides autodoc
functionality -- docstrings in the Emacs Lisp is automatically
inserted in the documentation.
.. note::
The source code is heavily borrowed from the `Common Lisp domain`_.
.. _`Common Lisp domain`:
https://github.com/russell/sphinxcontrib-cldomain
"""
import os
from os import path
import re
import itertools
import subprocess
import json
from docutils import nodes
from docutils.statemachine import string2lines, StringList
from sphinx import addnodes
from sphinx.locale import l_, _
from sphinx.roles import XRefRole
from sphinx.domains import Domain, ObjType
from sphinx.directives import ObjectDescription
from sphinx.util.nodes import make_refnode
from sphinx.util.compat import Directive
from sphinx.util.docfields import Field, GroupedField
DATA = {}
DATA_DOC_STRINGS = {}
DATA_ARGS = {}
def bool_option(arg):
"""Used to convert flag options to auto directives. (Instead of
directives.flag(), which returns None).
"""
return True
def string_list(delimiter):
"""
Return a parser for option_spec to parse strings separated by `delimiter`.
>>> parser = string_list(',')
>>> parser('a, b, c')
['a', 'b', 'c']
"""
return lambda argument: [v.strip() for v in argument.split(delimiter)]
class ELSExp(ObjectDescription):
doc_field_types = [
GroupedField('parameter', label=l_('Parameters'),
names=('param', 'parameter', 'arg', 'argument',
'keyword', 'kwparam')),
Field('returnvalue', label=l_('Returns'), has_arg=False,
names=('returns', 'return')),
]
option_spec = {
'nodoc': bool_option, 'noindex': bool_option,
}
def handle_signature(self, sig, signode):
symbol_name = []
def render_sexp(sexp, signode=None, prepend_node=None):
desc_sexplist = addnodes.desc_parameterlist()
desc_sexplist.child_text_separator = ' '
if prepend_node:
desc_sexplist.append(prepend_node)
if signode:
signode.append(desc_sexplist)
for atom in sexp:
if isinstance(atom, list):
render_sexp(atom, desc_sexplist)
else:
render_atom(atom, desc_sexplist)
return desc_sexplist
def render_atom(token, signode, noemph=True):
"add syntax hi-lighting to interesting atoms"
if token.startswith("&") or token.startswith(":"):
signode.append(addnodes.desc_parameter(token, token))
else:
signode.append(addnodes.desc_parameter(token, token))
package = self.env.temp_data.get('el:package')
objtype = self.get_signature_prefix(sig)
signode.append(addnodes.desc_annotation(objtype, objtype))
lisp_args = DATA_ARGS.get(package, {}).get(sig, [])
if lisp_args:
function_name = addnodes.desc_name(sig, sig + " ")
else:
function_name = addnodes.desc_name(sig, sig)
if lisp_args:
arg_list = render_sexp(lisp_args, prepend_node=function_name)
signode.append(arg_list)
else:
signode.append(function_name)
symbol_name = sig
if not symbol_name:
raise Exception("Unknown symbol type for signature %s" % sig)
return objtype.strip(), symbol_name
def get_index_text(self, name, type):
return _('%s (Lisp %s)') % (name, type)
def get_signature_prefix(self, sig):
return self.objtype + ' '
def add_target_and_index(self, name, sig, signode):
# note target
type, name = name
if name not in self.state.document.ids:
signode['names'].append(name)
signode['ids'].append(name)
signode['first'] = (not self.names)
self.state.document.note_explicit_target(signode)
inv = self.env.domaindata['el']['symbols']
if name in inv:
self.state_machine.reporter.warning(
'duplicate symbol description of %s, ' % name +
'other instance in ' + self.env.doc2path(inv[name][0]),
line=self.lineno)
inv[name] = (self.env.docname, self.objtype)
indextext = self.get_index_text(name, type)
if indextext:
self.indexnode['entries'].append(('single', indextext, name, ''))
def run(self):
result = super(ELSExp, self).run()
if "nodoc" not in self.options:
package = self.env.temp_data.get('el:package')
node = addnodes.desc_content()
string = DATA_DOC_STRINGS.get(package, {}) \
.get(self.names[0][1], "")
lines = string2lines(string)
self.state.nested_parse(StringList(lines), 0, node)
if (result[1][1].children and
isinstance(result[1][1][0], nodes.field_list)):
cresult = result[1][1].deepcopy()
target = result[1][1]
target.clear()
target.append(cresult[0])
target.extend(node)
target.extend(cresult[1:])
else:
cresult = result[1][1].deepcopy()
target = result[1][1]
target.clear()
target.extend(node)
target.extend(cresult)
return result
class ELCurrentPackage(Directive):
"""
This directive is just to tell Sphinx that we're documenting stuff in
namespace foo.
"""
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {}
def run(self):
env = self.state.document.settings.env
env.temp_data['el:package'] = self.arguments[0]
return []
def parse_text_list(argument, delimiter=','):
"""
Converts a space- or comma-separated list of values into a list
"""
if delimiter in argument:
entries = argument.split(delimiter)
else:
entries = argument.split()
return [v.strip() for v in entries]
def compose(f, g):
def h(*args, **kwds):
return f(g(*args, **kwds))
return h
def filter_by_exclude_regexp_list(candidates, regexp_list, getter=lambda x: x):
"""
Exclude elements in `candidates` that matches to one of the regexp.
>>> filter_by_exclude_regexp_list(['a', 'aa', 'bb'], ['a+'])
['bb']
>>> filter_by_exclude_regexp_list(['a', 'ab', 'bb'], ['a+', 'a?b$'])
['bb']
>>> filter_by_exclude_regexp_list(
... [{'key': 'a'}, {'key': 'ab'}, {'key': 'bb'}],
... ['a+', 'a?b$'],
... lambda x: x['key'])
[{'key': 'bb'}]
"""
for compiled in map(re.compile, regexp_list):
test = compose(compiled.match, getter)
candidates = itertools.filterfalse(test, candidates)
return list(candidates)
def simple_sed(scripts, string):
r"""
A simple sed-like function
>>> simple_sed(['s/before/after/g'], 'and then before that ...')
'and then after that ...'
>>> simple_sed([r's/([0-9])/\1\1/g'], 'there are 2 apples')
'there are 22 apples'
"""
for scr in scripts:
scr = scr.lstrip('s')
scr_split = scr[1:].split(scr[0])
(regexp, replace) = scr_split[:2]
string = re.sub(regexp, replace, string)
return string
class ELKeyMap(Directive):
has_content = False
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec = {
'exclude': parse_text_list,
'replace': string_list('\n'),
}
def run(self):
env = self.state.document.settings.env
package = env.temp_data.get('el:package')
keymap_list = DATA.get(package, {}).get('keymap', [])
keymap_name = self.arguments[0]
for keymap in keymap_list:
if keymap['name'] == keymap_name:
break
else:
return [self.state.reporter.warning(
"Keymap {0} not found".format(keymap_name))]
nodelist = []
mapdoc = keymap['doc']
if mapdoc:
nd = nodes.paragraph()
lines = string2lines(doc_to_rst(mapdoc))
self.state.nested_parse(StringList(lines), 0, nd)
nodelist.append(nd)
exclude = self.options.get('exclude', [])
replace = self.options.get('replace', [])
for keybind in filter_by_exclude_regexp_list(
keymap['data'], exclude, lambda x: x['func']):
desc = addnodes.desc()
desc['domain'] = 'el'
desc['objtype'] = 'keybind'
desc['noindex'] = False
signode = addnodes.desc_signature()
# signode += addnodes.desc_annotation("", 'keybind ')
key = simple_sed(replace, keybind['key'])
signode += addnodes.desc_name("", key)
signode += addnodes.desc_addname("", " " + keybind['func'])
desc += signode
if keybind['doc']:
nd = addnodes.desc_content()
lines = string2lines(doc_to_rst(keybind['doc']))
self.state.nested_parse(StringList(lines), 0, nd)
desc += nodes.definition("", nd)
nodelist.append(desc)
return nodelist
class ELXRefRole(XRefRole):
def process_link(self, env, refnode, has_explicit_title, title, target):
if not has_explicit_title:
target = target.lstrip('~') # only has a meaning for the title
# if the first character is a tilde, don't display the package
if title[0:1] == '~':
title = title[1:]
dot = title.rfind(':')
if dot != -1:
title = title[dot + 1:]
return title, target
class ELDomain(Domain):
"""EL language domain."""
name = 'el'
label = 'Common Lisp'
object_types = {
'package': ObjType(l_('package'), 'package'),
'function': ObjType(l_('function'), 'function'),
'macro': ObjType(l_('macro'), 'macro'),
'variable': ObjType(l_('variable'), 'variable'),
}
directives = {
'package': ELCurrentPackage,
'function': ELSExp,
'macro': ELSExp,
'variable': ELSExp,
'keymap': ELKeyMap,
}
roles = {
'symbol': ELXRefRole(),
}
initial_data = {
'symbols': {},
}
def clear_doc(self, docname):
for fullname, (fn, _) in self.data['symbols'].items():
if fn == docname:
del self.data['symbols'][fullname]
def find_obj(self, env, name):
"""Find a Lisp symbol for "name", perhaps using the given package
Returns a list of (name, object entry) tuples.
"""
symbols = self.data['symbols']
if ":" in name:
if name in symbols:
return [(name, symbols[name])]
else:
def filter_symbols(symbol):
symbol = symbol[0]
if name == symbol:
return True
if ":" in symbol:
symbol = symbol.split(":")[1]
if name == symbol:
return True
return False
return [f for f in filter(filter_symbols, symbols.items())]
def resolve_xref(self, env, fromdocname, builder,
typ, target, node, contnode):
matches = self.find_obj(env, target)
if not matches:
return None
elif len(matches) > 1:
env.warn_node(
'more than one target found for cross-reference '
'%r: %s' % (target, ', '.join(match[0] for match in matches)),
node)
name, obj = matches[0]
return make_refnode(builder, fromdocname, obj[0], name,
contnode, name)
def get_symbols(self):
for refname, (docname, type) in self.data['symbols'].items():
yield (refname, refname, type, docname, refname, 1)
def doc_to_rst(docstring):
docstring = _eldoc_quote_re.sub(r":el:symbol:`\1`", docstring)
return docstring
_eldoc_quote_re = re.compile(r"`(\S+)'")
def index_package(emacs, package, prefix, pre_load, extra_args=[]):
"""Call an external lisp program that will return a dictionary of
doc strings for all public symbols."""
lisp_script = path.join(path.dirname(path.realpath(__file__)),
"eldomain.el")
command = [emacs, "-Q", "-batch", "-l", pre_load,
"--eval", '(setq eldomain-prefix "{0}")'.format(prefix),
"-l", lisp_script] + extra_args
proc = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
if proc.poll() != 0:
raise RuntimeError(
"Error while executing '{0}'.\n\n"
"STDOUT:\n{1}\n\nSTDERR:\n{2}\n".format(
' '.join(command), stdout, stderr))
DATA[package] = lisp_data = json.loads(stdout.decode())
DATA_DOC_STRINGS[package] = {}
# FIXME: support using same name for function/variable/face
for key in ['face', 'variable', 'function']:
for data in lisp_data[key]:
doc = data['doc']
if doc:
DATA_DOC_STRINGS[package][data['name']] = doc_to_rst(doc)
DATA_ARGS[package] = {}
for data in lisp_data['function']:
DATA_ARGS[package][data['name']] = data['arg']
def load_packages(app):
emacs = app.config.emacs_executable
# `app.confdir` will be ignored if `elisp_pre_load` is an absolute path
pre_load = path.join(app.confdir, app.config.elisp_pre_load)
for (name, prefix) in app.config.elisp_packages.items():
index_package(emacs, name, prefix, pre_load)
def setup(app):
app.add_domain(ELDomain)
app.add_config_value('emacs_executable',
os.getenv("EMACS") or 'emacs',
'env')
app.add_config_value('elisp_pre_load', 'conf.el', 'env')
app.add_config_value('elisp_packages', {}, 'env')
app.connect('builder-inited', load_packages)

View file

@ -0,0 +1,153 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ELDomainExample.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ELDomainExample.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/ELDomainExample"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ELDomainExample"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View file

@ -0,0 +1,190 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\ELDomainExample.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\ELDomainExample.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

View file

@ -0,0 +1,2 @@
(add-to-list 'load-path (file-name-directory load-file-name))
(require 'eldomain-example)

View file

@ -0,0 +1,251 @@
# -*- coding: utf-8 -*-
#
# EL Domain Example documentation build configuration file, created by
# sphinx-quickstart on Sun Jun 10 19:32:14 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath(os.path.join('..', '..')))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = [
'sphinx.ext.todo',
'eldomain',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'EL Domain Example'
copyright = u'2012, Takafumi Arakaki'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0'
# The full version, including alpha/beta/rc tags.
release = '0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'ELDomainExampledoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'ELDomainExample.tex', u'EL Domain Example Documentation',
u'Takafumi Arakaki', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'eldomainexample', u'EL Domain Example Documentation',
[u'Takafumi Arakaki'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'ELDomainExample', u'EL Domain Example Documentation',
u'Takafumi Arakaki', 'ELDomainExample', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for EL domain -----------------------------------------------------
emacs_executable = 'emacs-snapshot'
elisp_packages = {'eldomain-example': 'ee:'}

View file

@ -0,0 +1,20 @@
(defgroup eldomain-example nil
"Group for `eldomain-example' package."
:group 'application
:prefix "ee:")
(defface ee:face-example
'((t :inherit header-line))
"Face documentation example."
:group 'eldomain-example)
(defvar ee:variable-example nil
"Variable documentation example referring to `ee:function-example'.")
(defmacro ee:macro-example (x y &optional z &rest args)
"Macro documentation example referring to `ee:variable-example'.")
(defun ee:function-example (x y &optional z &rest args)
"Function documentation example referring to `ee:macro-example'.")
(provide 'eldomain-example)

View file

@ -0,0 +1,41 @@
Welcome to EL Domain Example's documentation!
=============================================
These are the example of the output of EL domain.
.. el:package:: eldomain-example
.. el:variable:: ee:face-example
.. el:variable:: ee:variable-example
.. el:macro:: ee:macro-example
.. el:function:: ee:function-example
ReST source code:
.. sourcecode:: rst
.. el:package:: eldomain-example
.. el:variable:: ee:face-example
.. el:variable:: ee:variable-example
.. el:macro:: ee:macro-example
.. el:function:: ee:function-example
Emacs lisp source code:
.. literalinclude:: eldomain-example.el
:language: cl
Other examples
==============
.. toctree::
no-package
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

View file

@ -0,0 +1,14 @@
Example usage without specifying package
========================================
.. el:variable:: unknown/variable-example
Documenting variable without specifying package...
.. el:macro:: unknown/macro-example
Documenting face without specifying package...
.. el:function:: unknown/function-example
Documenting function without specifying package...

View file

@ -51,9 +51,9 @@ copyright = u'2015, John Miller'
# built documents.
#
# The short X.Y version.
version = '0.8'
version = '0.9'
# The full version, including alpha/beta/rc tags.
release = '0.8.2'
release = '0.9.1'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.

View file

@ -384,6 +384,7 @@ Notebook
.. el:variable:: ein:helm-kernel-history-search-auto-pattern
.. el:variable:: ein:output-type-preference
.. el:variable:: ein:shr-env
.. el.variable:: ein:worksheet-show-slide-data
Console
^^^^^^^
@ -563,6 +564,22 @@ everything the log buffer. You can reset the patch and log level with
Change Log
==========
v0.10.0
-------
* Allow user to change the kernel of a running notebook.
* The notebooklist buffer now lists all opened notebook buffers.
v0.9.1
------
* Fix issues with shared-output and notebook connected buffers.
v0.9.0
------
* Add support for setting slide attributes for notebook/worksheet cells.
v0.8.2
------

@ -1 +0,0 @@
Subproject commit 03ac7481c2073146cc8e31a0bce7aea35151ea63

@ -1 +0,0 @@
Subproject commit 028fefec499598add1a87b92ed991891f38f0c7b

@ -1 +0,0 @@
Subproject commit 00aef6e43d44c6f25323d1a7bdfdc929a3b4ce04

@ -1 +0,0 @@
Subproject commit b47d801d4e1ff67323eda4d602e78c31fbc5a08a

@ -1 +0,0 @@
Subproject commit c3f86536a33ae30263cb7dccd049758939e45082

@ -1 +0,0 @@
Subproject commit f15c82bf423e6d49cf107836ba1ce39fc1138933

@ -1 +0,0 @@
Subproject commit bea36be3404d458bfd9bdba2a9e4da54d5bbbf92

@ -1 +0,0 @@
Subproject commit 52af663788c7d69228ef85e0a93d0e4b56af1bb9

@ -1 +0,0 @@
Subproject commit 23547740903063ccc145e021c1ca3a6bfbd1c9f6

@ -1 +0,0 @@
Subproject commit 1107b7b967c0dcdbf005d7e19d8bfd0c34e04e73

@ -1 +0,0 @@
Subproject commit 69a377a537a9f21e22bea23e3165e1ddbc422cd2

View file

@ -47,10 +47,21 @@
(defun ein:output-property (maybe-property)
(cdr (assoc maybe-property ein:output-type-map)))
(defun ein:get-slideshow (cell)
(setq slide_type (oref cell :slidetype))
(setq SS_table (make-hash-table))
(setf (gethash 'slide_type SS_table) slide_type)
SS_table)
(defmethod ein:cell-to-nb4-json ((cell ein:codecell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
(let ((metadata `((collapsed . ,(if (oref cell :collapsed) t json-false))
(autoscroll . json-false)
(ein.tags . (,(format "worksheet-%s" wsidx)))))
(ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table)
))
(outputs (if discard-output []
(oref cell :outputs)))
(renamed-outputs '())
@ -79,15 +90,23 @@
(source . ,(ein:cell-get-text cell))))
(defmethod ein:cell-to-nb4-json ((cell ein:textcell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
`((cell_type . ,(oref cell :cell-type))
(source . ,(ein:cell-get-text cell))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))))))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table)))))
(defmethod ein:cell-to-nb4-json ((cell ein:headingcell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
(let ((header (make-string (oref cell :level) ?#)))
`((cell_type . "markdown")
(source . ,(format "%s %s" header (ein:cell-get-text cell)))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx))))))))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table)
)))))
(defmethod ein:cell-to-json ((cell ein:headingcell) &optional discard-output)
(let ((json (call-next-method)))

View file

@ -183,6 +183,7 @@ See also: https://github.com/tkf/emacs-ipython-notebook/issues/94"
(outputs :initarg :outputs :initform nil :type list)
(metadata :initarg :metadata :initform nil :type list) ;; For nbformat >= 4
(events :initarg :events :type ein:events)
(slidetype :initarg :slidetype :initform "-" :type string)
(cell-id :initarg :cell-id :initform (ein:utils-uuid) :type string))
"Notebook cell base class")
@ -190,7 +191,7 @@ See also: https://github.com/tkf/emacs-ipython-notebook/issues/94"
((traceback :initform nil :initarg :traceback :type list)
(cell-type :initarg :cell-type :initform "code")
(kernel :initarg :kernel :type ein:$kernel)
(element-names :initform (:prompt :input :output :footer))
(element-names :initform (:prompt :input :output :footer :slidetype))
(input-prompt-number :initarg :input-prompt-number
:documentation "\
Integer or \"*\" (running state).
@ -220,7 +221,7 @@ auto-execution mode flag in the connected buffer is `t'.")))
(defclass ein:textcell (ein:basecell)
((cell-type :initarg :cell-type :initform "text")
(element-names :initform (:prompt :input :footer))))
(element-names :initform (:prompt :input :footer :slidetype))))
(defclass ein:htmlcell (ein:textcell)
((cell-type :initarg :cell-type :initform "html")))
@ -265,13 +266,20 @@ auto-execution mode flag in the connected buffer is `t'.")))
(apply (ein:cell-class-from-type type) "Cell" args))
(defun ein:cell-from-json (data &rest args)
(let* ((data (ein:preprocess-nb4-cell data))
(cell (ein:cell-init (apply #'ein:cell-from-type
(plist-get data :cell_type) args)
data)))
(if (plist-get data :metadata)
(ein:oset-if-empty cell :metadata (plist-get data :metadata)))
cell))
(setq data (ein:preprocess-nb4-cell data))
(setq cell (ein:cell-init (apply #'ein:cell-from-type
(plist-get data :cell_type) args)
data))
(if (plist-get data :metadata)
(ein:oset-if-empty cell :metadata (plist-get data :metadata)))
(setq slideshow (plist-get (oref cell :metadata) :slideshow))
(if (not (null slideshow))
(progn
(setq slide_type (nth 0 (cdr slideshow)))
(oset cell :slidetype slide_type)))
(message "read slidetype %s" (oref cell :slidetype))
(message "reconstructed slideshow %s" (ein:get-slide-show cell))
cell)
(defmethod ein:cell-init ((cell ein:codecell) data)
(ein:oset-if-empty cell :outputs (plist-get data :outputs))
@ -308,6 +316,8 @@ auto-execution mode flag in the connected buffer is `t'.")))
(oset new :input (if (ein:cell-active-p cell)
(ein:cell-get-text cell)
(oref cell :input)))
;; copy slidetype
(oset new :slidetype (oref cell :slidetype))
;; copy output when the new cell has it
(when (memq :output (oref new :element-names))
(oset new :outputs (mapcar 'identity (oref cell :outputs))))
@ -335,9 +345,12 @@ auto-execution mode flag in the connected buffer is `t'.")))
;; copy element attribute
(loop for k in (oref new :element-names)
with old-element = (oref cell :element)
do (oset new :element
do (progn
(oset new :element
(plist-put (oref new :element) k
(plist-get old-element k))))
(plist-get old-element k)))
)
)
;; setting ewoc nodes
(loop for en in (ein:cell-all-element cell)
for node = (ewoc-data en)
@ -493,24 +506,40 @@ Return language name as a string or `nil' when not defined.
(output (ein:cell-insert-output (cadr path) data))
(footer (ein:cell-insert-footer data))))
(defun ein:get-slide-show (cell)
(setq slide_type (oref cell :slidetype))
(setq SS_table (make-hash-table))
(setf (gethash 'slide_type SS_table) slide_type)
SS_table)
(defun ein:maybe-show-slideshow-data (cell)
(when (ein:worksheet-show-slide-data-p ein:%worksheet%)
(format " - Slide [%s]:" (or (ein:oref-safe cell :slidetype) " "))))
(defmethod ein:cell-insert-prompt ((cell ein:codecell))
"Insert prompt of the CELL in the buffer.
Called from ewoc pretty printer via `ein:cell-pp'."
;; Newline is inserted in `ein:cell-insert-input'.
(ein:insert-read-only
(concat
(format "In [%s]:" (or (ein:oref-safe cell :input-prompt-number) " "))
(format "In [%s]" (or (ein:oref-safe cell :input-prompt-number) " "))
(ein:maybe-show-slideshow-data cell)
(when (oref cell :autoexec) " %s" ein:cell-autoexec-prompt))
'font-lock-face 'ein:cell-input-prompt))
(defmethod ein:cell-insert-prompt ((cell ein:textcell))
(ein:insert-read-only
(format "%s:" (oref cell :cell-type))
(concat
(format "%s:" (oref cell :cell-type))
(ein:maybe-show-slideshow-data cell))
'font-lock-face 'ein:cell-input-prompt))
(defmethod ein:cell-insert-prompt ((cell ein:headingcell))
(ein:insert-read-only
(format "h%s:" (oref cell :level))
(concat
(format "h%s:" (oref cell :level))
(ein:maybe-show-slideshow-data cell))
'font-lock-face 'ein:cell-input-prompt))
(defmethod ein:cell-insert-input ((cell ein:basecell))
@ -1018,10 +1047,14 @@ prettified text thus be used instead of HTML type."
(defun ein:output-property-p (maybe-property)
(assoc maybe-property ein:output-type-map))
(defmethod ein:cell-to-nb4-json ((cell ein:codecell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
(let ((metadata `((collapsed . ,(if (oref cell :collapsed) t json-false))
(autoscroll . json-false)
(ein.tags . (,(format "worksheet-%s" wsidx)))))
(autoscroll . ,json-false)
(ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table)))
(outputs (if discard-output []
(oref cell :outputs)))
(renamed-outputs '())
@ -1089,15 +1122,19 @@ prettified text thus be used instead of HTML type."
(source . ,(ein:cell-get-text cell))))
(defmethod ein:cell-to-nb4-json ((cell ein:textcell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
`((cell_type . ,(oref cell :cell-type))
(source . ,(ein:cell-get-text cell))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))))))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table)))))
(defmethod ein:cell-to-nb4-json ((cell ein:headingcell) wsidx &optional discard-output)
(setq SS_table (ein:get-slide-show cell))
(let ((header (make-string (oref cell :level) ?#)))
`((cell_type . "markdown")
(source . ,(format "%s %s" header (ein:cell-get-text cell)))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx))))))))
(metadata . ((ein.tags . (,(format "worksheet-%s" wsidx)))
(slideshow . ,SS_table))))))
(defmethod ein:cell-to-json ((cell ein:headingcell) &optional discard-output)
(let ((json (call-next-method)))

View file

@ -105,6 +105,8 @@
:msg_id (ein:utils-uuid)
:username (ein:$kernel-username kernel)
:session (ein:$kernel-session-id kernel)
;; version?
:date (format-time-string "%Y-%m-%dT%T" (current-time)) ; ISO 8601 timestamp
:msg_type msg-type)
:metadata (make-hash-table)
:content content

View file

@ -93,10 +93,10 @@ This function may raise an error."
(make-local-variable 'parse-sexp-ignore-comments)
(make-local-variable 'indent-line-function)
(make-local-variable 'indent-region-function)
(make-local-variable 'beginning-of-defun-function)
(make-local-variable 'end-of-defun-function)
(setq beginning-of-defun-function 'ein:worksheet-beginning-of-cell-input)
(setq end-of-defun-function 'ein:worksheet-end-of-cell-input)
(set (make-local-variable 'beginning-of-defun-function)
'ein:worksheet-beginning-of-cell-input)
(set (make-local-variable 'end-of-defun-function)
'ein:worksheet-end-of-cell-input)
(ein:ml-lang-setup-python)
(ein:ml-set-font-lock-defaults))

View file

@ -516,6 +516,23 @@ on server url/port."
(ein:log 'error
"Kernelspc query call failed with status %s." symbol-status))
(defun ein:notebook-switch-kernel (notebook kernel-name)
"Change the kernel for a running notebook. If not called from a
notebook buffer then the user will be prompted to select an opened notebook."
(interactive
(let* ((notebook (or (ein:get-notebook)
(completing-read
"Select notebook [URL-OR-PORT/NAME]: "
(ein:notebook-opened-buffer-names))))
(kernel-name (completing-read
"Select kernel: "
(ein:list-available-kernels (ein:$notebook-url-or-port notebook)))))
(list notebook kernel-name)))
(setf (ein:$notebook-kernelspec notebook) (ein:get-kernelspec (ein:$notebook-url-or-port notebook)
kernel-name))
(ein:log 'info "Restarting notebook %s with new kernel %s." (ein:$notebook-notebook-name notebook) kernel-name)
(ein:notebook-restart-kernel notebook))
;;; This no longer works in iPython-2.0. Protocol is to create a session for a
;;; notebook, which will automatically create and associate a kernel with the notebook.
(defun ein:notebook-start-kernel (notebook)
@ -702,6 +719,7 @@ This is equivalent to do ``C-c`` in the console program."
(ws-cells (mapcar (lambda (data) (ein:cell-from-json data)) cells))
(worksheet (ein:notebook--worksheet-new notebook)))
(oset worksheet :saved-cells ws-cells)
;(mapcar (lambda (data) (message "test %s" (oref data :metadata))) ws-cells)
(list worksheet)))
(defun ein:notebook-to-json (notebook)
@ -741,7 +759,9 @@ This is equivalent to do ``C-c`` in the console program."
`((metadata . ,(ein:aif (ein:$notebook-metadata notebook)
it
(make-hash-table)))
(cells . ,(apply #'vector all-cells)))))
(cells . ,(apply #'vector all-cells)))
))
(defun ein:notebook-save-notebook (notebook retry &optional callback cbargs)
(let ((content (ein:content-from-notebook notebook)))
@ -1248,6 +1268,7 @@ This hook is run regardless the actual major mode used."
(defvar ein:notebook-mode-map (make-sparse-keymap))
(let ((map ein:notebook-mode-map))
(define-key map "\C-cS" 'ein:worksheet-toggle-slideshow-view)
(define-key map "\C-c\C-c" 'ein:worksheet-execute-cell)
(define-key map (kbd "M-RET") 'ein:worksheet-execute-cell-and-goto-next)
(define-key map (kbd "<M-S-return>")
@ -1265,6 +1286,7 @@ This hook is run regardless the actual major mode used."
(define-key map "\C-c\C-a" 'ein:worksheet-insert-cell-above)
(define-key map "\C-c\C-b" 'ein:worksheet-insert-cell-below)
(define-key map "\C-c\C-t" 'ein:worksheet-toggle-cell-type)
(define-key map "\C-c\C-d" 'ein:worksheet-toggle-slide-type)
(define-key map "\C-c\C-u" 'ein:worksheet-change-cell-type)
(define-key map "\C-c\C-s" 'ein:worksheet-split-cell-at-point)
(define-key map "\C-c\C-m" 'ein:worksheet-merge-cell)
@ -1326,6 +1348,7 @@ This hook is run regardless the actual major mode used."
("Insert cell above" ein:worksheet-insert-cell-above)
("Insert cell below" ein:worksheet-insert-cell-below)
("Toggle cell type" ein:worksheet-toggle-cell-type)
("Toggle slide type" ein:worksheet-toggle-slide-type)
("Change cell type" ein:worksheet-change-cell-type)
("Split cell at point" ein:worksheet-split-cell-at-point)
("Merge cell" ein:worksheet-merge-cell)
@ -1381,10 +1404,12 @@ This hook is run regardless the actual major mode used."
("Kernel"
,@(ein:generate-menu
'(("Restart kernel" ein:notebook-restart-kernel-command)
("Switch kernel" ein:notebook-switch-kernel)
("Interrupt kernel" ein:notebook-kernel-interrupt-command))))
("Worksheets [Experimental]"
,@(ein:generate-menu
'(("Rename worksheet" ein:worksheet-rename-sheet)
'(("Toggle slide metadata view" ein:worksheet-toggle-slideshow-view)
("Rename worksheet" ein:worksheet-rename-sheet)
("Insert next worksheet"
ein:notebook-worksheet-insert-next)
("Insert previous worksheet"
@ -1464,7 +1489,9 @@ Note that print page is not supported in IPython 0.12.1."
(interactive "P")
(let ((url (apply #'ein:url
(ein:$notebook-url-or-port ein:%notebook%)
(ein:$notebook-notebook-id ein:%notebook%)
(if (>= (ein:$notebook-api-version ein:%notebook%) 3)
"notebooks")
(ein:$notebook-notebook-path ein:%notebook%)
(if print (list "print")))))
(message "Opening %s in browser" url)
(browse-url url)))

View file

@ -522,62 +522,81 @@ Notebook list data is passed via the buffer local variable
(sessions (make-hash-table :test 'equal)))
(ein:content-query-sessions sessions (ein:$notebooklist-url-or-port ein:%notebooklist%) t)
(loop for note in (ein:$notebooklist-data ein:%notebooklist%)
for urlport = (ein:$notebooklist-url-or-port ein:%notebooklist%)
for name = (plist-get note :name)
for path = (plist-get note :path)
;; (cond ((= 2 api-version)
;; (plist-get note :path))
;; ((= 3 api-version)
;; (ein:get-actual-path (plist-get note :path))))
for type = (plist-get note :type)
for opened-notebook-maybe = (ein:notebook-get-opened-notebook urlport path)
do (widget-insert " ")
if (string= type "directory")
do (progn (widget-create
'link
:notify (lexical-let ((urlport urlport)
(path name))
(lambda (&rest ignore)
(ein:notebooklist-open urlport
(ein:url (ein:$notebooklist-path ein:%notebooklist%)
path))))
"Dir")
(widget-insert " : " name)
(widget-insert "\n"))
if (string= type "notebook")
do (progn (widget-create
'link
:notify (lexical-let ((name name)
(path path))
(lambda (&rest ignore)
(run-at-time 3 nil
#'ein:notebooklist-reload ein:%notebooklist%) ;; TODO using deferred better?
(ein:notebooklist-open-notebook
ein:%notebooklist% path)))
"Open")
(widget-insert " ")
(when (gethash path sessions)
(widget-create
'link
:notify (lexical-let ((session (car (gethash path sessions)))
(nblist ein:%notebooklist%))
(lambda (&rest ignore)
(run-at-time 1 nil
#'ein:notebooklist-reload
ein:%notebooklist%)
(ein:kernel-kill (make-ein:$kernel :url-or-port (ein:$notebooklist-url-or-port nblist)
:session-id session))))
"Stop")
(widget-insert " "))
(widget-create
'link
:notify (lexical-let ((path path))
(lambda (&rest ignore)
(ein:notebooklist-delete-notebook-ask
path)))
"Delete")
(widget-insert " : " name)
(widget-insert "\n"))))
for urlport = (ein:$notebooklist-url-or-port ein:%notebooklist%)
for name = (plist-get note :name)
for path = (plist-get note :path)
;; (cond ((= 2 api-version)
;; (plist-get note :path))
;; ((= 3 api-version)
;; (ein:get-actual-path (plist-get note :path))))
for type = (plist-get note :type)
for opened-notebook-maybe = (ein:notebook-get-opened-notebook urlport path)
do (widget-insert " ")
if (string= type "directory")
do (progn (widget-create
'link
:notify (lexical-let ((urlport urlport)
(path name))
(lambda (&rest ignore)
(ein:notebooklist-open urlport
(ein:url (ein:$notebooklist-path ein:%notebooklist%)
path))))
"Dir")
(widget-insert " : " name)
(widget-insert "\n"))
if (string= type "notebook")
do (progn (widget-create
'link
:notify (lexical-let ((name name)
(path path))
(lambda (&rest ignore)
(run-at-time 3 nil
#'ein:notebooklist-reload ein:%notebooklist%) ;; TODO using deferred better?
(ein:notebooklist-open-notebook
ein:%notebooklist% path)))
"Open")
(widget-insert " ")
(when (gethash path sessions)
(widget-create
'link
:notify (lexical-let ((session (car (gethash path sessions)))
(nblist ein:%notebooklist%))
(lambda (&rest ignore)
(run-at-time 1 nil
#'ein:notebooklist-reload
ein:%notebooklist%)
(ein:kernel-kill (make-ein:$kernel :url-or-port (ein:$notebooklist-url-or-port nblist)
:session-id session))))
"Stop")
(widget-insert " "))
(widget-create
'link
:notify (lexical-let ((path path))
(lambda (&rest ignore)
(ein:notebooklist-delete-notebook-ask
path)))
"Delete")
(widget-insert " : " name)
(widget-insert "\n")))
(widget-insert "\n---------- All Opened Notebooks ----------\n\n")
(loop for buffer in (ein:notebook-opened-buffers)
do (progn (widget-create
'link
:notify (lexical-let ((buffer buffer))
(lambda (&rest ignore)
(switch-to-buffer buffer)))
"Open")
(widget-create
'link
:notify (lexical-let ((buffer buffer))
(lambda (&rest ignore)
(kill-buffer buffer)
(run-at-time 1 nil
#'ein:notebooklist-reload
ein:%notebooklist%)))
"Close")
(widget-insert " : " (buffer-name buffer))
(widget-insert "\n"))))
(ein:notebooklist-mode)
(widget-setup))
@ -770,28 +789,39 @@ Now you can open notebook list by `ein:notebooklist-open'." url-or-port))
;;; Notebook list mode
(define-derived-mode ein:notebooklist-mode fundamental-mode "ein:notebooklist"
"IPython notebook list mode.")
(defun ein:notebooklist-prev-item () (interactive) (move-beginning-of-line 0))
(defun ein:notebooklist-next-item () (interactive) (move-beginning-of-line 2))
(setq ein:notebooklist-mode-map (copy-keymap widget-keymap))
(defvar ein:notebooklist-mode-map
(let ((map (make-sparse-keymap)))
(set-keymap-parent map (make-composed-keymap widget-keymap
special-mode-map))
(define-key map "\C-c\C-r" 'ein:notebooklist-reload)
(define-key map "p" 'ein:notebooklist-prev-item)
(define-key map "n" 'ein:notebooklist-next-item)
map)
"Keymap for ein:notebooklist-mode.")
(easy-menu-define ein:notebooklist-menu ein:notebooklist-mode-map
"EIN Notebook List Mode Menu"
`("EIN Notebook List"
,@(ein:generate-menu
'(("Reload" ein:notebooklist-reload)
("New Notebook" ein:notebooklist-new-notebook)
("New Notebook (with name)"
ein:notebooklist-new-notebook-with-name)
("New Junk Notebook" ein:junk-new)))))
(defun ein:notebooklist-revert-wrapper (&optional ignore-auto noconfirm preserve-modes)
(ein:notebooklist-reload))
(define-derived-mode ein:notebooklist-mode special-mode "ein:notebooklist"
"IPython notebook list mode.
Commands:
\\{ein:notebooklist-mode-map}}"
(set (make-local-variable 'revert-buffer-function)
'ein:notebooklist-revert-wrapper))
(let ((map ein:notebooklist-mode-map))
(define-key map "\C-c\C-r" 'ein:notebooklist-reload)
(define-key map "g" 'ein:notebooklist-reload)
(define-key map "p" 'ein:notebooklist-prev-item)
(define-key map "n" 'ein:notebooklist-next-item)
(define-key map "q" 'bury-buffer)
(easy-menu-define ein:notebooklist-menu map "EIN Notebook List Mode Menu"
`("EIN Notebook List"
,@(ein:generate-menu
'(("Reload" ein:notebooklist-reload)
("New Notebook" ein:notebooklist-new-notebook)
("New Notebook (with name)"
ein:notebooklist-new-notebook-with-name)
("New Junk Notebook" ein:junk-new))))))
(provide 'ein-notebooklist)

View file

@ -41,6 +41,7 @@
(defvar ein:header-line-format '(:eval (ein:header-line)))
(defvar ein:header-line-tab-map (make-sparse-keymap))
(defvar ein:header-line-insert-tab-map (make-sparse-keymap))
(defvar ein:header-line-switch-kernel-map (make-sparse-keymap))
(defvar ein:header-line-tab-help
"\
mouse-1 (left click) : switch to this tab
@ -250,6 +251,11 @@ insert-prev insert-next move-prev move-next)"
'keymap ein:header-line-insert-tab-map
'help-echo "Click (mouse-1) to insert a new tab."
'mouse-face 'highlight
'face 'ein:notification-tab-normal)
(propertize (format "|%s|" (ein:$kernelspec-name (ein:$notebook-kernelspec ein:%notebook%)))
'keymap ein:header-line-switch-kernel-map
'help-echo "Click (mouse-1) to change the running kernel."
'mouse-face 'highlight
'face 'ein:notification-tab-normal))))))
@ -267,6 +273,9 @@ insert-prev insert-next move-prev move-next)"
(define-key ein:header-line-insert-tab-map
[header-line mouse-1] 'ein:header-line-insert-new-tab)
(define-key ein:header-line-switch-kernel-map
[header-line mouse-1] 'ein:header-line-switch-kernel)
(defmacro ein:with-destructuring-bind-key-event (key-event &rest body)
(declare (debug (form &rest form))
(indent 1))
@ -332,6 +341,17 @@ Generated by `ein:header-line-define-mouse-commands'" slot)
(funcall (oref notification :insert-next)
(car (last (funcall (oref notification :get-list)))))))
(defun ein:header-line-switch-kernel (key-event)
(interactive "e")
(let* ((notebook (or (ein:get-notebook)
(completing-read
"Select notebook [URL-OR-PORT/NAME]: "
(ein:notebook-opened-buffer-names))))
(kernel-name (completing-read
"Select kernel: "
(ein:list-available-kernels (ein:$notebook-url-or-port notebook)))))
(ein:notebook-switch-kernel notebook kernel-name)))
(defun ein:header-line ()
(format
"IP[%s]: %s"

View file

@ -73,17 +73,18 @@
(beginning-of-line 0)
(recenter 0))
(define-derived-mode ein:pager-mode fundamental-mode "ein:pager"
"IPython notebook pager mode."
(view-mode)
(defvar ein:pager-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-b" 'ein:pager-goto-docstring-bset-loc)
map)
"Keymap for ein:pager-mode.")
(define-derived-mode ein:pager-mode view-mode "ein:pager"
"IPython notebook pager mode.
Commands:
\\{ein:pager-mode-map}"
(font-lock-mode))
(setq ein:pager-mode-map (make-sparse-keymap))
(let ((map ein:pager-mode-map))
(define-key map "\C-c\C-b" 'ein:pager-goto-docstring-bset-loc)
(define-key map "q" 'bury-buffer)
map)
(provide 'ein-pager)

View file

@ -1,7 +1,6 @@
(define-package "ein"
"0.8.0"
"0.10.0"
"Emacs IPython Notebook"
'((websocket "1.5")
(request "0.2")
(cl-generic "0.2")))

View file

@ -55,6 +55,16 @@
;;; Cell related
(defmethod ein:cell-insert-prompt ((cell ein:shared-output-cell))
"Insert prompt of the CELL in the buffer.
Called from ewoc pretty printer via `ein:cell-pp'."
;; Newline is inserted in `ein:cell-insert-input'.
(ein:insert-read-only
(concat
(format "In [%s]" (or (ein:oref-safe cell :input-prompt-number) " "))
(when (oref cell :autoexec) " %s" ein:cell-autoexec-prompt))
'font-lock-face 'ein:cell-input-prompt))
(defmethod ein:cell-execute ((cell ein:shared-output-cell) kernel code
&optional popup &rest args)
(unless (plist-get args :silent)
@ -234,16 +244,18 @@ shared output buffer. You can open the buffer by the command
;;; ein:shared-output-mode
(define-derived-mode ein:shared-output-mode fundamental-mode "ein:so"
(defvar ein:shared-output-mode-map
(let ((map (make-sparse-keymap)))
(define-key map "\C-c\C-x" 'ein:tb-show)
(define-key map "\M-." 'ein:pytools-jump-to-source-command)
(define-key map (kbd "C-c C-.") 'ein:pytools-jump-to-source-command)
map)
"The map for ein:shared-output-mode-map.")
(define-derived-mode ein:shared-output-mode special-mode "ein:so"
"Shared output mode."
(font-lock-mode))
(let ((map ein:shared-output-mode-map))
(define-key map "\C-c\C-x" 'ein:tb-show)
(define-key map "\M-." 'ein:pytools-jump-to-source-command)
(define-key map (kbd "C-c C-.") 'ein:pytools-jump-to-source-command)
(define-key map "q" 'bury-buffer))
(add-hook 'ein:shared-output-mode-hook 'ein:truncate-lines-on)

View file

@ -163,17 +163,19 @@
(interactive)
(ewoc-goto-next (oref ein:%traceback% :ewoc) 1))
(define-derived-mode ein:traceback-mode fundamental-mode "ein:tb"
(defvar ein:traceback-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "RET") 'ein:tb-jump-to-source-at-point-command)
(define-key map "p" 'ein:tb-prev-item)
(define-key map "n" 'ein:tb-next-item)
map)
"Keymap for ein:traceback-mode.")
(define-derived-mode ein:traceback-mode special-mode "ein:tb"
(font-lock-mode))
(add-hook 'ein:traceback-mode-hook 'ein:truncate-lines-on)
(let ((map ein:traceback-mode-map))
(define-key map (kbd "RET") 'ein:tb-jump-to-source-at-point-command)
(define-key map "p" 'ein:tb-prev-item)
(define-key map "n" 'ein:tb-next-item)
(define-key map "q" 'bury-buffer))
(provide 'ein-traceback)
;;; ein-traceback.el ends here

View file

@ -40,6 +40,14 @@
(define-obsolete-variable-alias
'ein:notebook-enable-undo 'ein:worksheet-enable-undo "0.2.0")
(defcustom ein:worksheet-show-slide-data nil
"Controls whether to show slide metadata by default when
opening or creating worksheets. Note that viewing of slide
metadata can be toggled in an open worksheet using the command
C-cS."
:type 'boolean
:group 'ein)
(defcustom ein:worksheet-enable-undo 'yes
"Configure undo in notebook buffers.
@ -92,6 +100,9 @@ this value."
(kernel :initarg :kernel :type ein:$kernel)
(dirty :initarg :dirty :type boolean :initform nil)
(metadata :initarg :metadata :initform nil)
(show-slide-data-p :initarg :show-slide-data-p
:initform nil
:accessor ein:worksheet-show-slide-data-p)
(events :initarg :events)))
(ein:deflocal ein:%worksheet% nil
@ -105,6 +116,7 @@ this value."
(apply #'make-instance 'ein:worksheet
:nbformat nbformat :get-notebook-name get-notebook-name
:discard-output-p discard-output-p :kernel kernel :events events
:show-slide-data-p ein:worksheet-show-slide-data
args))
(defmethod ein:worksheet-bind-events ((ws ein:worksheet))
@ -186,6 +198,14 @@ this value."
(set-buffer-modified-p dirty))
(oset ws :dirty dirty))
(defun ein:worksheet-toggle-slideshow-view ()
"Changes the display of slideshow metadata in the current worksheet."
(interactive)
(let ((ws (ein:worksheet--get-ws-or-error)))
(setf (ein:worksheet-show-slide-data-p ws)
(not (ein:worksheet-show-slide-data-p ws)))
(ein:worksheet-render ws)))
(defmethod ein:worksheet-render ((ws ein:worksheet))
(with-current-buffer (ein:worksheet--get-buffer ws)
(setq ein:%worksheet% ws)
@ -526,7 +546,27 @@ directly."
(when (ein:codecell-p new)
(oset new :kernel (oref ws :kernel)))
(ein:worksheet-empty-undo-maybe)
(when focus (ein:cell-goto new relpos)))))
(when focus (ein:cell-goto new relpos))))
)
(defun ein:worksheet-toggle-slide-type (ws cell &optional focus)
"Toggle the slide metadata of the cell at point. Available slide settings are:
[slide, subslide, fragment, skip, notes, - (none)]."
(interactive (list (ein:worksheet--get-ws-or-error)
(ein:worksheet-get-current-cell)
t))
(setq new_slide_type (ein:case-equal (oref cell :slidetype)
(("-") "slide")
(("slide") "subslide")
(("subslide") "fragment")
(("fragment") "skip")
(("skip") "notes")
(("notes") "-")))
(message "changing slide type %s" new_slide_type)
(oset cell :slidetype new_slide_type)
(ewoc-invalidate (oref cell :ewoc) (ein:cell-element-get cell :prompt))
(ein:worksheet-empty-undo-maybe)
(when focus (ein:cell-goto cell)))
(defun ein:worksheet-change-cell-type (ws cell type &optional level focus)
"Change the cell type of the current cell.

View file

@ -5,7 +5,7 @@
;; Author: John Miller <millejoh at millejoh.com>, Takafumi Arakaki <aka.tkf at gmail.com>
;; URL: http://millejoh.github.io/emacs-ipython-notebook/
;; Keywords: applications, tools
;; Version: 0.8.2
;; Version: 0.10.0
;; This file is NOT part of GNU Emacs.
@ -115,5 +115,8 @@
;; See also:
;; `CLiki : naming conventions <http://www.cliki.net/naming%20conventions>`_
;; Integrate ein into core emacs functionality
(add-to-list 'mouse-buffer-menu-mode-groups
'("^ein:" . "ein"))
;;; ein.el ends here

View file

@ -51,6 +51,18 @@
'("ein-mumamo" "nxhtml" "markdown-mode" "websocket" "request"
"auto-complete" "popup" "fuzzy" "pos-tip" "smartrep"))
(defvar zeroein:subtrees
'("lib/websocket https://github.com/ahyatt/emacs-websocket.git master --squash"
"lib/auto-complete https://github.com/auto-complete/auto-complete.git master --squash"
"lib/fuzzy https://github.com/auto-complete/fuzzy-el.git master --squash"
"lib/popup https://github.com/auto-complete/popup-el.git master --squash"
"lib/pos-tip https://github.com/emacsmirror/pos-tip.git master --sqaush"
"lib/smartrep https://github.com/myuhe/smartrep.el.git master --squash"
"lib/markdown-mode https://github.com/defunkt/markdown-mode.git master --squash"
"lib/ert https://github.com/ohler/ert.git master --squash"
"lib/request https://github.com/tkf/emacs-request master --squash"
"lib/ein-mumamo https://github.com/millejoh/ein-mumamo master --squash"))
;; Loading the new python.el fails in Emacs 23.
(when (>= emacs-major-version 24)
(add-to-list 'zeroein:dependencies "python"))
@ -58,11 +70,9 @@
;;; Install dependencies
(call-process "git" nil
nil ; (get-buffer "*Messages*")
nil
"submodule" "update" "--init")
(loop for subtree in zeroein:subtrees
do (call-process "git" nil nil nil
"subtree" "pull" "--prefix" subtree))
;;; `load-path' configurations

@ -1 +0,0 @@
Subproject commit 2000d037ea96ef6792746feb2ff9ded5b7b0dcb5

View file

@ -0,0 +1,10 @@
[bumpversion]
current_version = 0.3.1
commit = True
tag = True
tag_name = v{new_version}
[bumpversion:file:mocker.el]
[bumpversion:file:Cask]

1
tests/mocker/.ert-runner Normal file
View file

@ -0,0 +1 @@
-L .

14
tests/mocker/.travis.yml Normal file
View file

@ -0,0 +1,14 @@
language: emacs-lisp
sudo: no
env:
- EVM_EMACS=emacs-24.1-travis
- EVM_EMACS=emacs-24.2-travis
- EVM_EMACS=emacs-24.3-travis
- EVM_EMACS=emacs-24.4-travis
- EVM_EMACS=emacs-24.5-travis
- EVM_EMACS=emacs-25-pre-travis
before_install:
- curl -fsSkL https://gist.github.com/rejeep/ebcd57c3af83b049833b/raw > travis.sh && source ./travis.sh
- evm install "$EVM_EMACS" --use --skip
script:
make travis-ci

11
tests/mocker/Cask Normal file
View file

@ -0,0 +1,11 @@
(source gnu)
(source melpa-stable)
(package "mocker" "0.3.1"
"mocking framework for emacs.")
(depends-on "eieio" "1.4")
(development
(depends-on "ert-runner")
(depends-on "shut-up"))

25
tests/mocker/Makefile Normal file
View file

@ -0,0 +1,25 @@
EMACS ?= emacs
CASK ?= cask
test: unit-tests
unit-tests: elpa
${CASK} exec ert-runner
elpa:
mkdir -p elpa
${CASK} install 2> elpa/install.log
clean-elpa:
rm -rf elpa
clean-elc:
rm -f *.elc test/*.elc
clean: clean-elpa clean-elc
print-deps:
${EMACS} --version
@echo CASK=${CASK}
travis-ci: print-deps test

View file

@ -0,0 +1,206 @@
[![Build Status](https://travis-ci.org/sigma/mocker.el.png?branch=master)](https://travis-ci.org/sigma/mocker.el)
Mocker.el is a mocking framework for Emacs lisp.
Its single entry point, `mocker-let` provides an `let` like interface to
defining mock objects. Actually, `mocker-let` is a wrapper around `flet`, which
can be seen as a way to manually generate mocks.
## Usage
### Basic usage
Let's start with a simple example:
```lisp
(mocker-let ((foo (x y z)
((:input '(1 2 3) :output 4)
(:input '(4 5 6) :output 10)))
(bar (x)
((:input '(42) :output 4))))
(+ (foo 1 2 3)
(foo 4 5 6)
(bar 42)))
```
Each mock is defined in a function-style, and is associated with a set of
"records" that map expected inputs to desired outputs.
### Call order
By default, the order of definition within a mock has to be respected by the
wrapped code, so that in this situation it would be an error to observe `(foo
4 5 6)` before `(foo 1 2 3)`.
```lisp
(mocker-let ((foo (x y z)
((:input '(1 2 3) :output 4)
(:input '(4 5 6) :output 10)))
(bar (x)
((:input '(42) :output 4))))
(+ (foo 4 5 6)
(foo 1 2 3)
(bar 42)))
```
In such a situation, you'll get a typed error with a message like
```
(mocker-record-error "Violated record while mocking `foo'. Expected input like: `(1 2 3)', got: `(4 5 6)' instead")
...
```
If order is not important, you can obtain the same effect as before by
specifying it:
```lisp
(mocker-let ((foo (x y z)
:ordered nil
((:input '(1 2 3) :output 4)
(:input '(4 5 6) :output 10)))
(bar (x)
((:input '(42) :output 4))))
(+ (foo 4 5 6)
(foo 1 2 3)
(bar 42)))
```
### Counting calls
In many situations it can be pretty repetitive to list all the expected calls
to a mock. In some, the count might even be a range rather than a fixed number.
The `:min-occur` and `:max-occur` options allow to tune that. By default, they
are both set to 1, so that exactly 1 call is expected. As a special case,
setting `:max-occur` to nil will accept any number of calls.
An `:occur` shorthand is also provided, to expect an exact number of calls.
```lisp
(mocker-let ((foo (x)
((:input '(1) :output 1 :min-occur 1 :max-occur 3))))
(+ (foo 1) (foo 1)))
```
This example will accept between 1 and 3 calls to `(foo 1)`, and complain if
that constraint is not fulfilled.
Note the applied algorithm is greedy, so that as many calls as possible will
count as part of the earliest constraints.
### Flexible input/output
The examples above are fine, but they suppose input and output are just
constant expressions. A useful addition is the ability to match arbitrary input
and generate arbitrary output.
To this end, the `:input-matcher` and `:output-generator` options can be used
instead (actually think of `:input` and `:output` as convenience shortcuts for
constant matcher/generator).
```lisp
(mocker-let ((foo (x)
:ordered nil
((:input-matcher 'oddp :output-generator 'identity :max-occur 2)
(:input-matcher 'evenp :output 0))))
(+ (foo 1) (foo 2) (foo 3)))
```
Both `:input-matcher` and `:output-generator` values need to be functions (or
function symbols) accepting the same arguments as the mocked function itself.
## Extensibility
Each record definition actually builds a `mocker-record` object, that's
responsible for checking the actual behavior. By providing alternative
implementations of those records, one can adapt the mocking to special needs.
### Stubs
As a quick proof of concept, an implementation of a stub is provided with the
class `mocker-stub-record` which casualy ignores any input and always emits the
same output:
```lisp
(mocker-let ((foo (x)
((:record-cls 'mocker-stub-record :output 42))))
(foo 12345))
```
### Passthrough
In some occasions, you might want to mock only some calls for a function, and
let other calls invoke the real one. This can be achieved by using the
`mocker-passthrough-record`. In the following example, the first call to
`ignore` uses the real implementation, while the second one is mocked to return
`t`:
```lisp
(mocker-let ((ignore (x)
:records ((:record-cls mocker-passthrough-record
:input '(42))
(:input '(58) :output t))))
(or (ignore 42)
(ignore 58)))
```
### Provide your own
Customized classes can be provided, that can even introduce a mini-language for
describing the stub. This can be achieved by overloading
`mocker-read-record` correctly.
In case the customized record class is meant to be used in many tests, it might
be more convenient to use a pattern like:
```lisp
(let ((mocker-mock-default-record-cls 'mocker-stub-record))
(mocker-let ((foo (x)
((:output 42)))
(bar (x y)
((:output 1))))
(+ (foo 12345)
(bar 5 14))))
```
Also note that `mocker-stub-record` set their `:min-occur` to 0 and
`:max-occur` to nil, if not specified otherwise.
## Comparison to other mocking solutions
* el-mock.el (http://www.emacswiki.org/emacs/EmacsLispMock)
* el-mock.el uses a small DSL for recording behavior, which is great for
conciseness. mocker.el instead uses regular lisp as much as possible, which
is more flexible.
* el-mock.el does not allow recording multiple behaviors (the same call will
always return the same value). This makes it difficult to use in real
situation, where different call sites for the same function might have to
behave differently.
## Examples
```lisp
;;; automatically answer some `y-or-n-p' questions
(mocker-let ((y-or-n-p (prompt)
((:input '("Really?") :output t)
(:input '("I mean... for real?") :output nil))))
...)
```
```lisp
;;; blindly accept all `yes-or-no-p' questions
(mocker-let ((yes-or-no-p (prompt)
((:record-cls mocker-stub-record :output t))))
...)
```
```lisp
;;; make `foo' generate the fibonacci suite, no matter how it's called
(mocker-let ((foo (x)
((:input-matcher (lambda (x) t)
:output-generator (lexical-let ((x 0) (y 1))
(lambda (any)
(let ((z (+ x y)))
(setq x y y z))))
:max-occur nil))))
...)
```

368
tests/mocker/mocker.el Normal file
View file

@ -0,0 +1,368 @@
;;; mocker.el --- mocking framework for emacs
;; Copyright (C) 2011 Yann Hodique.
;; Author: Yann Hodique <yann.hodique@gmail.com>
;; Keywords: lisp, testing
;; Version: 0.3.1
;; Package-Requires: ((eieio "1.3") (el-x "0.2.4"))
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;;
;;; Code:
(eval-when-compile
(require 'cl))
(require 'eieio)
(eval-and-compile
;; use dflet from el-x if available
(if (require 'dflet nil t)
(defalias 'mocker-flet 'dflet)
;; fallback to regular flet, hoping it's still there
(defalias 'mocker-flet 'flet)))
(defvar mocker-mock-default-record-cls 'mocker-record)
(put 'mocker-mock-error 'error-conditions '(mocker-mock-error error))
(put 'mocker-mock-error 'error-message "Mocker mock error")
(put 'mocker-record-error 'error-conditions '(mocker-record-error error))
(put 'mocker-record-error 'error-message "Mocker record error")
(defun mocker--plist-remove (plist key)
;; courtesy of pjb
(if (eq (car plist) key) (cdr (cdr plist))
(cons (car plist)
(cons (cadr plist)
(mocker--plist-remove (cddr plist) key)))))
;;; Mock object
(defclass mocker-mock ()
((function :initarg :function :type symbol)
(orig-def :initarg :orig-def :initform nil)
(argspec :initarg :argspec :initform nil :type list)
(ordered :initarg :ordered :initform t)
(records :initarg :records :initform nil :type list)))
(defmethod constructor :static ((mock mocker-mock) newname &rest args)
(let* ((obj (call-next-method))
(recs (oref obj :records))
(func (oref obj :function)))
(oset obj :orig-def (when (fboundp func) (symbol-function func)))
(oset obj :records nil)
(mapc #'(lambda (r)
(apply 'mocker-add-record obj r))
recs)
obj))
(defmethod mocker-add-record ((mock mocker-mock) &rest args)
(object-add-to-list mock :records
(let ((cls mocker-mock-default-record-cls)
(tmp (plist-get args :record-cls)))
(when tmp
(setq cls tmp
args (mocker-read-record cls
(mocker--plist-remove
args :record-cls))))
(apply 'make-instance cls :-mock mock
:-sym (make-symbol "unique") args))
t))
(defmethod mocker-fail-mock ((mock mocker-mock) args)
(signal 'mocker-mock-error
(list (format (concat "Unexpected call to mock `%s'"
" with input `%s'")
(oref mock :function) args))))
(defvar mocker-inhibit nil)
(defmethod mocker-run ((mock mocker-mock) &rest args)
(if (not mocker-inhibit)
(let* ((mocker-inhibit t)
(rec (mocker-find-active-record mock args))
(ordered (oref mock :ordered)))
(cond ((null rec)
(mocker-fail-mock mock args))
((or (not ordered) (mocker-test-record rec args))
(mocker-run-record rec args))
(t
(mocker-fail-record rec args))))
(apply (oref mock :orig-def) args)))
(defmethod mocker-find-active-record ((mock mocker-mock) args)
(let ((first-match (lambda (pred seq)
(let ((x nil))
(while (and seq
(not (setq x (funcall pred (pop seq))))))
x))))
(let* ((ordered (oref mock :ordered))
rec)
(if ordered
(setq rec (funcall
first-match
#'(lambda (r)
(when (oref r :-active)
(if (mocker-test-record r args)
(progn
(mocker-use-record r)
r)
(mocker-skip-record r args))))
(oref mock :records)))
(setq rec (funcall
first-match
#'(lambda (r)
(and
(oref r :-active)
(mocker-test-record r args)
(progn
(mocker-use-record r)
r)))
(oref mock :records))))
rec)))
(defmethod mocker-verify ((mock mocker-mock))
(mapc #'(lambda (r) (when (and (oref r :-active)
(< (oref r :-occurrences)
(oref r :min-occur)))
(signal 'mocker-record-error
(list (format
(concat "Expected call to mock `%s',"
" with input like %s,"
" was not run.")
(oref mock :function)
(mocker-get-record-expectations r))))))
(oref mock :records)))
;;; Mock record base object
(defclass mocker-record-base ()
((min-occur :initarg :min-occur :initform 1 :type number)
(max-occur :initarg :max-occur :initform nil :type (or null number))
(-occur :initarg :occur :initform nil :type (or null number))
(-occurrences :initarg :-occurrences :initform 0 :type number
:protection :protected)
(-mock :initarg :-mock)
(-active :initarg :-active :initform t :protection :protected)
(-sym :initarg :-sym)))
(defmethod constructor :static ((rec mocker-record-base) newname &rest args)
(let* ((obj (call-next-method))
(occur (oref obj :occur)))
(when occur
(oset obj :min-occur (max (oref obj :min-occur)
occur))
(oset obj :max-occur (if (oref obj :max-occur)
(min (oref obj :max-occur) occur)
occur)))
obj))
(defmethod mocker-read-record :static ((rec mocker-record-base) spec)
spec)
(defmethod mocker-use-record ((rec mocker-record-base))
(let ((max (oref rec :max-occur))
(n (1+ (oref rec :-occurrences))))
(oset rec :-occurrences n)
(when (and (not (null max))
(= n max))
(oset rec :-active nil))))
(defmethod mocker-skip-record ((rec mocker-record-base) args)
(if (>= (oref rec :-occurrences)
(oref rec :min-occur))
(oset rec :-active nil)
(mocker-fail-record rec args)))
(defmethod mocker-test-record ((rec mocker-record-base) args)
(error "not implemented in base class"))
(defmethod mocker-run-record ((rec mocker-record-base) args)
(error "not implemented in base class"))
(defmethod mocker-get-record-expectations ((rec mocker-record-base)))
(defmethod mocker-fail-record ((rec mocker-record-base) args)
(signal 'mocker-record-error
(list (format (concat "Violated record while mocking `%s'."
" Expected input like: %s, got: `%s' instead")
(oref (oref rec :-mock) :function)
(mocker-get-record-expectations rec)
args))))
;;; Mock input recognizer
(defclass mocker-input-record (mocker-record-base)
((input :initarg :input :initform nil :type list)
(input-matcher :initarg :input-matcher :initform nil)))
(defmethod constructor :static ((rec mocker-input-record) newname &rest args)
(let* ((obj (call-next-method)))
(when (or (not (slot-boundp obj :max-occur))
(and (oref obj :max-occur)
(< (oref obj :max-occur)
(oref obj :min-occur))))
(oset obj :max-occur (oref obj :min-occur)))
obj))
(defmethod mocker-test-record ((rec mocker-input-record) args)
(let ((matcher (oref rec :input-matcher))
(input (oref rec :input)))
(cond (matcher
(apply matcher args))
(t
(equal input args)))))
(defmethod mocker-get-record-expectations ((rec mocker-input-record))
(format "`%s'" (or (oref rec :input-matcher) (oref rec :input))))
;;; Mock record default object
(defclass mocker-record (mocker-input-record)
((output :initarg :output :initform nil)
(output-generator :initarg :output-generator :initform nil)))
(defmethod mocker-run-record ((rec mocker-record) args)
(let ((generator (oref rec :output-generator))
(output (oref rec :output)))
(cond (generator
(apply generator args))
(t
output))))
;;; Mock simple stub object
(defclass mocker-stub-record (mocker-record-base)
((output :initarg :output :initform nil)))
(defmethod constructor :static ((rec mocker-stub-record) newname &rest args)
(let* ((obj (call-next-method)))
(unless (slot-boundp obj :min-occur)
(oset obj :min-occur 0))
(unless (slot-boundp obj :max-occur)
(oset obj :max-occur nil))
obj))
(defmethod mocker-test-record ((rec mocker-stub-record) args)
t)
(defmethod mocker-run-record ((rec mocker-stub-record) args)
(oref rec :output))
(defmethod mocker-get-record-expectations ((rec mocker-stub-record))
"anything")
;;; Mock passthrough record
(defclass mocker-passthrough-record (mocker-input-record)
())
(defmethod mocker-run-record ((rec mocker-passthrough-record) args)
(let* ((mock (oref rec :-mock))
(def (oref mock :orig-def)))
(when def
(apply def args))))
;;; Helpers
(defun mocker-gen-mocks (mockspecs)
"helper to generate mocks from the input of `mocker-let'"
(mapcar #'(lambda (m)
(let* ((func (car m))
(argspec (cadr m))
(rest (cddr m))
(sym (make-symbol (concat (symbol-name func) "--mock"))))
(list sym
(apply 'make-instance 'mocker-mock
:function func
:argspec argspec
(let* ((order (if (plist-member rest :ordered)
(prog1
(plist-get rest :ordered)
(setq rest
(mocker--plist-remove
rest :ordered)))
(oref-default 'mocker-mock
:ordered))))
(list :ordered order)))
(if (plist-member rest :records)
(plist-get rest :records)
(car rest)))))
mockspecs))
;;;###autoload
(defmacro mocker-let (mockspecs &rest body)
"Generate temporary bindings according to MOCKSPECS then eval
BODY. The value of the last form in BODY is returned.
Each element of MOCKSPECS is a list (FUNC ARGS [OPTIONS]
RECORDS).
FUNC is the name of the function to bind, whose original
definition must accept arguments compatible with ARGS.
OPTIONS can be :ordered nil if the records can be executed out of
order (by default, order is enforced).
RECORDS is a list ([:record-cls CLASS] ARG1 ARG2...).
Each element of RECORDS will generate a record for the
corresponding mock. By default, records are objects of the
`mocker-record' class, but CLASS is used instead if specified.
The rest of the arguments are used to construct the record
object. They will be passed to method `mocker-read-record' for
the used CLASS. This method must return a valid list of
parameters for the CLASS constructor. This allows to implement
specialized mini-languages for specific record classes.
"
(declare (indent 1) (debug t))
(let* ((mocks (mocker-gen-mocks mockspecs))
(vars (mapcar #'(lambda (m)
`(,(car m) ,(cadr m)))
mocks))
(specs (mapcar
#'(lambda (m)
(let* ((mock-sym (car m))
(mock (cadr m))
(func (oref mock :function))
(spec (oref mock :argspec))
(call (or (and (member '&rest spec) 'apply)
'funcall))
(args (loop for el in spec
if (or (not (symbolp el))
(not (equal
(elt (symbol-name el) 0)
?&)))
collect el)))
(list func
spec
`(,call #'mocker-run ,mock-sym ,@args))))
mocks))
(inits (mapcar #'(lambda (m)
(cons 'progn
(mapcar #'(lambda (rec)
`(mocker-add-record ,(car m)
,@rec))
(nth 2 m))))
mocks))
(verifs (mapcar #'(lambda (m)
`(mocker-verify ,(car m)))
mocks)))
`(let (,@vars)
,@inits
(prog1
,(macroexpand `(mocker-flet (,@specs)
,@body))
,@verifs))))
(provide 'mocker)
;;; mocker.el ends here

View file

@ -0,0 +1,279 @@
;;; mocker-tests.el --- tests for mocker.el
;; Copyright (C) 2011 Free Software Foundation, Inc.
;; Author: Yann Hodique <yann.hodique@gmail.com>
;; Keywords: lisp, testing
;; This file is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;; This file is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Commentary:
;; This file contains tests for mocker.el
;;; Code:
(eval-when-compile
(require 'cl))
(require 'mocker)
(eval-and-compile
(when (null (ignore-errors (require 'ert)))
(defmacro* ert-deftest (name () &body docstring-keys-and-body)
(message "Skipping tests, ERT is not available"))))
(ert-deftest mocker-let-basic ()
(should
(eq t (mocker-let () t))))
(ert-deftest mocker-let-single ()
(should
(eq t
(mocker-let ((foo () :records ((:output t))))
(foo)))))
(ert-deftest mocker-let-single-implicit-records ()
(should
(eq t
(mocker-let ((foo ()
((:output t))))
(foo)))))
(ert-deftest mocker-let-no-record ()
(should-error
(mocker-let ((foo () :records ()))
(foo))
:type 'mocker-mock-error))
(ert-deftest mocker-let-multiple ()
(should
(eq 42
(mocker-let ((foo () :records ((:output 6)))
(bar () :records ((:output 7))))
(* (foo) (bar))))))
(ert-deftest mocker-let-nested ()
(should
(eq 42
(mocker-let ((foo () :records ((:output 6))))
(mocker-let ((bar () :records ((:output 7))))
(* (foo) (bar)))))))
(ert-deftest mocker-let-multiple-inputs ()
(should
(eq 42
(mocker-let ((foo (x) :records ((:input '(1) :output 6)))
(bar (x) :records ((:input '(2) :output 7))))
(* (foo 1) (bar 2))))))
(ert-deftest mocker-let-multiple-inputs-invalid ()
(should-error
(mocker-let ((foo (x) :records ((:input '(1) :output 6)))
(bar (x) :records ((:input '(2) :output 7))))
(* (foo 2) (bar 2)))
:type 'mocker-record-error))
(ert-deftest mocker-let-single-input-matcher ()
(should
(eq t
(mocker-let ((foo (x)
:records ((:input-matcher 'integerp :output t))))
(foo 4)))))
(ert-deftest mocker-let-single-input-matcher-invalid ()
(should-error
(mocker-let ((foo (x)
:records ((:input-matcher 'integerp :output t))))
(foo t))
:type 'mocker-record-error))
(ert-deftest mocker-let-multiple-output-generator ()
(should
(eq 2
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity))
(:input '(4)
:output-generator (lambda (x) 0)))))
(+ (foo 2) (foo 4))))))
(ert-deftest mocker-let-multiple-calls-min ()
(should
(eq 4
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:min-occur 2))))
(+ (foo 2) (foo 2))))))
(ert-deftest mocker-let-multiple-calls-illimited ()
(should
(eq 8
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:max-occur nil))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))))
(ert-deftest mocker-let-multiple-calls-exact ()
(should
(eq 8
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:occur 4))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))))
(ert-deftest mocker-let-multiple-calls-multiple-records ()
(should
(eq 12
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:max-occur 2)
(:input '(2)
:output-generator (lambda (x) (* 2 x))
:occur 2))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))))
(ert-deftest mocker-let-multiple-calls-multiple-same-records ()
(should
(eq 8
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:max-occur 2)
(:input '(2)
:output-generator (function identity)
:max-occur 2))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))))
(ert-deftest mocker-let-multiple-calls-unexpected ()
(should-error
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:max-occur 2))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))
:type 'mocker-record-error)
(ert-deftest mocker-let-multiple-calls-unexpected-exact ()
(should-error
(mocker-let ((foo (x)
:records ((:input '(2)
:output-generator (function identity)
:occur 2))))
(+ (foo 2) (foo 2) (foo 2) (foo 2))))
:type 'mocker-record-error)
(ert-deftest mocker-let-stub-simple ()
(should
(let ((mocker-mock-default-record-cls 'mocker-stub-record))
(eq t
(mocker-let ((foo (x) :records ((:output t))))
(and (foo 1) (foo 42) (foo 666)))))))
(ert-deftest mocker-let-stub-simple-explicit ()
(should
(eq t
(mocker-let ((foo (x) :records ((:record-cls mocker-stub-record
:output t))))
(and (foo 1) (foo 42) (foo 666))))))
(ert-deftest mocker-let-stub-limited ()
(should-error
(let ((mocker-mock-default-record-cls 'mocker-stub-record))
(mocker-let ((foo (x) :records ((:output t :max-occur 2))))
(and (foo 1) (foo 42) (foo 666))))
:type 'mocker-mock-error))
(ert-deftest mocker-let-multiple-calls-unordered ()
(should
(eq 18
(mocker-let ((foo (x y z)
:ordered nil
((:input '(1 2 3) :output 4)
(:input '(4 5 6) :output 10)))
(bar (x)
((:input '(42) :output 4))))
(+ (foo 4 5 6)
(foo 1 2 3)
(bar 42))))))
(ert-deftest mocker-passthrough-basic ()
(should
(not
(mocker-let ((ignore (x)
:records ((:record-cls mocker-passthrough-record
:input '(42)))))
(ignore 42)))))
(ert-deftest mocker-passthrough-mixed ()
(should
(mocker-let ((ignore (x)
:records ((:record-cls mocker-passthrough-record
:input '(42))
(:input '(58) :output t))))
(or (ignore 42)
(ignore 58)))))
(ert-deftest mocker-passthrough-mixed-error ()
(should-error
(mocker-let ((ignore (x)
:records ((:record-cls mocker-passthrough-record
:input '(42))
(:input '(58) :output t))))
(or (ignore 42)
(ignore 42)))
:type 'mocker-record-error))
(ert-deftest mocker-passthrough-multiple ()
(should
(mocker-let ((ignore (x)
((:input-matcher (lambda (x) t)
:output t :max-occur 2)
(:record-cls mocker-passthrough-record
:input '(42) :max-occur nil))))
(and (ignore 1)
(ignore 2)
(not (or
(ignore 42) (ignore 42) (ignore 42) (ignore 42)))))))
(ert-deftest mocker-inhibit-mock-not-consumed ()
(should-error
(let ((mocker-inhibit t))
(mocker-let ((ignore (x)
((:input '(42) :output t))))
(ignore 42)))
:type 'mocker-record-error))
(ert-deftest mocker-inhibit-mocking ()
(should
(not
(mocker-let ((ignore (x)
((:input '(42) :output t))))
(and (ignore 42)
(let ((mocker-inhibit t))
(ignore 42)))))))
(ert-deftest mocker-rest-args ()
(should
(mocker-let ((f (a b &rest args) ((:input '(1 2 3 4) :output t))))
(f 1 2 3 4))))
(provide 'mocker-tests)
;;; mocker-tests.el ends here