1

I have a buffer that will have either plain text or an image (text properties) near the end of the buffer. I would like to delete any new lines or whitespace at the end of the buffer. How can I do this?

The following works if there is an image:  (delete-region (previous-property-change (point-max)) (point-max)). However, if there is no image, it deletes plain text -- which is not what I want.

The following works if there is no image, but deletes the image if there is one (which is also not what I want):

(save-excursion
  (goto-char (point-max))
  (let ((trailing-whitespace+newlines (abs (skip-chars-backward "\s\r\n\t"))))
    (when (> trailing-whitespace+newlines 0)
      (delete-char trailing-whitespace+newlines))))
  • Does the delete-trailing-whitespace command have the same problem with deleting the image? – stevoooo Apr 10 '17 at 19:17
  • @stevoooo -- thank you for the suggestion. I just tried delete-trailing-whitespace and it deletes all of the images in the buffer that are on lines by themselves, including the last image on a line just before the end of the buffer. I fear that even if I try restricting the region using the optional arguments to that function, I will still have the same problem as posed in the question with programmatically determining the appropriate beginning point. – lawlist Apr 10 '17 at 19:53
1

I think the problem is that insert-image uses " " by default for the text to put in the buffer to hold the image. If you pass a non-whitespace string as the second (optional) argument to the insert-image function then delete-whitespace should do the right thing and leave the image in the buffer as it's no longer associated with whitespace text.

0

Here is a working draft that might become final after I try it out some more. I experimented with a few of the property search functions in the manual -- https://www.gnu.org/software/emacs/manual/html_node/elisp/Property-Search.html -- in a forwards and reverse search. I beleive it is possible to use some of those functions in a solution, but I have tentatively chosen instead to move backwards one character at a time until locating an image or text.

(save-excursion
  (goto-char (point-max))
  (catch 'done
    (while (looking-back "[\s\r\n\t]" nil)
      (let* ((plist (text-properties-at (1- (point))))
             (image-p (eq (car (plist-get plist 'display)) 'image)))
        (if image-p
          (throw 'done nil)
          (delete-char -1))))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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