Adobe
Adobe

Reputation: 13487

Custom toggler?

I want to have toggler which would add/remove ".. " (there's a space -- but I can't make it more pronounced) string in front of every line above (point). Here's my best bet:

(defun rst-comment-above (Point)
  (interactive "d")
  (save-excursion
    (goto-char 1)
    (cond

     ((numberp (get this-command 'state))
      ((replace-regexp "^\\.\\. " "" nil (point) (get this-command 'state)))
      (put this-command 'state ""))

     (t
     (replace-regexp "^" ".. " nil (point) Point)
     (put this-command 'state Point))
)))

it works for the first time, but for the second it says:

(invalid-function
 (replace-regexp "^\\.\\. " "" nil (point) (get this-command (quote state))))

Edit:

@user4815162342:

So I comment the thing above:

I comment the thing above

Then I insert new lines:

I insert new lines

Then I want to uncomment the thing, and I get:

upon uncommenting the thing, and I get

But probably its not that important. I do not generally enter anything in the commented area. I just note that the issue. What is some what more important -- is to store the 'state of the given file across the sessions. Is it hard to implement?

Upvotes: 0

Views: 79

Answers (2)

user4815162342
user4815162342

Reputation: 155216

The error comes from the extra set of parentheses on the line where you call replace-regexp. That line should be:

(replace-regexp "^\\.\\. " "" nil (point) (get this-command 'state))

There are several other problems with your code.

  1. Storing the current value of point doesn't work well because you add characters to the buffer, which makes the point move forward. This makes (once the above syntax error is fixed) the function miss the last several instances of "..".
    • The fix is to store the point marker.
  2. You should be using (point-min) instead of hard-coding the buffer beginning to 1, or your code will fail to work when buffer narrowing is in effect.
  3. Finally, replace-regexp, as its documentation states, is not meant to be called from Lisp programs.

Here is a revised version of your function:

(defun rst-comment-above ()
  (interactive)
  (let ((pm (point-marker))
        (prev-marker (get this-command 'rst-prev-marker)))
    (save-excursion
      (goto-char (point-min))
      (cond ((null prev-marker)
             (while (< (point) pm)
               (insert "..")
               (forward-line 1))
             (put this-command 'rst-prev-marker pm))
            (t
             (while (< (point) prev-marker)
               (when (looking-at "^\\.\\.")
                 (replace-match ""))
               (forward-line 1))
             (put this-command 'rst-prev-marker nil))))))

Upvotes: 1

Stefan
Stefan

Reputation: 28551

Any reason why you don't use M-; in rst-mode?

Upvotes: 0

Related Questions