-
Notifications
You must be signed in to change notification settings - Fork 86
/
pymacs.rst.in
1966 lines (1573 loc) · 90.1 KB
/
pymacs.rst.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
.. role:: code(strong)
.. role:: file(literal)
.. role:: var(emphasis)
================================================================
Pymacs version @VERSION@
================================================================
---------------------------
Extending Emacs with Python
---------------------------
:Author: François Pinard
:Email: [email protected]
:Copyright: © Progiciels Bourbeau-Pinard inc., Montréal 2003, 2008, 2010, 2012
.. contents::
.. sectnum::
..
There exists a `Romanian translation`__ of this manual.
__ http://webhostinggeeks.com/science/pymacs-framework-ro
.. By `Alexander Ovsov` [email protected]
Introduction
============
What is Pymacs?
---------------
Pymacs is a powerful tool which, once started from Emacs, allows two-way
communication between Emacs Lisp and Python. Pymacs aims to employ
Python as an extension language for Emacs rather than the other way
around, and this asymmetry is reflected in some design choices. Within
Emacs Lisp code, one may load and use Python modules. Python functions
may themselves use Emacs services, and handle Emacs Lisp objects kept in
Emacs Lisp space.
The goals are to write *naturally* in both languages, debug with ease,
fall back gracefully on errors, and allow full cross-recursion.
It is very easy to install Pymacs, as neither Emacs nor Python need to
be compiled nor relinked. Emacs merely starts Python as a subprocess,
and Pymacs implements a communication protocol between both processes.
Report problems, documentation flaws, or suggestions to François Pinard:
+ mailto:[email protected]
Documentation and examples
--------------------------
The main Pymacs site conveys the Pymacs documentation (you are reading
its Pymacs manual right now) and distributions:
+ http://pymacs.progiciels-bpi.ca
I expect average Pymacs users to have a deeper knowledge of Python
than Emacs Lisp. People have widely varying approaches in writing
:file:`.emacs` files, as far as Pymacs is concerned:
+ Some can go and write almost no Emacs Lisp, yet a bit is still
necessary for establishing a few loading hooks. For many simple
needs, one can do a lot without having to learn much.
+ On the other hand, for more sophisticated usages, people cannot
really escape knowing the Emacs Lisp API to some extent, because they
should be familiar, programming-wise, with what is a buffer, a point,
a mark, etc. and what are the allowed operations on those.
While Pymacs examples are no substitute for a careful reading of the
Pymacs manual, the contemplation and study of others' nice works may
well enligthen and deepen your understanding. A few examples are
included within the Pymacs distribution, each as a subdirectory of the
:file:`contrib/` directory, and each having its own :file:`README` file.
These are listed below, easiest examples first:
+ Paul Winkler's example
+ http://pymacs.progiciels-bpi.ca/Winkler.html
+ Fernando Pérez' examples
+ http://pymacs.progiciels-bpi.ca/Perez.html
+ http://pymacs.progiciels-bpi.ca/contrib/Perez/
+ Giovanni Giorgi's files
+ http://pymacs.progiciels-bpi.ca/Giorgi.html
+ http://pymacs.progiciels-bpi.ca/contrib/Giorgi/
+ A reformatter for boxed comments
+ http://pymacs.progiciels-bpi.ca/rebox.html
+ http://pymacs.progiciels-bpi.ca/contrib/rebox/
A few more substantial examples of Pymacs usage have been brought to my
attention, and are available externally (listed here in no particular
order):
+ pymdev — A Python Emacs Development Module:
+ http://www.toolness.com/pymdev/
+ Ropemacs — Features like refactoring and code-assists:
+ http://rope.sf.net/ropemacs.html
+ http://rope.sf.net/hg/ropemacs
+ Bicycle Repair Man — A Refactoring Tool for Python:
+ http://bicyclerepair.sourceforge.net/
+ Emacs Freex — A personal wiki on steroids:
+ http://www.princeton.edu/%7Egdetre/software/freex/docs/index.html
+ PyJde — Java dev source code browsing features in Emacs using Python:
+ http://code.google.com/p/pyjde/
The QaTeX project was influenced by Pymacs, according to its author:
+ http://qatex.sourceforge.net/
+ http://www.pytex.org/doc/eurotex2005.pdf
Other resources
---------------
You are welcome writing to or joining the following mailing list, where
there are a few people around likely to give you feedback:
+ mailto:[email protected]
+ https://groups.google.com/group/pymacs-devel/
If you have no fear of wider crowds :-), there still is:
+ mailto:[email protected]
There are other Web sites specifically about Pymacs. `Giovanni Giorgi`__
has one of them:
+ http://blog.objectsroot.com/projects/pymacs/
__ http://blog.objectsroot.com/
There is an entry for Pymacs on Freecode:
+ http://freecode.com/projects/pymacs/
Installation
============
Check the search paths
----------------------
You should make sure that both Emacs and Python are usable, whatever the
directory happens to be the current one. This is particularly important
at the time Emacs launches Python under the scene, as Python ought to be
found then started. On most systems, this means setting the search path
correctly.
The following notes, for MS Windows, have been provided by Greg Detre.
+ After ``Start / Run / Cmd``, type ``python``. If this works
wherever you are, then your Python installation directory is already
in your system's :code:`PATH` environment variable. If that's not the
case, follow the instructions here to add it:
http://www.computerhope.com/issues/ch000549.htm
+ You may have to add the directory containing the Python scripts that
you want to run through Pymacs to your :code:`PYTHONPATH` variable,
in the same fashion as above. You can test this by running Python,
and then::
import sys
sys.path
or just::
import my_python_scripts
from somewhere besides your scripts directory.
Edit the configuration file
---------------------------
In most cases, you may safely skip this step, as it is only needed in
unusual, problematic circumstances. Merely check that none of the
following applies to you.
+ Under Aquamacs (which is a MacOS X native port of Emacs), it has
been reported that one gets `Lisp nesting exceeds max-lisp-eval-depth`
messages while interactively requesting the documentation for Lisp
functions (we do not know why). If you have this problem, edit file
:file:`ppppconfig.py`, locate the line defining :code:`DEFADVICE_OK`,
make sure it gets the string ``'nil'`` as a value, instead of the
string ``'t'``, then save the edited file before proceeding further.
This should work around the problem. The price to pay is that you
will not get the Python docstring for modules imported through Pymacs.
Check if Pymacs would work
--------------------------
To know, before installing Pymacs, if it would work on your system, try
the validation suite by running ``make check``. The suite is fairly
elementary, but nevertheless, it is able to detect some common show
stoppers. To check a particular Emacs and Python combination, use
``make check EMACS=some_Emacs PYTHON=some_Python``.
If ``PYTHON`` is left unset or empty, then the command for starting the
Pymacs helper is ``python``. Otherwise, it may be set to give the full
path of the Python executable if it exists at some location outside the
program search path. It may also be given when the interpreter name is
different, for exemple when the Python version is part of the program
name.
If ``EMACS`` is left unset or empty, then the command for starting the
Emacs editor is ``emacs``. For normal Pymacs usage, Emacs is launched
by the user long before Pymacs is itself started, and consequently,
there is absolutely no need to tell Pymacs which Emacs is needed. For
the validation suite however, it may be set to give the full path of
the executable if the Emacs program exists at some location outside
the program search path. It may also be given when the editor name is
different, for example when the Emacs version is part of the program
name, or when this is a different editor. For example, ``make check
EMACS=xemacs`` runs the validation suite using ``xemacs`` for an editor.
The remaining of this section may be safely be skipped for mere Pymacs
installation.
I did not base the validation suite on Junit (the Python unit testing
framework is a re-implementation of it), but on Codespeak's pylib
:file:`py.test`, which is much simpler, and still very powerful. The
:code:`pylib` project is driven by Holge Kregel, but attracted some
Python brains, like Armin Rigo (known for Psyco, among other things --
I think his :code:`lsprof` has also been added to Python 2.5 under the
name :code:`cProfile`). This gang addresses overdone/heavy methods in
Python, and do them better. Even :file:`py.test` is a bit more complex
that I would want, and has (or at least had) flaws on the Unicode side,
so I rewrote my own, as a simple single file. I merely translated it
from French to English, to make it more distributable within Pymacs.
I initially tried using Emacs stdin and stdout for communicating
expressions to evaluate and getting back results, from within the
validation suite. This did not prove useful so, so after some fight, I
reluctantly put this avenue aside. Currently, the suite writes problems
in files, for Emacs to read, and Emacs writes replies in files, for the
suite to check. Busy waiting (with small sleep added in the loops) is
used on both sides. This is all too heavy, and it slows down the suite.
Hopefully, the suite is not run often, this is not a real problem.
Install the Pymacs proper
-------------------------
Pymacs is lean. Putting the documentation and administrative
files aside, there is one Python file and one Emacs Lisp file to it, to
be installed in turn. Always start with the Python file.
+ For the Python part
From the top-level of the Pymacs distribution, execute ``make
install``. If you do not have a Make program (Microsoft Windows?)
read the ``Makefile`` file and emulate what ``make install`` does,
maybe something like this::
python pppp -C ppppconfig.py \
Pymacs.py.in pppp.rst.in pymacs.el.in pymacs.rst.in contrib tests
python setup.py install
Without ``make install``, you might also have to combine the two first
lines above into a single longer one, without the backslash.
If the Python interpreter has a non-standard name or
location, rather do ``make install PYTHON=Some_Python`` (see the
previous section for a discussion). First, the script copies a few
source files while configuring them: it presets the version string and
the name of the Python interpreter, it also adapts the Python source
code which might differ, for example, between Python 2 and Python 3.
Second, it installs the Python file through the Python standard
Distutils tool. To get an option reminder, do ``python setup.py
install --help``. Consult the Distutils documentation if you need
more information about this.
That's normally all to it. To check that :file:`Pymacs.py` is
properly installed, start an interactive Python session and type
``from Pymacs import lisp``: you should not receive any error.
A special difficulty arises when the particular Python you use
does not have Distutils already installed. In such a case, ``make
install`` prints a warning, leaving to you the task of figuring out
where the ``Pymacs/`` directory is best copied, and making that copy.
+ For the Emacs part
This is usually done by hand now. First select some directory along
the list kept in your Emacs :code:`load-path`, for which you have
write access, and copy file :file:`pymacs.el` in that directory.
If you want speed, you should ideally byte-compile this file. To do
so, go to that directory, launch Emacs, then give the command ``M-x
byte-compile-file RET pymacs.el RET``. If for some reason you intend
to such commands often, you could create a little script to do so.
Here is an example of such a script, assuming here that you use Emacs
and want to install in directory :file:`~/share/emacs/lisp/`::
#!/bin/bash
cp pymacs.el ~/share/emacs/lisp/
emacs -batch -eval '(byte-compile-file "~/share/emacs/lisp/pymacs.el")'
You should be done now. To check that :file:`pymacs.el` is properly
installed, return to your usual directories, start Emacs and give
it the command ``M-x load-library RET pymacs RET``: you should not
receive any error.
Some features from previous Pymacs releases have been dropped:
+ Environment variable ``PYMACS_EMACS`` is gone, and environment
variable ``PYMACS_PYTHON`` is usually not needed.
+ There used to be a script for installing the Emacs Lisp file. As it
was difficult to get it right in all circumstances; the script grew
an interactive mode and lot of options. This is just not worth the
complexity, so this script is now gone.
+ Examples were all installed automatically, but at least for some of
them, this was more pollution than help. You may browse the contents of
the :file:`contrib/` directory to learn about available examples.
Prepare your :file:`.emacs` file
--------------------------------
The :file:`.emacs` file is not given in the distribution, you likely
have one already in your home directory. You need to add these lines::
(autoload 'pymacs-apply "pymacs")
(autoload 'pymacs-call "pymacs")
(autoload 'pymacs-eval "pymacs" nil t)
(autoload 'pymacs-exec "pymacs" nil t)
(autoload 'pymacs-load "pymacs" nil t)
(autoload 'pymacs-autoload "pymacs")
;;(eval-after-load "pymacs"
;; '(add-to-list 'pymacs-load-path YOUR-PYMACS-DIRECTORY"))
If you plan to use a special directory to hold your own Pymacs code in
Python, which should be searched prior to the usual Python import search
path, then uncomment the last two lines (by removing the semi-colons)
and replace :var:`YOUR-PYMACS-DIRECTORY` by the name of your special
directory. If the file :file:`~/.emacs` does not exist, merely create
it with the above lines. You are now all set to use Pymacs.
To check this, start a fresh Emacs session, and type ``M-x
pymacs-eval RET``. Emacs should prompt you for a Python expression.
Try ``repr(2L**111) RET`` (rather use ``repr(2**111) RET``
if you are using Python 3). The mini buffer should display
`"2596148429267413814265248164610048L"` (yet there is no ``L`` suffix
in Python 3).
Let's do a second test. Whether in the same Emacs session or not, ``M-x
pymacs-load RET`` should prompt you for a Python module name. Reply
``os RET RET`` (the second ``RET`` is for accepting the default prefix).
This should have the effect of importing the Python :code:`os` module
within Emacs. Typing ``M-: (os-getcwd) RET`` should echo the current
directory in the message buffer, as returned by the :code:`os.getcwd`
Python function.
Porting and caveats
-------------------
Pymacs has been initially developed on Linux, Python 1.5.2, and Emacs
20, and is currently developed using Python 2.6, Python 3.1, Emacs 23.1
and XEmacs 21.4. It is expected to work out of the box on many flavours
of Unix, MS Windows and Mac OSX, and also on many version of Python,
Emacs and XEmacs.
Pymacs 0.26 requires Python 2.6 or better, and Python 3 is supported
since Pymacs 0.25. For an older Python 2 distribution, you might
decide for an older Pymacs as well; it is rather easy to fetch any
older Pymacs version using GitHub facilities. If you use something
older than Python 2.2, you'll have to jump before Pymacs 0.23.
Pymacs uses Emacs weak hash tables. It can run without them, but then,
complex Python objects transmitted to Emacs will tie Python memory
forever. It should not be a practical problem in most simple cases.
Some later versions of Emacs 20 silently create ordinary tables when
asked for weak hash tables. Older Emacses do not have hash tables.
In earlier versions, Pymacs was installing a :file:`Pymacs` Python
package holding a single :file:`pymacs.py` file (besides the
mandatory :file:`__init__.py`). This is now replaced by a single
:file:`Pymacs.py` file, and because of the capitalisation, the API did
not need to change.
Emacs Lisp structures and Python objects
========================================
Conversions
-----------
Whenever Emacs Lisp calls Python functions giving them arguments, these
arguments are Emacs Lisp structures that should be converted into Python
objects in some way. Conversely, whenever Python calls Emacs Lisp
functions, the arguments are Python objects that should be received
as Emacs Lisp structures. We need some conventions for doing such
conversions.
Conversions generally transmit mutable Emacs Lisp structures as mutable
objects on the Python side, in such a way that transforming the object
in Python will effectively transform the structure on the Emacs Lisp
side (strings are handled a bit specially however, see below). The
other way around, Python objects transmitted to Emacs Lisp often loose
their mutability, so transforming the Emacs Lisp structure is not
reflected on the Python side.
Pymacs sticks to standard Emacs Lisp, it explicitly avoids various Emacs
Lisp extensions. One goal for many Pymacs users is taking some distance
from Emacs Lisp, so Pymacs is not overly pushing users deeper into it.
Simple objects
--------------
Emacs Lisp :code:`nil` and the equivalent Emacs Lisp ``()`` yield Python
:code:`None`. Python :code:`None`, Python :code:`False` and the Python
empty list ``[]`` are returned as :code:`nil` in Emacs Lisp. Notice
the assymetry, in that three different Python objects are mapped into
a single Emacs Lisp object. So, neither :code:`False` nor ``[]`` are
likely produced by automatic conversions from Emacs Lisp to Python.
Emacs Lisp :code:`t` yields Python :code:`True`. Python :code:`True` is
returned as :code:`t` in Emacs Lisp.
Emacs Lisp numbers, either integer or floating, are converted in
equivalent Python numbers. Emacs Lisp characters are really numbers
and yield Python numbers. In the other direction, Python numbers are
converted into Emacs Lisp numbers, with the exception of long Python
integers and complex numbers.
Emacs Lisp strings are usually converted into equivalent Python strings.
As Python strings do not have text properties, these are not reflected.
This may be changed by setting the :code:`pymacs-mutable-strings`
option: if this variable is not :code:`nil`, Emacs Lisp strings are
then transmitted opaquely. Python strings are always converted into
Emacs Lisp strings. Python releases before version 3 make a distinction
between Unicode and narrow strings: Unicode strings are then produced
on the Python side for Emacs Lisp multi-byte strings, but only when
they do not fit in ASCII, otherwise Python narrow strings are produced.
Conversely, Emacs Lisp multi-byte strings are produced for Python
strings, but only when they do not fit ASCII, otherwise Emacs Lisp
uni-byte strings are produced. Currently, Pymacs behaviour is undefined
for users wandering outside the limits of Emacs' :code:`utf-8` coding
system.
Emacs Lisp symbols yield ``lisp[STRING]`` notations on the Python
side, where :var:`STRING` names the symbol. In the other direction,
Python ``lisp[STRING]`` corresponds to an Emacs Lisp symbol printed
with that :var:`STRING` which, of course, should then be a valid Emacs
Lisp symbol name. As a convenience, ``lisp.SYMBOL`` on the Python side
yields an Emacs Lisp symbol with underscores replaced with hyphens;
this convention is welcome, as Emacs Lisp programmers commonly prefer
using dashes, where Python programmers use underlines. Of course, this
``lisp.SYMBOL`` notation is only usable when the :var:`SYMBOL` is a
valid Python identifier, while not being a Python keyword.
Sequences
---------
The case of strings has been discussed in the previous section.
Proper Emacs Lisp lists, those for which the :code:`cdr` of last cell
is :code:`nil`, are normally transmitted opaquely to Python. If
:code:`pymacs-forget-mutability` is set, or if Python later asks for
these to be expanded, proper Emacs Lisp lists get converted into Python
lists, if we except the empty list, which is always converted as Python
:code:`None`. In the other direction, Python lists are always converted
into proper Emacs Lisp lists.
Emacs Lisp vectors are normally transmitted opaquely to Python.
However, if :code:`pymacs-forget-mutability` is set, or if Python
later asks for these to be expanded, Emacs Lisp vectors get converted
into Python tuples. In the other direction, Python tuples are always
converted into Emacs Lisp vectors.
Remember the rule: `Round parentheses correspond to square brackets!`.
It works for lists, vectors, tuples, seen from either Emacs Lisp or
Python.
The above choices were debatable. Since Emacs Lisp proper lists
and Python lists are the bread-and-butter of algorithms modifying
structures, at least in my experience, I guess they are more naturally
mapped into one another, this spares many casts in practice. While in
Python, the most usual idiom for growing lists is appending to their
end, the most usual idiom in Emacs Lisp to grow a list is by cons'ing
new items at its beginning::
(setq accumulator (cons 'new-item accumulator))
or more simply::
(push 'new-item accumulator)
So, in case speed is especially important and many modifications
happen in a row on the same side, while order of elements ought to
be preserved, some ``(nreverse ...)`` on the Emacs Lisp side or
``.reverse()`` on the Python side might be needed. Surely, proper
lists in Emacs Lisp and lists in Python are the normal structure for
which length is easily modified.
We cannot so easily change the size of a vector, the same as it is a bit
more of a stunt to *modify* a tuple. The shape of these objects is
fixed. Mapping vectors to tuples, which is admittedly strange, will
only be done if the Python side requests an expanded copy, otherwise an
opaque Emacs Lisp object is seen in Python. In the other direction,
whenever an Emacs Lisp vector is needed, one has to write
``tuple(python_list)`` while transmitting the object. Such
transmissions are most probably to be unusual, as people are not going
to blindly transmit whole big structures back and forth between Emacs
and Python, they would rather do it once in a while only, and do only
local modifications afterwards. The infrequent casting to :code:`tuple`
for getting an Emacs Lisp vector seems to suggest that we did a
reasonable compromise.
In Python, both tuples and lists have O(1) access, so there is no real
speed consideration there. Emacs Lisp is different: vectors have
O(1) access while lists have O(N) access. The rigidity of Emacs Lisp
vectors is such that people do not resort to vectors unless there
is a speed issue, so in real Emacs Lisp practice, vectors are used
rather parsimoniously. So much, in fact, that Emacs Lisp vectors are
overloaded for what they are not meant: for example, very small vectors
are used to represent X events in key-maps, programmers only want to
test vectors for their type, or users just like bracketed syntax. The
speed of access is hardly an issue then.
Opaque objects
--------------
Emacs Lisp handles
,,,,,,,,,,,,,,,,,,
When a Python function is called from Emacs Lisp, the function arguments
have already been converted to Python types from Emacs Lisp types and
the function result is going to be converted back to Emacs Lisp.
Several Emacs Lisp objects do not have Python equivalents, like for
Emacs windows, buffers, markers, overlays, etc. It is nevertheless
useful to pass them to Python functions, hoping that these Python
functions will *operate* on these Emacs Lisp objects. Of course, the
Python side may not itself modify such objects, it has to call for
Emacs services to do so. Emacs Lisp handles are a mean to ease this
communication.
Whenever an Emacs Lisp object may not be converted to a Python object,
an Emacs Lisp handle is created and used instead. Whenever that Emacs
Lisp handle is returned into Emacs Lisp from a Python function, or
is used as an argument to an Emacs Lisp function from Python, the
original Emacs Lisp object behind the Emacs Lisp handle is automatically
retrieved.
Emacs Lisp handles are either instances of the internal :code:`Lisp`
class, or of one of its subclasses. If :var:`OBJECT` is an Emacs
Lisp handle, and if the underlying Emacs Lisp object is an Emacs
Lisp sequence, then whenever ``OBJECT[INDEX]``, ``OBJECT[INDEX] =
VALUE`` and ``len(OBJECT)`` are meaningful, these may be used to
fetch or alter an element of the sequence directly in Emacs Lisp
space. Also, if :var:`OBJECT` corresponds to an Emacs Lisp function,
``OBJECT(ARGUMENTS)`` may be used to apply the Emacs Lisp function over
the given arguments. Since arguments have been evaluated the Python
way on the Python side, it would be conceptual overkill evaluating them
again the Emacs Lisp way on the Emacs Lisp side, so Pymacs manage to
quote arguments for defeating Emacs Lisp evaluation. The same logic
applies the other way around.
Emacs Lisp handles have a ``value()`` method, which merely returns
self. They also have a ``copy()`` method, which tries to *open
the box* if possible. Emacs Lisp proper lists are turned into Python
lists, Emacs Lisp vectors are turned into Python tuples. Then,
modifying the structure of the copy on the Python side has no effect on
the Emacs Lisp side.
For Emacs Lisp handles, ``str()`` returns an Emacs Lisp representation
of the handle which should be :code:`eq` to the original object if
read back and evaluated in Emacs Lisp. ``repr()`` returns a Python
representation of the expanded Emacs Lisp object. If that Emacs Lisp
object has an Emacs Lisp representation which Emacs Lisp could read
back, then ``repr()`` value is such that it could be read back and
evaluated in Python as well, this would result in another object which
is :code:`equal` to the original, but not necessarily :code:`eq`.
Python handles
,,,,,,,,,,,,,,
The same as Emacs Lisp handles are useful for handling Emacs Lisp
objects on the Python side, Python handles are useful for handling
Python objects on the Emacs Lisp side.
Many Python objects do not have direct Emacs Lisp equivalents, including
long integers, complex numbers, modules, classes, instances and surely a
lot of others. When such are being transmitted to the Emacs Lisp side,
Pymacs use Python handles. These are automatically recovered into the
original Python objects whenever transmitted back to Python, either as
arguments to a Python function, as the Python function itself, or as the
return value of an Emacs Lisp function called from Python.
The objects represented by these Python handles may be inspected or
modified using the basic library of Python functions. For example, in::
(pymacs-exec "import re")
(setq matcher (pymacs-eval "re.compile('PATTERN').match"))
(pymacs-call matcher ARGUMENT)
the :code:`setq` line above could be decomposed into::
(setq compiled (pymacs-eval "re.compile('PATTERN')")
matcher (pymacs-call "getattr" compiled "match"))
This example shows that one may use :code:`pymacs-call` with
:code:`getattr` as the function, to get a wanted attribute for a Python
object.
Usage on the Emacs Lisp side
============================
Special Emacs Lisp functions
----------------------------
Pymacs is mainly launched and used through a few special functions,
among all those added by Pymacs for Emacs Lisp. These few imported
functions are listed and detailed in the following subsections. They
really are the preferred way to call Python services with Pymacs.
Even then, we do not expect that :code:`pymacs-exec`,
:code:`pymacs-eval`, :code:`pymacs-call` or :code:`pymacs-apply` will
be much used, if ever, in most Pymacs applications. In practice, the
Emacs Lisp side of a Pymacs application might call either
:code:`pymacs-autoload` or :code:`pymacs-load` a few times for linking
into the Python modules, with the indirect effect of defining
trampoline functions for these modules on the Emacs Lisp side, which
can later be called like usual Emacs Lisp functions.
:code:`pymacs-exec`
,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-exec TEXT)`` gets :var:`TEXT` executed as a Python
statement, and its value is always :code:`nil`. So, this function may
only be useful because of its possible side effects on the Python side.
This function may also be called interactively::
M-x pymacs-exec RET TEXT RET
:code:`pymacs-eval`
,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-eval TEXT)`` gets :var:`TEXT` evaluated as a Python
expression, and returns the value of that expression converted back to
Emacs Lisp.
This function may also be called interactively::
M-x pymacs-eval RET TEXT RET
:code:`pymacs-call`
,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-call FUNCTION ARGUMENT...)`` will get Python to
apply the given :var:`FUNCTION` over zero or more :var:`ARGUMENT`.
:var:`FUNCTION` is either a string holding Python source code for a
function (like a mere name, or even an expression), or else, a Python
handle previously received from Python, and hopefully holding a callable
Python object. Each :var:`ARGUMENT` gets separately converted to Python
before the function is called. :code:`pymacs-call` returns the resulting
value of the function call, converted back to Emacs Lisp.
:code:`pymacs-apply`
,,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-apply FUNCTION ARGUMENTS)`` will get Python to
apply the given :var:`FUNCTION` over the given :var:`ARGUMENTS`.
:var:`ARGUMENTS` is a list containing all arguments, or :code:`nil`
if there is none. Besides arguments being bundled together
instead of given separately, the function acts pretty much like
:code:`pymacs-call`.
:code:`pymacs-load`
,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-load MODULE PREFIX)`` imports the Python
:var:`MODULE` into Emacs Lisp space. :var:`MODULE` is the name of the
file containing the module, without any :file:`.py` or :file:`.pyc`
extension. If the directory part is omitted in :var:`MODULE`, the
module will be looked into the current Python search path. Dot notation
may be used when the module is part of a package. Each top-level
function in the module produces a trampoline function in Emacs Lisp
having the same name, except that underlines in Python names are
turned into dashes in Emacs Lisp, and that :var:`PREFIX` is uniformly
added before the Emacs Lisp name (as a way to avoid name clashes).
:var:`PREFIX` may be omitted, in which case it defaults to base name
of :var:`MODULE` with underlines turned into dashes, and followed by a
dash.
Note that :code:`pymacs-load` has the effect of declaring the module
variables and methods on the Emacs Lisp side, but it does *not* declare
anything on the Python side. Of course, Python imports the module
before making it available for Emacs, but there is no Pymacs ready
variable on the Python side holding that module. If you need to import
:var:`MODULE` in a variable on the Python side, the proper incantation
is ``(pymacs-exec "import MODULE")``. And of course, this latter
statement does not declare anything on the Emacs Lisp side.
Whenever :code:`pymacs_load_hook` is defined in the loaded
Python module, :code:`pymacs-load` calls it without arguments,
but before creating the Emacs view for that module. So, the
:code:`pymacs_load_hook` function may create new definitions or even add
:code:`interaction` attributes to functions.
The return value of a successful :code:`pymacs-load` is the module
object. An optional third argument, :var:`noerror`, when given and not
:code:`nil`, will have :code:`pymacs-load` to return :code:`nil` instead
of raising an error, if the Python module could not be found.
When later calling one of these trampoline functions, all provided
arguments are converted to Python and transmitted, and the function
return value is later converted back to Emacs Lisp. It is left to
the Python side to check for argument consistency. However, for an
interactive function, the interaction specification drives some checking
on the Emacs Lisp side. Currently, there is no provision for collecting
keyword arguments in Emacs Lisp.
This function may also be called interactively::
M-x pymacs-load RET MODULE RET PREFIX RET
If you find yourself using :code:`pymacs-call` a lot for builtin Python
functions, you might rather elect to import all Python builtin functions
and definitions directly into Emacs Lisp space, and call them directly
afterwards. Here is a recipe (use the first line for Python 2, or the
second line for Python 3)::
M-x pymacs-load RET __builtin__ RET py- RET
M-x pymacs-load RET builtins RET py- RET
After such a command, calling the function ``py-getattr``, say, with an
opaque Python object and with a string naming an attribute, returns the
value of that attribute for that object.
:code:`pymacs-autoload`
,,,,,,,,,,,,,,,,,,,,,,,
Function ``(pymacs-autoload FUNCTION MODULE PREFIX DOCSTRING
INTERACTIVE)`` is meant to mimic the functionality of the standard
Emacs :code:`autoload` function.
It declares :var:`FUNCTION` to be autoloaded from the specified Python
:var:`MODULE`. The :code:`pymacs-load` for this module is delayed
until :var:`FUNCTION` is actually called. Of course, if there are
many such functions declared as autoloading the module, calling any of
them will then load the module and resolve the autoloading for all of
them at once. For the meaning of the optional :var:`PREFIX` argument,
see the documentation for the :code:`pymacs-load` function above.
Before the function gets loaded for real, Emacs may still provide a
documentation for it, which the user gives through the contents of the
optional :var:`DOCSTRING`. Emacs also needs to know if the function
may be called interactively and, when this is the case, the arguments
it may accept. If the :var:`INTERACTIVE` argument is not provided, or
when it is :code:`nil`, the function is not known to be interactive. A value
of :code:`t` for :var:`INTERACTIVE` means that the function is
interactive, but has no arguments. Otherwise, :var:`INTERACTIVE`
receives a description of the interaction to interactively get the
function arguments. See the Emacs documentation for function
:code:`autoload` and :code:`interactive` for more information.
If, at the moment of the :code:`pymacs-autoload` call, :var:`FUNCTION`
is already related to a loaded Python function, the autoloading
declaration is ignored.
Here are examples of usage for the :code:`pymacs-autoload` function::
(pymacs-autoload 'os-getenv "os" nil nil "sEnv name: ")
(pymacs-autoload 'posix-getenv "os" "posix-" nil
'(list (read-string "Env name: ")))
The second example could be written more simply as in the first
example. Moreover, both examples of an :var:INTERACTIVE argument are
merely given here for illustration, as the real :code:`os-getenv`
function is *not* interactive.
Leo Liu, who contributed this feature, writes:
There is one corner case where :code:`pymacs-python-reference` returns
:code:`nil`. This happens when a function is defined in using
``lisp("""[some lisp code]""")``. The Ropemacs project `does this`__.
At the moment :code:`pymacs-autoload` cannot autoload such functions,
and one cannot write::
(pymacs-autoload 'ropemacs-mode "ropemacs" "rope-")
I wonder if :code:`pymacs-python-reference` could return something —
such as :code:`lisp` maybe — for such cases.
__ https://bitbucket.org/agr/ropemacs/src/6913282b6166/ropemacs/__init__.py#cl-534
Special Emacs Lisp variables
----------------------------
Users could alter the inner working of Pymacs through a few variables,
these are all documented here. Except for :code:`pymacs-python-command`
and :code:`pymacs-load-path`, which should be set before calling any
Pymacs function, the value of these variables can be changed at any
time.
:code:`pymacs-python-command`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
This variable is initialized with the Python executable that was used
at installation time. It tells Emacs about the Python interpreter to
launch far starting the Pymacs helper. The value of this variable may
be overridden by setting the ``PYMACS_PYTHON`` environment variable, yet
in practice, for newer versions of Pymacs, this is rarely needed.
While the Python part of Pymacs is pre-processed and yields different
sources for Python 2 and Python 3 (among other possibilities), the
Emacs part of Pymacs is mostly configured at run time for various Emacs
versions, so the same Emacs source is likely to work unaltered, would it
be for different versions of Emacs and for different versions of Python.
So it makes sense, at least in some special circumstances, giving the
capability of selecting a specific Python interpreter by programmatical
means within Emacs.
:code:`pymacs-load-path`
,,,,,,,,,,,,,,,,,,,,,,,,
Users might want to use special directories for holding their Python
modules, when these modules are meant to be used from Emacs. Best is to
preset :code:`pymacs-load-path`, :code:`nil` by default, to a list of
these directory names. (Tilde expansions and such occur automatically.)
Here is how it works. The first time Pymacs is needed from Emacs, a
Pymacs helper is automatically started as an Emacs subprocess, and
given as arguments all strings in the :code:`pymacs-load-path` list.
These arguments are added at the beginning of :code:`sys.path`, or
moved at the beginning if they were already on :code:`sys.path`. So
in practice, nothing is removed from :code:`sys.path`.
:code:`pymacs-after-load-functions`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
The functions installed on this hook, if any, are run after loading a
Python module. Each function is called with a single argument, which
is the Python module name, as given as the first argument to
:code:`pymacs-load`.
This hook initially contains no functions.
:code:`pymacs-trace-transit`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,
The :code:`*Pymacs*` buffer, within Emacs, holds a trace of transactions
between Emacs and Python. When :code:`pymacs-trace-transit` is
:code:`nil`, the buffer only holds the last bi-directional transaction
(a request and a reply). In this case, it gets erased before each and
every transaction. If that variable is :code:`t`, all transactions are
kept. This could be useful for debugging, but the drawback is that
this buffer could grow big over time, to the point of diminishing Emacs
performance. As a compromise, that variable may also be a cons cell
of integers ``(KEEP . LIMIT)``, in which case the buffer is reduced to
approximately :var:`KEEP` bytes whenever its size exceeds :var:`LIMIT`
bytes, by deleting an integral number of lines from its beginning. The
default setting for :code:`pymacs-trace-transit` is ``(5000 . 30000)``.
:code:`pymacs-forget-mutability`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
The default behaviour of Pymacs is to transmit Emacs Lisp objects to
Python in such a way that they are fully modifiable from the Python
side, would it mean triggering Emacs Lisp functions to act on them.
When :code:`pymacs-forget-mutability` is not :code:`nil`, the behaviour
is changed, and the flexibility is lost. Pymacs then tries to expand
proper lists and vectors as full copies when transmitting them on the
Python side. This variable, seen as a user setting, is best left to
:code:`nil`. It may be temporarily overridden within some functions,
when deemed useful.
There is no corresponding variable from objects transmitted to Emacs
from Python. Pymacs automatically expands what gets transmitted.
Mutability is preserved only as a side-effect of not having a natural
Emacs Lisp representation for the Python object. This asymmetry is on
purpose, yet debatable. Maybe Pymacs could have a variable telling that
mutability is important for Python objects? That would give Pymacs
users the capability of restoring the symmetry somewhat, yet so far, in
our experience, this has never been needed.
:code:`pymacs-mutable-strings`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Strictly speaking, Emacs Lisp strings are mutable. Yet, it does not
come naturally to a Python programmer to modify a string *in-place*, as
Python strings are never mutable. When :code:`pymacs-mutable-strings`
is :code:`nil`, which is the default setting, Emacs Lisp strings are
transmitted to Python as Python strings, and so, loose their mutability.
Moreover, text properties are not reflected on the Python side. But
if that variable is not :code:`nil`, Emacs Lisp strings are rather
passed as Emacs Lisp handles. This variable is ignored whenever
:code:`pymacs-forget-mutability` is set.
Timeout variables
,,,,,,,,,,,,,,,,,
Emacs needs to protect itself a bit, in case the Pymacs service program,
which handles the Python side of requests, would not start correctly, or
maybe later die unexpectedly. So, whenever Emacs reads data coming from
that program, it sets a time limit, and take some action whenever that
time limit expires. All times are expressed in seconds.
The :code:`pymacs-timeout-at-start` variable defaults to 30 seconds,
this time should only be increased if a given machine is so heavily
loaded that the Pymacs service program has not enough of 30 seconds to
start, in which case Pymacs refuses to work, with an appropriate message
in the mini buffer.
The two remaining timeout variables almost never need to be changed
in practice. When Emacs is expecting a reply from Python, it might
repeatedly check the status of the Pymacs service program when that
reply is not received fast enough, just to make sure that this program
did not die. The :code:`pymacs-timeout-at-reply` variable, which
defaults to 5, says how many seconds to wait without checking, while
expecting the first line of a reply. The :code:`pymacs-timeout-at-line`
variable, which defaults to 2, says how many seconds to wait without
checking, while expecting a line of the reply after the first.
:code:`pymacs-auto-restart`
,,,,,,,,,,,,,,,,,,,,,,,,,,,
The Pymacs helper process is started as soon as it is needed, and gets
associated with the :code:`*Pymacs*` buffer. When that buffer is
killed, as it occurs automatically whenever the Emacs session is ending,
the Pymacs helper process is killed as well. Any other disappearance of
the helper is unexpected, and might be the consequence of some error in
the Python side of the user application (or a Pymacs bug, maybe!).
When the Pymacs helper dies, all useful Python objects it might contain
also die with it. So, after an unexpected death, there might now exist
dangling references in Emacs Lisp space towards vanished Python objects,
and using these references may be fatal to the application. When the
Pymacs helper dies, the safest thing to do is stopping all Pymacs
functionality and even exiting Emacs. On the other hand, it is not
always practical having to restart everything in such cases: the user
knows best, and is the one who ultimately decides.
The Pymacs helper death is detected at the time a new Pymacs request
gets initiated from the Emacs side. Pymacs could not do much without a
Pymacs helper, so it has either to restart a new Pymacs helper, or abort
the Pymacs request. The variable :code:`pymacs-auto-restart` controls how
this is done. The possible values are:
+ ``nil`` — the Pymacs request is unconditionally aborted,
+ ``t`` — a new Pymacs helper is silently launched, and the previous helper
death might well go unnoticed,
+ ``'ask`` — the user interactively decides whether to restart the
Pymacs helper or not. This is the default value.
:code:`pymacs-dreadful-zombies`
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
When a Pymacs helper gets restarted in a given Emacs session, brand new
Python objects may be created within that new helper. There is not
enough information kept on the Emacs Lisp side for the new Pymacs helper
to recreate the useful Python objects which disappeared. However, there
is enough machinery to recover all their slot numbers (all references to
opaque Python objects from Emacs Lisp space are transmitted in form of
object slot numbers).
The new Pymacs helper is given the list of all previous slot numbers
still referenced from the Emacs side, and is then careful at never
allocating a new Python object using an old slot number, as this might
possibly create fatal confusion. All the previous slots are initialized
with so-called *zombies* on the Python side. If Emacs later calls a
vanished Python object, this merely awakes its zombie, which will then
make some noise, then fall asleep again. The noise has the form of a
diagnostic within the ``*Messages*`` buffer, sometimes visible in the
mini-buffer too, at least when the mini-buffer is not simultaneously
used for some other purpose.
Zombies get more dreadful if :code:`pymacs-dreadful-zombies` is set to a
non-:code:`nil` value. In this case, calling a vanished Python object
raises an error that will eventually interrupt the current computation.
Such a behaviour might be useful for debugging purposes, or for making
sure that no call to a vanished Python object goes unnoticed.
In previous Pymacs releases, zombies were always dreadful, under the
assumption that calling a vanished object is a real error. However, it
could cause irritation in some circumstances, like when associated with
frequently triggered Emacs Lisp hook functions. That's why that, by
default, zombies have been finally turned into more innocuous beings!
Usage on the Python side
========================
Python setup