How to accomplish equivalent of Vim's Ctrl-n in GNU Emacs? - emacs

Vim's Ctrl+N generally works like this: I type few letters, hit Ctrl+N, and Vim provides me with completions based on words in my all opened buffers.
Solution for Emacs doesn't have to be identical. I mainly use it like this: declare variable, then use it in later code. But I like the lightweight approach of not parsing the source code.

You want dabbrev-expand, bound to M-/ by default. I haven't used Vim, but from your description, it does the exact same thing.

try hippie-expand, bound to your favorite key
(global-set-key (kbd "M-/") 'hippie-expand)
Instead of presenting a completion-list, repeatedly hitting the bound-key cycles through the completions in-place.
Why "hippie"-expand? I have no idea, and I actually avoided looking at the function because the name was uninformative and off-putting, until I read the write-up at 'Life Is Too Short For Bad Code'. (The EmacsWiki entry on hippie-expand also asks "why 'hippie?'" but can't answer it, either.)

I personally use AutoComplete It gives you a nice dropdown box. You can select how many letters you want to type before it activates and customise what you want to show up, including stuff in dabbrev-expand.

;; Allow tab to autocomplete
(defun indent-or-expand (arg)
"Either indent according to mode, or expand the word preceding point."
(interactive "*P")
(if (and
(or (bobp) (= ?w (char-syntax (char-before))))
(or (eobp) (not (= ?w (char-syntax (char-after))))))
(dabbrev-expand arg)
(tab-to-tab-stop)))
(defun my-tab-fix ()
(local-set-key [tab] 'indent-or-expand))
(add-hook 'as-mode-hook 'my-tab-fix)
(add-hook 'java-mode-hook 'my-tab-fix)
(add-hook 'c-mode-hook 'my-tab-fix)
(add-hook 'sh-mode-hook 'my-tab-fix)
(add-hook 'emacs-lisp-mode-hook 'my-tab-fix)

The matter, in my opinion is that emacs completion I tryed doesn't complete regarding the context.
For instance, if you write some OOP with a method foobar() and an argument foo, M-/ will suggest you both foo and foobar.
But it would be great if you are calling an object method, not to provide just "foo" completion.
Has anyone a solution?

Aif> This requires much more than what "hippie expand" has to offer. If you code C/C++ you COULD use ECB http://ecb.sourceforge.net/ but frankly, the project is quite dead and this addon is not very reliable. If you need really good intelligent completion you should try Eclipse (CDT). But if you code python then Emacs (rope + flymake) is just as fine as Eclipse (PyDev).

Related

Emacs/AUCTeX prefix arguments

In LaTeX mode C-c C-c is bound to:
(TeX-command-master &optional OVERRIDE-CONFIRM)
Normally this interactive function runs a command, perhaps a LaTeX compilation, asking for confirmation.
In tex-buf.el it reads:
If a prefix argument OVERRIDE-CONFIRM is given, confirmation will
depend on it being positive instead of the entry in `TeX-command-list'.
This is a bit cryptic for me and reading C-h v TeX-command-list didn't help.
How can I pass the prefix argument to "TeX-command-master" so that I avoid all the confirmation requests?
Take a look at Emacs' documentation to find out about prefix arguments. In general, you can pass a command a prefix argument with C-u followed by a number. For one-digit numbers, you can also just type Meta followed by the digit. Thus to pass a positive prefix argument to TeX-command-master you could type:
M-1 C-c C-c
However, this will actually add another minibuffer confirmation, namely about the shell command to be used to compile the LaTeX source. Without the prefix argument, a command-dependent default is used for that.
If you want to avoid the question about the command to use, you can bind the undocumented variable TeX-command-force to "LaTeX" via:
(setq TeX-command-force "LaTeX")
However, this will have the downside that you're basically binding C-c C-c to the "latex" command, you cannot use any of the other commands such as "bibtex" or "view".
Other than that, LaTeX-mode does not allow for any customization of C-c C-c. Your best options are to either advise the function TeX-command-query or to bind C-c C-c to a wrapper function to set TeX-command-force dynamically. The latter would probably be the preferred option if you also want to auto-save the buffer.
It seems that the mystery of the OVERRIDE-CONFIRM continues. In the meantime a fellow suggests that, if we are unable to manage TeX-command-master, we can simply rewrite it.
In my version, based on his, if the buffer is not modified, the external viewer is launched; if the buffer is modified the compiler is run.
Everything with no confirmation for saving or running the given command.
(defun my-run-latex ()
(interactive)
(if (buffer-modified-p)
(progn
(setq TeX-save-query nil)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
(TeX-view)))
Of course one can bind my-run-latex to whatever keybinding.
On the user's point of view this is a solution to my own question.
Do I click the close tag? Well, on the curious guy point of view I am still interested in understanding the mysterious TeX-command-master technicalities.
If someone should happen to know...
P.S.
Yes, TeX-save-query overrides the save-file request, also with TeX-command-master, that is C-c C-c. But you will still be asked to confirm the command action.
Build & view
Again, this solution, instead of modifying the behaviour of the TeX-command-master, rewrites it. The rewritten version of the command, named build-view, follows a rather straightforward logic.
If the LaTeX file buffer is not-modified, it runs the default viewer;
If the buffer is dirty, it runs the default LaTeX compiler and, after the build, opens the output in the default viewer.
Here's the code:
(defun build-view ()
(interactive)
(if (buffer-modified-p)
(progn
(let ((TeX-save-query nil))
(TeX-save-document (TeX-master-file)))
(setq build-proc (TeX-command "LaTeX" 'TeX-master-file -1))
(set-process-sentinel build-proc 'build-sentinel))
(TeX-view)))
(defun build-sentinel (process event)
(if (string= event "finished\n")
(TeX-view)
(message "Errors! Check with C-`")))
You can now type M-x build-view and start the told build-view process or associate it with a new keybinding such as “F2”:
(add-hook 'LaTeX-mode-hook '(lambda () (local-set-key (kbd "<f2>") 'build-view)))
Note: As suggested by Tyler, TeX-save-query variable is changed locally, therefore the old C-c C-c/ TeX-command-master is unaffected and will keep asking confirmations.
Do edit this code to make it better or easier to read!
I puzzled over the OVERRIDE-CONFIRM bit for a while, and couldn't figure out how it was supposed to work. If you want to automatically run Latex on your file, without being bothered about saving it first, or confirming that you want latex (rather than view, bibtex etc), you could use a function like this:
(defun my-run-latex ()
(interactive)
(TeX-save-document (TeX-master-file))
(TeX-command "LaTeX" 'TeX-master-file -1))
Bind this to something handy, and you'll still have C-c C-c for when you want to use the default processing commands. You may want to modify the TeX-command line if "Latex" isn't the processor you want to call.
If you are just looking to compile the latex source without a confirmation dialog, just add the following to your .emacs:
(setq TeX-command-force "")
You can then compile the source with C-c C-c and it won't ask to confirm. The only problem with this solution is that you can no longer change the command, but with most documents you won't want to. I might suggest that at the same time you can add this to your .emacs for even more flexibility, giving you a C-c C-c equivalent to the former behavior:
(define-key LaTeX-mode-map "\C-c\C-a"
;;; 'a' for ask, change to anything you want
(lambda (arg) (interactive "P")
(let ((TeX-command-force nil))
(TeX-command-master arg))))
You can then just work away at your document, do a C-x C-s, C-c C-c and then C-c C-v to see it. Like others have suggested you can also do the same for the save command and have it compile automatically on save, but some of my documents are in CVS and so I avoid putting hooks on that.
Credit to Ivan for some help on this one - don't know if he is on StackOverflow
I think the gist of this question is "how do I quickly compile my TeX document from AUCTeX without all the key presses and confirmations?"
My answer to that is to use the latexmk command rather than trying to coerce AUCTeX to do it.
latexmk -pdf -pvc myfile.tex
latexmk will monitor the file in question and rebuilt it as soon as you save it. If you use a good pdf viewer, it will notice the change in PDF and re-display it immediately. On OS X, skim works well for this.

Binding similar commands from different modes to the same key

I use emacs in multiple modes (ESS, Auctex, Slime, elisp, etc...) all using evil-mode key-bindings. Each of the interaction modes have similar functions for evaluating regions, lines or buffers that I have bound to shortcuts using spacebar as a prefix.
;; bind slime's eval and elisp eval to the key sequence "<SPC>e"
(evil-define-key 'normal lisp-mode-map (kbd "<SPC>e") 'slime-eval-last-expression)
(evil-define-key 'normal lisp-interaction-mode-map (kbd "<SPC>e") 'eval-last-sexp)
I would like to set a default key for a "type" of function, so that I don't need to have an entry like the above for every interaction mode I use and for every command. This would hopefully give a more readable .emacs init file and make it easier to change my key-bindings in the future.
I'm fairly sure that I could do this myself using a series of hooks, but I wonder if there is any existing or built-in support for this?
Thanks
tensorproduct
I don't know anything about Evil, so I'll give the normal Emacs solution:
(global-set-key [?\s ?e] #'my-eval-last-sexp)
(defvar my-eval-last-sexp-command #'undefined)
(defun my-eval-last-sexp ()
(interactive)
(call-interactively my-eval-last-sexp-command))
(add-hook 'emacs-lisp-mode-hook
(lambda () (set (make-local-variable 'my-eval-last-sexp-command) #'eval-last-sexp))
(add-hook 'lisp-mode-hook
(lambda () (set (make-local-variable 'my-eval-last-sexp-command) #'slime-eval-last-expression))
...
As you can see, there's only one mention of the key you want (in this case [?\s ?e]). But you don't save much on the amount of code you have to write. You might improve it by making my-eval-last-sexp a bit more complex (e.g. it could try to guess the command name from the major mode name), or by replacing the hook function with a global alist.
Hopefully, in some future Emacs, all such source-code modes that interact with some interpreter/compiler will share more of their code so that your problem will simply disappear.

Dynamically show/hide menu bar in Emacs

I have menu-bar-open bound on f11 and menu-bar turned off, and because of that, f11 calls tmm-menubar, which is inconvenient and doesn't have mode-specific menu items for some reason (like org and tbl in org-mode). I want it to behave this way: make menu-bar visible, enable user to choose menu item, after that make menu-bar invisible again.
What is the most idiomatic and elegant way to to that?
I thought on writing advices, but Emacs developers usually recommend against it, as it causes problems for debug, and standard Emacs code does not include advices.
I use Emacs 24.1 in GUI.
In Emacs-24 you can simply do this:
(global-set-key [f9] 'toggle-menu-bar-mode-from-frame)
Not sure about versions of Emacs older than 24.
Just be sure that f9 is really available in your installation.
If you're running a graphical Emacs session with menu-bar-mode disabled, then C-<mouse-3> should bring up the entire contents of the menu as a popup dialogue box. If you're running Emacs in a terminal, however, this definitely won't work; you haven't specified which is the case, so I'll try not to make assumptions. It's also possible to create custom mouse bindings (optionally, with keyboard modifiers) to the mouse-popup-menubar and/or mouse-popup-menubar-stuff functions, but ultimately that would only enable you to replicate behavior similar to the standard functionality that I've described above.
Due to the somewhat inflexible and global nature of menu-bar-mode (i.e., the fact that it applies across all Emacs frames and provides for relatively little customization via hooks, etc.), I think it would be very difficult to achieve precisely the behavior you desire with vanilla Emacs. It might be possible to write a custom function to temporarily enable menu-bar-mode and then use something like post-command-hook to disable it again after a selection is made, but I'm not certain. I'll try to investigate further if time allows.
Also, you might wish to look into third-party menu-bar packages, (q.v., the Menu Bar section of EmacsWiki).
Edit: I've hacked together a rather kludgy solution that you may find useful...
(add-hook
'pre-command-hook
(lambda ()
(when (eq menu-bar-mode 42)
(menu-bar-mode -1))))
(defun my-menu-bar-open ()
(interactive)
(unless menu-bar-mode
(menu-bar-mode 1))
(menu-bar-open)
(setq menu-bar-mode 42))
I've tested this in a graphical session and it appears to simulate the behavior that you wanted, as long as you don't perform any action that Emacs registers as a command between executing my-menu-bar-open and making your selection (which is basically anything other than navigating the menu itself). The choice of 42 is a magic number (and a Douglas Adams homage) intended to minimize the risk that the hook function would be activated for more typical values of the menu-bar-mode variable. I don't claim that this is in any way elegant, but, in its decidedly ugly way, it does work. If you decide to use this, simply bind my-menu-bar-open to f11 (or whatever you prefer), i.e.:
(global-set-key [f11] 'my-menu-bar-open)
Alternatively, you can probably achieve very similar functionality by using pre-command-hook in an analogous fashion and instead advising menu-bar-open to perform a temporary toggle of menu-bar-mode.
A small improvement to Greg's answer, which keeps pre-command-hook clean:
(menu-bar-mode -1)
(defun my-menu-bar-open-after ()
(remove-hook 'pre-command-hook 'my-menu-bar-open-after)
(when (eq menu-bar-mode 42)
(menu-bar-mode -1)))
(defun my-menu-bar-open (&rest args)
(interactive)
(let ((open menu-bar-mode))
(unless open
(menu-bar-mode 1))
(funcall 'menu-bar-open args)
(unless open
(setq menu-bar-mode 42)
(add-hook 'pre-command-hook 'my-menu-bar-open-after))))
(global-set-key [f10] 'my-menu-bar-open)
I have tested this in GNU Emacs 25.2 and 26.3:
(menu-bar-mode -1)
(advice-add 'menu-bar-open
:around
(lambda (orig-fun &rest args)
(menu-bar-mode 1)
(apply orig-fun args)
(menu-bar-mode -1)))
Resulting behaviour (assuming that menu-bar-open is bound to F10, which is the default):
The menu bar is not shown by default.
If you press F10, the menu bar will be shown.
Once you leave the menu bar, the menu bar will be gone until the next time you press F10.
Note that this is more like a hack than a proper solution.

How to minify .emacs configuration file?

I was wondering if anyone can provide me with some help on minifying my .emacs file.
Currently I have it set up where each language I use have a custom tab, for example, if I have a hook for Java, it would look like this.
;; Java Hook
(defun e-java-mode-hook ()
(setq tab-width 4)
(setq indent-tabs-mode t)
(define-key java-mode-map (kbd "") 'java-insert-tab))
(defun java-insert-tab (&optional arg)
(interactive "P")
(insert-tab arg))
(add-hook 'java-mode-hook 'e-java-mode-hook)
And if I were to add another language like CSS or JavaScript, I would add another hook for CSS and another hook for JavaScript. So I was wondering if there's a global way of setting it so it would apply to any and all language?
I am currently running GNU Emacs 23.2.1 on Windows 7.
I agree with Tyler; although it's a bit complicated, you would be better off in the long run if you try to understand and customize the default indentation features. The Emacs Wiki has good resources, and there are other relevant Q&As here on Stack Overflow.
Binding the tab key to insert-tab means you completely lose the benefit of the likes of indent-region, and any other intelligent behaviour that a major mode might offer.
To address your specific questions regardless, however:
1) If you are defining (java-insert-tab) and (css-insert-tab) and (javascript-insert-tab) etc, and they all do exactly the same thing... well, hopefully you can see that you don't actually need more than one of those functions. Just give it a more generic name, and re-use it.
2) (local-set-key ...) does the same thing as (define-key (current-local-map) ...), which means you can also have a single generic function to override the tab keybinding, regardless of the major mode.
(defun my-coding-config ()
(setq tab-width 4)
(setq indent-tabs-mode t)
(local-set-key (kbd "<tab>") 'my-insert-tab))
(defun my-insert-tab (&optional arg)
(interactive "P")
(insert-tab arg))
Then you just need to add my-coding-config to each applicable mode hook variable. If there are a lot of them, you might wrap it up in a list like this:
;; Use my coding hook for all programming modes
(mapcar
(lambda (language-mode-hook)
(add-hook language-mode-hook 'my-coding-config))
'(java-mode-hook
javascript-mode-hook
css-mode-hook
...))
3) If you look at C-h v tab-width RET and likewise for indent-tabs-mode, you'll notice that they both say "Automatically becomes buffer-local when set in any fashion."
As an alternative to the customize interface already mentioned, you can use (set-default 'indent-tabs-mode t) to establish the default value for such variables. In the absence of code which sets a buffer-local value, all of your buffers will use the default, which might help you to avoid writing unnecessary mode hooks.
I'm not sure what you're trying to do. If you want to set the tab-width to 4 spaces globally, then you can do that using the customize command:
M-x customize-variable tab-width <ret>
Any changes you make to tab-width in customize will be applied globally. So you won't need to set it individually for each mode with hooks.
If you have different settings you want to apply to different modes, you will necessarily have to have code specific for each mode in your .emacs.
More generally, it looks like you're trying to build your own custom tab insertion commands - does the built-in indentation not do what you need? I think it will be easier to customize the indentation settings in Emacs than to manually insert tabs where you want them.
If you haven't already, take a look at the manual section on indentation and see if you might be able to do what you need without a lot of extra hooks:
C-h r m Indentation
(that is: h-elp, r-ead the manual, m-enu item Indentation)
or:
(info "(emacs)Indentation")
espect.el is doing exactly what you want.
From the docs:
This mode makes it easy to configure settings for individual
buffers with a concice and extensible mini-language. It abstracts
away common configuration selection tasks, like checking the mode
or filename, into a simple declarative syntax. Declare conditions;
run a function when the new buffer matches them. This makes it
easy to do things like turn on flyspell-prog-mode for your favorite
programming languages, or make all text-mode buffers ending in .mkn
have special properties.

Globally override key binding in Emacs

How can I set a key binding that globally overrides and takes precedence over all other bindings for that key? I want to override all major/minor mode maps and make sure my binding is always in effect.
This of course doesn't work:
(global-set-key "\C-i" 'some-function)
It works in text-mode, but when I use lisp-mode, C-i is rebound to lisp-indent-line.
I can go through and override this binding in lisp-mode and in every other mode individually, but there must be an easier way. Every time I install a new mode for a new file type, I'd have to go back and check to make sure that all of my key bindings aren't being overridden by the new mode.
I want to do this because I want to emulate bindings I've already learned and ingrained from other editors.
I use a minor mode for all my "override" key bindings:
(defvar my-keys-minor-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-i") 'some-function)
map)
"my-keys-minor-mode keymap.")
(define-minor-mode my-keys-minor-mode
"A minor mode so that my key settings override annoying major modes."
:init-value t
:lighter " my-keys")
(my-keys-minor-mode 1)
This has the added benefit of being able to turn off all my modifications in one fell swoop (just disable the minor mode) in case someone else is driving the keyboard or if I need to see what a default key binding does.
Note that you may need to turn this off in the minibuffer:
(defun my-minibuffer-setup-hook ()
(my-keys-minor-mode 0))
(add-hook 'minibuffer-setup-hook 'my-minibuffer-setup-hook)
As an addition to scottfrazer's answer, I've written the following so that my keybindings retain precedence, even if subsequently-loaded libraries bring in new keymaps of their own.
Because keymaps can be generated at compile time, load seemed like the best place to do this.
(add-hook 'after-load-functions 'my-keys-have-priority)
(defun my-keys-have-priority (_file)
"Try to ensure that my keybindings retain priority over other minor modes.
Called via the `after-load-functions' special hook."
(unless (eq (caar minor-mode-map-alist) 'my-keys-minor-mode)
(let ((mykeys (assq 'my-keys-minor-mode minor-mode-map-alist)))
(assq-delete-all 'my-keys-minor-mode minor-mode-map-alist)
(add-to-list 'minor-mode-map-alist mykeys))))
Install use-package, eval and you're done:
(require 'bind-key)
(bind-key* "C-i" 'some-function)
I found this question while searching for "emacs undefine org mode keybindings", because I wanted to unbind the existing C-c C-b behavior to allow my global map to bury-buffer to work in an org buffer.
This ended up being the simplest solution for me:
(add-hook 'org-mode-hook
(lambda ()
(local-unset-key (kbd "C-c C-b"))))
Although scottfrazer's answer is exactly what you asked for, I will mention for posterity another solution.
From The Emacs Manual:
"Don't define C-c letter as a key in Lisp programs. Sequences consisting of C-c and a letter (either upper or lower case) are reserved for users; they are the only sequences reserved for users, so do not block them."
If you bind your personal global bindings to C-c plus a letter, then you "should" be safe. However, this is merely a convention, and any mode is still able to override your bindings.
If you want to "always use the keybinds in the map, unless I explicitly override them for a specific mode-map", and assuming you are using scottfrazier's approach, you want:
(defun locally-override (key cmd)
(unless (local-variable-p 'my-keys-minor-mode-map)
(set (make-variable-buffer-local 'my-keys-minor-mode-map)
(make-sparse-keymap))
(set-keymap-parent my-keys-minor-mode-map
(default-value 'my-keys-minor-mode-map)))
(define-key my-keys-minor-mode-map key cmd))
So
(locally-override "\C-i" nil)
should remove the "\C-i" binding from the minor mode in the current buffer only. Warning: this is completely untested, but seems like the right approach. The point of setting the parent rather than just coping the global value of my-keys-minor-mode-map is so any later changes to the global value are automatically reflected in the local value.
I don't think you can. That is roughly equivalent to saying that you want to define a global variable that cannot be hidden by local variable declarations in functions. Scope just doesn't work that way.
However, there might be a way to write an elisp function to go through the mode list and reassign it in every single one for you.
Unless you really want to do this yourself, you should check around and see if anyone else already has done it.
There is a package for Emacs which gives your windows-like keybindings. You should be able to find it through google.