Where/How to store text, if not in kill-ring/registers [elisp, emacs] - emacs

I would like to be able to store text between 2 positions (the string in between), but I don't know where to conveniently store it, perhaps just locally, or even globally (let or setq). The answer is probably out there, but I couldn't find it.
Example:
I would like to store text in a symbol in order to search for it backwards. Let's say the region from (point) until the first whitespace character.
My previous way of doing this was using (kill-ring-save), but I know this is a bad practice.
From (here) (message "hello")(point)
I would be interested in both better techniques for doing this, as well as the best way to store a string which is somehwere around (point).

The regular no-frills answer would be to just use let. Contrary to what you seem to believe, it does not allocate global storage. In fact, it does just the opposite.
(let ((myvalue "temporary string"))
(message myvalue) )
=> "temporary string"
myvalue
=> Lisp error: (void-variable myvalue)
And you can easily write a function with a variable whose value is set only during the function's execution. The interactive form allows you to easily obtain the values of point and mark.
(defun mysearch (point mark)
(interactive "r")
(let ((str (buffer-substring-no-properties point mark))
(message "your search for %s can commence ..." str) ) )
A common idiom is to use save-excursion to move point to another place, then grab the region between the original location and where you ended up, then do something with it. When you exit the save-excursion, the cursor's position (and several other things) will be restored to how they were before.
(defun mysearch ()
(interactive)
(save-excursion
(let ((here (point)) str)
(forward-word -1)
(setq str (buffer-substring-no-properties (point) here))
(message "your search for %s can commence ..." str) ) ) )
Perhaps you also want to look at http://ergoemacs.org/emacs/elisp_idioms.html
If you need to persist the value between function invocations, then the common thing to do is to defvar a variable like #phils suggests. Several variables with a common prefix sounds like you should be creating a separate module for yourself. For a flexible solution with low namespace footprint, create your own obarray (and achieve some sort of guru status). See also http://www.gnu.org/software/emacs/manual/html_node/elisp/Creating-Symbols.html#Definition%20of%20mapatoms

If a temporary local scope is all you require, then you definitely want to use let.
Otherwise you would usually define a variable (keeping in mind when you name it that elisp has no name spaces, so best practice is to use as reliably unique a prefix for all symbol names in a given library as practical).
(defvar SYMBOL &optional INITVALUE DOCSTRING)
If you omit the INITVALUE argument, the variable will not be bound initially, but ensures that your variable will use dynamic binding once used.
Then you just setq the variable as required.
Edit:
To obtain a buffer's contents between two points, use either of
(buffer-substring START END)
(buffer-substring-no-properties START END)
depending on whether or not you wish to preserve text properties.

Related

indent-[code-]rigidly called from emacs LISP function

I'm trying to write an emacs LISP function to un-indent the region
(rigidly). I can pass prefix arguments to indent-code-rigidly or
indent-rigidly or indent-region and they all work fine, but I don't
want to always have to pass a negative prefix argument to shift things
left.
My current code is as below but it seems to do nothing:
(defun undent ()
"un-indent rigidly."
(interactive)
(list
(setq fline (line-number-at-pos (region-beginning)))
(setq lline (line-number-at-pos (region-end)))
(setq curIndent (current-indentation))
;;(indent-rigidly fline lline (- curIndent 1))
(indent-region fline lline 2)
;;(message "%d %d" curIndent (- curIndent 1))
)
)
I gather that (current-indentation) won't get me the indentation of the first line
of the region, but of the first line following the region (so a second quesiton is
how to get that!). But even when I just use a constant for the column (as shown,
I don't see this function do any change.
Though if I uncomment the (message) call, it displays reasonable numbers.
GNU Emacs 24.3.1, on Ubuntu. And in case it matters, I use
(setq-default indent-tabs-mode nil) and (cua-mode).
I must be missing something obvious... ?
All of what Tim X said is true, but if you just need something that works, or an example to show you what direction to take your own code, I think you're looking for something like this:
(defun unindent-rigidly (start end arg &optional interactive)
"As `indent-rigidly', but reversed."
(interactive "r\np\np")
(indent-rigidly start end (- arg) interactive))
All this does is call indent-rigidly with an appropriately transformed prefix argument. If you call this with a prefix argument n, it will act as if you had called indent-rigidly with the argument -n. If you omit the prefix argument, it will behave as if you called indent-rigidly with the argument -1 (instead of going into indent-rigidly's interactive mode).
There are a number of problems with your function, including some vary
fundamental elisp requirements. Highly recommend reading the Emacs Lisp
Reference Manual (bundled with emacs). If you are new to programming and lisp,
you may also find An Introduction to Emacs Lisp useful (also bundled with
Emacs).
A few things to read about which will probably help
Read the section on the command loop from the elisp reference. In particular,
look at the node which describes how to define a new command and the use of
'interactive', which you will need if you want to bind your function to a key
or call it with M-x.
Read the section on variables from the lisp reference
and understand variable scope (local v global). Look at using 'let' rather
than 'setq' and what the difference is.
Read the section on 'positions' in the elisp reference. In particular, look at
'save-excursion' and 'save-restriction'. Understanding how to define and use
the region is also important.
It isn't clear if your writing this function just as a learning exercise or
not. However, just in case you are doing it because it is something you need to
do rather than just something to learn elisp, be sure to go through the Emacs
manual and index. What you appear to need is a common and fairly well supported
requirement. It can get a little complicated if programming modes are involved
(as opposed to plain text). However, with emacs, if what you need seems like
something which would be a common requirement, you can be fairly confident it is
already there - you just need to find it (which can be a challenge at first).
A common convention is for functions/commands to be defined which act 'in
reverse' when supplied with a negative or universal argument. Any command which
has this ability can also be called as a function in elisp code with the
argument necessary to get that behaviour, so understanding the inter-play
between commands, functions and calling conventions is important.

Watch a sexpr for edits

I'd like to tell Emacs to 'watch' a particular form (identified by its car) within a buffer and evaluate it whenever I edit it.
One approach I can think of is to add a function to post-self-insert-hook, which would find and parse the targeted form and compare it with its previously stored state.
It doesn't sound too inefficient, especially if a 'calls per second' maximum is enforced (e.g. using current-time).
Is there is a higher level / more idiomatic way to accomplish this? It sounds like the sort of problem that has been solved already.
I think the most natural way is to create an overlay that would span from the beginning to the end of the form.
Overlays have a modification-hooks property, and you can add a watcher function to it.
The overlay will contract or expand appropriately if you modify buffer contents strictly inside it, but you'll need to decide what to do when buffer is edited at the edges of the form. See insert-in-front-hooks, insert-behind-hooks and the last two arguments to make-overlay. I'd probably just re-create the overlay in most of these cases, just to be sure about the new bounds.
About the "calls per second" thing, you can use run-with-idle-timer.
Part of what #Dmitry mentioned can be turn into simple prototype. Mark (message "text") and run M-xeval-on-modify-add
(defun eval-on-modify-add ()
(interactive)
(let ((ov (make-overlay (region-beginning) (region-end))))
(overlay-put ov 'modification-hooks '(eval-on-modify-execute))))
(defun eval-on-modify-execute (ov &optional flag &rest rv)
(if flag
(eval-region (overlay-start ov) (overlay-end ov))))
(message "test")

How to make the tilde overwrite a space in Emacs?

I'd like (in TeX-related modes) the tilde key to insert itself as usual if point is on anything (in particular a line end), but if a point is on space, I'd like the tilde to overwrite it. (This would be a quite useful feature after pasting something into TeX source file.) I hacked something like this:
(defun electric-tie ()
"Inserts a tilde at point unless the point is at a space
character, in which case it deletes the space first."
(interactive)
(while (equal (char-after) 32) (delete-char 1))
(while (equal (char-before) 32) (delete-char -1))
(insert "~"))
(add-hook 'TeX-mode-hook (lambda () (local-set-key "~" 'electric-tie)))
My questions are simple: is it correct (it seems to work) and can it be done better? (I assume that if the answer to the first question is in the affirmative, the latter is a question of style.)
As mentioned, it's better to use a "character" literal than a number literal. You have the choice between ? , ?\ , and ?\s where the last one is only supported since Emacs-22 but is otherwise the recommended way, since it's (as you say) "more easily visible" and also there' no risk that the space char will be turned into something else (or removed) by things like fill-paragraph or whitespace trimming.
You can indeed use eq instead of equal, but the difference is not important.
Finally, I'd call (call-interactively 'self-insert-command) rather than insert by hand, but the difference is not that important (e.g. it'll let you insert 3 tildes with C-u ~).
Some points:
Instead of 32 use ?  (question-mark space) to express character literal.
Instead of defining keys in the major-mode hooks, do it in an eval-after-load block. The difference is that major-mode hook runs every time you use the major-mode, but there is only one keymap per major-mode. So there is no point in repeatedly redefining a key in it.
see: https://stackoverflow.com/a/8139587/903943
It looks like this command should not take a numeric argument, but it's worth understanding interactive specs to know how other commands you write can be made to be more flexible by taking numeric arguments into consideration.
One more note about your new modifications:
Your way to clear spaces around point is not wrong, but I'd do this:
(defun foo ()
(interactive)
(skip-chars-forward " ")
(delete-region (point) (+ (point) (skip-chars-backward " "))))

How can I open a temporary buffer

For very long time I have done: C-x b and then some "unique" name like xbxb. So I use switch-to-buffer with a non-existent buffer. You can imagine what C-x C-b shows me: Lots of such names. xbxb, xbxbxxx .... It really gets annoying after some time (a week or so), since I discover that I have already used all good names.
Is there a more canonical way of opening a new buffer? If I want to run a shell a further time, I say C-u M-x shell. Something along that line would be ideal.
You can use make-temp-name to generate a name for a file or buffer with a random postfix. With that as a base, you can write something like this:
(defun generate-buffer ()
(interactive)
(switch-to-buffer (make-temp-name "scratch")))
where "scratch" can be replaced by whatever prefix you'd like.
make it so:
(defun new-scratch ()
"open up a guaranteed new scratch buffer"
(interactive)
(switch-to-buffer (loop for num from 0
for name = (format "blah-%03i" num)
while (get-buffer name)
finally return name)))
I signed up just to answer this question (because I use this function a lot, so I thought it'd be useful to share it here):
(defun tmpbuf (buf)
"open a buffer,
if it doesn't exist, open a new one"
(interactive "sBuffer name: ")
(switch-to-buffer
(get-buffer-create (concat "*" buf "*"))))
I'm not really sure what you want. You say that "I discover that I have already used all good names", so letting Emacs generate the names isn't going to be any good, but if you are going to specify the name yourself, it doesn't get any more canonical than C-xb name RET.
Otherwise, one of the functions already suggested to let you enter a string and use that with some kind of "tmp buffer" pattern to create a new name would seem sensible.
Or scratch.el might prove useful, if what you actually wanted was a single temp buffer per major mode.
You could almost certainly benefit from binding C-xC-b to ibuffer, and using filters and/or groups to separate out the temporary buffers from the more important ones. That would deal with the list getting cluttered.
You seem oddly resistant to writing a new function? Even if there did turn out to be something built in, there's nothing wrong with using custom functions -- that's generally how you go about customising Emacs to your liking.
(defun yashi/new-scratch-buffer-in-org-mode ()
(interactive)
(switch-to-buffer (generate-new-buffer-name "*temp*"))
(org-mode))
(bind-key "<f7>" 'yashi/new-scratch-buffer-in-org-mode)
I'm using deft for a quick note-taking but sometimes I know I won't need the content but need a buffer in Org mode. For that, it's been serving me well. Hit F7 again will create a buffer with similar name, *temp*<2> in my case, acording to Uniquify.
BTW, here is a command to launch a new buffer with a new deft file, if you are interested. F6 to launch it.
(defun yashi/deft-new-file ()
(interactive)
(let ((deft-filter-regexp nil))
(deft-new-file)))
(bind-key "<f6>" 'yashi/deft-new-file)
I use this to open up a temporary buffer. Good thing? Helps me track which buffers I'd opened, and when.
(defun tmp-buffer()
"Make a temporary buffer and switch to it - Like C-n for Sublime etc"
(interactive)
(switch-to-buffer (get-buffer-create (concat "tmp-" (format-time-string "%m.%dT%H.%M.%S")))))
You are given access to someone else's Emacs and you want to open a new buffer. If you are lucky, this someone has set enable-recursive-minibuffers to t. If not, you can temporarily do M-: to eval this Emacs Lisp expression (don't forget to restore this parameter later):
(setq enable-recursive-minibuffers t)
Now, you open a new buffer:
C-xb prompts for a buffer name
C-uM-: will eval and print the result of the expression to the minibuffer prompt:
(random)
This gives you a random number in the full range of representable integers (including negative ones), which is very unlikely to be already taken. Press Return to conclude to switch to the new buffer.
I was looking for a solution for which I have the freedom to give a name or it randomly generates a name. I merged the andswer of #dotemacs and the answer of R. P. Dillon. I'm a n00b in elisp so it took me some half an hour to resolve some of my stupid mistakes.
(defun mm/generate-temp-buffer (buf)
"A function to generate temprory buffers using either
a random name or given name"
(interactive "sNew temp buffer name: ")
(switch-to-buffer
(get-buffer-create
(concat "*tmp*"
(if (equal buf "")
(make-temp-name "")
buf)
"*")
)))
This is how it works:
you run the function (M-x mm/generate-temp-buffer)
you are asked for a name.
2.1. if you type something it will create a buffer named *tmp*YOUR_STRING*
2.2. if you don't give an input and just press RET, it will create a buffer named something like *tmp*o8f4Mf*
Hopefully this is useful to others and save someone's time.

emacs: how do I use edebug on code that is defined in a macro?

I don't even know the proper terminology for this lisp syntax, so I don't know if the words I'm using to ask the question, make sense. But the question makes sense, I'm sure.
So let me just show you. cc-mode (cc-fonts.el) has things called "matchers" which are bits of code that run to decide how to fontify a region of code. That sounds simple enough, but the matcher code is in a form I don't completely understand, with backticks and comma-atsign and just comma and so on, and furthermore it is embedded in a c-lang-defcost, which itself is a macro. I don't know what to call all that, but I want to run edebug on that code.
Look:
(c-lang-defconst c-basic-matchers-after
"Font lock matchers for various things that should be fontified after
generic casts and declarations are fontified. Used on level 2 and
higher."
t `(;; Fontify the identifiers inside enum lists. (The enum type
;; name is handled by `c-simple-decl-matchers' or
;; `c-complex-decl-matchers' below.
,#(when (c-lang-const c-brace-id-list-kwds)
`((,(c-make-font-lock-search-function
(concat
"\\<\\("
(c-make-keywords-re nil (c-lang-const c-brace-id-list-kwds))
"\\)\\>"
;; Disallow various common punctuation chars that can't come
;; before the '{' of the enum list, to avoid searching too far.
"[^\]\[{}();,/#=]*"
"{")
'((c-font-lock-declarators limit t nil)
(save-match-data
(goto-char (match-end 0))
(c-put-char-property (1- (point)) 'c-type
'c-decl-id-start)
(c-forward-syntactic-ws))
(goto-char (match-end 0)))))))
I am reading up on lisp syntax to figure out what those things are and what to call them, but aside from that, how can I run edebug on the code that follows the comment that reads ;; Fontify the identifiers inside enum lists. ?
I know how to run edebug on a defun - just invoke edebug-defun within the function's definition, and off I go. Is there a corresponding thing I need to do to edebug the cc-mode matcher code forms?
What does def-edebug-spec do, and would I use it here? If so, how?
According to (elisp)Top > Debugging > Edebug > Edebug and Macros you have to tell Edebug how to debug a macro by defining it with debug statements or by using def-edebug-spec. This tells it what parameters should be evaluated and which shouldn't. So it can be done. In fact it looks as if c-lang-defconst already been fitted for edebug. Here is the definition in case you were interested:
(def-edebug-spec c-lang-defconst
(&define name [&optional stringp] [&rest sexp def-form]))
However, if you just want to see what the body evaluates to, then the way to do that is to use something like macro-expand-last-sexp below to see the result. Position your cursor after the sexp you want expanded (as you would for C-x C-e) and run M-x macro-expand-last-sexp RET. This will show you what it gets expanded to. You may run into troubles if you try to expand something like ,(....) so you may have to copy that sexp somewhere else and delete the , or ,#.
(defun macro-expand-last-sexp (p)
"Macro expand the previous sexp. With a prefix argument
insert the result into the current buffer and pretty print it."
(interactive "P")
(let*
((sexp (preceding-sexp))
(expanded (macroexpand sexp)))
(cond ((eq sexp expanded)
(message "No changes were found when macro expanding"))
(p
(insert (format "%S" expanded))
(save-excursion
(backward-sexp)
(indent-pp-sexp 1)
(indent-pp-sexp)))
(t
(message "%S" expanded)))))
I guess it depends on exactly what you are trying to do.
Use macroexpand or macroexpand-all to turn it into macro-free code and debug as usual?
Backticks &co may be best illustrated by an example:
(let ((a 1)
(b (list 2 3)))
`(a ,a ,b ,#b))
-> (a 1 (2 3) 2 3)
A backtick (or backquote`) is similar to a quote(') in that it prevents evaluation, except its effect can be selectively undone with a comma(,); and ,# is like ,, except that its argument, which must be a list, is spliced into the resulting list.