Commits

seanmcl  committed 56c3db9

Ocp.indent-buffer elisp

  • Participants
  • Parent commits 4b7f859

Comments (0)

Files changed (2)

File ocp-indent/ocp-indent-stdin

+#!/bin/bash
+
+ocp-indent <(while read line; do echo $line; done)

File ocp-indent/ocp-indent.el

+
+(defcustom Ocp.indent-program (format "%s/bin/ocp-indent-stdin" (getenv "HOME"))
+  "Program to use to indent your code")
+;; (setq Ocp.indent-program "/Users/seanmcl/bin/ocp-indent-stdin")
+
+(defun Ocp.indentation ()
+  (save-excursion
+    (beginning-of-line)
+    (let ((beg (point)))
+      (forward-to-indentation 0)
+      (- (point) beg))))
+
+(defun Ocp.in-indentation ()
+  "t iff cursor is before the first non-whitespace char on a line"
+  (let* ((beg (save-excursion (beginning-of-line) (point)))
+         (s (buffer-substring beg (point))))
+    (if (string-match "^\\s-*$" s) t nil)))
+
+;; ;; If cursor is before any characters, tab sends you to the new indentation
+;; ;; Otherwise, go to (oldCol - oldIndent + newIndent)
+;; ;; oldCol - oldIndent is nonnegative
+(defun Ocp.indent-buffer ()
+  (interactive)
+  (let* ((coding-system-for-write 'utf-8)
+         (coding-system-for-read 'utf-8)
+         (windows (get-buffer-window-list (current-buffer)))
+         (window-info
+          (mapcar (lambda (w) (list w (window-point w) (window-start w))) windows))
+         (pt (point))
+         (mk (mark))
+         (old-indent (Ocp.indentation))
+         (in-indentation (Ocp.in-indentation))
+         (old-col (current-column))
+         (ws (window-start))
+         (ln (line-number-at-pos pt)))
+    (call-process-region (point-min) (point-max) Ocp.indent-program t t)
+    (goto-char (point-min))
+    (forward-line (1- ln))
+    (if in-indentation (forward-to-indentation 0)
+      (let ((new-indent (Ocp.indentation))
+            (col (- old-col old-indent)))
+        (assert (>= col 0))
+        (forward-char (+ col new-indent))))
+    (set-mark mk)
+    (mapc (lambda (info)
+            (let ((w (nth 0 info))
+                  (pt (nth 1 info))
+                  (st (nth 2 info)))
+              ;;(set-window-point w pt)
+              (set-window-start w st))) window-info)))
+
+(provide 'ocp-indent)