atm i'm using emacs to write some python code, so far it works quite fine except one problem that is really a bit annoying.
Always when I update something inside a self written module i reevaluate the buffer and the module in the python shell inside emacs doesn't get updated. i always have to end the python process and start it again to get the change. I figured out that emacs copies some things to a tmp dir to execute them, so i guess it has something to do with this.
Maybe someone out there had the same problem and solved it already so help would be appreciated
You have to reload the module manually in the shell in order for it to take effect.
See the documentation here on the Python reload function
I asked a similar question which you can see here
I found a better solution that needs no emacs config:
simply do
$ ipython profile create
that should create ipython profile in
$HOME/.ipython/profile_default/ipython_config.py
then put the following inside
c = get_config()
c.TerminalInteractiveShell.editor = 'emacsclient'
c.InteractiveShellApp.extensions = [
'autoreload'
]
c.InteractiveShellApp.exec_lines = []
c.InteractiveShellApp.exec_lines.append('%load_ext autoreload')
c.InteractiveShellApp.exec_lines.append('%autoreload 2')
then restart emacs. Now each time you save changes to file inside emacs - ipython would reload it automatically
and the following I have in my emacs config
;; ------------------
;; misc python config
;; ------------------
(company-mode -1)
(elpy-enable)
(elpy-use-ipython "ipython")
(setq python-shell-interpreter "ipython" python-shell-interpreter-args "--simple-prompt --pprint")
(setq python-check-command "flake8")
(setq elpy-rpc-backend "jedi")
(setq elpy-rpc-python-command "python")
; https://github.com/gregsexton/ob-ipython/issues/28
(setq python-shell-completion-native-enable nil)
if you want to see my full python config, it's here
You can advise a python-mode.el function to get the desired effect (at least, if I am understanding your request properly). Put the following in your Emacs init file:
(defun py-reload-file (buf)
"Reload buffer's file in Python interpreter."
(let ((file (buffer-file-name buf)))
(if file
(progn
;; Maybe save some buffers
(save-some-buffers (not py-ask-about-save) nil)
(let ((reload-cmd
(if (string-match "\\.py$" file)
(let ((f (file-name-sans-extension
(file-name-nondirectory file))))
(format "if globals().has_key('%s'):\n reload(%s)\nelse:\n import %s\n"
f f f))
(format "execfile(r'%s')\n" file))))
(save-excursion
(set-buffer (get-buffer-create
(generate-new-buffer-name " *Python Command*")))
(insert reload-cmd)
(py-execute-base (point-min) (point-max))))))))
(defadvice py-execute-region
(around reload-in-shell activate)
"After execution, reload in Python interpreter."
(save-window-excursion
(let ((buf (current-buffer)))
ad-do-it
(py-reload-file buf))))
Now, when you're in a python program, you can select a region of code, press C-| to evaluate the region and the python program will be reloaded (or imported if it wasn't previously loaded) in the Python interpreter buffer. The ENTIRE module will be reloaded, not just the region that was selected and you will be prompted to save the python file if it hasn't already been saved. Note that the caveats that were mentioned in the replies to your previous question still apply (e.g. - If you have class instances already created from the imported module, have instantiated other objects, etc, they won't be reloaded). General breakage may occur, so caveat emptor!).
I'd recommend using Elpy as discussed here.
Add the following to your Emacs configuration file:
(defun my-restart-python-console ()
"Restart python console before evaluate buffer or region to avoid various uncanny conflicts, like not reloding modules even when they are changed"
(interactive)
(if (get-buffer "*Python*")
(let ((kill-buffer-query-functions nil)) (kill-buffer "*Python*")))
(elpy-shell-send-region-or-buffer))
(global-set-key (kbd "C-c C-x C-c") 'my-restart-python-console)
restart your Emacs run your code using C-c C-x C-c
In short, this code has the "if clause" for checking if Python buffer is open. This will help to be able to run C-c C-x C-c at any time of development even when there is no Python process already open. Another part is kill-buffer-query-functions which neglects the prompt for killing the Python buffer.
Related
I am using emacs on Ubuntu 16.04 and added the configuration for flycheck-mode to include the python3 setup below:
Emacs: How do I set flycheck to Python 3?
Answer: https://stackoverflow.com/a/55000284/719016
(custom-set-variables
'(flycheck-python-flake8-executable "python3")
'(flycheck-python-pycompile-executable "python3")
'(flycheck-python-pylint-executable "python3"))
But my python3 buffer still gives me an invalid syntax [E0001] error in a line like below:
print("# My message for the stderr", file=stderr)
The syntax checkers loaded are python-pylint and python-pycompile (for some reason python-flake8 does not seem to be found.
Any ideas why?
Well, if you took the answer that you quoted literally, your configuration isn't getting loaded. The answer suggests putting the config in ~/.emacs.c/custom.el. That's a typo. The correct path is ~/.emacs.d/custom.el. The more correct answer is to put the config in the file pointed to by custom-file. The most correct answer is to never edit the custom file by hand. Instead use the customize facility.
Run M-x customize-group flycheck.
Scroll to the bottom of the buffer and click on "Flycheck executables".
Find the python executables you want to change. (Always use python3 for Python3 stuff, even if you only have Python3 on your system. It'll save you headaches later.)
Scroll to the top of the buffer.
Click "Apply and Save".
Boom. Your settings are saved in the correct "custom.el" file.
Now, load up a Python3 file you want to use flycheck with. If it's not doing what you expect, check things with C-c ! v (aka flycheck-verify-setup.) Confirm individual checkers with C-c ! ? (aka flycheck-describe-checker.) Check the variables you think you're setting with C-h v. Cut-n-paste them from flycheck's website if you have to.
Don't worry about flake8's config file. It will properly cascade as you expect.
And, lastly, as #jenesaisquois suggests:
#!/usr/bin/env python3
import sys
print("# My message for the stderr", file=sys.stderr)
I am using emacs-for-python provided by gabrielelanaro at this link.
Indentation doesn't seem to be working for me at all.
It doesn't happen automatically when I create a class, function or any other block of code that requires automatic indentation(if, for etc.) and press enter or Ctrl + j. Instead emacs says "Arithmetic Error".
It doesn't happen when I press Tab anywhere in a .py file. Again, every Tab press causes "Arithmetic error".
Also, when I manually indent code using spaces, I can't erase those spaces! Backspace-ing these indents also causes "Arithmetic Error".
This problem surfaces when I use the regular Python AC mode as well.
emacs : GNU Emacs 24.3.1 (x86_64-pc-linux-gnu, GTK+ Version 3.10.7)
of 2014-03-07 on lamiak, modified by Debian
Check the value of python-indent-offset. If it is 0, change it M-x set-variable RET python-indent-offset RET 4 RET.
Emacs tries to guess the offset used in a Python file when opening it. It might get confused and set that variable to 0 for some badly-formatted Python file. If this is indeed the problem, please do file a bug report using M-x report-emacs-bug and the text of the Python file so that the auto-detection can be fixed.
It is related to this bug
http://debbugs.gnu.org/cgi/bugreport.cgi?bug=15975
The quickest workaround which I found was too add Jorgens Answer into .emacs file, add the following at the end of your .emacs file
(add-hook 'python-mode-hook
(lambda () (setq python-indent-offset 4)))
Can you comment the lines related to auto-complete in your init.el?
; (add-to-list 'load-path "~/.emacs.d/auto-complete-1.3.1")
; (require 'auto-complete)
; (add-to-list 'ac-dictionary-directories "~/.emacs.d/ac-dict")
; (require 'auto-complete-config)
; (ac-config-default)
; (global-auto-complete-mode t)
Can anyone who understands Lisp please help resolve this warning?
I upgraded to Emacs 24.3 and whenever I create a Python file using Emacs I get this warning message. Searched in python.el and found the following section of code that produces the warning:
(let ((indentation (when block-end
(goto-char block-end)
(python-util-forward-comment)
(current-indentation))))
(if indentation
(set (make-local-variable 'python-indent-offset) indentation)
(message "Can't guess python-indent-offset, using defaults: %s"
python-indent-offset)))
And here is my .emacs setup:
(setq-default c-basic-offset 4
tab-width 4
indent-tabs-mode nil)
(add-hook 'c-mode-common-hook
(lambda ()
(c-set-offset 'arglist-intro '+)
(c-set-offset 'arglist-close 0)))
(add-hook 'python-mode-hook
(lambda ()
(c-set-offset 'arglist-intro '+)
(c-set-offset 'arglist-close 0)))
When you open a python file, emacs guesses the indentation offset (number of spaces to indent) based on that file style. When you create a file (the case you describe), emacs cannot guess (file is empty) so it uses your default (4) and notifies the user.
In other words: it is a harmless warning; if you find this is a bug please report it as such.
If you don't like emacs guessing the offset, customize the variable python-indent-guess-indent-offset to nil, and then emacs will use always your default (very unsafe in python, where indentation has meaning and you could be editing a file created by somebody else with other defaults).
If all you want is to silence the warnings, while letting emacs still guess the offset as juanleon's answer explains, you can switch the python-indent-guess-indent-offset-verbose variable off.
(setq python-indent-guess-indent-offset t)
(setq python-indent-guess-indent-offset-verbose nil)
Per this comprehensive answer on the emacs SE.
Look in python.el, not python.elc. If you do not have python.el, then google for it (at least to look at it -- you do not need it to use Emacs). *.elc is a byte-compiled file, which is pretty much incomprehensible to humans.
The source code, in python.el, will tell you just what python-indent-guess-indent-offset does, and hence why you see the result you see.
In addition to the previous answers, and silencing the warning, this procedure deals with the problem and gives two examples for why the warning is useful.
Get a list of currently open buffers with C-x C-b. Filter those with a Python
extension, add quotes around them, and replace them in this command:
(dolist (f '(
"/path/to/file1"
"/path/to/file2"
))
(message (concat "Opening file: " f))
(find-file (expand-file-name f)))
Execute the command (select the region, then M-x evaluate-region). Then *Messages* looks like this:
Opening file: /path/to/file1
Opening file: /path/to/file2
Can’t guess python-indent-offset, using defaults: 4
For information about GNU Emacs and the GNU system, type C-h C-a.
I had files I had used for testing and that I had forgotten, for example:
from time import sleep
sleep(10000)
I only realized it thanks to this message and I deleted the files.
In another case, I had a useful file with just global variables, so I added this
line:
# -*- mode: python; python-indent-offset: 4 -*-
SOME_GLOBAL_VAR = 0
Although this does set the buffer-local variable (check by changing to 6, then
checking the value with C-h v python-indent-offset), it only does so after the
warning message, not before. I decided to tolerate this message.
I have many classes and defs ...
I want to have + and - keys before class and def to collapse the class or open it ( toggle it ).
How i can do this?
Hideshow works out of the box and folds python code. It is built-in my version of emacs (24.3.1)
I have never needed more than these commands:
M-x hs-minor-mode
M-x hs-hide-all
M-x hs-show-all
To toggle use C-c # C-c which probably needs rebinding. You might also want to setup a hook in your .emacs file for hs-minor-mode to automatically be enabled when opening .py files.
I use it in combination the following to jump around.
M-x imenu <my_func_name>
You can get code folding (and more) with CEDET. With CEDET, you should consider putting the following setting in your emacs configuration file:
(global-semantic-folding-mode t)
CEDET handles Python and other languages.
Other ideas about how you can make emacs even more convenient when programming can be found on StackOverflow.
I say "project file" in the loosest sense. I have a few python projects that I work on with ropemacs using emacs W32 for Windows. What would be ideal is if I could have an icon I could click on on my desktop to open up emacs, open up the rope project, and set the speed bar in the top-level directory of that project. Then I could also maybe have a way to open up the next project in its own emacs set up the same way (but for that project). Of course, it's also acceptable if there were an emacs command or a shell command I could use to achieve the same effect instead of an icon on my desktop.
Is there any way to do this? I have absolutely no elisp-fu. :-(
You could get everything set up the way you want for a project, then use the answer I posted about using desktop.el and named sessions:
What alternate session managers are available for Emacs?
I'm actually working on a solution to this very problem. I always had a group of files I wanted to open/close at the same time, plus do things like open a magit-status window, a dired buffer, etc. I've started on my own project mode called metaproject. It's in the very early stages, but is functional enough that I'm using it for project groups at work now.
Check it out here: http://nafai77.github.com/metaproject/
What's in git is pretty stable, though sparsely documented. I'm going to start working on it again here soon. I currently have the basics of a small plug-in architecture, so you can register custom actions that can be done on project open.
I use the following "solution" for myself: A project root is defined by a directory that contains a Makefile. I've bound F12 to the mode specific elisp function that "compiles" the project by makeing the first target of the corresponding Makefile. This is found by recursively going upwards from the directory of the current file.
It is a little bit of setup, but you will never have to reconstruct your .metadata directory as was frequently the case with Eclipse before. And once set up, you just have to place the proper Makefiles around and you have your projects.
(defun get-makefile-recursively-higher ()
(loop for i below 100 for cwd = (expand-file-name default-directory)
then next for next = (expand-file-name (concat cwd "/..")) for file =
(concat cwd "/" "Makefile") do (cond ((and (file-exists-p file))
(return file))) until (equal cwd next))
)
This is then used e.g. by the LaTeX and Python mode as follows:
(defun py-execute-prog (&optional target)
"Invoke python on the file being edited in the current buffer using
arguments obtained from the minibuffer. It will save all of the modified
buffers before trying to execute the file."
(interactive)
(let* (makefile file cmd)
(setq makefile (get-makefile-recursively-higher))
(setq file (buffer-file-name (current-buffer)))
(setq cmd (concat "make -f " makefile))
(setq default-directory (file-name-directory makefile))
(save-some-buffers (not py-ask-about-save) nil)
(setq py-pdbtrack-do-tracking-p t)
(if (get-buffer py-output-buffer)
(kill-buffer py-output-buffer)) ; Get rid of buffer if it exists.
(global-unset-key "\C-x\C-l" )
(global-unset-key "\C-x\C-p" )
(global-unset-key "\C-x\C-e" )
(global-unset-key "\C-x\C-n" )
(global-set-key "\C-x\C-l" 'py-last-exception)
(global-set-key "\C-x\C-p" 'py-previous-exception)
(global-set-key "\C-x\C-e" 'py-current-line-exception)
(global-set-key "\C-x\C-n" 'py-next-exception)
(define-key comint-mode-map [mouse-3] 'py-current-line-exception)
(make-comint "Python Output" "make" nil "-f" makefile)
(if (not (get-buffer py-output-buffer))
(message "No output.")
(setq py-exception-buffer (current-buffer))
(pop-to-buffer py-output-buffer)
)))
(defun make-tex (&optional target)
(interactive)
(let (makefile cmd)
(setq makefile (get-makefile-recursively-higher))
(save-buffer)
(TeX-save-document (TeX-master-file))
(setq cmd (concat "make -j4 -f " makefile " LATEXPARAM=\"-halt-on-error -file-line-error\""
" TEXMASTER=" (expand-file-name (TeX-master-file)) ".tex"
" TEXMASTERDIR=" (file-name-directory makefile) "/"))
(when (stringp target)
(setq cmd (concat cmd " " target))
)
(ad-activate-regexp "auto-compile-yes-or-no-p-always-yes")
(compile cmd)
(ad-deactivate-regexp "auto-compile-yes-or-no-p-always-yes")
)
)
There's eproject, but it seems to be very sparsely documented.
You can roll your own in bash/cmd.exe. The windows emacs distribution comes with a .bat file called runemacs.bat which accepts files to open as arguments. Write a small script and it should be able to open everything up from one icon.
See http://www.emacswiki.org/emacs/CategoryProgrammerUtils#ProjectSupport. There are several packages which manage "projects". I favor mk-project, but then again, I wrote it. ;-)
You can use Desktop bookmarks, Dired bookmarks, or Bookmark-List bookmarks to do what you want -- see Bookmark+. You can even encapsulate code and multiple bookmarks in a single bookmark to get just the state and setup you want.
See also: Icicles support for projects for more options.