bug-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

bug#2887: Suggestions for simple.el


From: Arni Magnusson
Subject: bug#2887: Suggestions for simple.el
Date: Sun, 19 Apr 2009 13:41:39 +0000 (GMT)

[Arni Magnusson wrote:]

(defun pos-at-beginning-of-line (N)
  "Return the position at beginning of line N."
  (save-excursion
    (goto-char (point-min))(line-beginning-position N)))

(defun pos-at-end-of-line (N)
  "Return the position at end of line N."
  (save-excursion
    (goto-char (point-min))(line-end-position N)))

(defun comment-line-or-region ()
  "Comment line or region."
  (interactive)
  (require 'newcomment)
  (if (and mark-active transient-mark-mode)
      (comment-region
       (pos-at-beginning-of-line
        (line-number-at-pos (region-beginning)))
       (pos-at-end-of-line
        (line-number-at-pos (region-end))))
    (comment-region
     (line-beginning-position)(line-end-position))))

[Stefan Monnier wrote:]

A perfect example of the kind of performance bug that comes up when you think in terms of lines, as encouraged by pos-at-beginning/end-of-line. The above should be:

(defun comment-line-or-region ()
  "Comment line or region."
  (interactive)
  (require 'newcomment)
  (if (and mark-active transient-mark-mode)
      (comment-region
       (save-excursion
         (goto-char (region-beginning))(line-beginning-position))
       (save-excursion
         (goto-char (region-end))(line-end-position)))
    (comment-region
     (line-beginning-position)(line-end-position))))

line-number-at-pos is also a "function to avoid", just as bad as goto-line. Your code will walk over the whole buffer 4 times (twice to compute the line-number at region beg and end, then twice to find the beg/end of those 2 lines).

---

Aha, now I see what you mean. One should use relative motion in Emacs Lisp programs and avoid referring to absolute line numbers (`goto-line', `line-beginning-position', `line-end-position', `line-number-at-pos').

Thank you Stefan, for explaining this to me - now I would like to help others to avoid using these functions in Emacs Lisp programs, when possible. Couldn't this be mentioned in the docstrings and in the Emacs Lisp Manual? They had already helped me by tagging a warning sign on functions like:

  `next-line', `previous-line'
  `beginning-of-buffer', `end-of-buffer'
  `replace-string', `replace-regexp'
  `insert-file', `insert-buffer'

In my notes, I have also written that (goto-char (point-min)) is better than (goto-line 1), but now I can't see where this is documented.

Besides the docstrings and the function entries in the manual, there is a section in the manual called "Emacs Programming Tips" where the pitfalls of *-line-* functions could be mentioned.

Thanks,

Arni






reply via email to

[Prev in Thread] Current Thread [Next in Thread]