Table of Contents

Various useful things from my .emacs file.

1. General text-processing functions

1.1. Do anything to each line in the buffer or region

(E.g., number some lines)

(defun btv/replace-lines (f)
  (let ((begin (point-min))
        (end (point-max)))
    (when (use-region-p)
      (setq begin (region-beginning))
      (setq end (region-end))
      (goto-char begin)
      (let* ((s (filter-buffer-substring (point) end 'delete))
             (r (string-join (mapcar f (split-string s "\n")) "\n")))
        (insert r)

;; Assuming lexical binding is on.
(defun btv/numberize ()
  (let ((n 0))
     (lambda (l) (setq n (+ 1 n)) (format "%d. %s" n l))))

2. GitHub functions

2.1. Go to the current file in GitHub

(Or copy the link to it, with prefix arg)

;; Taken (with modifications) from
(defun btv/get-buffer-file-url ()
      ((rev (magit-rev-abbrev "HEAD"))
       (repo (forge-get-repository 'stub))
       (file (magit-file-relative-name buffer-file-name))
            (let ((l1 (line-number-at-pos (region-beginning)))
                  (l2 (line-number-at-pos (- (region-end) 1))))
              (format "#L%d-L%d" l1 l2))
    (forge--format repo "https://%h/%o/%n/blob/%r/%f%L"
                   `((?r . ,rev) (?f . ,file) (?L . ,highlight)))))

(defun btv/forge-browse-buffer-file (prefix)
  (interactive "P")
  (let ((f (if prefix 'kill-new 'browse-url)))
    (funcall f (btv/get-buffer-file-url))))

3. Comment processing

3.1. Mark a block of consecutive comments

(defun btv/find-comments-region () 
    (let* ((syn (syntax-ppss))
           (cur-com-begin (and (nth 4 syn) (nth 8 syn))))
      (if cur-com-begin (goto-char cur-com-begin)))
    (let ((begin (point)))
      (while (forward-comment -1)
        (setq begin (point)))
      (let ((result))
        (while (forward-comment 1)
          (setq result `(,begin . ,(point))))

(defun btv/mark-comments ()
  (let ((region (btv/find-comments-region)))
    (when region
      (goto-char (car region))
      (set-mark (cdr region))

3.2. Auto-fill them (i.e., intelligently linebreak)

(defun btv/fill-comments ()
     (if (btv/mark-comments)
         (fill-paragraph nil t))))

4. Projectile functions

4.1. Visit all files matching a regex

(defun btv/projectile-open-files-by-regex (r)
  (interactive "M")
  (let* ((project-root (projectile-acquire-root))
         (files (projectile-project-files project-root))
         (match (--filter (string-match r it) files)))
    (dolist (elt match)
      (find-file (expand-file-name elt project-root)))))

Author: User Ec2-user

Created: 2023-09-07 Thu 22:03