0

I've recently made this little function:

(defun luctins/rust-continue-comment ()
    (interactive)
    (if (nth 4 (syntax-ppss))
        (let ((co (concat "\n"
                          (save-match-data
                            (mwim-beginning-of-line)
                            (re-search-forward "///?!?" (line-end-position) t 1)
                            (match-string 0)))))
          (if (length> co 0)
              (progn (mwim-end-of-line)
                     (insert co)
                     (indent-for-tab-command))
            (message "failed to match")))))

(define-key rust-mode-map (kbd "C-<return>") 'luctins/rust-continue-comment)

that when called inside a comment, extends the comment type by one line so it's easier to type out long doc comments with line breaks.

How could I make this operate directly on the buffer contents, and not on interactive cursor movements?

Luctins
  • 120
  • 7

1 Answers1

1

I’m going to guess that you are worried that moving the cursor is slow. Luckily it is not.

Yes, in principle Emacs must scan the contents of the buffer looking for the newlines, and then you use a regex which will scan those buffer contents again looking for the start of a comment. Emacs doesn’t even use SIMD for these scans, it just calls the standard memchr function. It seems like it would be slower than it needs to be.

In practice, however, it’s not that bad. Finding the start of the current line only requires scanning backwards until you find the previous newline character, which won’t take that long even if there are millions of characters in the current line. It could be 8× faster if Emacs used SIMD, but it’s just not going to be a problem as is.

But it gets even better, because Emacs caches the location of the newlines whenever it finds them. (Actually it caches regions of the buffer that are known not to contain any newlines, which is weird and complicated, but makes sense when you consider that it has to remember which parts of the buffer it has scanned somehow.) This means that calling (beginning-of-buffer) is unlikely to actually need to do any scanning, since it will look in the cache first.

Most importantly, however, is the fact that you are calling your function interactively. It’s not in a hot loop, a human has to press a keyboard shortcut to activate it. Pressing the keys will take longer than it takes to run the function. Moving your fingers to the next key you want to press will probably take longer than running the function. As long as the function is faster than a human, nothing else matters.

db48x
  • 17,977
  • 1
  • 22
  • 28