Evaluate Emacs js-mode buffer in Nyxt current buffer

Today, I wanted to scrap information from a site, so this question came to my mind: How to evaluate the content of a js-mode Emacs buffer in the Nyxt current buffer? I came up with this set of functions. I created three functions in Emacs for js-mode buffers: Evaluate a region nyxt-javascript-send-region, evaluate an entire buffer nyxt-javascript-send-buffer and clearing the content of the console nyxt-javascript-clear-console.

Any feedback is appreciated.

;;; utilities-nyxt.el - Utilities for Nyxt-Emacs users
;;
;; The connection between Emacs and Nyxt is done through the
;; nyxt-javascript-send-string function. As for this version, this
;; package assumes that you have one only SLIME connection. The
;; default SLIME connection is choosen.
;;
;; If you have never connected Emacs to a SWANK server, the
;; following is the list of steps to do it:
;;
;; 1. Execute start-swank in Nyxt.
;;
;; 2. Execute slime-connect in Emacs.
;;
;; More information on Slime can be found in the master branch
;; repository: https://github.com/slime/slime

(require 'slime)

(defun nyxt-javascript-send-string (string)
  (let ((sexp (concat "(ffi-buffer-evaluate-javascript-async (current-buffer) "
                      (prin1-to-string string)
                      ")")))
    (slime-interactive-eval sexp)))

(defun nyxt-javascript-send-region (start end)
  "Evaluate the region in the Nyxt current-buffer."
  (interactive
   (list (region-beginning) (region-end)))
  (let ((string (buffer-substring-no-properties
                 start
                 end)))
    (nyxt-javascript-send-string string)))

(defun nyxt-javascript-send-buffer ()
  "Evaluate the current buffer in the Nyxt current-buffer."
  (interactive)
  (let* ((string (save-restriction
                   (widen)
                   (buffer-substring-no-properties
                    (point-min)
                    (point-max)))))
    (nyxt-javascript-send-string string)))

(defun nyxt-javascript-clear-console ()
  "Clear console."
  (interactive)
  (nyxt-javascript-send-string "console.clear()"))

(define-key js-mode-map (kbd "C-c C-c") 'nyxt-javascript-send-buffer)
(define-key js-mode-map (kbd "C-c C-r") 'nyxt-javascript-send-region)
(define-key js-mode-map (kbd "C-c M-o") 'nyxt-javascript-clear-console)
2 Likes

Really cool, thanks for sharing :slight_smile: