4

I want to write a function to indent SQL embedded in a markdown file.

It seems to make sense to use the region for this.

However, the looping form I am using is:

(defun rr/sql-indent-region (beginning end)
  (interactive "r")
  (while (< (point) end)
     ...
     (forward-word 1)

The ... is adding \n characters after SELECT, FROM, GROUP BY etc, so that the block I started with no longer ends at END.

As I write this, I guess one option would be to copy the region to a temporary buffer, and use (< (point) (point-max)). Is that the best way to proceed?

1 Answer 1

3

There are several common approaches you could take. I don't think there's any single "best" option in general.

Using a temporary buffer is entirely reasonable. Buffers are cheap to create. insert-buffer-substring is useful here.

You can also just use narrowing in the current buffer, in which case (point-max) will be the end of the narrowed region, just like in the temporary buffer. C-hig (elisp)Narrowing. Note also eobp.

Finally you could use a marker for the end position, which will dynamically adjust itself when the text before the marker is modified. C-hig (elisp)Markers

In your case I would suggest using narrowing, but experimenting with all three options could be useful.

https://github.com/alex-hhh/emacs-sql-indent may be of interest to you as well.

1
  • 2
    Another option is to iterate from end to beginning. In the current case it's probably not a good choice, but in many other cases it's a fine option.
    – Stefan
    Aug 23, 2018 at 3:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.