Sometimes questions arise: Is the current buffer bookmarked? If yes, what is the name of the bookmark? This is useful to know when bookmarking the same file again at a new cursor position with the same bookmark name.
The following function returns the name of the bookmark, if the current buffer, which must be a file, is bookmarked. Otherwise nil.
(defun bookmarked-p ()
"Return bookmark name, if current buffer's file is bookmarked."
(require 'bookmark)
(setq bookm-ass nil)
(when (and (buffer-file-name (current-buffer))
(member (abbreviate-file-name (buffer-file-name (current-buffer)))
(mapcar 'bookmark-get-filename
(bookmark-all-names))))
(let ((current-buf (abbreviate-file-name
(buffer-file-name (current-buffer)))))
(dolist (bookm-name (bookmark-all-names))
(setq bookm-ass
(add-to-list 'bookm-ass (cons
(bookmark-get-filename bookm-name) bookm-name))))
(cdr (assoc current-buf bookm-ass)))))
The function above can be used for interactive rebookmarking:
(defun bookmarked-p-rebookmark ()
"If `bookmarked-p' returns a bookmark name, `bookmark-set' that name."
(interactive)
(if (bookmarked-p)
(let ((current-bmname (bookmarked-p)))
(bookmark-set current-bmname)
(message "Current location is bookmarked to `%s'" current-bmname))
(if (not (buffer-file-name (current-buffer)))
(message "Current buffer is not associated with a file")
(message "Current buffer is not bookmarked"))))
Also: Save place mode
As an alternative to rebookmarking, Emacs has a save-place-mode
that tracks current locations in buffers where activated. It can be activated globally with (save-place-mode 1)
in the config and the result is similar to desktop-save-mode
which opens up latest locations in earlier visited buffers.
If I were to use save-place-mode
(which I don’t), I’d do so judiciously for some file types. For example:
(add-hook 'org-mode-hook 'save-place-local-mode)