Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Emacs, copy current file and line number to clipboard
(defun copy-current-line-position-to-clipboard ()
"Copy current line in file to clipboard as '</path/to/file>:<line-number>'"
(interactive)
(let ((path-with-line-number
(concat (buffer-file-name) ":" (number-to-string (line-number-at-pos)))))
(x-select-text path-with-line-number)
(message (concat path-with-line-number " copied to clipboard"))))
(define-key global-map (kbd "M-l") 'copy-current-line-position-to-clipboard)
@Gleek
Copy link

Gleek commented Mar 8, 2018

A slightly different implementation worked for me

(defun copy-current-line-position-to-clipboard ()
  "Copy current line in file to clipboard as '</path/to/file>:<line-number>'."
  (interactive)
  (let ((path-with-line-number
         (concat (buffer-file-name) ":" (number-to-string (line-number-at-pos)))))
    (kill-new path-with-line-number)
    (message (concat path-with-line-number " copied to clipboard"))))

@ZenAnnard
Copy link

ZenAnnard commented Jan 9, 2019

I made a slight change to change the $HOME in the copied path to ~ which makes it easier to share with colleagues if you have standardised directory paths:

(defun copy-current-line-position-to-clipboard ()
    "Copy current line in file to clipboard as '</path/to/file>:<line-number>'."
    (interactive)
    (let ((path-with-line-number
           (concat (dired-replace-in-string (getenv "HOME") "~" (buffer-file-name)) ":" (number-to-string (line-number-at-pos)))))
      (kill-new path-with-line-number)
      (message (concat path-with-line-number " copied to clipboard"))))

@jclosure
Copy link

jclosure commented Mar 1, 2019

For unit testing in Elixir, we test like this: MIX_ENV=test mix test path/to/test.exs:110. Now that I can just grab the file:lineno from where point is in my buffer of test.exs to run specific tests, my dev flow is much more streamline. Thanks...

@celwell-reify
Copy link

celwell-reify commented Aug 28, 2020

git-link will figure out your remote repo on GitHub and copy to your clipboard a link to the line number.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment