How to pop local and global marks with a common keybinding in Emacs

676 views Asked by At

Is there any way to combine local and global marks together? what I am trying to do is just to have a common keybinding to pop-global-mark and set-mark-command. Something like; "try to pop the local mark, if there are no remaining ones, then try pop the global mark".

This is needed to move back around the code, and not thinking if i should press C-u C-SPC or C-x C-SPC, depending if the jump between functions was inside or outside the same file.

2

There are 2 answers

1
sds On BEST ANSWER

First of all, you cannot really use set-mark-command in code because it checks this-command and last-command so it will not work as intended.

However, examining its code, I came up with (untested!):

(defun pop-local-or-global-mark ()
  "Pop to local mark if it exists or to the global mark if it does not."
  (interactive)
  (if (mark t)
      (pop-to-mark-command)
      (pop-global-mark)))
2
Drew On

I think you're perhaps under a misconception that C-u C-SPC and C-x C-SPC actually "pop" the mark rings, in the sense of shortening them. I say this because you write "if there are no remaining ones".

They do not. They cycle the mark rings. So continuing to pop the local mark ring will not eventually lead to it being empty, allowing your envisioned command to then move on to pop the global mark ring.

These two rings are separate primarily because they are used differently. The global ring gets you from buffer to buffer (only). The local rings move you around within individual buffers (only).

So my advice would be to not look for what you are looking for ;-). Or if you really want it, then define commands that actually do pop the rings, in the sense of removing markers.

FWIW, there are alternatives to these two commands, including commands that let you see the text associated with the markers and choose a destination using, e.g., completion.

In Icicles for instance, C-u C-SPC combines marker cycling with setting the mark, as your intro sentence requests (but not as your title requests -- there are separate Icicles commands for cycling the local and global rings). Similarly, C-x C-SPC does this for the global ring. In Icicle mode, by default, these keys are bound to multi-commands icicle-goto-marker-or-set-mark-command and icicle-goto-global-marker-or-pop-global-mark.