Killing current block in C mode - emacs

Is there an easy way to configure a single key-combination to kill the content of the inner-most block currently under the cursor. In other words
if (foo) {
bar;
baz;
}
would transform into
if (foo) {
}
when hitting the key-combination with the cursor anywhere inside the block. Similarly, I would like to be able to have one key-combination to kill the content of the guard of the if-clause if the cursor was anywhere on foo.

Yes. Install expand-region: M-x package-install expand-region, and add (require 'expand-region) to your .emacs.
The function you are looking for is er/inside-pairs, which will expand until hitting () {}, "", etc. To bind it to a specific key command like C-=, put this in your .emacs:
(global-set-key (kbd "C-=") 'er/inside-pairs)

Related

In emacs how to create a mapping to a function returned by another function?

I'm using emacs with evil-mode, I want to map <leader>tt to the function projectile-dired however if a dired buffer is being shown then it should be mapped to the evil-delete-buffer, so in essence creating a map to a toggle function.
After learning the basics of emacs lisp I came up with this solution:
(defun toggle-projectile-dired ()
"Toggles projectile-dired buffer."
(interactive)
(or
(when (derived-mode-p 'dired-mode)
(evil-delete-buffer (current-buffer)))
(projectile-dired)))
;; This is how the mapping is done
(evil-leader/set-key "tt" 'toggle-projectile-dired)
But what I did with this solution was to create a map to a function that in the end calls to another function.
While my solution works (and I'm fine with it) what I could not do was to return the function to be called (instead of calling it, as I did) how such approach should be written?
Or in other words, how to return a function name and make that mapping call the returning function?.
PD: This question is just for the sake of learn some elisp. Thanks!
EDIT:
Here is some pseudo code (javascript) of what I want to achieve:
function toggleProjectileDired() {
if (derivedModeP == 'dired-mode') {
// We're in dired buffer
return 'evilDeleteBuffer';
} else {
return 'projectileDired';
}
}
evilLeaderSetKey("tt", toggleProjectileDired());
My solution in pseudo code is:
function toggleProjectileDired() {
if (derivedModeP == 'dired-mode') {
// We're in dired buffer
evilDeleteBuffer();
} else {
projectileDired();
}
}
evilLeaderSetKey("tt", toggleProjectileDired);
As you can see, one returns the function name to be called while the other calls the function. How to return a function name to be called in elisp?
(Caveat: I don't use evil, and am not familiar with its custom keybinding functions.)
The canonical approach to making a key do one thing in dired-mode and another thing elsewhere is to define one binding in dired's keymap, and another binding in the global keymap (or whatever is appropriate). I would recommend that you try to follow this approach in most circumstances, because it makes it much simpler to see what's happening.
However, there is a way to do what you're asking for. These pages demonstrate some variations on the approach:
https://stackoverflow.com/a/22863701
http://endlessparentheses.com/define-context-aware-keys-in-emacs.html
http://paste.lisp.org/display/304865
In essence you use the :filter facility of menu items (n.b. menus are actually fancy keymaps in Emacs) to determine the command at run-time. Note that if the filter function returns nil, Emacs treats it as if no binding exists in that keymap, and continues looking for a binding in the remaining keymaps; so this feature facilitates bindings which are only conditionally active.
A non-evil version of your example might look like this:
(define-key global-map (kbd "<f6>")
`(menu-item "" projectile-dired
:filter ,(lambda (default)
(if (derived-mode-p 'dired-mode)
'evil-delete-buffer
default))))
Again, this would be more usual:
(global-set-key (kbd "<f6>") 'projectile-dired)
(eval-after-load "dired"
'(define-key dired-mode-map (kbd "<f6>") 'evil-delete-buffer))
FWIW, I actually think the general approach you started with is probably the best one in this instance. If typing KEY should always toggle dired in that window, then binding it to a toggle-dired command seems like the most self-explanatory implementation.

Opening a window into a specified buffer

How can I open a new window (for example using C-x 3) into a new buffer, rather than a mirrored buffer that just echoes what I type.
So for example, let's say I'm messing around with python and I want to run the script in the shell. As it is currently I do this: C-x 3, M-x shell and then start it up and running. I'd rather just C-x 3 and it automatically opens into shell. I'm really new to Emacs so I don't know where to look for this.
It sounds to me like this, or something similar, is what you are looking for:
(defun pop-to-buff-at-right (buffer)
"Pop to BUFFER at the right of the current window."
(interactive "B")
(pop-to-buffer buffer '(display-buffer-in-side-window
(side . right)
(inhibit-same-window . t))))
You do not want to just split the window, which is specifically about showing the same buffer twice. You want to switch to another buffer, but you want it to be displayed to the right of the current window.
In emacs it is easy to define custom commands and bind it to keys. For instance, if you add this to your init file:
(defun open-shell-at-left ()
(interactive) ;; Tell emacs this function can be called interactively
(split-window-right) ;; Just what C-x 3 does
(shell)) ;; Just what M-x shell does
(global-set-key (kbd "C-c 3") 'open-shell-at-left)
You will have what you want when you type C-c 3. In general, you can find documentation about what a key binding does by typing C-h k and the keybinding. From that point, it is easy to chain existing commands into new ones.

Running emacs keyboard macros in batch mode

I want to be able to save a keyboard macro in emacs and apply it to a file repeatedly in batch mode. To give a simple example, I made the following file paren-delete.el which is supposed to delete all parentheses and their contents. When I run emacs --batch target.txt --load paren-delete.el, nothing seems to have changed. It appears that only the first kbd function does what it's supposed to, so clearly I don't understand how that command works.
I know that it would be preferable to avoid keyboard macros and write my functions in proper elisp, but I'd prefer a quick-and-dirty solution, and I feel like I'm close.
(kbd "M-x load-library kmacro")
(fset 'delete-paren
(lambda (&optional arg) "Keyboard macro." (interactive "p")
(kmacro-exec-ring-item (quote ("^S(^M^B^#^[^N^W" 0 "%d")) arg)))
(start-kbd-macro nil)
(kbd "M-x delete-paren")
(end-kbd-macro)
(kbd "C-u 0 C-x e")
(save-buffer)
One answer:
Define a function that runs the macro: Write this in an Emacs-Lisp buffer leaving the cursor at the end::
(defun foo ()
M-x insert-kbd-macro RET
Now you have this text, but with the definition of your keyboard macro in place of XXXXX:
(defun foo () (setq last-kbd-macro XXXXX)
Replace setq last-kbd-macro by execute-kbd-macro, and add a final ):
(defun foo () (execute-kbd-macro XXXXX)
Then use C-x C-e after the definition or C-M-x anywhere inside it.
That defines function foo, which does just what your keyboard macro did (in the same context, e.g., same mode, so same key bindings).
Save the definition to your init file. You can use it with Emacs in batch mode. You can also add (interactive) after () to make it a command, so you can use it with M-x.
Another answer:
With Bookmark+, use C-u M-x bmkp-make-function-bookmark to create a bookmark from the last keyboard macro. You are prompted for the bookmark name.
Bookmarks are persistent. To use a bookmark in batch mode, call it as an argument of bookmark-jump, like so: (bookmark-jump THE-BOOKMARK-NAME).

Emacs Org-Mode: how to fold block without going to block header?

I know I can go to a block header and fold/unfold by hitting the TAB key.
However suppose I'm inside a block that has hundreds of lines, and I just want to fold the current block, without having to go to the block header -- is there a keyboard short-cut that can do that? Or is there an elisp function that does that, so that I can bind some shortcut to that function?
Create a keybinding that performs the following function:
(defun zin/org-cycle-current-headline ()
(interactive)
(outline-previous-heading)
(org-cycle))
This will jump back to the previous headline and then cycle. Since the headline is already open, it will close it. It also places the point at the start of the headline.
If you wrap the two commands in (save-excursion ) it will retain the point, however that could lead to entering information inside the ellipsis without realizing it. Alternately you can change the command to call a non-interactive form:
(defun zin/org-cycle-current-headline ()
(interactive)
(org-cycle-internal-local))
This is equivalent to the above with (save-excursion ).
C-c C-p will get you to the heading, TAB will fold. You can create a keyboard macro for this, or the equivalent ELISP:
(defun up-n-fold ()
(interactive)
(progn
(outline-previous-visible-heading 1)
(org-cycle)))
Edit: corrected C-c p for C-c C-p as noted by many below. Thanks!
I am not sure whether such a function exists, but it is not hard to create one. Just replace the following keystrokes with functions: C-M-r^*Entertab.

How can I easily reload Emacs lisp code as I am editing it?

As an Emacs beginner, I am working on writing a minor mode. My current (naive) method of programming elisp consists of making a change, closing out Emacs, restarting Emacs, and observing the change. How can I streamline this process? Is there a command to refresh everything?
You might try using M-C-x (eval-defun), which will re-evaluate the top-level form around point. Unlike M-x eval-buffer or C-x C-e (exal-last-sexp), this will reset variables declared with defvar and defcustom to their initial values, which might be what's tripping you up.
Also try out C-u C-M-x which evaluates the definition at point and sets a breakpoint there, so you get dropped into the debugger when you hit that function.
M-x ielm is also very useful as a more feature-rich Lisp REPL when developing Emacs code.
M-x eval-buffer should do it.
What Sean said. In addition, I have (eval-defun) bound to a key, along with a test. The development loop then becomes: 1) edit function, 2) press eval-and-test key, 3) observe results, 4) repeat. This is extremely fast.
During development I write a test, bind it to jmc-test, then use the above key to run it on my just-edited function. I edit more, then press key again, testing it again. When the function works, I zap jmc-test, edit another function, and write another jmc-test function. They're nearly always one line of code, so easy to just bang out.
(defun jmc-eval-and-test ()
(interactive)
(eval-defun nil)
(jmc-test))
(define-key emacs-lisp-mode-map (kbd "<kp-enter>") 'jmc-eval-and-test)
(when t
(defun myfunc (beer yum)
(+ beer yum))
(defun jmc-test () (message "out: %s" (myfunc 1 2))))
When editing "myfunc", if I hit keypad enter, it prints "out: 3".
It all depends on what you're writing and how you've written it. Toggling the mode should get you the new behavior. If you're using [define-minor-mode][1], you can add code in the body of the macro that keys off the mode variable:
(define-minor-mode my-minor-mode
"doc string"
nil
""
nil
(if my-minor-mode
(progn
;; do something when minor mode is on
)
;; do something when minor mode is off
)
But, another way to check it quickly would be to spawn a new Emacs from your existing one:
M-x shell-command emacs&
I just define a function called ldf (short for load-file) in my .emacs file,
like this:
(defun ldf (arg) (interactive "P") (load-file (buffer-file-name)))
As you can see, this little function looks up the filename of the current buffer and then loads the file. Whenever I need to reload the current buffer elisp file, just type "M-x ldf"