Prevent completing-read from exiting with nil - emacs

I'm reading the documentation on completing-read, but I can't find a way to do what I need.
It says that:
(completing-read PROMPT COLLECTION &optional PREDICATE REQUIRE-MATCH
INITIAL-INPUT HIST DEF INHERIT-INPUT-METHOD)
. . .
REQUIRE-MATCH can take the following values:
- t means that the user is not allowed to exit unless the input is (or completes to) an element of COLLECTION or is null.
- nil means that the user can exit with any input.
- `confirm' means that the user can exit with any input, but she needs to confirm her choice if the input is not an element of COLLECTION.
- `confirm-after-completion' means that the user can exit with any input, but she needs to confirm her choice if she called
`minibuffer-complete' right before `minibuffer-complete-and-exit'
and the input is not an element of COLLECTION.
- anything else behaves like t except that typing RET does not exit if it does non-null completion.
What I need to do is something like:
(completing-read "What kind of project should I create? "
haxe-project-kinds
(lambda (x) (message "predicate: %s" x)) t)
This shouldn't return nil, because if it does, it's an error - but I don't want to run the user through all other options until she discovers that she got the very first one wrong.
More than that, the behaviour advertised in the documentation doesn't match what really happens. It makes absolutely no difference what I put in the 4'th argument's position, the behaviour is unchanged.

I'm not sure exactly which part of what you want is not satisfied by your sample code, so it's hard to give a good answer. My guess is that you want to prevent the user from hitting RET with an empty answer. Indeed completing-read does not prevent that, even with require-match set. The way this is usually handled is by using a non-nil value for the default argument, in which case this value is returned when the user just hits RET.
If that's not good enough, then you're probably going to have to use minibiffer-with-setup-hook and in the hook, setup a special keymap you've created for this purpose where RET is bound to a new function that signals an error if the minibuffer is empty and calls minibuffer-complete-and-exit otherwise.

Related

Avoid accidental execution in comint mode

Sometimes when in comint mode the point is anywhere in the buffer and I press Return by mistake. This sends the text at point to the underlying process, which can be really dangerous. Often this text contains many lines and, by chance or not, one of them could be a valid command.
Is there any way to tell comint not to execute anything on Return except the last input?
The documented way seems to be override comint-get-old-input variable with a custom function. Easiest will be something like this:
(setq comint-get-old-input (lambda () (end-of-buffer) (comint-get-old-input-default)))
It goes to the end of buffer first, and only then calls coming-get-olt-input-default, effectively not messing with the previous output. Put it in your init.el, brief testing shows that it works.

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.

How to completely erase Emacs Calc's state?

This has got to be a stupid simple question, but I haven't been able to find an answer despite searching Google multiple times in multiple ways, and digging through the Calc documentation.
GIVEN an instance of Emacs, with Calc running, and having performed multiple calculations including storing variables and equations, some of which may have come from the "~/.emacs.d/calc.el" file,
HOW do you return Calc to a pristine state without restarting Emacs?
Pristine: Nothing on the stack. Nothing in the trail. No stored variables or equations. Etc.
M-x calc-reset, which is also bound to C-x * 0, is what you need. From the info manual:
The C-x * 0' command ('calc-reset'; that's 'C-x *' followed by a
zero) resets the Calculator to its initial state. This clears the
stack, resets all the modes to their initial values (the values that
were saved withm m' (calc-save-modes')), clears the caches (*note
Caches::), and so on. (It does _not_ erase the values of any
variables.) With an argument of 0, Calc will be reset to its default
state; namely, the modes will be given their default values. With a
positive prefix argument,C-x * 0' preserves the contents of the stack
but resets everything else to its initial state; with a negative prefix
argument, `C-x * 0' preserves the contents of the stack but resets
everything else to its default state.
EDIT: Oops. Even that doesn't clear variables. I'm not sure if there is a straightforward way to get all the way back to pristine :(
EDIT 2: It looks like Calc stores all variables, including 'built-ins' like pi and e, as global variables with the prefix 'var-'. As far as I can tell, it doesn't keep track of which variables were set by the mode (like pi), and which were set by users. Furthermore, the default user variables are stored as var-q0, var-q1 etc. So in order to clear out all the variables, you'd need to compile a list of variables and states present at startup, erase everything not in that list, and then restore the original values of the variables in that list. That's certainly possible, but a little tedious.
Edit 3: Here's my attempt. I took another look at calc-mode, and at start up it defines the variables I've added to my-calc-builtin-vars below. The second line will remove all variables in Emacs that start with the prefix 'var-' and are not in this list. This will include any variables defined by you, or in another package. So let's hope no-one else uses the prefix 'var-'. And it will not reset the value of the built-in variables, so if you have redefined pi to 3, it will remain 3.
(setq my-calc-builtin-vars
'("var-nan" "var-uinf" "var-sym" "var-lines" "var-Modes"
"var-EvalRules" "var-inf" "var-phi" "var-pi" "var-gamma" "var-π"
"var-φ" "var-γ" "var-spec" "var-e" "var-i"))
(defun really-reset-calc ()
(interactive)
(calc-reset nil)
(mapc #'(lambda (el) (unintern el))
(remove nil (mapcar
#'(lambda (el) (unless (member el my-calc-builtin-vars) el))
(all-completions "var-" obarray)))))
UPDATE: August 6, 2016
Current built-in vars list:
(setq my-calc-builtin-vars
'("var-CommuteRules" "var-Decls" "var-DistribRules" "var-EvalRules"
"var-FactorRules" "var-FitRules" "var-Holidays" "var-IntegAfterRules"
"var-IntegLimit" "var-InvertRules" "var-JumpRules" "var-MergeRules"
"var-Modes" "var-NegateRules" "var-e" "var-gamma" "var-i" "var-phi"
"var-pi" "var-γ" "var-π" "var-φ"))
M-# 0
That should be all you need to do.

Lisp: creating a macro to cycle through a created list per document

Let's say I want to create a new document, and cycle quickly through a list.
If it's only for one "word", I think there should be a general way to do this.
For instance:
"blue orange red yellow black white"
Does anyone know a way how to cycle through those items when I create:
\begin{orange}
... and I want to press a key to cycle through this list, replacing orange with the next item on the list (doing this procedure in the opposite direction wouldn't be hard then)?
I tried many different ideas with macro's (placing the list on the top of the document, and doing a whole bunch of i-searches), but that doesn't cut it.
I'd be willing to put the list in an elisp file, though I have no clue how to use that variable from elisp in, let's say, a LaTeX document (.tex).
Well, this might be possible, but depends on how much effort you are willing to put into writing eLisp code to make it work. It's not possible by just some configuration option. I would be looking into extending autocomplete by adding new sources to it, something like:
(defvar tex-tag-ac-sources
'((init . tex-tag-ac-init)
(requires . 0)
(candidates . tex-tag-ac-candidates)
(document . tex-tag-ac-documentation)
(match . tex-tag-completion-filter)
(prefix . tex-tag-ac-prefix-matcher)
(symbol . "s"))
"The source generator for autocompletion needed for interaction
with auto-complete")
Where tex-tag-ac-candidates, tex-tag-ac-documentation, tex-tag-completion-filter and tex-tag-ac-prefix-matcher are function that do autocompletion. I.e. init function is called once when the autocompletion process starts for a specified prefix. It's called w/o arguments. The candidates is the function that is responsible for showing the filtered list of candidates, it's called w/o arguments, you would filter the candidates in the filter function, it is called with the prefix collected so far and the list of candidates so far. Lastly, the matcher function is invoked on the text of the file to see if the completion is needed at point. So, if it returns t, the init is called, and then loops through filter-candidates as you type.
While this is a bit involved... you'd definitely have a completion for anything you want. Obviously, if those functions in source are defined by you, then, if you wanted to, you could read completion arguments dynamically or have them generated dynamically in some way.
Ah, you would add the sources to autocomplete by something like:
(auto-complete (list tex-tag-ac-sources))
if doing it on per call basis, or
(setq ac-sources (list tex-tag-ac-sources <other sources>))
You can find more info here: http://cx4a.org/software/auto-complete/manual.html#Using_Source
EDIT: I translated the macro into a function.
Here is a way I did it. I created a file called "list.list" where my "lists" are saved. I saved the LaTeX templates for Beamer in there. I inserted them like this:
Antibes Bergen Berkeley Berlin ..... Antibes
Note that you should always put the first entry in twice to allow it to loop.
Here is the code:
(defun cycle-list-word ()
(interactive)
(right-word)
(backward-kill-word 1)
(find-file "/emacs-24.1/list.list")
(search-forward (substring-no-properties (car kill-ring)) nil t)
(right-word)
(backward-kill-word 1)
(bury-buffer)
(yank)
)

How can I filter compilation output only for a specific mode or buffer in Emacs?

I have a HTML page, with html-mode enabled. I call function sgml-validate to check for any markup errors. It's based on compilation-mode. I want to remove some warnings from the compilation output, so I wrote a function and hooked it to compilation-filter-hook (this variable is not documented, but compilation-filter invokes it). Everything works. My problem is that how can I ensure my filter function only gets called when I started the compilation process on a HTML page (via sgml-validate)?
I see two methods, but none of them worked:
First, I can check the value of major-mode. But it always returns compilation-mode, since that is enabled on the *compilation* buffer. (I found a filter function in the source code of grep+, and they did check the value of major-mode. I can't figure out how can it work correctly.)
The other idea was than to only hook my filter function to the HTML file's buffer, but for similar reasons it couldn't work as the output of compilation process goes to a seperate buffer.
It sounds like you can advise smgl-validate so that it performs the filtering before it performs all it's other operations. For example:
(defadvice sgml-validate (around fix-filtering command activate)
(let ((return-value ad-do-it))
(filter-function return-value))))
Meanwhile, I found that compilation-start accepts an optional argument mode, which will be the major mode for the compilation buffer. So I can create a major mode derived from compilation-mode, and define there my filter function now hooked to the proper buffer.
The only problem is now that sgml-validate does not allow me to set the mode argument on compilation-start, but that's another question.
(I don't consider this the ultimate solution, of course.)