How to copy / paste region from emacs buffer using link to line + file?

From time to time I see people inserting portions of code with a link to the file name and line number. Sort of

;; ----- line:3391 file: simple.el.gz -----;;; (if (eq last-command 'kill-region) (kill-append (filter-buffer-substring beg end) (< end beg)) (kill-new (filter-buffer-substring beg end))) ;; ----- line:3394 --------------------------;;; 

This is mostly useful for posting comments by code. I can easily wrap a simple function for myself, but I'm sure someone has already done this in a smart and beautiful way.

Thanks.

[EDIT]

Since this functionality is only needed occasionally, and for only one copy / paste action, I ended up using an alternative solution for the switchable version proposed by @thisirs.

 (defun kill-with-linenum (beg end) (interactive "r") (save-excursion (goto-char end) (skip-chars-backward "\n \t") (setq end (point)) (let* ((chunk (buffer-substring beg end)) (chunk (concat (format "╭──────── #%-d ─ %s ──\nβ”‚ " (line-number-at-pos beg) (or (buffer-file-name) (buffer-name)) ) (replace-regexp-in-string "\n" "\nβ”‚ " chunk) (format "\n╰──────── #%-d ─" (line-number-at-pos end))))) (kill-new chunk))) (deactivate-mark)) 

It is based on Unicode and produces this output:

 ╭──────── #3557 ─ /usr/share/emacs/24.1.50/lisp/simple.el.gz ── β”‚ (if (eq this-command t) β”‚ (setq this-command 'yank)) β”‚ nil) ╰──────── #3559 ─ 
+4
source share
1 answer

I came up with this using a wrapper:

 (defun filter-buffer-substring-add-line (func beg end delete) (concat (format ";; line:%5d file: %s\n" (line-number-at-pos beg) (or (buffer-file-name) (buffer-name))) (funcall func beg end delete) (format "\n;; line:%5d" (line-number-at-pos end)))) (defun kill-add-line-toggle () (interactive) (if (memq 'filter-buffer-substring-add-line filter-buffer-substring-functions) (progn (setq filter-buffer-substring-functions (delq 'filter-buffer-substring-add-line filter-buffer-substring-functions)) (message "Add line is off!")) (push 'filter-buffer-substring-add-line filter-buffer-substring-functions) (message "Add line is on!"))) 
+3
source

All Articles