---
title: "Using fnmate with ESS"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Using fnmate with ESS}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

# Here is your lisp

```{lisp, eval = FALSE}
;; Helpers

(defun text-around-cursor (&optional rows-around)
  (let ((rows-around (or rows-around 10))
  (current-line (line-number-at-pos))
  (initial-point (point)))
    (save-mark-and-excursion
      (goto-line (- current-line rows-around))
      (set-mark (point))
      (goto-line (+ current-line rows-around))
      (end-of-line)
      ;; Return a list of text, index
      (list (buffer-substring-no-properties (mark) (point))
            (+ (- initial-point (mark)) 1)))))

(defun strip-ess-output-junk (r-buffer)
  (with-current-buffer r-buffer
    (goto-char (point-min))
    (while (re-search-forward "\\+\s" nil t)
      (replace-match ""))))

(defun exec-r-fn-to-buffer (r_fn text)
  (let ((r-process (ess-get-process))
        (r-output-buffer (get-buffer-create "*R-output*")))
    (ess-string-command
     (format "cat(%s(%s))\n" r_fn text)
     r-output-buffer nil)
    (strip-ess-output-junk r-output-buffer)
    (save-mark-and-excursion
      (goto-char (point-max))
      (newline)
      (insert-buffer r-output-buffer))))

;; fnmate functions for keybindings
 (defun fnmate ()
   (interactive)
   (let* ((input-context (text-around-cursor))
          (text (prin1-to-string (car input-context)))
          (index (cdr input-context)))
     (ess-eval-linewise (format "fnmate::fnmate_fn.R(%s, %s)" text index))))


(defun fnmate-below ()
  (interactive)
  (let* ((input-context (text-around-cursor))
         (text (prin1-to-string (car input-context)))
         (index (cdr input-context))
         (args (format "%s, %s" text index)))
    (exec-r-fn-to-buffer "fnmate::fnmate_below" args)))

```
