indent-[code-]rigidly called from emacs LISP function - emacs

I'm trying to write an emacs LISP function to un-indent the region
(rigidly). I can pass prefix arguments to indent-code-rigidly or
indent-rigidly or indent-region and they all work fine, but I don't
want to always have to pass a negative prefix argument to shift things
left.
My current code is as below but it seems to do nothing:
(defun undent ()
"un-indent rigidly."
(interactive)
(list
(setq fline (line-number-at-pos (region-beginning)))
(setq lline (line-number-at-pos (region-end)))
(setq curIndent (current-indentation))
;;(indent-rigidly fline lline (- curIndent 1))
(indent-region fline lline 2)
;;(message "%d %d" curIndent (- curIndent 1))
)
)
I gather that (current-indentation) won't get me the indentation of the first line
of the region, but of the first line following the region (so a second quesiton is
how to get that!). But even when I just use a constant for the column (as shown,
I don't see this function do any change.
Though if I uncomment the (message) call, it displays reasonable numbers.
GNU Emacs 24.3.1, on Ubuntu. And in case it matters, I use
(setq-default indent-tabs-mode nil) and (cua-mode).
I must be missing something obvious... ?

All of what Tim X said is true, but if you just need something that works, or an example to show you what direction to take your own code, I think you're looking for something like this:
(defun unindent-rigidly (start end arg &optional interactive)
"As `indent-rigidly', but reversed."
(interactive "r\np\np")
(indent-rigidly start end (- arg) interactive))
All this does is call indent-rigidly with an appropriately transformed prefix argument. If you call this with a prefix argument n, it will act as if you had called indent-rigidly with the argument -n. If you omit the prefix argument, it will behave as if you called indent-rigidly with the argument -1 (instead of going into indent-rigidly's interactive mode).

There are a number of problems with your function, including some vary
fundamental elisp requirements. Highly recommend reading the Emacs Lisp
Reference Manual (bundled with emacs). If you are new to programming and lisp,
you may also find An Introduction to Emacs Lisp useful (also bundled with
Emacs).
A few things to read about which will probably help
Read the section on the command loop from the elisp reference. In particular,
look at the node which describes how to define a new command and the use of
'interactive', which you will need if you want to bind your function to a key
or call it with M-x.
Read the section on variables from the lisp reference
and understand variable scope (local v global). Look at using 'let' rather
than 'setq' and what the difference is.
Read the section on 'positions' in the elisp reference. In particular, look at
'save-excursion' and 'save-restriction'. Understanding how to define and use
the region is also important.
It isn't clear if your writing this function just as a learning exercise or
not. However, just in case you are doing it because it is something you need to
do rather than just something to learn elisp, be sure to go through the Emacs
manual and index. What you appear to need is a common and fairly well supported
requirement. It can get a little complicated if programming modes are involved
(as opposed to plain text). However, with emacs, if what you need seems like
something which would be a common requirement, you can be fairly confident it is
already there - you just need to find it (which can be a challenge at first).
A common convention is for functions/commands to be defined which act 'in
reverse' when supplied with a negative or universal argument. Any command which
has this ability can also be called as a function in elisp code with the
argument necessary to get that behaviour, so understanding the inter-play
between commands, functions and calling conventions is important.

Related

Can Lisp's macro system also extend its commenting syntax?

I love Racket's #;. I want to see it in every language that I ever use again. Can it be added to other Lisps via their macro systems? Or does the commenting character break the macro system's ability to read the code?
A sufficient answer will demonstrate a macro being built in any Lisp other than Racket that allows for a change in the commenting system. You need not actually implement Racket's #;, but I would like it if you do. Lisps with the least similarity to Racket, e.g. Clojure or any non-Scheme will be particularity nice to see.
#; isn't a macro, it's what Common lisp would call a readmacro: what it does is defined at read time, not later than that. Read macros which aim to completely suppress input are mildly perilous because there needs to be a way of saying 'read the following thing, but ignore it', and that's only possible if any other readmacros behave well: there's nothing to stop someone defining a readmacro which produces some side-effect even if reading is suppressed.
However, well-behaved readmacros (which includes all of the standard ones and the rest of the standard reader) in CL won't do that: they'll listen to whether reading is being suppressed, and behave accordingly.
CL allows you to do this as standard by using its conditionalisation on features, and in particular #+(or) <expr> will always skip <expr>.
But you can define your own: #; is not predefined so you can define it:
(set-dispatch-macro-character
#\# #\;
(lambda (stream char n)
(declare (ignore char))
(let ((*read-suppress* t))
(dotimes (i (or n 1) (values))
(read stream)))))
After this, or at least with a better tested version of this, then #; <expr> (or obviously #;<expr>) will read as whitespace, and #2; ... ... will skip two following expressions:
> (let ((x #;1 #2; 2 3 4)) x)
4
What you are looking for is #+(or) reader macro.
Since (or) evaluates to nil, the condition is always false the following form is never evaluated.

How to toggle between indentations on emacs?

emacs n00b here.
I face this problem at least once a week, I have a function call with its arguments one per line, but I'd like to reformat that such that all the arguments go to one line, i.e. I want to go from:
f(
x,
y,
z
);
to:
f(x, y, z);
what's the best way to do that?
In general, a simple approach to custom reformatting requirements is to create a keyboard macro which does the required editing in a generic way.
Abilities like moving across sexps & balanced expressions, searching and replacing within regions, and narrowing and widening the buffer all make this sort of thing pretty straightforward.
You can then give the macro a name, output its definition into your init file, and bind it to a key for future usage, all with no elisp knowledge required.
C-hig (emacs) Keyboard Macros RET
Edit: (for "Emacs n00bs" everywhere).
DO learn how to use keyboard macros. The learning curve is pretty shallow1, and they will pay amazing dividends in the long term.
Once you've learned how they work, force yourself to use them: Whenever you encounter a problem, say to yourself "Can I do this with a keyboard macro?" and if you think the answer is yes, then give it a try.
If you don't make yourself use them to begin with, you probably won't often think about them when use-cases crop up; but once they're a familiar part of your tool kit you'll find yourself using them very regularly.
1 Shallow, but probably longer than you expect, as you gradually come to realise just how much you can actually accomplish with the things. My own moment of clarity came when it occurred to me that I wasn't restricted to a single buffer, and correlating/extracting/transforming data from multiple buffers was something I could automate easily.
And of course macros can do anything that you can do, so their power grows with your own knowledge of Emacs.
Well, I doubt that it is the best way to do it but I wrote a function anyways. So here it goes:
(defun format-args-column-to-inline()
"Takes a c-style function whose arguments listed one per line and puts them inline."
(interactive)
(beginning-of-line 1)
(re-search-forward "(")
(forward-char -1)
(let ((start (point)))
(save-restriction
(save-excursion
(forward-sexp 1)
(narrow-to-region start (point)))
(while (re-search-forward "$")
(progn
(delete-forward-char 1)
(just-one-space 1))))))
Put your cursor somewhere in the first line and call the function.
Edit: Just saw that you wanted something slightly different. The output of this function is f( x, y, z ); [note the trailing and leading space of the argument list].

Why is "goto-line" in Emacs for interactive use only?

What problem can happen if the goto-line function is used in a non-interactive elisp program? Its docstring gives a warning saying that:
This function is usually the wrong thing to use in a Lisp program.
What you probably want instead is something like:
(goto-char (point-min)) (forward-line (1- N))
Moreover, when I try to byte-compile-file my init file including goto-line, I get a unpleasant warning like this once again:
.emacs:170:19:Warning: `goto-line' used from Lisp code
That command is designed for interactive use only
Is using goto-line in a non-interactive program really so dangerous? Relatedly, why is the suggested forward-line solution preferable?
Firstly, this prevents Elisp programmers from fall into bad habits -- writing
inefficient code in a line-number centric way. i.e. instead of using
(forward-line 1) calculating the current line number, incrementing, and using
goto-line.
From this mailing list article:
In a nutshell, the reason why goto-line should not be a frequently
used command is that normally there's no reason to want to get to line
number N unless you have a program that told you there's something
interesting on that line.
Secondly, goto-line manipulates the user's environment in addition to moving
the point (i.e. push-mark). For non-interactive use, this may not be what
you want. On the other hand if having considered all this, you believe
goto-line is exactly what you need, then just call it like this:
(defun foo ()
(interactive)
(with-no-warnings
(goto-line N)))
And you won't get any compiler warnings.
in addition to what was said:
"goto-line" finally recurs onto "(forward-line (1- line)", which in effect does the work. All other of the 43 lines of "goto-line" command body deal with interactive use. For example considering a possibly universal argument.
When writing a program resp. when running it, your computer is in another state than following an interactive call. Thus you should address this state by using "forward-line" straight on.

How to call interactive Emacs Lisp function with a prefix argument, from another Emacs Lisp function?

I want to write an Emacs Lisp function that will turn on flyspell-mode regardless of the current state of the mode. Function flyspell-mode-on is deprecated. The documentation suggests that a positive prefix argument will turn flyspell-mode, but unfortunately running
(flyspell-mode 1)
results in an error message:
Wrong number of arguments: (lambda (flyspell-mode 1)), 0
If I could figure out how to call flyspell-mode with a prefix argument, I believe I could solve this problem.
The most relevant section I can find in the Emacs Lisp manual is the section entitled "Interactive Call", which describes such commands as call-interactively. This is emphatically not what I want.
(The ultimate problem I am trying to solve is to create a mode hook that turns on the mode regardless of its current state.)
N.B. The title of the question emacs lisp call function with prefix argument programmatically makes it appear to be related, but that question was asking about how to create an interactive command, and the issue was ultimately resolved by using call-interactively.
EDIT: This question is moot; I have found an alternate solution to my original problem:
(add-hook 'text-mode-hook
(function (lambda ()
(require 'flyspell)
(if flyspell-mode nil (flyspell-mode)))))
But I would still like to know how to call an Emacs Lisp function with a prefix argument, from another Emacs Lisp function, with nothing interactive.
UPDATE: Perhaps I should have asked why I was getting that error message...
It looks like your version of Flyspell mode does not follow the minor mode conventions, which require that you can turn on a minor mode with (name-of-mode t) or any positive prefix argument, turn it off with (name-of-mode 0) any negative prefix argument, and toggle it with (name-of-mode nil).
If you have the latest version of Flyspell, a bug report might be in order. I have the version shipped with GNU Emacs 23.2 on my machine, and it respects the convention. My version also defines two functions turn-on-flyspell and turn-off-flyspell, both trivial wrappers around flyspell-mode; functions with such names are common, but not official conventions. The functions flyspell-mode-on and flyspell-mode-off are apparently intended for internal use.
As a general matter, commands read the current prefix argument from the current-prefix-arg variable. Don't confuse that with prefix-arg, which is the value for the next command (only a few commands like universal-argument touch this variable). Thus, if you need to pass a prefix argument when calling a function, bind or set current-prefix-arg.
(let ((current-prefix-arg t))
(flyspell-mode))
If you are not calling a function interactively, then the (interactive) declaration is not used to obtain the arguments.
In the vast majority of cases, you do not need to worry about whether an argument can be a "prefix argument" for non-interactive calls; just check the function documentation, and pass the value you need for whatever it is you want to do.
If for some reason you do need to replicate sending a prefix argument in a non-interactive context, you will need to check that function's (interactive) declaration and determine exactly how it is using that argument, and ensure that you replicate that behaviour for the argument you do pass.
For full details, see:
C-hf interactive RET
M-: (info "(elisp) Prefix Command Arguments") RET
In more complex cases where the function changes its behaviour based on the current-prefix-arg variable, you may be able to set that variable directly.
(let ((current-prefix-arg '(4)))
(foo current-prefix-arg))
I can think of this.. Should be more better
(call-interactively (lambda ()
(interactive)
(flyspell-mode '(4))))
UPDATE:
I can run this directly.. what am i missing from the question.?
(flyspell-mode '(4))
EDITED: Removed quote for lambda expression (I added this note because SX forces an edit to be at least six characters long, so this can be deleted).
FWIW, the `flyspell-mode' function has accepted an argument (as in "(flyspell-mode 1)") at least since Emacs-21, so I don't know how you got that error.
But while I'm here, I might as well point out that (add-hook 'text-mode-hook 'flyspell-mode) has changed meaning in Emacs-24: instead of meaning "toggle flyspell-mode in text modes" it will now mean "enable flyspell-mode in text modes". It's a backward-incompatible change, but I believe it will fix more latent bugs than it will introduce.
See my comment for the fix to the source of your problem. As for the answer to your question, the way the prefix arg is turned into some kind of Lisp argument depends on the interactive spec, so the only way to do it reliably (i.e. without prior knowledge such as the fact that it's a minor mode function) is to call the function interactively:
(let ((current-prefix-arg '(4)))
(call-interactively 'flyspell-mode))
I'm not Emacs and Elisp master (yet ;)) but I think in this case you may use Ctrl-u 1 Alt-x flyspell-mode.

How to make flyspell bypass some words by context?

I use Emacs for writing most of my writings. I write using reStructuredText, and then transform them to LaTeX after some preprocessing since I write my citations รก-la LaTeX. This is an excerpt of one of my texts (in Spanish):
En \cite[pp.~XXVIII--XXIX]{Crnkovic2002} se brindan algunos riesgos
que se pueden asumir con el desarrollo basado en componentes, los
This text is processed by some custom scripts that deals with the \cite part so rst2latex can do its job.
When I activate flyspell-mode it signals most of the citation keys as spelling errors.
How can I tell flyspell not to spellcheck things within \cite commands.
Furthermore, how can I combine rst-mode and flyspell, so that rst-mode would keep flyspell from spellchecking the following?
reST comments
reST code literal
reST directive parameters and arguments
reST raw directive contents
Any ideas?
You can set the variable ispell-parser to the value 'tex so that flyspell will ignore (la)tex sequences. To do so, you can either set it manually in each buffer like so:
M-: (setq 'ispell-parser 'tex)
or you write a little function that will do that for you. Put the following in your .emacs file:
(defun flyspell-ignore-tex ()
(interactive)
(set (make-variable-buffer-local 'ispell-parser) 'tex))
Then you can still invoke it manually, using
M-x flyspell-ignore-tex
or you could add a hook that calls that function automatically whenever you edit a file of a certain type. You would do the latter by adding the newly defined function to your auto-mode-alist. Say your filenames typically end with ".rst", then add this line to your .emacs file:
(add-to-list 'auto-mode-alist '("\\.rst$" . flyspell-ignore-tex))
As for the second part of your question: making flyspell-mode ignore larger regions, such as, e.g., reST comments, is not easily achievable. It becomes clear when you think about the way flyspell works: it checks text on a word-by-word basis. For that, flyspell-word only looks at one word at a time which it sends to an ispell process running in the background. The ispell process does the dictionary lookup and returns whether or not the current word is correct. If flyspell-word had to check every single time whether or not the current word is part of a comment or other region that should not be checked, it would be rather slow, because that would include quite a bit of searching through the buffer.
Now of course, one could approach this a little bit smarter and first find the non-comment regions etc. and then do the word-by-word checking only in those parts that are outside of those regions - but unfortunately, that's not the way flyspell is implemented.
If you can do without the "fly" part, however, ispell-mode has a mechanism to customize which regions of a buffer can be skipped. This is done via the variable ispell-skip-region-alist. But although flyspell-mode works off ispell-mode, for the reasons outlined above that variable is not used by flyspell-mode.
You can also use flyspell-generic-check-word-predicate as I explained in this question at Super User.
(aspell's tex filter may do exactly what you want - but if you want a more general solution)
Although I am using the code below to persuade flyspell to not flag certain words with numbers in them,
you can use this sort of hook to match certain context.
looking-at starts at the position you want - so you may want to search backwards for start/end of whatever context you care about.
(when "another attempt to accept certain words flyspell/ispell/aspell flags as incorrect"
(defun flyspell-ignore-WordNumber99-stuff/ag (beg end info)
(save-excursion
(goto-char beg)
(cond
((or
(looking-at "\\bWord1\\b")
(looking-at "\\bWord99Foo\\b")
)
t)
(t nil)
)
)
)
)
(add-hook 'flyspell-incorrect-hook 'flyspell-ignore-WordNumber99-stuff/ag)