kris
kris

Reputation: 23592

How to trim trailing whitespace in js2-mode in emacs

Trimming trailing whitespace works fine on all non-JS files. I've got these lines in my .emacs:

(add-hook 'before-save-hook 'delete-trailing-whitespace)
(add-hook 'before-save-hook 'whitespace-cleanup)

I've also used M-x customize-group <enter> js2-mode to set:

Js2 Cleanup Whitespace: [Hide Value] [Toggle]  on (non-nil)
   [State]: SAVED and set.

Non-nil to invoke `delete-trailing-whitespace' before saves.

But it still doesn't trim whitespace on saves! What am I missing?

Edited to add: in response to Drew's suggestions,

  1. Running delete-trailing whitespace manually on the file does work.
  2. Still doesn't work without whitespace cleanup, which isn't surprising because...
  3. delete-trailing-whitespace doesn't seem to be called on saves.
  4. Neither does basic-save-buffer.

I'm not sure how to investigate how js2-mode is intercepting/preventing the before-save-hooks from being triggered.

Upvotes: 2

Views: 408

Answers (2)

marneborn
marneborn

Reputation: 699

I got it to work by wrapping delete-trailing-whitespace in a lambda instead of quote.

(add-hook 'js2-mode-hook (lambda () 
                           (add-hook 'before-save-hook (lambda () (delete-trailing-whitespace)))

Upvotes: 1

Drew
Drew

Reputation: 30701

  1. Test whether delete-trailing-whitespace works on JS files when you invoke it normally (manually).

  2. Try without whitespace-cleanup on the same hook -- IOW, simplify to see what the problem is.

  3. Load the source file (simple.el) that defines delete-trailing-whitespace. Then M-x debug-on-entry delete-trailing-whitespace. Then save a JS file and see whether d-t-w even gets called. If it does, step through the debugger to find out whether or not it deletes whitespace (and the whitespace is perhaps put back afterward), and if not, why not.

  4. If it is never called, then load the file (files.el) that defines the function (basic-save-buffer) that invokes buffer-save-hook. M-x cancel-debug-on-entry RET to cancel the first, then M-x debug-on-entry basic-save-buffer. Similarly, see whether the hook is run, if not, why not, if so, why it doesn't DTRT, etc.

  5. Note that basic-save-hook is not run to completion if one of the hook functions raises an error. See what functions are on the hook, etc. Determine whether an error is preventing TRT.

You get the idea: investigate.

Upvotes: 4

Related Questions