How to map a key in Emacs to move from one period (full-stop) to the other - emacs

I use Emacs to write research papers (which include a lot of text .. duh). I always want to move from a period (.) to another period - basically, move from beginning of a sentence to the end (and vice-versa). I have not found any key map that does this (M-a, M-e, C-x C-t are not what I require). I don't have much experience with elisp. If someone can point to me and existing key-map or a function, I would be very grateful.
TIA
S.

M-e (forward-sentence) is the right way to go. It would take care of going to the end of the next sentence (although I think it relies on there being two spaces after the period to decide that it's a sentence end rather than an abbreviation point).
If you just want to jump to the next ., you can use this (I presume you're editing your files in text-mode).
(add-hook 'text-mode-hook (lambda ()
(local-set-key (kbd "C-c .")
(lambda () (interactive) (search-forward "." nil t)))))
and use C-c . to jump to the next period.

Related

Emacs: Assign a function to a keybinding, and with repeated presses, undo the last press and redo at a wider setting

Here's the bigger picture of what I'm trying to do:
With a keypress, it will insert an opening and closing parenthesis right after/before the innermost closing/opening delimiter (bracket, brace, parenthesis, whatever).
But if it is pressed immediately after, it will undo the last insertions, seek out the next closing delimiter, and put it after that, and so on.
I have a working version of the first part, but am looking for "best practices" for the second part (where it undoes and moves outwards)
As a motivator and concrete example, this is a typical scenario when coding in Python. I work with list comprehensions a lot, and often I construct the list, and then decide I want to sum all elements, etc. So I would first type:
[x*x for x in some_lst if is_prime(x)]
and then I'll want to encapsulate this list with a "sum" command:
sum([x*x for x in some_lst if is_prime(x)])
I don't want to have to keep moving the cursor to both the beginning and the end just to insert the parentheses. I'd rather have the point in the list, press a keystroke, have it figure out the delimiters, and place the mark just before the opening inserted parenthesis so that I can type "sum". My function below seems to work (piggybacking on the "expand-region" package):
(defun add-paren ()
(interactive)
(er/mark-outside-pairs)
(exchange-point-and-mark)
(insert-string ")")
(exchange-point-and-mark)
(insert-string "(")
(left-char 1)
)
What's the best practice for the 2nd step?
(Any suggestions/improvements to the above would also be appreciated. This is my first "real" function in Elisp.)
Thanks.
Update: Thanks everyone for the tips. I'll probably use some of them in my final solution. My original question still stands: Is there a standard pattern of "undoing and redoing at a larger scale", or will each problem have its own custom solution? Suppose I use smartparens as suggested to do it all in one keystroke, but I want it to occur on the 3rd level out. What I want is to press the keystroke 3 times and have it place the parentheses there.
So after the first keystroke, it places the parentheses at the innermost level. Pressing it again should remove the inserted parentheses, and place them in the next level up, and so on...
(BTW, not trying to reinvent the wheel. I suspect some of the packages listed may have exactly what I need - I just want practice coding in Elisp).
Update 2:
I guess there is no best practice for this? Anyway, I solved the problem using both expand-region and smartparens:
(defun add-paren ()
(interactive)
(if (eq last-command 'add-paren)
;; (message "AAAA")
(delete-paren)
)
(setq currpoint (point))
(er/mark-outside-pairs)
(if (eq currpoint (point))
(er/mark-outside-pairs)
)
(sp-wrap-with-pair "(")
(left-char 1)
)
(global-set-key (kbd "<f5>") 'add-paren)
(defun delete-paren ()
(interactive)
(setq currloc (point))
(sp-unwrap-sexp)
(goto-char currloc)
(left-char 1)
)
You're already using expand-region. Why not combine that with one of the many "surround region with..." modes?
I personally like smartparens (available via Marmalade or MELPA), but there are many other similar tools.
Use er/expand-region until you've got an appropriate selection, then
( to wrap in parentheses.
When programming, there are several hundred slightly different edit-tasks of this kind. Therefor created a toolkit for it.
In example given, the form might be described as delimited, more precisely bracketed.
ar-bracketed-atpt would mark it.
It's set here like this:
(global-set-key [(super \])] 'ar-bracketed-atpt)
Then comes in another class of commands which do several things on active region. In this case:
M-x ar-parentize-or-copy-atpt RET
It is bound to C-c )
A tarball for all this stuff is available here:
https://launchpad.net/s-x-emacs-werkstatt/
FWIW, I'd do it as follows:
go before the open bracket.
type sum C-M-SPC (
The C-M-SPC selects the parenthesized (well, "bracketized") expression, and the subsequent ( wraps it in parens (because of electric-pair-mode).
I guess there is no best practice for this? Anyway, I solved the problem using both expand-region and smartparens:
(defun add-paren ()
(interactive)
(if (eq last-command 'add-paren)
;; (message "AAAA")
(delete-paren)
)
(setq currpoint (point))
(er/mark-outside-pairs)
(if (eq currpoint (point))
(er/mark-outside-pairs)
)
(sp-wrap-with-pair "(")
(left-char 1)
)
(global-set-key (kbd "<f5>") 'add-paren)
(defun delete-paren ()
(interactive)
(setq currloc (point))
(sp-unwrap-sexp)
(goto-char currloc)
(left-char 1)
)

Undo buffer-search in Emacs

After doing a (re-search-forward str) in the current buffer, it would be nice in some cases to have an easy method to return to the previous buffer position. The behavior should be like (undo) for buffer changes. So if I do two searches forward, first from position A to B, and then from B to C, I would like to press a key to go back one step (from C to B), and pressing the key again would leave me at A..
If you are using re-search-forward in Lisp code (and you probably should be, if you are using it at all, even though it is a command), then do not set the mark in order to be able to return to your starting point.
Instead, simply save the starting position ((point)) as, say, variable beg, and then use goto-char beg.
See this paragraph in (elisp) The Mark:
Novice Emacs Lisp programmers often try to use the mark for the
wrong purposes. The mark saves a location for the user's
convenience. An editing command should not alter the mark unless
altering the mark is part of the user-level functionality of the
command. (And, in that case, this effect should be documented.)
To remember a location for internal use in the Lisp program, store
it in a Lisp variable. For example:
(let ((beg (point)))
(forward-line 1)
(delete-region beg (point))).
With this
(global-set-key
(kbd "M-p")
(lambda()(interactive) (set-mark-command 4)))
I can jump backwards one by one through a few C-M-s.
Note that this works for isearch-forward-regexp, not for plain
re-search-forward (this one doesn't set the mark).
But with elisp it's no problem - just call push-mark before
re-search-forward.
To sum up, the following seems to work:
(defun my-search-fun (str)
(interactive)
(push-mark)
(beginning-of-buffer)
(re-search-forward str))
(defun my-undo-search ()
(interactive)
(pop-mark)
(goto-char (mark))

emacs: back two lines in function?

I have a function in my emacs dot file to insert a date in my journal. After adding it, I would like to jump back a couple of lines and place the cursor below the date. How do I do that in the function?
(defun ddd ()
"Insert date at point journal style."
(interactive)
(insert (format-time-string "[%Y-%m-%d %a]"))
(insert "\n")
(insert "\n")
(insert "\n")
(insert "** end\n")
(gobacktwolineshere))
Any ideas?
You want the function forward-line, specifically
(forward-line -2)
goes backward two lines. For more information, type C-h f forward-line RET inside emacs. Depending on where you've left point, you might not end up at the beginning of the line. If you want this, add a call to beginning-of-line.
Remember that if you can tell Emacs to do it interactively (e.g. with <up> or C-p in this instance) then you can ask Emacs what it does when you type that, by prefixing C-hk.
In this case, Emacs tells you that those keys run the command previous-line, and also:
If you are thinking of using this in a Lisp program, consider using
forward-line with a negative argument instead. It is usually easier
to use and more reliable (no dependence on goal column, etc.).
You might want to use save-excursion to make it more robust:
(defun ddd ()
"Insert date at point journal style."
(interactive)
(insert (format-time-string "[%Y-%m-%d %a]\n"))
(save-excursion (insert "\n\n** end\n")))
If you know how many characters you want to go back, you can use (backward-char 9).

Emacs: Insert word at point into replace string query

Is there an analogue to inserting the word after point into the isearch query by hitting C-w after C-s but for the replace string (and replace regexp) queries?
I also enjoy Sacha Chua's modification of C-x inserting whole word around point into isearch:
http://sachachua.com/blog/2008/07/emacs-keyboard-shortcuts-for-navigating-code/
This too would be really useful in some cases if it could be used in replace string.
I'd be very thankful for any tips!
Thank you!
This will do it, although it isn't as fancy as C-w in isearch because you can't keep hitting that key to extend the selection:
(defun my-minibuffer-insert-word-at-point ()
"Get word at point in original buffer and insert it to minibuffer."
(interactive)
(let (word beg)
(with-current-buffer (window-buffer (minibuffer-selected-window))
(save-excursion
(skip-syntax-backward "w_")
(setq beg (point))
(skip-syntax-forward "w_")
(setq word (buffer-substring-no-properties beg (point)))))
(when word
(insert word))))
(defun my-minibuffer-setup-hook ()
(local-set-key (kbd "C-w") 'my-minibuffer-insert-word-at-point))
(add-hook 'minibuffer-setup-hook 'my-minibuffer-setup-hook)
EDIT:
Note that this is in the standard minibuffer, so you can use it use it anywhere you have a minibuffer prompt, for example in grep, occur, etc.
Two answers:
Replace+ automatically picks up text at point as the default value when you invoke replace commands.
More generally, Icicles does something similar to what scottfrazer's code (above) does, but it is more general. At any time, in any minibuffer, you can hit M-. (by default) to pick up text ("things") at point and insert it in the minibuffer. You can repeat this, to either (a) pick up successive things (e.g. words) of the same kind, accumulating them like C-w does for Isearch, or (b) pick up alternative, different things at point. More explanation here.
I think this exists in Emacs already - you just start replace with M-S-% and then press M-n (while the minibuffer is empty), this fills in the word under cursor, there are more useful things you can do with this, check http://endlessparentheses.com/predicting-the-future-with-the-m-n-key.html?source=rss#disqus_thread.

Emacs command to insert and indent line above cursor

I frequently find myself typing on a line, when I realize I need(ed) a variable definition (or something similar) on the line above. What I would like is to
press C-return from anywhere on a line and have the cursor move to a newly inserted blank line above, with correct indentation (or at least the same as the original line).
be able to yank any text...
and C-u C-space to get back to the original position
I've managed to do #1, but my emacs-fu isn't strong enough to do the rest.
Here's my humble solution:
(defun my-insert-before-line ()
(interactive)
(save-excursion
(beginning-of-line)
; I've changed the order of (yank) and (indent-according-to-mode)
; in order to handle the case when yanked line comes with its own indent
(yank)(indent-according-to-mode)
; could be as well changed to simple (newline) it's metter of taste
; and of usage
(newline-and-indent)))
Hope it helps.
Here's what you can do if you are not a Zen master emacs dude.
Emacs has a record-macro thing, kmacro-start-macro and kmacro-end-macro.
After recording your macro, do name-last-kbd-macro. then visit .emacs, and do insert-kbd-macro.
You then have an fset statement that defines your macro. It may look funny, and it is not as maintainable as elisp, but if you stuff it into your .emacs, that macro (by that name) will be available to any of your editing sessions. And you can bind it to a key sequence as well.
Probably bad form to answer my own question, but Cheeso's answer motivated me to do some lisp programming for the second time in ten years (my original version was a named keyboard macro, but it stepped all over the kill/mark-rings). Here's what I came up with
(defun insert-and-indent-line-above ()
(interactive)
(push-mark)
(let*
((ipt (progn (back-to-indentation) (point)))
(bol (progn (move-beginning-of-line 1) (point)))
(indent (buffer-substring bol ipt)))
(newline)
(previous-line)
(insert indent)))
(global-set-key [ (control return) ] 'insert-and-indent-line-above)
there are probably many better ways of doing this, but two hours of lisp-hacking can hardly be called wasted time :-)