Sometimes it may happen that we would like to open the current buffer in another text editor (notepad, gedit, texmaker, ....). What are the best ways to do it?
You could use something such as the following
(defun open-external (&optional editor) (interactive "sEditor to use: ") (let ((file (buffer-file-name (current-buffer)))) (if (executable-find editor) (if file (shell-command (format "%s %s" (executable-find editor) file)) (user-error "Current buffer has no associated file.")) (user-error "Editor (%s) not found on path" editor))))
buffer-file-name rather than
buffer-name to ensure you get the associated file from the filesystem. It also validates that both the file and the editor selected are found on path (or explicitly pointed to).
This version opens the buffer in an external program (use a prefix to change the default). If the buffer is not visiting a file, open it up in a temporary file:
(defvar alternate-editor "gedit" "Editor to use when visiting a buffer outside of emacs.") (defun open-in-alternate-editor (&optional arg) "Open buffer in alternative editor. If buffer is unsaved, bring it up in a temporary file. With prefix argument, ask for the editor to use." (interactive "P") (let ((edit (executable-find (if arg (read-from-minibuffer "Enter editor to use: " alternate-editor) alternate-editor))) (file (or (buffer-file-name) (make-temp-file "unsaved-emacs-buffer-"))) (buff (unless (buffer-file-name) (save-restriction (widen) (buffer-string))))) (when (null edit) (error "Can't find alternate editor")) (unless (buffer-file-name) (with-temp-file file (insert buff))) (start-process "Alternate Editor" nil edit file)))
Note that the
defvar might be overkill -- you could just replace it with whatever string you like within the
You could for example define your own command for edit that takes the current buffer name as input
(defun ppop-open-in-gedit () (interactive "") (shell-command (format "gedit %s" (buffer-file-name)))) (global-set-key (kbd "<f10>") 'ppop-open-in-gedit)
I would check if the buffer has a corresponding file, but you get the idea.