Nathan Lippi
Nathan Lippi

Reputation: 5237

Elisp: Old variable values seem to stick

Beginner question for emacs lisp.

In my .emacs I have written the following:

(defun line-text-up-with-parentheses-above()
  (interactive)
  (line-text-up-with-char-above "("))

(defun line-text-up-with-char-above(charval)
  (interactive)
  (setq now-point   (point))
  (previous-line)
  (setq above-point (point))
  (forward-char)
  (search-forward charval (line-end-position) nil)
  (setq above-paren (point))
  (goto-char now-point)
  (insert (make-string (- above-paren above-point) ? )))

(global-set-key (kbd "\<C-S-iso-lefttab>") 'line-text-up-with-parentheses-above)

The function intends to line the text at the point up with the character after the "(" on the line above it.

Everything seem to work fine, unless the function is called twice in a row. In this case, the text before the point advances exactly the same amount as last time.

Seems like the variables aren't being set the second time around.

Does anyone know how to fix this?

Many thanks!

Upvotes: 1

Views: 106

Answers (3)

event_jr
event_jr

Reputation: 17707

Protip: align and specifically align-regexp.

Upvotes: 1

Tyler
Tyler

Reputation: 10032

I think the variables are being set correctly (although Lindydancer is correct to suggest let instead of setq). And your function works fine for me if I call it with point at the first non-whitespace character on the line you want to 'line up'. The only problem I see is that the function lines up with wherever point is when you call it, which is not correct if point is not at the first non-whitespace character.

You can fix this be adding (back-to-indentation) immediately after (interactive) in line-text-up-with-char-above. Actually, once you wrap everything in save-excursion you'll want to add back-to-indentation as the first function within the save-excursion form.

Upvotes: 1

Lindydancer
Lindydancer

Reputation: 26124

You calculate the intended indentation. However, you always insert it regardless of how many spaces the current line contains.

You could either simply delete the spaces on the current line before inserting the new spaces, or you could try to calculate the number of spaces needed and insert or delete, as needed.

Some hints:

  • By using setq you are using global variables, try to bind them using let.

  • Instead of recording where the point is before you move it around and restore it afterwards, you could use the special construct save-excursion.

Upvotes: 4

Related Questions