js-elisp / jane-lib.el

  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
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
;; This file contains utilities for emacs-lisp programming with the
;; function naming conventions of OCaml code at Jane Street.  The most
;; important features are `defunl' and `letl' for defining lexically
;; scoped functions.

;;; NOTES:
;;
;; Conventions due to dynamic scope hell.
;;
;; We must be careful with function arguments and local variables due to dynamic scope.
;; (defun List.iter (f l)
;;   (mapc f l)
;;   nil)
;;
;; (defun List.iteri (f l)
;;   (let ((ctr 0))
;;     (List.iter (lambda (b)
;;                  (funcall f ctr b)
;;                  (setq ctr (+ ctr 1))) l)))
;;
;; This definition of List.iteri fails.  In (List.iteri g l)
;; `f' is bound to g in the beginning of the body of List.iteri, but when List.iter
;; is called, f gets rebound to (lambda (b) ...).  Thus the funcall fails
;; because it expects only 1 argument.
;;
;; For example
;;
;; (defun List.iteri (f l)
;;   (let ((ctr 0))
;;     (List.iter (lambda (x)
;;                  (funcall f ctr x)
;;                  (setq ctr (+ ctr 1))) l)))
;;
;; (let ((ctr 0))
;;   (List.iteri (lambda (i x) (setq ctr (+ ctr i x))) '(1 1 1 1 1))
;;   (Jane.test ctr 15))
;;
;; This test fails, as `ctr' is rebound in the body of List.iteri.
;;
;; To avoid this, for any higher-order function we use `letl'
;; to define local variables and `defunl' to define the function.

;; Don't show warnings that cl is being used at runtime
;; Using the cl package at runtime is considered bad style among
;; purist emacs-lisp hackers.
;; http://www.gnu.org/software/emacs/manual/html_node/cl/Overview.html
;; In particular:
;;
;;   Please note: the CL functions are not standard parts of the Emacs Lisp name
;;   space, so it is legitimate for users to define them with other, conflicting
;;   meanings. To avoid conflicting with those user activities, we have a policy that
;;   packages installed in Emacs must not load CL at run time. (It is ok for them to
;;   load CL at compile time only, with eval-when-compile, and use the macros it
;;   provides.) If you are writing packages that you plan to distribute and invite
;;   widespread use for, you might want to observe the same rule.
;;
;; I don't think there's any reason to reimplement efficient folds just
;; to avoid importing cl.  It seems to be another internecine war
;; among Emacs factions.

(require 'bytecomp)
(setq byte-compile-warnings (remove 'cl-functions byte-compile-warning-types))
(require 'cl)


;; Util

(defun Jane.test (e1 e2)
  (assert (equal e1 e2))
  t)

(defmacro Jane.with-current-directory (dir &rest form)
  (declare (indent defun))
  (declare (debug (stringp body)))
  ;; We [expand-file-name] so that a relative [dir] will work.  We use a trailing "/"
  ;; because otherwise the last arc in the path is dropped.
  `(let ((default-directory (format "%s/" (expand-file-name ,dir))))
     ,@form))

(defmacro Emacs.protect-from-quit (&rest form)
  (declare (indent defun))
  (declare (debug (body)))
  `(let ((inhibit-quit t))
     ,@form))

(defun nequal (x y) (not (equal x y)))


;; Lexical defun and let

(defmacro defunl (name arglist &rest body)
  "Lexical defun.  Not for use with interactive functions"
  (declare (indent defun))
  (let* (;; remove &optional and &rest
         (args (remove-if
                (lambda (s) (equal (substring (symbol-name s) 0 1) "&"))
                arglist))
         (args (mapcar (lambda (arg) (list arg arg)) args))
         ;; put the doc string before the lexical-let
         (doc_body (if (and (> (length body) 1)
                            (stringp (car body)))
                       `(,(car body) . ,(cdr body))
                     `(nil . ,body)))
         (doc (car doc_body))
         (body (cdr doc_body)))
    `(defun ,name ,arglist
       ,(if doc doc)
       (lexical-let
           ,args
         ,@body))))
;; (macroexpand '(defunl f (x y) (+ x y)))
;; (macroexpand '(defunl f (x y) "abc" (+ x y)))

(def-edebug-spec defunl
  (&define name lambda-list
           [&optional stringp]   ; Match the doc string, if present.
           [&optional ("interactive" interactive)]
           def-body))

(defmacro letl (varlist &rest body)
  (declare (indent 1))
  `(lexical-let ,varlist ,@body))
;; (macroexpand '(letl ((x 5)) (+ x x)))
;; (letl ((x 5)) (+ x x))

(def-edebug-spec letl
  ((&rest
    &or symbolp (gate symbolp &optional form))
   body))

(defmacro letl* (varlist &rest body)
  (declare (indent 1))
  (declare (debug (form &rest form)))
  `(lexical-let* ,varlist ,@body))

(def-edebug-spec letl*
  ((&rest
    &or symbolp (gate symbolp &optional form))
   body))

(font-lock-add-keywords
 'emacs-lisp-mode
 '(("\\<\\(defunl\\)" 1 font-lock-keyword-face)
   ("\\<\\(letl\\*?\\)" 1 font-lock-keyword-face))
 t)


;; Options

(defun Option.value (x default) (if x x default))


;; Lists

;; Ahh, the beauty of dynamic scoping.  Uniquify variable names by appending
;; the defining function name.  Blech...

(defunl List.foldr (f b l)
  (reduce f l :initial-value b :from-end t))
(Jane.test (List.foldr 'concat "" '("a" "b" "c")) "abc")
(Jane.test (List.foldr 'cons nil '(1 2 3)) '(1 2 3))
(Jane.test (List.foldr (lambda (x y) (- x y)) 0 '(1 2 3)) 2)

(defunl List.foldl (f b l)
  (reduce f l :initial-value b))
(Jane.test (List.foldl 'concat "" '("a" "b" "c")) "abc")
(Jane.test (List.foldl 'cons nil '("a" "b" "c")) '(((nil . "a") . "b") . "c"))
(Jane.test (List.foldl (lambda (x y) (- x y)) 0 '(1 2 3)) -6)

(defunl List.filter (f l) (remove-if-not f l))
(Jane.test (List.filter (lambda (x) (> x 3)) '(1 2 3 4 5 6)) '(4 5 6))

(defunl List.find (f l)
  (if (null l) nil
    (let ((hd (car l))
          (tl (cdr l)))
      (if (funcall f hd) hd (List.find f tl)))))
(Jane.test (List.find (lambda (x) (> x 3)) '()) nil)
(Jane.test (List.find (lambda (x) (> x 3)) '(1 2 3 4 5 6)) 4)

(defunl List.exists (p l)
  (if (List.find p l) t nil))
(Jane.test (List.exists (lambda (x) (< x 10)) '(1 2 3 4 5)) t)
(Jane.test (List.exists (lambda (x) (> x 10)) '(1 2 3 4 5)) nil)

(defunl List.mem (l x)
  (not (null (List.find (lambda (y) (equal x y)) l))))
(Jane.test (List.mem '(1 2 3) 4) nil)
(Jane.test (List.mem '(1 2 3 4) 4) t)

(defunl List.assoc (x l)
  (let ((res (assoc x l)))
    (when res (cdr res))))
(Jane.test (List.assoc 5 '((5 . 6) (1 . 3))) 6)
(Jane.test (List.assoc 5 '((5 6) (1 3))) '(6))

(defunl List.iter (f l) (mapc f l) nil)
(let ((ctr 0))
  (List.iter (lambda (x) (setq ctr (+ ctr x))) '(1 2 3 4 5))
  (Jane.test ctr 15))

(defunl List.iteri (f l)
  (letl ((ctr 0))
    (List.iter (lambda (x)
                 (funcall f ctr x)
                 (setq ctr (+ ctr 1))) l)))
(let ((ctr 0))
  (List.iteri (lambda (i x) (setq ctr (+ ctr i x))) '(1 1 1 1 1))
  (Jane.test ctr 15))

(defunl List.concat (l) (apply 'append l))
(Jane.test (List.concat '((1 2) (3 4) (5 6))) '(1 2 3 4 5 6))

(defunl List.map (f l) (mapcar f l))
(Jane.test (List.map '1+ '(1 2 3)) '(2 3 4))

(defunl List.mapi (f l)
  (letl ((i 0))
    (mapcar (lambda (x)
              (letl ((y (funcall f i x)))
                (setq i (1+ i))
                y)) l)))
(Jane.test (List.mapi (lambda (i _) i) '(0 0 0)) '(0 1 2))
(Jane.test (List.mapi (lambda (a b) (+ a b)) '(1 2 3)) '(1 3 5))

(defunl List.upto-aux (n from acc)
  (if (< n from) acc
    (List.upto-aux (1- n) from (cons n acc))))

(defunl List.upto (n &optional from)
  (let ((from (if from from 0)))
    (if (< n from) nil (List.upto-aux n from nil))))

(Jane.test (List.upto 3) '(0 1 2 3))
(Jane.test (List.upto 3 2) '(2 3))

(defunl List.concat-map (f l)
  (apply 'append (List.map f l)))
(Jane.test (List.concat-map 'List.upto '(0 1 2)) '(0 0 1 0 1 2))

(defunl List.filter-map (f l)
  (List.foldr (lambda (x acc)
                (let ((y (apply f (list x))))
                  (if y (cons y acc) acc)))
              () l))
(Jane.test (List.filter-map (lambda (x) (if (< x 4) (1+ x) nil)) '(1 2 3 4 5)) '(2 3 4))

(defunl List.partition (p l)
  (List.foldr (lambda (x acc)
                (let ((yes (car acc))
                      (no  (cdr acc))
                      (res (funcall p x)))
                  (if res
                      (cons (cons x yes) no)
                    (cons yes (cons x no)))))
              (cons nil nil) l))
(Jane.test (List.partition (lambda (x) (< x 4)) '(1 2 3 4 5)) '((1 2 3) . (4 5)))

(defunl List.inter (l1 l2)
  (List.filter (lambda (x) (List.mem l2 x)) l1))
(Jane.test (List.inter '(1 2 3) '(2 3 4)) '(2 3))
(Jane.test (List.inter '(1 2 3) '()) '())

(defunl List.intersperse (sep l)
  (if (null l) l
    (cons (car l)
          (apply 'append (mapcar (lambda (x) (list sep x)) (cdr l))))))
(Jane.test (List.intersperse 5 '()) '())
(Jane.test (List.intersperse 5 '(1)) '(1))
(Jane.test (List.intersperse 5 '(1 2)) '(1 5 2))
(Jane.test (List.intersperse 5 '(1 2 3)) '(1 5 2 5 3))

(defunl List.last (l)
  (car (last l)))
(Jane.test (List.last '()) nil)
(Jane.test (List.last '(1 2 3)) 3)

(defunl List.take (l n)
  (cond
   ((equal n 0) nil)
   ((equal l nil) nil)
   (t (cons (car l) (List.take (cdr l) (1- n))))))
(Jane.test (List.take '(1 2 3 4) 2) '(1 2))
(Jane.test (List.take '(1 2 3 4) 6) '(1 2 3 4))

(defunl List.drop (l n)
  (cond
   ((equal n 0) l)
   ((equal l nil) nil)
   (t (List.drop (cdr l) (1- n)))))
(Jane.test (List.drop '(1 2 3 4) 2) '(3 4))
(Jane.test (List.drop '(1 2 3 4) 6) '())

(defunl List.butlast (l)
  (let ((zero-or-one (lambda (l) (or (null l) (null (cdr l))))))
  (cond
   ((null l) nil)
   ((null (cdr l)) nil)
   (t (cons (car l) (List.butlast (cdr l)))))))
(Jane.test (List.butlast '(1 2 3 4)) '(1 2 3))


;; Strings

(defun String.strip-newlines (s)
  (if (null s) nil
    (assert (string-or-null-p s) "strip-newlines: %s" s)
    (replace-regexp-in-string "\n" "" s)))
(Jane.test (String.strip-newlines nil) nil)
(Jane.test (String.strip-newlines "a\nb\nc") "abc")

(defun String.truncate (s n)
  (let ((k (length s)))
    (if (< k n) s
      (substring s 0 n))))
(Jane.test (String.truncate "abcdef" 3) "abc")
(Jane.test (String.truncate "abcdef" 300) "abcdef")

(defun String.lines (s)
  (split-string s "\n"))
(Jane.test (String.lines "a\nb\nc") '("a" "b" "c"))
(Jane.test (String.lines "abc") '("abc"))
(Jane.test (String.lines "\n") '("" ""))

(defun String.strip (s)
  "Replace space before and after a string"
  (let ((s (replace-regexp-in-string "^[[:space:]]*" "" s)))
    (replace-regexp-in-string "[[:space:]]*$" "" s)))
(Jane.test (String.strip " abc def ") "abc def")

(defun String.eval (s)
  "Eval a string as code"
  (with-temp-buffer (insert s) (eval-buffer)))
;; Can't test.  Always returns nil.

(defun String.escaped (s)
  "Escape newlines and quotes"
  (let ((tab '(("\n" . "\\\\n")
               ;;("\"" . "\\\\\"")
               )))
    (List.foldl (lambda (s p)
                  (let ((l (car p))
                        (r (cdr p)))
                    (replace-regexp-in-string l r s)))
                s tab)))
(Jane.test (String.escaped "abc\ndef\"ghi\"") "abc\\ndef\"ghi\"")
(Jane.test (String.escaped "abc") "abc")


;; Hash tables

(setq tbl (make-hash-table :test 'equal))
(puthash 'a 5 tbl)
(puthash 'b 6 tbl)
(puthash 'c 7 tbl)

(defun Hashtbl.to-alist (tbl)
  (let ((data nil))
    (maphash (lambda (k v) (setq data (cons `(,k ,v) data))) tbl)
    (reverse data)))
(Jane.test (Hashtbl.to-alist tbl) '((a 5) (b 6) (c 7)))

(defun Hashtbl.keys (tbl)
  (List.map 'car (Hashtbl.to-alist tbl)))
(Jane.test (Hashtbl.keys tbl) '(a b c))

(defun Hashtbl.data (tbl)
  (List.map 'cadr (Hashtbl.to-alist tbl)))
(Jane.test (Hashtbl.data tbl) '(5 6 7))

(defunl Hashtbl.iter (f tbl)
  (maphash f tbl))
(let ((ctr 0))
  (Hashtbl.iter (lambda (_ x) (setq ctr (+ ctr x))) tbl)
  (Jane.test ctr 18))


;; Shell

(defun Shell.readlink (path)
  "Canonize the path by eliminating symlinks and dots"
  (if (not path) nil
    (let ((res (String.strip-newlines
                (shell-command-to-string (format "readlink -f %s" path)))))
      (if (equal res "") nil res))))
;; (Shell.readlink "/usr/../home")
;; (Shell.readlink "/usr/local//share")
;; (Shell.readlink "/..")
;; (Shell.readlink "/...")
;; (Shell.readlink "/../.")
;; (Shell.readlink nil)

(defun Shell.dirname (path)
  (if (not path) nil
    (let ((res (String.strip-newlines
                (shell-command-to-string (format "dirname %s" path)))))
      (if (equal res "") nil res))))
;; (Shell.dirname nil)
;; (Shell.dirname "/")
;; (Shell.dirname "/a/b")
;; (Shell.dirname "/../b")

(defun Shell.basename (path)
  (if (not path) nil
    (let ((res (String.strip-newlines
                (shell-command-to-string (format "basename %s" path)))))
      (if (equal res "") nil res))))
;; (Shell.basename "/a/b/c")
;; (Shell.basename "/")
;; (Shell.basename "/../b")

(defun Shell.mail (subject addr body)
  (shell-command-to-string (format "echo \"%s\" | mail -s \"%s\" \"%s\"" body subject addr))
  nil)
;; (Shell.mail "test" "smclaughlin@janestreet.com" "abc")


;; Buffers

(defun Buffer.name (buffer-or-name)
  "Allow the (string) name of a buffer to be passed to buffer-name"
  (if (bufferp buffer-or-name) (buffer-name buffer-or-name) buffer-or-name))
;; (Buffer.name nil)
;; (Buffer.name "abc")
;; (Buffer.name (get-buffer "*shell*"))

(defun Buffer.safe-get (buffer-or-name)
  "Allow the (string) name of a buffer to be passed to buffer-name"
  (if (bufferp buffer-or-name) (buffer-name buffer-or-name) buffer-or-name))

(defun Buffer.get (buffer-or-name)
  "get-buffer that returns nil on a nil argument"
  (if (null buffer-or-name) nil (get-buffer buffer-or-name)))

(defun Buffer.kill (buffer-or-name)
  "Kill a buffer.  Don't raise an exception of there is no such buffer.
Just return nil.  This is the spec of `kill-buffer', but the former
raises an exception."
  (condition-case nil
      (kill-buffer buffer-or-name)
    (error nil)))
;;(Buffer.kill "abc")
;;(Buffer.kill "abcccc")

(defun Buffer.kill-no-query-no-hooks (&optional buffer-or-name)
  (interactive)
  "Kill a buffer without any questions.  If there's no such buffer, just
return nil"
  (let ((buffer-or-name (if buffer-or-name buffer-or-name (current-buffer)))
        (funs kill-buffer-query-functions)
        (hook kill-buffer-hook))
    (unwind-protect
        (progn
          (setq kill-buffer-query-functions nil)
          (setq kill-buffer-hook nil)
          (Buffer.kill buffer-or-name))
      (setq kill-buffer-query-functions funs)
      (setq kill-buffer-hook hook))))
;;(Buffer.kill-no-query "*Backtrace*")

(defun Buffer.num-lines (buf)
  (save-excursion
    (with-current-buffer buf
      (count-lines (point-min) (point-max)))))
;; (Buffer.num-lines path)

(defun Buffer.clear (buffer)
  "Remove all contents of a given buffer"
  (with-current-buffer buffer
    (delete-region (point-min) (point-max))))


;; Filename

(defun Filename.strip-final-slash (path)
  "/a/b/c/ ---> /a/b/c"
  (let ((n (length path)))
    (if (equal (elt path (- n 1)) ?/)
        (substring path 0 (- n 1))
      path)))
;; (Filename.strip-final-slash "/a/b/c")
;; (Filename.strip-final-slash "/a/b/c/")

(defun Filename.root-dir-p (path) (equal (Shell.readlink path) "/"))
;; (Filename.root-dir-p nil)
;; (Filename.root-dir-p "/")
;; (Filename.root-dir-p "/usr/local/../../")

(defun Filename.up1-dir (dir)
  "Go up 1 directory.  The input must be an existing directory."
  (if (null dir) (Emacs.error "up1-dir: %s" dir)
    (assert (file-directory-p dir))
    (Shell.readlink (concat dir "/.."))))
;; (Filename.up1-dir nil)
;; (Filename.up1-dir "/")
;; (Filename.up1-dir "/doesnt-exist")
;; (Filename.up1-dir "/usr/local")

(defun Filename.directory-of (file-or-dir)
  "Get the directory of a path.  If a file, give the enclosing dir.
If a dir, return the dir"
  (if (null file-or-dir) (Emacs.error "directory-of: %s" file-or-dir)
    (let ((res (if (file-directory-p file-or-dir)
                   file-or-dir
                 (Shell.dirname file-or-dir))))
      (assert (file-directory-p res))
      (Shell.readlink res))))
;; (Filename.directory-of nil)
;; (Filename.directory-of "/usr/local")
;; (Filename.directory-of "~/tmp")
;; (Filename.directory-of "/usr/local/a.txt")

(defun Filename.default-directory ()
  (Filename.strip-final-slash default-directory))
;; (Filename.strip-final-slash "/home/sweeks/jane/base/core/lib_test/")


;; Windows

(defun Window.select-another-window (&optional w)
  "Select a window other than w.  Return nil if there is no such window."
  (let ((w (if w w (selected-window))))
    (get-window-with-predicate (lambda (w1) (not (equal w w1))) nil t)))

(defun Window.all-visible ()
  "Return all visible windows in all visible frames."
  (apply 'append (mapcar (lambda (f) (window-list f "no-mini")) (frame-list))))
;; (Window.all-visible)


;; Timers

(defunl Timer.handle-exn (f handler)
  (assert (functionp f))
  (assert (functionp handler))
  (condition-case err
      (funcall f)
    ((error arith-error)
     (funcall handler err))))

(defunl Timer.run (secs repeat f handler)
  (lexical-let*
      ((f f)
       (handler handler)
       (fn (lambda () (Timer.handle-exn f handler))))
    (run-with-timer secs repeat fn)))

;; (defun tmp () (error "bug"))
;; (defun tmp-handler (err)
;; (tmp)
;; (tmp-handler nil)
;; (setq timer (Timer.run 1 1 'tmp 'tmp-handler))
;; (Timer.handle-exn 'tmp 'tmp-handler)
;; (Timer.handle-exn (lambda () (error "bug"))
;;                   (lambda (err) (message "tmp raised an exn: %s" err)))
;; (setq timer
;;       (Timer.run 1 1
;;                  (lambda () (error "bug"))
;;                  (lambda (err) (message "tmp raised an exn: %s" err))))
;; (cancel-timer timer)


;; Logging
;; inspired by log-buffer.el Cedric Lallain <kandjar76@hotmail.com>

(defun Log.create (buffer-name)
  "Create a new log buffer, called BUFFER-NAME.
If BUFFER-NAME already exist, the function will just set the read-only flag.
The log buffer is returned as a result of this call."
  (let ((buffer (get-buffer-create buffer-name)))
    (with-current-buffer buffer (toggle-read-only 1))
    buffer))

(defconst Log.buffer-max-size 100000
  "Max size of the log buffer in characters")

(defun Log.printf(log-buffer format-string &rest args)
  "Display the text in the log buffer at the very end of it."
  (let ((inhibit-read-only t) ;; the log is probably read-only
	(auto-window-vscroll t)
	(kill-whole-line t) ;; kill the newline as well as the line contents
        (fmt (concat "[%s] " format-string "\n"))
        (time (format-time-string "%y/%m/%d %H:%M:%S" (current-time)))
	(user-buffer (current-buffer))
	(user-window (selected-window))
	(log-window (get-buffer-window log-buffer)))
    (with-current-buffer log-buffer
      (let* ((marker (point-marker))
             (log-point (point))
             (at-bottom (= log-point (point-max))))
        ;; insert the log message on the last line
        (goto-char (point-max))
        (insert (apply 'format (cons fmt (cons time args))))
        ;; maybe delete the first line of the log
        (when (> (buffer-size log-buffer) Log.buffer-max-size)
          (let ((beg (point-min)))
            (goto-char (point-min))
            (forward-line 1)
            (delete-region beg (point))))
        ;; restore window point
        (when log-window
          (if at-bottom
              (progn (select-window log-window)
                     (goto-char (point-max))
                     (recenter (1- (window-body-height log-window))))
            (goto-char (marker-position marker)))
          (select-window user-window))
        (set-marker marker nil)))))
;; (Omake.Server.logf "sean: %s %d" "abc" 8)


;; Misc commands

(defun Emacs.grab-line ()
  "Grab the line of point"
  (interactive)
  (save-excursion
    (end-of-line)
    (let ((end (point)))
      (beginning-of-line)
      (buffer-substring-no-properties (point) end))))

(defun Buffer.last-lines (buffer-or-name n)
  "return the last N lines of a buffer"
  (save-excursion
    (with-current-buffer buffer-or-name
      (goto-char (point-max))
      (let* ((aux nil) ;; dummy for compilation warning
             (aux (lambda (k)
                    (if (equal k 0) nil
                      (let* ((l (Emacs.grab-line))
                             (res (forward-line -1))
                             (rest (when (equal res 0) (funcall aux (- k 1)))))
                        (cons l rest))))))
        (reverse (funcall aux n))))))
;; (length (Buffer.last-lines "*Help*" 10))
;; (with-current-buffer "tmp" (goto-char (point-min) (Emacs.grab-line)))

(defun Buffer.goto-line (n)
  (goto-char (point-min))
  (forward-line (1- n)))

(defun Emacs.error (str &rest args)
  (error (concat "[ERROR] " str) args))

(defun Emacs.window-buffers ()
  "Get all buffers being displayed in a window"
  (List.map 'window-buffer (window-list)))

(defun Emacs.window-files ()
  "Get the file names of all buffers being displayed in a window"
  (List.filter-map 'buffer-file-name (Emacs.window-buffers)))

(defun Emacs.add-hook-append (hook f) (add-hook hook f t))

(defun Emacs.insert (s)
  "Don't raise an exception when s is nil"
  (when s (insert s)))

(defun Emacs.color (s face) (propertize s 'face face))

(defun Overlay.delete-soon (overlay)
  "Set an overlay for some period of time"
  (unwind-protect
      (sit-for 60)
    (delete-overlay overlay)))

(defun Emacs.y-or-n-p (prompt)
  (let ((result (y-or-n-p prompt)))
    ;; The [(message nil)] is necessary to clear the minibuffer.
    (message nil)
    result))

(defun Emacs.insert-object (x) (insert (prin1-to-string x)))
;; (Emacs.insert-object "sean")

(defun File.byte-compile-check ()
  (interactive)
  (let ((file (read-file-name "File: ")))
    (byte-compile-file file)
    (message "removing compiled file")
    (remove-file (concat file "c"))))


;; Hg

(defun hg-resolve-file ()
  (interactive)
  "Run 'hg resolve -m' on the current file"
  (let* ((file (buffer-file-name (current-buffer))))
    (shell-command (format "hg resolve -m %s" file))))

(require 'dired)
(defun hg-resolve-file-dired ()
  (interactive)
  "Run 'hg resolve -m' on the current file in a dired buffer"
  (let* ((file (dired-file-name-at-point)))
    (shell-command (format "hg resolve -m %s" file))))

(provide 'jane-lib)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.