wrap s-expression in slime (emacs) - emacs

Is there a short way to wrap an s-expression using slime?
Suppose i have finished some piece of code and I realize I need a variable (e.g. for efficiency reasons) and therefore want to wrap it with let or want to make it tail recursive and need to wrap it with labels, what is the fastest way to do this? Is there a shortcut?
IntelliJ (a Java IDE) allows things like:
x > 3.if + TAB
yielding
if (x > 3) {
}
So are there any "sexp-wrapping" shortcuts (postfix or prefix) in slime/emacs?

The bar represents the cursor.
With paredit
There is a wrap-round command, bound to M-(. But when adding context to an expression, I generally do as follows:
|code
Open the parenthesis (the closing one is added automatically):
(|)code
... type ...
(let |)code
Call paredit-forward-slurp-sexp (C-right)
(let | code)
See also the The Animated Guide to Paredit.
Without paredit
|code
Call mark-sexp (C-M-Space), then kill the region; type and yank (paste) the text where you need it.
See also Expressions with Balanced Parentheses (e.g. forward-sexp), available in Emacs.

Related

Call a command with arguments in Emacs minibuffer

I know that M-x (execute-extended-command) allows one to call a command in Emacs by typing its name. That however doesn't allow me to call command with arguments, e.g "backward-word 5"
I am aware that C-5 M-b produces the desired result but I am looking for a general method.
Does anyone know how to do this?
Thanks,
Danny
Eval it: M-: (backward-word 5) RET.
#abo-abo provided the general answer: use M-:.
However, if you are interested not only in obtaining the side effects of the evaluation, and not only in a cursory overview of the return value, but in the full return value (regardless of its size and complexity), then vanilla Emacs M-: is not what you want.
For that, I substitute pp-eval-expression for eval-expression wrt its key bindings (including M-:), and I recommend this practice for others too:
(substitute-key-definition 'eval-expression 'pp-eval-expression global-map)
That pretty-prints the return value, and you can make it print the complete value (no ellipses: ...).
In addition, I offer a modified version of pp-eval-expression in library pp+.el. It has these advantages:
Reads with completion, using pp-read-expression-map.
Emacs-Lisp mode indentation and completion key bindings are available during input.
With a prefix arg, inserts the resulting value into the current buffer at point.
With a negative prefix arg, if the return value is a string, inserts it into the buffer without double-quotes (").
Font-locks the return value (syntax highlighting) for Emacs-Lisp mode. (And during display emacs-lisp-mode-hook and change-major-mode-hook are inhibited.)
Respects new user options pp-eval-expression-print-length,
pp-eval-expression-print-level, and standard option eval-expression-debug-on-error. The former are separate from the similar, standard options eval-expression-print-length and
eval-expression-print-level because the use cases are typically different.
If you use library Icicles then you get the same advantages as library pp+.el -- no need to load pp+.el also.

Emacs: abbrev-mode not expanding simple abbrev, possible causes?

I would like to assign the string 'target="_blank"' to the abbreviation 'tgt' as I use this a lot and it's annoying to have to type out each time.
The string above probably needs escapes and so on, so as a simpler starting point I have tried to assign 'target' to 'tgt'. Despite switching on abbrev-mode and defining this as a global abbrev, if I type 'tgt' and hit space, nothing happens. If I do M-x list-abbrevs I get this:
(global-abbrev-table)
"target" 1 "tgt"
So it seems to be recorded. I would have expected tgt to be expanded to target when I hit a space after tgt, but that doesn't happen. What am I missing? Have I completely misunderstood the nature of abbrevs? I have looked at the Emacs wiki page but like many Emacs pages it gives a number of complex solutions and annoyingly sparse coverage of the basics.
EDIT: embarassingly enough this looks like it was a combination of the wrong abbrev file and an assignment that was reversed, so that typing 'target' produced 'tgt'. I now have 'tgt' producing 'target="_blank"' as desired. Apologies everybody.
However, I now have a related question. This abbreviation expands when I hit space and typically I do not want a space after the 'target="_blank"' string. Is there a way to automatically remove the space?
You have to define the abbrev the other way around. The way you did it will expand "target" into "tgt".
To do the right thing, first type into a buffer what you want the abbrev to expand into. In your case that would be "target". Then, with the point right after the word, type C-x a g. This will prompt you for an abbrev for which you would type "tgt".
Et voilĂ : if abbrev-mode is turned on, typing tgt will now expand into "target".
There are other ways to define an abbrev, e.g. via M-x define-global-abbrev, thus it's best to check out the documentation.
The problem with removing the space after the abbrev is that Emacs will insert it after the abbrev has been expanded. So hitting space will basically two things: trigger the expansion of the abbrev and then run the normal self-insert command.
One simple way to avoid this is to type C-x ' or C-x a e to explicitly expand an abbrev rather then turning on abbrev-mode. Except, that's a bit annoying. If we look at the documentation again, however, we find:
Function: define-abbrev table name expansion &optional hook count
[...]
If hook is a non-nil symbol whose no-self-insert property is
non-nil, hook can explicitly control whether to insert the
self-inserting input character that triggered the expansion. If hook
returns non-nil in this case, that inhibits insertion of the
character. By contrast, if hook returns nil, expand-abbrev also
returns nil, as if expansion had not really occurred.
This means that if you put the following lines in, say, your ".emacs" file:
(defun my-after-abbrev-expand ()
(when (looking-back "\"\"\\|''\\|()\\|\\[\\]\\|{}")
(backward-char 1))
t)
(put 'my-after-abbrev-expand 'no-self-insert t)
then you can define an abbrev like so:
(define-abbrev global-abbrev-table "tgt" "target=\"\"" 'my-after-abbrev-expand)
to avoid the insertion of the space character. Also, the my-after-abbrev-expand function will move the point one position to the left if the expansion ends in two double quotes, two single quotes, or a pair of round, square or curly braces.

Retaining tab-to-tab-stop with Emacs replace-regexp

I have a very large text file with nearly 20 columns. Unfortunately the program which produced the file did not properly handle columns which began with a -10 (it only properly spaced data which had a total of 5 characters, not 6). Essentially I ended up with something that looks like this:
-10.072-10.179-10.2190.002
I want it to look like:
-10.072 -10.179 -10.219 0.002
and was almost able to do so with:
M-x replace-regexp RET -10\.... RET \&TAB RET
When I use TAB however, it only replaces with a space rather than tab- ideally a tab-to-tab-stop. If I manually go to one of these situations in the file and type TAB it properly does a tab-to-tab-stop to align the data with the proper column. How do I retain the tab-to-stop function within the replace-regexp?
The search and replace certainly ought to be inserting a tab. The apparent size of a tab can vary, of course, which is the only reason I can think of for it appearing to be a space. You could use whitespace-mode to make the difference more obvious.
As for tab-to-tab-stop, that's a dynamic function rather than a special kind of tab character, so you can't do that with a search and replace1. I would suggest using a keyboard macro instead, to get the same dynamic behaviour as manual typing.
F3
M-C-s -10.... RET
M-x tab-to-tab-stop RET
F4
or perhaps just: F3M-C-s -10.... RETTABF4
Then you can run the macro until it fails with C-0F4
(If you only want to run it on a portion of the buffer, you can simply narrow to the relevant region first.)
1 Not strictly true, as Emacs lets you evaluate arbitrary elisp as part of a replacement pattern; but it's not just a case of calling the tab-to-tab-stop function, so the macro is really much simpler.

In Emacs, how can I exclude '-' from the common delimiters?

When coding in elisp, I find that I'm stopping at hyphens when moving by words, and would prefer to ignore them.
What's the simplest way to do this?
M-x modify-syntax-entry RET - RET w RET should do it. Or if you prefer an elisp snippet that you can add into a hook, (modify-syntax-entry ?- "w")
The syntax table for a mode contains information on what constitutes various syntactic classes (e.g. words, spaces etc.). These are used to determine the operation of commands such as forward-word etc. Modifying it change the behaviour of these commands.
Instead of changing Emacs' notion of words, it might be preferably to navigate by s-expressions (C-M-f, C-M-b) to skip whole identifiers. That way, you keep the convenience to be able to navigate by the partial words if you want to change an identifier.
You can use interactive regex search. Pressing just C-M-s SPACE should search for any whitespace (you might need to configure search-whitespace-regexp).

How do you type lisp efficiently, with so many parentheses? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I try to keep my fingers on home row as much as possible.
Typing all the parentheses makes me move away from there a fair bit.
I use Emacs; the parentheses themselves are no issue, I'm comfortable with them. And I don't like modes that type them for me automatically.
I've thought about remapping the square brackets to parentheses and vice versa. Is this a good idea? What does everyone else do?
I would personally recommend the lethal combo of Emacs, SLIME & paredit.el
Paredit allows you to pseudo-semantically edit the LISP code at sexp level, and that makes the parentheses disappear almost completely. You can move around sexps as if they are simple words and even mutate them with just a couple of key-strokes. There is also a minor mode called Redshank which works in conjunction with Paredit and that provides more power.
Consider simple these examples (| is the position of the cursor):
(foo bar (baz| quux) zot) + C-( => (foo (bar baz| quux) zot)
(foo (bar |baz) quux zot) + C-) => (foo (bar |baz quux) zot)
(foo (bar baz |quux) zot) + C-{ => (foo bar (baz |quux) zot)
(foo (bar |baz quux) zot) + C-} => (foo (bar |baz) quux zot)
I have done some serious Common Lisp programming in my time, and paredit has proved to be invaluable to me. I can't even think of writing non-trivial LISP code without my toolbox. And after all that's the way it should be; you should never have to count or match your parentheses... once you master Paredit, the parentheses will just disappear from in front of your eyes.
Remapping the [] to () will help, but you will stop caring much after you start using Paredit.
Feel free to use the LISP specific portions from my dot-emacs.
With many non-US keyboard layouts, typing square brackets or braces is even more cumbersome than typing parentheses, anyway, which makes programming in most languages very strainful, so consider yourself lucky. ;)
As for me, I use a programmer-friendly non-standard keyboard layout that lets me type parentheses via [Super]-j and [Super]-k.
I have foot pedals. LeftFoot = open paren, RightFoot = close paren.
Well, I don't, but I don't use Lisp. It doesn't seem like a bad idea, though.
Could you imagine a variation on Lisp that used indentation instead of parens? (taking a page from the Python spec)
I take my fingers off the home keys....
I tried remapping in Emacs, but it creates new problems: say you're editing in a terminal window through ssh and you paste a snippet into the window; then parens and brackets get swapped in your pasting, not just your typing. If you try this, remap at a lower level in your system, like xmodmap.
(Of course, the obvious other problem is using other computers without your remapping. That was a nuisance too, though bearable.)
"... so many parenethesis"
The first thing I did was bind the '(' key to the sequence '('+')'+right(), so my parenthesis auto balance, leaving half as many left to type when writing new code.
You also want a convenient way to navigate out one paren -- bind C-] to the sequence search(')')+right(). Authoring becomes shorter now, as you don't need to take hands off the home position -- just type C-] every time you complete an S-expr.
Next thing I did was bind a key to a subroutine that pushes an existing item onto the current list ... so if // is the cursor position, then this command will transform:
(if (< //) (+ x 1)
(x)
(y))
to
(if (< (+ x 1) //)
(x)
(y))
Effectively pushing one item from the right into the current list -- very useful for editing existing code. The sequence '(', '<', C-S-], Space, '2' adds "compare less than 2" to an existing expression. Combined with C-], this lets you build new expressions very quickly from existing ones.
#jamesnvc,
I didn't think about binding () to [] keys... I'll have to try that, thx!
I remapped [] to () with xmodmap and like it. It was a bit weird getting used to writing code in languages that use [], but like any change, you get used to it. Having unshifted parens in Lisp is nicer than not having unshifted brackets in other languages, so it works out.
Anyway, here is the necessary xmodmap incantation for my US keyboard:
!! swap () and []
keycode 18 = 9 bracketleft
keycode 19 = 0 bracketright
keycode 34 = parenleft braceleft
keycode 35 = parenright braceright
I have to take my fingers off the home row to reach all the other shift-number operators, so I never thought about it much.
And once you type a left-parens, electric-parens give you the right.
If you use the parentheses more than the square brackets, by all means, remap away. I don't see how it could pose any more problems than, say, a lefty swapping her mouse buttons.
When I'm writing code, I generally spend much more time thinking and reading my code, than I do typing it. I've tried a couple of times in the past to switch to the Dvorak keyboard layout, but I lack obvious motivation because I can type much faster than I can think. Programming language syntax is a similar issue - as long as I can type code without leaving the keyboard (ie. using the mouse would be bad), I'm happy.
DrScheme has the keystrokes for parens and square braces flipped by default. It also has a feature where it magically guesses which one of the two you meant, so you rarely reach for shift-9.
Quack has a similar feature to that of DrScheme.
DivaScheme (my editor), is something completely different. It edits at the sexp level, so that the parens are no longer in the way.
Mostly, I just type them, but occasionally, I use M-( and M-) (especially when I am adding a LET binding "late in the stage"), to enclose the relevant nnumber of expressions.
I also changed my (dvorak) keyboard layout (via xmodmap) to switch the brackets ("[]") and parens, in conjunction with paredit-mode (which does indeed take some getting used to).
I use paredit and pair-mode packages but, for fast parenthesis typing I use electric-dot-and-dash to replace a double period in a () on a 5 ms delay (if I type slowly I get two dots then). It's a wonderful package (I hacked a bit for my personal preference; as I type with Dvorak keyboard, I replaced the dash key by a slash (// is not so common in lisp)).
To avoid the mess in parens, I add a package named 'highlight-parentheses to my tool set, and for maximum efficiency on sexp grabbings or text navigation in general, I also use vimpulse (as I am a Vim addict).
Rebind capslock to "(" and have the editor autoinsert ")" for you.
(This also helps for other languages with a lot of brackets, for instance HTML...)
I use Vim with vim-sexp and vim-sexp-mappings-for-regular-people then have mapped <leader>u to put me in normal mode inside of a new (.
map <leader>u i(