summaryrefslogtreecommitdiff
path: root/durand-align.el
blob: 079f4212f5aa61e0b62099446ee122823de70e66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
;;; durand-align.el --- Pixel alignment              -*- lexical-binding: t; -*-

;; Copyright (C) 2024  Jean Sévère Durand

;; Author: Jean Sévère Durand <durand@jsdurand.xyz>
;; Keywords: wp, faces

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; Some little functions to center buffer texts at pixel level
;; precision.

;;; Code:

(defun durand-center (&optional pixels)
  "Center the buffer.
If PIXELS is not-nil, use that as body width in pixels."
  (let* ((body-width (cond ((and pixels (numberp pixels) (> pixels 0))
                            pixels)
                           ((car (window-text-pixel-size
                                  nil
                                  (cons (window-start) 0)
                                  (window-end))))))
         (len (floor (- (window-body-width nil t) body-width) 2))
         (prop (list 'space :width (list len)))
         (str (propertize (string 32) 'display prop 'durand-center t)))
    (save-excursion
      (goto-char (point-min))
      (while (not (eobp))
        (cond
         ((get-text-property (point) 'durand-center)
          (put-text-property (point) (1+ (point)) 'display prop))
         ((insert str)))
        (forward-line 1)))))

(defun durand-cancel-center ()
  "Cancel the inserted characters."
  (save-excursion
    (goto-char (point-min))
    (while (not (eobp))
      (cond
       ((get-text-property (point) 'durand-center)
        (delete-char 1)))
      (forward-line 1))))


(provide 'durand-align)
;;; durand-align.el ends here