[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: send selection or current line to Terminal/iTerm

From: John Mastro
Subject: Re: send selection or current line to Terminal/iTerm
Date: Fri, 13 Jun 2014 19:30:35 -0700

Hi klebsiella,

I have another version for you to try. It behaved as expected in a few
simple tests on my machine.

Let me know how it goes.



;;; Begin iterm.el

;; To match SublimeText's key binding:
;; (global-set-key (kbd "<C-return>") 'iterm-send-text)

(require 'pcase)
(require 'thingatpt)

(defun iterm-escape-string (str)
  (let* ((str (replace-regexp-in-string "\\\\" "\\\\" str nil t))
         (str (replace-regexp-in-string "\"" "\\\"" str nil t)))

(defun iterm-last-char-p (str char)
  (let ((length (length str)))
    (and (> length 0)
         (string= (substring str (- length 1)) (string char)))))

(defun iterm-chop-newline (str)
  (let ((length (length str)))
    (if (iterm-last-char-p str ?\n)
        (substring str 0 (- length 1))

(defun iterm-maybe-add-newline (str)
  (if (iterm-last-char-p str ? )
      (concat str "\n")

(defun iterm-handle-newline (str)
  (iterm-maybe-add-newline (iterm-chop-newline str)))

(defun iterm-send-string (str)
  "Send STR to a running iTerm instance."
  (let ((str (iterm-escape-string (iterm-handle-newline str))))
     (concat "osascript -e 'tell app \"iTerm\"' "
             "-e 'set mysession to current session of current terminal' "
             (format "-e 'tell mysession to write text \"%s\"' " str)
             "-e 'end tell'"))))

(defun iterm-text-bounds ()
  (pcase-let ((`(,beg . ,end) (if (use-region-p)
                                  (cons (region-beginning) (region-end))
                                (bounds-of-thing-at-point 'symbol))))
    (list beg end)))

(defun iterm-send-text (beg end)
  "Send buffer text in region from BEG to END to iTerm.
If called interactively without an active region, send the symbol
at point instead."
  (interactive (iterm-text-bounds))
  (let ((str (iterm-escape-string (buffer-substring-no-properties beg
    (iterm-send-string str)))

(provide 'iterm)

reply via email to

[Prev in Thread] Current Thread [Next in Thread]