Skip to content

Instantly share code, notes, and snippets.

@dov
Created October 25, 2023 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dov/006bd26ca44ccea03920cfdc2c13d2a8 to your computer and use it in GitHub Desktop.
Save dov/006bd26ca44ccea03920cfdc2c13d2a8 to your computer and use it in GitHub Desktop.
Evaluate the current file in local or remote shell
(if (string-match "x86_64-w64-mingw32" system-configuration)
(setq temp-dir "C:/Temp")
(setq temp-dir "/tmp"))
(defun shell-command-on-buffer (command extension)
"Send the current buffer to a shell command"
(interactive)
(let* ((remote-maybe (file-remote-p default-directory))
(tramp-prefix (if remote-maybe remote-maybe ""))
(cmd-buffer-name (concat "*" (capitalize command) " Output*"))
(cmd-filename
(if (buffer-modified-p)
(concat tramp-prefix temp-dir "/buffer." extension)
(buffer-file-name))))
(if (buffer-modified-p)
(write-region (point-min) (point-max) cmd-filename))
(if remote-maybe
;; If remote, we have to get rid of the tramp prefix
(let* ((remote-prefix-len (length remote-maybe))
(fn (substring cmd-filename remote-prefix-len)))
(shell-command (concat command " \"" fn "\"") cmd-buffer-name))
(shell-command (concat command " \"" cmd-filename "\"") cmd-buffer-name))
;; The following makes it easy to go to the resulting output buffer
(setq my-buffer (current-buffer))
(switch-to-buffer cmd-buffer-name)
(switch-to-buffer my-buffer)))
(defun shell-python-on-buffer ()
"Send the current (python) buffer to be evaluated by the python shell"
(interactive)
(shell-command-on-buffer "python" "py"))
(defun shell-perl-on-buffer ()
"Send the current (python) buffer to be evaluated by the perl shell"
(interactive)
(shell-command-on-buffer "perl" "pl"))
(defun shell-lua-on-buffer ()
"Send the current (lua) buffer to be evaluated by the lua shell"
(interactive)
(shell-command-on-buffer "lua" "lua"))
(defun my-lua-mode-hook ()
(interactive)
(define-key lua-mode-map [(control c) (control c)] 'shell-lua-on-buffer))
(add-hook 'lua-mode-hook 'my-lua-mode-hook)
(defun my-python-mode-hook ()
(interactive)
(define-key python-mode-map [(control c) (control c)] 'shell-python-on-buffer))
(add-hook 'python-mode-hook 'my-python-mode-hook)
(defun my-perl-mode-hook ()
(interactive)
(define-key perl-mode-map [(control c) (control c)] 'shell-perl-on-buffer))
(add-hook 'perl-mode-hook 'my-perl-mode-hook)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment