1

I'm moving my R setup over to emacs and ess -- and am struggling with the emacs / LISP customisation process.

In an answer to another question, I learnt how to create a function that concats a function name with the token at point and sends it to *R*.

This was great as a once off -- but now my .emacs is filling up with boilerplate code (see the code block at the bottom).

What i'd really like is a way to declare mappings in a single line:

(define-key ess-mode-map (kbd "C-c s") _concat_summary_token_)
(define-key ess-mode-map (kbd "C-c p") _concat_print_token_)

The below code-block is an example of what i have at the moment -- two is okay, but i have ten already and plans to add more ... so i'm going to get lost in boilerplate!

(defun r-summary-at-point ()
  (interactive)
  (let ((sym (ess-symbol-at-point)))
    (if sym
        (ess-send-string (get-buffer-process "*R*")
                         (concat "summary(" (symbol-name sym) ")\n") t)
      (message "No valid R symbol at point"))))
(define-key ess-mode-map (kbd "C-c s") 'r-summary-at-point)

(defun r-print-at-point ()
  (interactive)
  (let ((sym (ess-symbol-at-point)))
    (if sym
        (ess-send-string (get-buffer-process "*R*")
                         (concat "print(" (symbol-name sym) ")\n") t)
      (message "No valid R symbol at point"))))
(define-key ess-mode-map (kbd "C-c p") 'r-print-at-point)
3

I'll give you an hint:

(defun apply-r-func-at-point (func)
    "Apply R FUNC at point, FUNC should be a string."
    (let ((sym (ess-symbol-at-point)))
    (if sym
        (ess-send-string (get-buffer-process "*R*")
                         (concat  func "(" (symbol-name sym) ")\n") t)
      (message "No valid R symbol at point"))))

(defun r-summary-at-point ()
  (interactive) (apply-r-func-at-point "summary"))
(define-key ess-mode-map (kbd "C-c s") 'r-summary-at-point)

(defun r-print-at-point ()
  (interactive)     (apply-r-func-at-point "print"))
(define-key ess-mode-map (kbd "C-c p") 'r-print-at-point)
| improve this answer | |
  • i've tested this and it works ... but what i would really like is a way to do this all in a single line (combining the defun and define-key function calls). is that possible? – ricardo May 19 at 0:12
  • 1
    @Ricardo: you could with a lambda function, but you're sacrificing a lot of flexibility and readability for the sake of saving 1 line in your init file. – Dan May 19 at 1:01
  • What are the downsides? I’m learning so I would certainly read a link. The issue is that I might have twenty of these (or more). – ricardo May 19 at 2:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.