First of all, a few stylistic recommendations. (Style is important in
programming :-D) In Lisps, we use dashes as separators, so your function is
better called my-eval
, not my/eval
:
(defun my-eval()
(interactive)
(if (region-active-p) (eval-region region-beginning region-end)
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)))
(global-set-key (kbd "C-x C-e") 'my-eval)
Now, Lisp code is bare syntax trees, so they have levels of nesting and
proper indentation is very important, it helps to see how expressions are
composed. Also, it's a good idea to have one empty line between top level
forms:
(defun my-eval()
(interactive)
(if (region-active-p)
(eval-region region-beginning region-end)
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)))
(global-set-key (kbd "C-x C-e") 'my-eval)
Isn't it beautiful?
You can find out more about region-beginning
and region-end
with help of
built-in help system: type C-h f region-beginning RET. Here we
see that this is a function, actually. You call this function and it returns
position of beginning of region. To call functions you place their names on
the first position in a form:
(function-name arg1 arg2 ...)
Since region-beginning
and region-end
don't take arguments we write:
(defun my-eval()
(interactive)
(if (region-active-p)
(eval-region (region-beginning) (region-end))
(eval-last-sexp EVAL-LAST-SEXP-ARG-INTERNAL)))
Great. Now we only need to fix EVAL-LAST-SEXP-ARG-INTERNAL
. As written
you're trying to use value that symbol EVAL-LAST-SEXP-ARG-INTERNAL
is bound
to, but chances are it's not bound to any value, so you will get an
error. You can read about first argument of eval-last-sexp
using the same
trick: C-h f eval-last-sexp RET. Documentation tells us how the
argument is used, it's mainly used to handle various interactive details. We
can preserve these behavioral details in my-eval
this way:
(defun my-eval()
(interactive)
(if (region-active-p)
(eval-region (region-beginning) (region-end))
(call-interactively #'eval-last-sexp)))
This should do the trick. Note that when there is a region, eval-region
won't print anything in the mini-buffer. If this is not the desired
behavior, supply the print-flag
argument:
(defun my-eval()
(interactive)
(if (region-active-p)
(eval-region (region-beginning) (region-end) t)
(call-interactively #'eval-last-sexp)))
(global-set-key (kbd "C-x C-e") #'my-eval)