4

The proper way to deal with region is using (interactive "r"). But in my case, (interactive "r") always complaints:

The mark is not set now, so there is no region

after fresh Emacs startup. This problem occurred if we never invoke mark region before. After invoking mark region, problem solved. Am I missing something?

Take this MWE:

(defun try-region (begin end)
  (interactive "r")
  (if (use-region-p)
      (message "Region Active")
    (message "Region not active")))

It always complaints "The mark is not set now, so there is no region" if I never invoked mark region before. So I need to modify my code to use (buffer-substring-no-properties (region-beginning) (region-end) to deal with region instead.

Related: How to use (interactive “r”) function in this situation?

1 Answer 1

4

The use-region-p test should be within the interactive spec.

"r" is for functions that always use the region. You probably want to use something like:

(defun try-region (&optional begin end)
  (interactive (if (use-region-p) (list (region-beginning) (region-end))))
  (message (if begin "Region Active" "Region not active")))
3
  • I really was expecting answer from you, but I don't hope a lot cause your last seen was months ago. I thought it was a bug, turns out not. The key is " 'r' is for functions that always use the region". I keep trying using "r" for that case cause I saw a lot of project did the same.I don't know if they aware of this or not. Searching for examples, turns out I found them in emacs source. Thanks a lot.
    – azzamsa
    Feb 7, 2019 at 15:49
  • @Drew I don't think so: "r" is supposed to pass the begin/end of the region (and it does so regardless of mark-active), so if the mark is not set, it just can't do that. We could change the behavior to pass nil for beg/end when there's no mark but that would rarely be useful (testing use-region-p in the body of the function together with "r" in the interactive form is fundamentally flawed because it only works right for interactive calls: for non-interactive calls you shouldn't presume that beg/end have anything to do with point&mark).
    – Stefan
    Nov 25, 2022 at 1:53
  • @Stefan: I wonder (OT): Why does a buffer start out with no mark, instead of, say, having a mark at point = 1 by default? What use is a markless buffer? Do you know of any code that makes use of that or really depends on it?
    – Drew
    Nov 25, 2022 at 17:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.