Emacs package customization and autoloads - emacs

I am adding Customize support for a package that provides a couple of global mode-independent commands. As I do not want to load the package unless the user explicitly invokes the commands through keybindings yet I want to allow customization right after the user installs the package, I tried to use code like:
;;;###autoload
(defcustom foo-bar nil
"bar setting for for"
:type boolean)
;;;###autoload
(defun foo-command-1 () ...)
With that after I install the package I can invoke foo-command-1. I can also use customize-variable to set and save foo-bar. However, when I start Emacs again, the value of foo-bar is reset to default and Emacs complains that the value is changed outside customize.
AFAICS the reason for this is that the code that Emacs puts into the autoloads file for defcustom assumes that it will run before Emacs calls custom-set-variables in the init.el. However, this is not the case with a package which autoloads are run after the init file.
Is this a known problem? To workaround I replaced the above with something like:
;;;###autoload
(unless (fboundp 'foo-command-1)
(defcustom foo-bar nil
"bar setting for for"
:type boolean))
;;;###autoload
(defun foo-command-1 () ...)
That copies the whole defcustom definition into the autoloads and prevents running it the second time when the package is loaded for real. This works and saved options are properly restored. Still I am puzzled why ###autoload for defcustom does not do the right thing on its own.

Yes, what you did is a reasonable way to accomplish what you want. If you want to autoload a defcustom and you care about when it will be evaluated relative to other code, then you need to control that timing in some way. The way you chose is reasonable.
A user's init file can load custom-file at any point the user chooses. And if no custom-file is used it is still not sure at what point the part of the init-file code that is managed by Customize will be evaluated with respect to other parts that might depend on values that it sets.

As a general rule, you don't want to autoload variables.
Yes, it's a known problem, and there's no really good solution to it (each solution I could come up with had its own set of bugs/misbehaviors), which is why all I can say is "don't autoload variables, please".
Even in the case where it happens to do what you want, it's undesirable in my experience. It just has too many quirks and corner cases.

Related

emacs doremi: to change color-themes

I'm trying to get doremi working in emacs. Specifically, at this stage, to allow me to quickly scroll through a condensed list of color-themes and see each theme as I go through it. For this I would use the 'M-x doremi-color-themes+' command.
What I've done:
Installed color-themes (successfull)
Installed doremi.el, doremi-cmd.el, ring+.el and added
(add-to-list 'loadpath "~/elisp/themes")
(add-to-list 'loadpath "~/elisp/doremi/")
(require 'color-theme)
(color-theme-initialize)
(color-theme-classic)
;; create a list of color themes to scroll through using 'doremi-cmd
(setq my-color-themes (list 'color-theme-classic
'color-theme-retro-green
'color-theme-gray30
'color-theme-subtle-hacker
'color-theme-jonadabian-slate))
(require 'doremi)
(require 'doremi-cmd)
(require 'ring+)
to the .emacs file.
What emacs does:
When I type the comand 'M-x doremi-color-themes+' into the mini-buffer it seems to accept that I've given it a valid command and tells me to use the and arrow keys to move through the list. But when I do that all that happens is the cursor moves up and down in the active window. No changing of color-themes.
Being somewhat new to emacs (and especially customising it) I'm sure I have missed a step or put something in the wrong place. Perhaps there's some sort of (setq 'bla-bla-bla (...)) I need to do?
Sorry for your trouble. Please state your Emacs version (M-x emacs-version), and your version of color-theme.el.
You do not need to require library ring+.el if you use Emacs 23 or later (its code was included in GnuEmacs 23.)
You do not need to use (color-theme-initialize) or (color-theme-classic). The former is done automatically by doremi-color-themes+.
Try starting from emacs -Q (i.e., no init file, ~/.emacs), to be sure there is no interference from stuff in your init file.
Your variable my-color-themes is not referenced anywhere. Instead of defining that variable, just customize user option doremi-color-themes. (Or leave its value nil, which means that all color themes will be cycled through.)
Feel free to contact me by email if you continue to have a problem. Or continue here, if you prefer.
[Just to be sure: you are using color-theme.el, right? There is a lot of confusion out there between Emacs "custom themes" and color themes. Do Re Mi supports both, but they are different critters.]
After a bit for back and forth with #Drew we found a solution to the problem.
It turned out the major problem was that I was using emacs in 'terminal mode' rather than as a GUI application. Bare in mind I'm using a mac.
In the context of Terminal, my arrow keys send escape sequences and so doremi cannot read the event as intended. So it just escapes and applies the message to the active buffer.
There is an answer.
By adding the following lines to my .emacs file (or whatever your init file for emacs is) I was able to redirect doremi to use two other keys. ie. not the up and down arrows.
(setq doremi-down-keys '(?n))
(setq doremi-up-keys '(?p))
Doing this tells doremi to use 'n' as the down key and 'p' as the up key. And all works just fine.
Because I am only new to the world of programming and computing I may often use incorrect terminology. If this is the case please let me know and I will edit accordingly for clarity and consistency.

What Emacs Lisp function is to `require` as `autoload` is to `load`?

I am trying to program GNU Emacs 23 to issue require commands lazily, on demand, instead of up front in my .emacs file. If I wanted to delay the execution of a load command, I could use autoload. But require and load take different sorts of arguments.
Is there a predefined function that does for require the same job that autoload does for load? And if not, what tools would people recommend that I use to roll my own?
There is not difference between require and load with regards to autoload. require is just a frontend to load, which more or less comes down to:
(defun require (feature &optional filename noerror)
(unless (featurep feature)
(let ((filename (or filename (symbol-name feature))))
(load filename noerror))))
As you can see, the symbol name given to require is equal to the filename given to load. As a matter of fact, the first (require 'foo) evaluated in an Emacs session is equivalent to (load "foo").
Thus, you can just use (auto-load 'foo-function "foo") for foo-function from the library foo, that you can load with (require 'foo).
One more answer to help clarify (this was a little verbose for a comment):
autoload says "if this function isn't already defined, then load this file (if and when the function is called)."
require says "if this library isn't already loaded, then load this file (immediately)."
Note in particular that you don't need to use require to load a library; that's simply the way you ensure that you don't load it again (assuming you don't want to do that). The (provide 'FEATURE) expression in the library will be evaluated no matter how the library was loaded, which lets any future require know that it doesn't need to do anything.
It's a similar situation for autoload -- if the file has already been loaded (and therefore the function in question properly defined), then the autoload no longer has any effect.
What kind of "demand" do you have in mind for your "on demand"?
If a given command or other function needs (or soft-needs) a given library, then that function itself can use (require 'foo) or (require 'foo nil t). The library will be loaded on demand from that function.
Consider also whether you might need to load the file more than once, i.e., reload it in some situations, whether or not it has already been loaded.
For #2, for instance, my code that uses a library of Lisp macros, icicles-mac.el does not just use require, because I want to make sure that if a user gets a new version of that library (e.g., downloads a new source version and byte-compiles it) then that new version is used whenever s?he byte-compiles another library that needs it. (This is important -- when a library of macros changes, other libraries that use those macros generally need to be recompiled after loading the new macros file.) For that, instead of just (require 'icicles-mac) I use this:
(eval-when-compile
(or (condition-case nil
(load-library "icicles-mac") ; Use load-library to ensure latest .elc.
(error nil))
(require 'icicles-mac))) ; Require, so can load separately if not on `load-path'.

The major mode name of emacs-lisp

I want to load emacs init files faster, so I use the 'eval-after-load.
For example, when I load clojure file, I just put
(eval-after-load 'clojure-mode
'do-something)
It works.
But when I try
(eval-after-load 'emacs-lisp-mode
'do-something)
It doesn't work. I wonder to know the right major mode name of emacs-lisp.
Thanks.
Please read the documentation of eval-after-load:
eval-after-load LIBRARY FORM
This function arranges to evaluate form at the end of loading the file LIBRARY, each time LIBRARY is loaded. If LIBRARY is already loaded, it evaluates form right away. Don't forget to quote form!
[…] LIBRARY can also be a feature (i.e., a symbol), in which case form is evaluated at the end of any file where (provide LIBRARY) is called.
You have to pass the name of the file or library, which defines the major mode, as argument.
While some modes are defined in files of the same name (e.g. clojure-mode in clojure-mode.el), many files a different name, especially if the actually define multiple major modes.
emacs-lisp-mode is defined in lisp-mode.el, along with some other modes for Emacs Lisp editing (e.g. lisp-mode as a generic Lisp language mode, or lisp-interaction-mode for *scratch* buffers).
Hence, use (eval-after-load 'lisp-mode …)
Also, you have to give a single sexp as second argument, so you'll likely want to use (eval-after-load 'lisp-mode '(do-something)), to call the function do-something.
If you are using a snapshot build of Emacs, use with-eval-after-load, i.e. (with-eval-after-load 'lisp-mode (do-something)). It allows for more than a single form, and doesn't require quoting.
Just eval with M-: the variable major-mode. It actually is emacs-lisp-mode.
Note that *scratch* is actually in lisp-interaction-mode.
As to what you're trying to do, use (eval-after-load "lisp-mode").
As explained by #lunaryom, the arg passed to eval-after-load is not a function name but a feature name, which is basically a file name. So you need to find the name of the file from which the function is loaded.
We could provide a feature like eval-after-defun, and indeed it might be a good idea to do so. If you'd like such a thing, ask for it via M-x report-emacs-bug.

How to keep dir-local variables when switching major modes?

I'm committing to a project where standard indentations and tabs are 3-chars wide, and it's using a mix of HTML, PHP, and JavaScript. Since I use Emacs for everything, and only want the 3-char indentation for this project, I set up a ".dir-locals.el" file at the root of the project to apply to all files/all modes under it:
; Match projets's default indent of 3 spaces per level- and don't add tabs
(
(nil .
(
(tab-width . 3)
(c-basic-offset . 3)
(indent-tabs-mode . nil)
))
)
Which works fine when I first open a file. The problem happens when switching major modes- for example to work on a chunk of literal HTML inside of a PHP file. Then I lose all the dir-local variables.
I've also tried explicitly stating all of the modes I use in ".dir-locals.el", and adding to my .emacs file "dir-locals-set-class-variables / dir-locals-set-directory-class". I'm glad to say they all behave consistently, initially setting the dir-local variables, and then losing them as I switch the major mode.
I'm using GNU Emacs 24.3.1.
What's an elegant way of reloading dir-local variables upon switching a buffer's major-mode?
-- edit -- Thanks for the excellent answers and commentary both Aaron and phils! After posting here, I thought it "smelled" like a bug, so entered a report to GNU- will send them a reference to these discussions.
As per comments to Aaron Miller's answer, here is an overview of what happens when a mode function is called (with an explanation of derived modes); how calling a mode manually differs from Emacs calling it automatically; and where after-change-major-mode-hook and hack-local-variables fit into this, in the context of the following suggested code:
(add-hook 'after-change-major-mode-hook 'hack-local-variables)
After visiting a file, Emacs calls normal-mode which "establishes the proper major mode and buffer-local variable bindings" for the buffer. It does this by first calling set-auto-mode, and immediately afterwards calling hack-local-variables, which determines all the directory-local and file-local variables for the buffer, and sets their values accordingly.
For details of how set-auto-mode chooses the mode to call, see C-hig (elisp) Auto Major Mode RET. It actually involves some early local-variable interaction (it needs to check for a mode variable, so there's a specific look-up for that which happens before the mode is set), but the 'proper' local variable processing happens afterwards.
When the selected mode function is actually called, there's a clever sequence of events which is worth detailing. This requires us to understand a little about "derived modes" and "delayed mode hooks"...
Derived modes, and mode hooks
The majority of major modes are defined with the macro define-derived-mode. (Of course there's nothing stopping you from simply writing (defun foo-mode ...) and doing whatever you want; but if you want to ensure that your major mode plays nicely with the rest of Emacs, you'll use the standard macros.)
When you define a derived mode, you must specify the parent mode which it derives from. If the mode has no logical parent, you still use this macro to define it (in order to get all the standard benefits), and you simply specify nil for the parent. Alternatively you could specify fundamental-mode as the parent, as the effect is much the same as for nil, as we shall see momentarily.
define-derived-mode then defines the mode function for you using a standard template, and the very first thing that happens when the mode function is called is:
(delay-mode-hooks
(PARENT-MODE)
,#body
...)
or if no parent is set:
(delay-mode-hooks
(kill-all-local-variables)
,#body
...)
As fundamental-mode itself calls (kill-all-local-variables) and then immediately returns when called in this situation, the effect of specifying it as the parent is equivalent to if the parent were nil.
Note that kill-all-local-variables runs change-major-mode-hook before doing anything else, so that will be the first hook which is run during this whole sequence (and it happens while the previous major mode is still active, before any of the code for the new mode has been evaluated).
So that's the first thing that happens. The very last thing that the mode function does is to call (run-mode-hooks MODE-HOOK) for its own MODE-HOOK variable (this variable name is literally the mode function's symbol name with a -hook suffix).
So if we consider a mode named child-mode which is derived from parent-mode which is derived from grandparent-mode, the whole chain of events when we call (child-mode) looks something like this:
(delay-mode-hooks
(delay-mode-hooks
(delay-mode-hooks
(kill-all-local-variables) ;; runs change-major-mode-hook
,#grandparent-body)
(run-mode-hooks 'grandparent-mode-hook)
,#parent-body)
(run-mode-hooks 'parent-mode-hook)
,#child-body)
(run-mode-hooks 'child-mode-hook)
What does delay-mode-hooks do? It simply binds the variable delay-mode-hooks, which is checked by run-mode-hooks. When this variable is non-nil, run-mode-hooks just pushes its argument onto a list of hooks to be run at some future time, and returns immediately.
Only when delay-mode-hooks is nil will run-mode-hooks actually run the hooks. In the above example, this is not until (run-mode-hooks 'child-mode-hook) is called.
For the general case of (run-mode-hooks HOOKS), the following hooks run in sequence:
change-major-mode-after-body-hook
delayed-mode-hooks (in the sequence in which they would otherwise have run)
HOOKS (being the argument to run-mode-hooks)
after-change-major-mode-hook
So when we call (child-mode), the full sequence is:
(run-hooks 'change-major-mode-hook) ;; actually the first thing done by
(kill-all-local-variables) ;; <-- this function
,#grandparent-body
,#parent-body
,#child-body
(run-hooks 'change-major-mode-after-body-hook)
(run-hooks 'grandparent-mode-hook)
(run-hooks 'parent-mode-hook)
(run-hooks 'child-mode-hook)
(run-hooks 'after-change-major-mode-hook)
Back to local variables...
Which brings us back to after-change-major-mode-hook and using it to call hack-local-variables:
(add-hook 'after-change-major-mode-hook 'hack-local-variables)
We can now see clearly that if we do this, there are two possible sequences of note:
We manually change to foo-mode:
(foo-mode)
=> (kill-all-local-variables)
=> [...]
=> (run-hooks 'after-change-major-mode-hook)
=> (hack-local-variables)
We visit a file for which foo-mode is the automatic choice:
(normal-mode)
=> (set-auto-mode)
=> (foo-mode)
=> (kill-all-local-variables)
=> [...]
=> (run-hooks 'after-change-major-mode-hook)
=> (hack-local-variables)
=> (hack-local-variables)
Is it a problem that hack-local-variables runs twice? Maybe, maybe not. At minimum it's slightly inefficient, but that's probably not a significant concern for most people. For me, the main thing is that I wouldn't want to rely upon this arrangement always being fine in all situations, as it's certainly not the expected behaviour.
(Personally I do actually cause this to happen in certain specific cases, and it works just fine; but of course those cases are easily tested -- whereas doing this as standard means that all cases are affected, and testing is impractical.)
So I would propose a small tweak to the technique, so that our additional call to the function does not happen if normal-mode is executing:
(defvar my-hack-local-variables-after-major-mode-change t
"Whether to process local variables after a major mode change.
Disabled by advice if the mode change is triggered by `normal-mode',
as local variables are processed automatically in that instance.")
(defadvice normal-mode (around my-do-not-hack-local-variables-twice)
"Prevents `after-change-major-mode-hook' from processing local variables.
See `my-after-change-major-mode-hack-local-variables'."
(let ((my-hack-local-variables-after-major-mode-change nil))
ad-do-it))
(ad-activate 'normal-mode)
(add-hook 'after-change-major-mode-hook
'my-after-change-major-mode-hack-local-variables)
(defun my-after-change-major-mode-hack-local-variables ()
"Callback function for `after-change-major-mode-hook'."
(when my-hack-local-variables-after-major-mode-change
(hack-local-variables)))
Disadvantages to this?
The major one is that you can no longer change the mode of a buffer which sets its major mode using a local variable. Or rather, it will be changed back immediately as a result of the local variable processing.
That's not impossible to overcome, but I'm going to call it out of scope for the moment :)
Be warned that I have not tried this, so it may produce undesired results ranging from your dir-local variables not being applied, to Emacs attempting to strangle your cat; by any sensible definition of how Emacs should behave, this is almost certainly cheating. On the other hand, it's all in the standard library, so it can't be that much of a sin. (I hope.)
Evaluate the following:
(add-hook 'after-change-major-mode-hook
'hack-dir-local-variables-non-file-buffer)
From then on, when you change major modes, dir-local variables should (I think) be reapplied immediately after the change.
If it doesn't work or you don't like it, you can undo it without restarting Emacs by replacing 'add-hook' with 'remove-hook' and evaluating the form again.
My take on this:
(add-hook 'after-change-major-mode-hook #'hack-local-variables)
and either
(defun my-normal-mode-advice
(function &rest ...)
(let ((after-change-major-mode-hook
(remq #'hack-local-variables after-change-major-mode-hook)))
(apply function ...)))
if you can live with the annoying
Making after-change-major-mode-hook buffer-local while locally let-bound!
message or
(defun my-normal-mode-advice
(function &rest ...)
(remove-hook 'after-change-major-mode-hook #'hack-local-variables)
(unwind-protect
(apply function ...)
(add-hook 'after-change-major-mode-hook #'hack-local-variables)))
otherwise and finally
(advice-add #'normal-mode :around #'my-normal-mode-advice)

Emacs c-mode autoloading failed

I want to load my file named "my-c-setup.el" when the c-mode is loading. So, I'm using the function "autoload".
With my python setup, it works well :
lang.el
(autoload 'python-mode "my-python-setup" "" t)
my-python-setup.el
(require 'python)
; ...
I'm trying to do the same with the c-mode, but i does not work :
lang.el
(autoload 'c-mode "my-c-setup" "" t)
my-c-setup.el
(setq c-basic-offset 4)
; ...
When I try to open a file in c-mode (test.c for example), I have the following error :
File mode specification error: (error "Autoloading failed to define function c-mode")
Autoload is not what you're looking for. What it does is simply load some code the first time it is needed, which is a handy way to extend Emacs' functionality while still keeping the start-up time low.
To solve your problem, we gotta think about what you really want to do: do you simply want some of your code to be loaded at some point, or do you want buffer-local customizations for ever buffer that is in c-mode?
If you simply want Emacs to load your code at start-up, either put your code directly into your .emacs file or use load-file or require instead of autoload:
load-file simply takes a file name, loads the lisp code in that file and evaluates it. So if your code is in a file named "/path/to/my-c-setup.el", you could put the following line in your .emacs, and the code will be loaded on every start-up:
(load-file "/path/to/my-c-setup.el")
Perhaps you don't want to give the absolute path name for every file you load. In that case, you could use the function load-library instead which is similar to load-file but tries to find the given filename in any of the directories stored in the variable load-path:
(add-to-list 'load-path "/path/to")
(load-library "my-c-setup.el")
The advantage is that you have to do the add-to-list part only once, and all subsequent calls to load-library will be able to find code in that directory.
An alternative way is the provide/require mechanism: you can make your .el-file "provide" some feature by putting a (provide 'feature) call in it, e.g.
(provide 'my-c-mode-customizations)
Then put an according (require 'feature) in your .emacs file, and your code will be loaded as well:
(require 'my-c-mode-customizations)
However, if you want your code only be loaded when c-mode is activated on a buffer, the way to achieve that is through Emacs' Hook mechanism:
A hook is a variable where you can
store a function or functions to be
called on a particular occasion by an
existing program.
Most major modes provide a customizable hook variable to which you can add functions that will be called whenever the major mode is invoked. For instance, c-mode provides c-mode-hook. In order for your own customizations to be called whenever c-mode is turned on for a buffer, put them in a function, say, my-c-mode-customizations and add the following line to your .emacs file:
(add-hook 'c-mode-hook 'my-c-mode-customizations)
Of course, you still need autoload for Emacs to actually find the definition of that function.
Lisp's autoload does not call a function when a file is loaded but tells lisp that the function is available and that the given file provides it. Whenever someone calls the (not yet defined) function, the file is loaded.
I think that c-mode is already defined and thus fails to re-register.
Autoload doesn't do what you think it does.
http://www.gnu.org/software/emacs/elisp/html_node/Autoload.html
What you probably want are mode-hooks or eval-after-load.
See eval-after-load vs. mode hook for the difference between the two.