-
Notifications
You must be signed in to change notification settings - Fork 32
/
beancount.el
1370 lines (1182 loc) · 51.7 KB
/
beancount.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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; beancount.el --- A major mode to edit Beancount input files. -*- lexical-binding: t -*-
;; Copyright (C) 2013 Martin Blais <[email protected]>
;; Copyright (C) 2015 Free Software Foundation, Inc.
;; Copyright (C) 2019 Daniele Nicolodi <[email protected]>
;; Version: 0.9
;; Author: Martin Blais <[email protected]>
;; Author: Stefan Monnier <[email protected]>
;; Author: Daniele Nicolodi <[email protected]>
;; This file is not part of GNU Emacs.
;; This package 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 package 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 package. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; TODO: Add a flymake rule, using bean-check
;;; Code:
(autoload 'ido-completing-read "ido")
(require 'subr-x)
(require 'outline)
(require 'thingatpt)
(require 'cl-lib)
(require 'xref)
(require 'apropos)
(require 'rx)
;;;###autoload
(add-to-list 'auto-mode-alist '("\\.beancount\\'" . beancount-mode))
(defgroup beancount ()
"Editing mode for Beancount files."
:group 'beancount)
(defcustom beancount-transaction-indent 2
"Transaction indent."
:type 'integer)
(defcustom beancount-number-alignment-column 52
"Column to which align numbers in posting definitions. Set to
0 to automatically determine the minimum column that will allow
to align all amounts."
:type 'integer)
(defcustom beancount-highlight-transaction-at-point nil
"If t highlight transaction under point."
:type 'boolean)
(defcustom beancount-use-ido t
"If non-nil, use ido-style completion rather than the standard."
:type 'boolean)
(defcustom beancount-electric-currency nil
"If non-nil, make `newline' try to add missing currency to
complete the posting at point. The correct currency is determined
from the open directive for the relevant account."
:type 'boolean)
(defgroup beancount-faces nil "Beancount mode highlighting" :group 'beancount)
(defface beancount-directive
'((t :inherit font-lock-keyword-face))
"Face for Beancount directives.")
(defface beancount-tag
'((t :inherit font-lock-type-face))
"Face for Beancount tags.")
(defface beancount-link
'((t :inherit font-lock-type-face))
"Face for Beancount links.")
(defface beancount-date
'((t :inherit font-lock-constant-face))
"Face for Beancount dates.")
(defface beancount-account
'((t :inherit font-lock-builtin-face))
"Face for Beancount account names.")
(defface beancount-amount
'((t :inherit default))
"Face for Beancount amounts.")
(defface beancount-narrative
'((t :inherit font-lock-builtin-face))
"Face for Beancount transactions narrative.")
(defface beancount-narrative-cleared
'((t :inherit font-lock-string-face))
"Face for Beancount cleared transactions narrative.")
(defface beancount-narrative-pending
'((t :inherit font-lock-keyword-face))
"Face for Beancount pending transactions narrative.")
(defface beancount-metadata
'((t :inherit font-lock-type-face))
"Face for Beancount metadata.")
(defface beancount-highlight
'((t :inherit highlight))
"Face to highlight Beancount transaction at point.")
(defface beancount-outline-1
'((t :inherit outline-1))
"Outline level 1.")
(defface beancount-outline-2
'((t :inherit outline-2))
"Outline level 2.")
(defface beancount-outline-3
'((t :inherit outline-3))
"Outline level 3.")
(defface beancount-outline-4
'((t :inherit outline-4))
"Outline level 4.")
(defface beancount-outline-5
'((t :inherit outline-5))
"Outline level 5.")
(defface beancount-outline-6
'((t :inherit outline-6))
"Outline level 6.")
(defface beancount-outline-7
'((t :inherit outline-7))
"Outline level 7.")
(defface beancount-outline-8
'((t :inherit outline-8))
"Outline level 8.")
(defconst beancount-account-directive-names
'("balance"
"close"
"document"
"note"
"open"
"pad")
"Directive names that can appear after a date and are followd by an account.")
(defconst beancount-no-account-directive-names
'("commodity"
"event"
"price"
"query"
"txn")
"Directives with a date but without an account.
List of directive names that can appear after a date and that are
_not_ followed by an account.")
(defconst beancount-timestamped-directive-names
(append beancount-account-directive-names
beancount-no-account-directive-names)
"Directive names that can appear after a date.")
(defconst beancount-directive-names
'("include"
"option"
"plugin"
"poptag"
"pushtag")
"Directive names that can appear at the beginning of a line.")
(defconst beancount-account-categories
'("Assets" "Liabilities" "Equity" "Income" "Expenses"))
(defconst beancount-tag-chars "[:alnum:]-_/.")
(defconst beancount-account-chars "[:alnum:]-_:")
(defconst beancount-option-names
;; This list is kept in sync with the options defined in
;; beancount/parser/options.py.
'("account_current_conversions"
"account_current_earnings"
"account_previous_balances"
"account_previous_conversions"
"account_previous_earnings"
"account_rounding"
"account_unrealized_gains"
"allow_deprecated_none_for_tags_and_links"
"allow_pipe_separator"
"booking_method"
"conversion_currency"
"documents"
"infer_tolerance_from_cost"
"inferred_tolerance_default"
"inferred_tolerance_multiplier"
"insert_pythonpath"
"long_string_maxlines"
"name_assets"
"name_equity"
"name_expenses"
"name_income"
"name_liabilities"
"operating_currency"
"plugin_processing_mode"
"render_commas"
"title"))
(defconst beancount-date-regexp "[0-9]\\{4\\}[-/][0-9]\\{2\\}[-/][0-9]\\{2\\}"
"A regular expression to match dates.")
(defconst beancount-account-regexp
(concat (regexp-opt beancount-account-categories)
"\\(?::[[:upper:][:digit:]][[:alnum:]-_]+\\)+")
"A regular expression to match account names.")
(defconst beancount-number-regexp "[-+]?[0-9]+\\(?:,[0-9]\\{3\\}\\)*\\(?:\\.[0-9]*\\)?"
"A regular expression to match decimal numbers.")
(defconst beancount-currency-regexp "[A-Z][A-Z-_'.]*"
"A regular expression to match currencies.")
(defconst beancount-flag-regexp
;; Single char that is neither a space nor a lower-case letter.
"[^ a-z]")
(defconst beancount-transaction-regexp
(concat "^\\(" beancount-date-regexp "\\) +"
"\\(\\(?:txn+\\)\\|" beancount-flag-regexp "\\) +"
"\\(\".*\"\\)"))
(defconst beancount-posting-regexp
(concat "^\\s-+"
"\\(" beancount-account-regexp "\\)"
"\\(?:\\s-+\\(\\(" beancount-number-regexp "\\)"
"\\s-+\\(" beancount-currency-regexp "\\)\\)\\)?"))
(defconst beancount-balance-regexp
;; The grouping in this regular expression matches the one in
;; `beancount-posting-regexp' to be used in amount align
;; machinery. See `beancount-align-number'.
(concat "^" beancount-date-regexp "\\s-+balance\\s-+"
"\\(" beancount-account-regexp "\\)\\s-+"
"\\(\\(" beancount-number-regexp "\\)\\s-+\\(" beancount-currency-regexp "\\)\\)"))
(defconst beancount-directive-regexp
(concat "^\\(" (regexp-opt beancount-directive-names) "\\) +"))
(defconst beancount-timestamped-directive-regexp
(concat "^\\(" beancount-date-regexp "\\) +"
"\\(" (regexp-opt beancount-timestamped-directive-names) "\\) +"))
(defconst beancount-metadata-regexp
"^\\s-+\\([a-z][A-Za-z0-9_-]+:\\)\\s-+\\(.+\\)")
(defconst beancount-open-directive-regexp
(concat "^\\(" beancount-date-regexp "\\) +"
"\\(open\\) +"
"\\(" beancount-account-regexp "\\)"))
;; This is a grouping regular expression because the subexpression is
;; used in determining the outline level in `beancount-outline-level'.
(defvar beancount-outline-regexp "\\(;;;+\\|\\*+\\)")
;; Regular expression for all symbols recognised by the Xref backend.
(defconst beancount-xref-symbol-regexp
(rx-to-string `(or (regexp ,beancount-account-regexp)
(regexp ,(concat "#[" beancount-tag-chars "]+"))
(regexp ,(concat "\\^[" beancount-tag-chars "]+")))))
(defun beancount-outline-level ()
(let ((len (- (match-end 1) (match-beginning 1))))
(if (string-equal (substring (match-string 1) 0 1) ";")
(- len 2)
len)))
(defun beancount-face-by-state (state)
(cond ((string-equal state "*") 'beancount-narrative-cleared)
((string-equal state "!") 'beancount-narrative-pending)
(t 'beancount-narrative)))
(defun beancount-outline-face ()
(if outline-minor-mode
(cl-case (funcall outline-level)
(1 'beancount-outline-1)
(2 'beancount-outline-2)
(3 'beancount-outline-3)
(4 'beancount-outline-4)
(5 'beancount-outline-5)
(6 'beancount-outline-6)
(7 'beancount-outline-7)
(8 'beancount-outline-8)
(otherwise nil))
nil))
(defvar beancount-font-lock-keywords
`((,beancount-transaction-regexp (1 'beancount-date)
(2 (beancount-face-by-state (match-string 2)) t)
(3 (beancount-face-by-state (match-string 2)) t))
(,beancount-posting-regexp (1 'beancount-account)
(2 'beancount-amount nil :lax))
(,beancount-metadata-regexp (1 'beancount-metadata)
(2 'beancount-metadata t))
(,beancount-directive-regexp (1 'beancount-directive))
(,beancount-timestamped-directive-regexp (1 'beancount-date)
(2 'beancount-directive))
;; Fontify section headers when composed with outline-minor-mode.
(,(concat "^\\(" beancount-outline-regexp "\\).*") (0 (beancount-outline-face)))
;; Tags and links.
(,(concat "\\#[" beancount-tag-chars "]*") . 'beancount-tag)
(,(concat "\\^[" beancount-tag-chars "]*") . 'beancount-link)
;; Accounts not covered by previous rules.
(,beancount-account-regexp . 'beancount-account)
;; Number followed by currency not covered by previous rules.
(,(concat beancount-number-regexp "\\s-+" beancount-currency-regexp) . 'beancount-amount)
))
(defun beancount-tab-dwim (&optional arg)
(interactive "P")
(if (and outline-minor-mode
(or arg (outline-on-heading-p)))
(beancount-outline-cycle arg)
(indent-for-tab-command)))
(defvar beancount-mode-map-prefix [(control c)]
"The prefix key used to bind Beancount commands in Emacs")
(defvar beancount-mode-old-style-keybindings nil
"*Set this to non-nil to continue using old-style keybindings.
In mid-2023, `beancount-mode' changed the keybindings for many of its
commands. This was because the old bindings violated the Emacs
keybinding standards (see section \"Key Binding Conventions\" in the
Emacs Lisp documentation). However, you might be accustomed to the
old bindings and prefer to continue using them; this variable offers a
convenient way to do so. If it is non-nil when `beancount.el' is
loaded, then the old bindings will also be made available. (The new
bindings will be left in place too, since the key sequences they use
are reserved for the mode anyway.)")
(defvar beancount-mode-map
(let ((map (make-sparse-keymap))
(p beancount-mode-map-prefix))
(define-key map (kbd "TAB") #'beancount-tab-dwim)
(define-key map (kbd "M-RET") #'beancount-insert-date)
(define-key map (vconcat p [(\')]) #'beancount-insert-account)
(define-key map (vconcat p [(control c)]) #'beancount-transaction-clear)
(define-key map (vconcat p [(control l)]) #'beancount-check)
(define-key map (vconcat p [(control q)]) #'beancount-query)
(define-key map (vconcat p [(control x)]) #'beancount-context)
(define-key map (vconcat p [(control k)]) #'beancount-linked)
(define-key map (vconcat p [(control r)]) #'beancount-region-default)
(define-key map (vconcat p [(control t)]) #'beancount-region-value)
(define-key map (vconcat p [(control y)]) #'beancount-region-cost)
(define-key map (vconcat p [(control i)]) #'beancount-insert-prices)
(define-key map (vconcat p [(left)]) #'beancount-date-down-day)
(define-key map (vconcat p [(right)]) #'beancount-date-up-day)
(define-key map (vconcat p [(\;)]) #'beancount-align-to-previous-number)
(define-key map (vconcat p [(\:)]) #'beancount-align-numbers)
(when beancount-mode-old-style-keybindings
(define-key map [(control c)(control g)] #'beancount-transaction-clear)
(define-key map [(control c)(l)] #'beancount-check)
(define-key map [(control c)(q)] #'beancount-query)
(define-key map [(control c)(x)] #'beancount-context)
(define-key map [(control c)(k)] #'beancount-linked)
(define-key map [(control c)(r)] #'beancount-region-default)
(define-key map [(control c)(t)] #'beancount-region-value)
(define-key map [(control c)(y)] #'beancount-region-cost)
(define-key map [(control c)(p)] #'beancount-insert-prices))
map))
(defvar beancount-mode-syntax-table
(let ((st (make-syntax-table)))
(modify-syntax-entry ?\" "\"\"" st)
(modify-syntax-entry ?\; "<" st)
(modify-syntax-entry ?\n ">" st)
st))
;;;###autoload
(define-derived-mode beancount-mode prog-mode "Beancount"
"A mode for Beancount files.
\\{beancount-mode-map}"
:group 'beancount
:syntax-table beancount-mode-syntax-table
(setq-local paragraph-ignore-fill-prefix t)
(setq-local fill-paragraph-function #'beancount-indent-transaction)
(setq-local comment-start ";")
(setq-local comment-start-skip ";+\\s-*")
(setq-local comment-add 1)
(setq-local indent-line-function #'beancount-indent-line)
(setq-local indent-region-function #'beancount-indent-region)
(setq-local indent-tabs-mode nil)
(setq-local tab-always-indent 'complete)
(setq-local completion-ignore-case t)
(add-hook 'completion-at-point-functions #'beancount-completion-at-point nil t)
(add-hook 'post-command-hook #'beancount-highlight-transaction-at-point nil t)
(add-hook 'post-self-insert-hook #'beancount--electric-currency nil t)
(setq-local font-lock-defaults '(beancount-font-lock-keywords))
(setq-local font-lock-syntax-table t)
(setq-local outline-regexp beancount-outline-regexp)
(setq-local outline-level #'beancount-outline-level)
(setq-local xref-backend-functions #'beancount-xref-backend)
(setq imenu-generic-expression
(list (list nil (concat "^" beancount-outline-regexp "\\s-+\\(.*\\)$") 2))))
(defun beancount-collect-pushed-tags (begin end)
"Return list of all pushed (and not popped) tags in the region."
(goto-char begin)
(let ((tags (make-hash-table :test 'equal)))
(while (re-search-forward
(concat "^\\(push\\|pop\\)tag\\s-+\\(#[" beancount-tag-chars "]+\\)") end t)
(if (string-equal (match-string 1) "push")
(puthash (match-string-no-properties 2) nil tags)
(remhash (match-string-no-properties 2) tags)))
(hash-table-keys tags)))
(defun beancount-goto-transaction-begin ()
"Move the cursor to the first line of the transaction definition."
(interactive)
(beginning-of-line)
;; everything that is indented with at lest one space or tab is part
;; of the transaction definition
(while (looking-at-p "[ \t]+")
(forward-line -1))
(point))
(defun beancount-goto-transaction-end ()
"Move the cursor to the line after the transaction definition."
(interactive)
(beginning-of-line)
(if (looking-at-p beancount-transaction-regexp)
(forward-line))
;; everything that is indented with at least one space or tab as part
;; of the transaction definition
(while (looking-at-p "[ \t]+")
(forward-line))
(point))
(defun beancount-goto-next-transaction (&optional arg)
"Move to the next transaction.
With an argument move to the next non cleared transaction."
(interactive "P")
(beancount-goto-transaction-end)
(let ((done nil))
(while (and (not done)
(re-search-forward beancount-transaction-regexp nil t))
(if (and arg (string-equal (match-string 2) "*"))
(goto-char (match-end 0))
(goto-char (match-beginning 0))
(setq done t)))
(if (not done) (goto-char (point-max)))))
(defun beancount-goto-previous-transaction (&optional arg)
"Move to the previous transaction.
With an argument move to the previous non cleared transaction."
(interactive "P")
(beancount-goto-transaction-begin)
(let ((done nil))
(while (and (not done)
(re-search-backward beancount-transaction-regexp nil t))
(if (and arg (string-equal (match-string 2) "*"))
(goto-char (match-beginning 0))
(goto-char (match-beginning 0))
(setq done t)))
(if (not done) (goto-char (point-min)))))
(defun beancount-find-transaction-extents (p)
(save-excursion
(goto-char p)
(list (beancount-goto-transaction-begin)
(beancount-goto-transaction-end))))
(defun beancount-inside-transaction-p ()
(let ((bounds (beancount-find-transaction-extents (point))))
(> (- (cadr bounds) (car bounds)) 0)))
(defun beancount-looking-at (regexp n pos)
(and (looking-at regexp)
(>= pos (match-beginning n))
(<= pos (match-end n))))
(defvar beancount-accounts nil
"A list of the accounts available in this buffer.")
(make-variable-buffer-local 'beancount-accounts)
(defun beancount-completion-at-point ()
"Return the completion data relevant for the text at point."
(save-excursion
(save-match-data
(let ((pos (point)))
(beginning-of-line)
(cond
;; non timestamped directive
((beancount-looking-at "[a-z]*" 0 pos)
(list (match-beginning 0) (match-end 0)
(mapcar (lambda (s) (concat s " ")) beancount-directive-names)))
;; poptag
((beancount-looking-at
(concat "poptag\\s-+\\(\\(?:#[" beancount-tag-chars "]*\\)\\)") 1 pos)
(list (match-beginning 1) (match-end 1)
(beancount-collect-pushed-tags (point-min) (point))))
;; option
((beancount-looking-at
(concat "^option\\s-+\\(\"[a-z_]*\\)") 1 pos)
(list (match-beginning 1) (match-end 1)
(mapcar (lambda (s) (concat "\"" s "\" ")) beancount-option-names)))
;; timestamped directive
((beancount-looking-at
(concat beancount-date-regexp "\\s-+\\([[:alpha:]]*\\)") 1 pos)
(list (match-beginning 1) (match-end 1)
(mapcar (lambda (s) (concat s " ")) beancount-timestamped-directive-names)))
;; timestamped directives followed by account
((beancount-looking-at
(concat "^" beancount-date-regexp
"\\s-+" (regexp-opt beancount-account-directive-names)
"\\s-+\\([" beancount-account-chars "]*\\)") 1 pos)
(setq beancount-accounts nil)
(list (match-beginning 1) (match-end 1) #'beancount-account-completion-table))
;; pad directive followed by two accounts
((beancount-looking-at
(concat "^" beancount-date-regexp
"\\s-+" (regexp-opt '("pad"))
"\\s-+\\([" beancount-account-chars "]*\\)"
"\\s-+\\([" beancount-account-chars "]*\\)") 2 pos)
(setq beancount-accounts nil)
(list (match-beginning 2) (match-end 2) #'beancount-account-completion-table))
;; posting
((and (beancount-looking-at
(concat "[ \t]+\\([" beancount-account-chars "]*\\)") 1 pos)
;; Do not force the account name to start with a
;; capital, so that it is possible to use substring
;; completion and we can rely on completion to fix
;; capitalization thanks to completion-ignore-case.
(beancount-inside-transaction-p))
(setq beancount-accounts nil)
(list (match-beginning 1) (match-end 1) #'beancount-account-completion-table))
;; tags
((beancount-looking-at
(concat "[ \t]+#\\([" beancount-tag-chars "]*\\)") 1 pos)
(let* ((candidates nil)
(regexp (concat "\\#\\([" beancount-tag-chars "]+\\)"))
(completion-table
(lambda (string pred action)
(if (null candidates)
(setq candidates
(sort (beancount-collect-unique regexp 1) #'string<)))
(complete-with-action action candidates string pred))))
(list (match-beginning 1) (match-end 1) completion-table)))
;; links
((beancount-looking-at
(concat "[ \t]+\\^\\([" beancount-tag-chars "]*\\)") 1 pos)
(let* ((candidates nil)
(regexp (concat "\\^\\([" beancount-tag-chars "]+\\)"))
(completion-table
(lambda (string pred action)
(if (null candidates)
(setq candidates
(sort (beancount-collect-unique regexp 1) #'string<)))
(complete-with-action action candidates string pred))))
(list (match-beginning 1) (match-end 1) completion-table))))))))
(defun beancount-collect-pos-alist (regexp n)
"Return a list of conses mapping matches of REGEXP group N in the
current buffer to a position of the match beginning."
(let ((pos (point)))
(save-excursion
(save-match-data
(let (result)
(goto-char (point-min))
(while (re-search-forward regexp nil t)
;; Ignore matches around `pos' (the point position when
;; entering this funcyion) since that's presumably what
;; we're currently trying to complete.
(unless (<= (match-beginning 0) pos (match-end 0))
(push (cons (match-string-no-properties n) (match-beginning 0))
result)))
(nreverse result))))))
(defun beancount-get-account-names ()
"Return a list of known account names available in the buffer."
(when (null beancount-accounts)
;; Collecting a full list and then deduping it is a heavy
;; operation. But because of caching the will only happen once -
;; whenever a completion is requested.
(setq beancount-accounts
(sort (beancount-collect-unique beancount-account-regexp 0) #'string<)))
beancount-accounts)
(defun beancount-collect-unique (regexp n)
"Return an unique list of REGEXP group N in the current buffer."
(delete-dups (mapcar #'car (beancount-collect-pos-alist regexp n))))
(defun beancount-account-completion-table (string pred action)
(if (eq action 'metadata) '(metadata (category . beancount-account))
(with-current-buffer (let ((win (minibuffer-selected-window)))
(if (window-live-p win) (window-buffer win)
(current-buffer)))
(complete-with-action action (beancount-get-account-names) string pred))))
;; Default to substring completion for beancount accounts.
(defconst beancount--completion-overrides
'(beancount-account (styles basic partial-completion substring)))
(add-to-list 'completion-category-defaults beancount--completion-overrides)
(defun beancount-number-alignment-column ()
"Return the column to which postings amounts should be aligned to.
Returns `beancount-number-alignment-column' unless it is 0. In
that case, scan the buffer to determine the minimum column that
will allow to align all numbers."
(if (> beancount-number-alignment-column 0)
beancount-number-alignment-column
(save-excursion
(save-match-data
(let ((account-width 0)
(number-width 0))
(goto-char (point-min))
(while (re-search-forward beancount-posting-regexp nil t)
(if (match-string 2)
(let ((accw (- (match-end 1) (line-beginning-position)))
(numw (- (match-end 3) (match-beginning 3))))
(setq account-width (max account-width accw)
number-width (max number-width numw)))))
(+ account-width 2 number-width))))))
(defun beancount-compute-indentation ()
"Return the column to which the current line should be indented."
(save-excursion
(beginning-of-line)
(cond
;; Only timestamped directives start with a digit.
((looking-at-p "[0-9]") 0)
;; Otherwise look at the previous line.
((and (= (forward-line -1) 0)
(or (looking-at-p "[ \t].+")
(looking-at-p beancount-timestamped-directive-regexp)
(looking-at-p beancount-transaction-regexp)))
beancount-transaction-indent)
;; Default.
(t 0))))
(defun beancount-align-number (target-column)
(save-excursion
(beginning-of-line)
;; Check if the current line is a posting with a number to align.
(when (and (or (looking-at beancount-posting-regexp)
(looking-at beancount-balance-regexp))
(match-string 2))
(let* ((account-end-column (- (match-end 1) (line-beginning-position)))
(number-width (- (match-end 3) (match-beginning 3)))
(account-end (match-end 1))
(number-beginning (match-beginning 3))
(spaces (max 2 (- target-column account-end-column number-width))))
(unless (eq spaces (- number-beginning account-end))
(goto-char account-end)
(delete-region account-end number-beginning)
(insert (make-string spaces ? )))))))
(defun beancount-indent-line ()
(let ((indent (beancount-compute-indentation))
(savep (> (current-column) (current-indentation))))
(unless (eq indent (current-indentation))
(if savep (save-excursion (indent-line-to indent))
(indent-line-to indent)))
(beancount-align-number (beancount-number-alignment-column))))
(defun beancount-indent-region (start end)
"Indent a region automagically. START and END specify the region to indent."
(let ((deactivate-mark nil)
(beancount-number-alignment-column (beancount-number-alignment-column)))
(save-excursion
(setq end (copy-marker end))
(goto-char start)
(or (bolp) (forward-line 1))
(while (< (point) end)
(unless (looking-at-p "\\s-*$")
(beancount-indent-line))
(forward-line 1))
(move-marker end nil))))
(defun beancount-indent-transaction (&optional _justify _region)
"Indent Beancount transaction at point."
(interactive)
(save-excursion
(let ((bounds (beancount-find-transaction-extents (point))))
(beancount-indent-region (car bounds) (cadr bounds)))))
(defun beancount-transaction-clear (&optional arg)
"Clear transaction at point. With a prefix argument set the
transaction as pending."
(interactive "P")
(save-excursion
(save-match-data
(let ((flag (if arg "!" "*")))
(beancount-goto-transaction-begin)
(if (looking-at beancount-transaction-regexp)
(replace-match flag t t nil 2))))))
(defun beancount-insert-account (account-name)
"Insert one of the valid account names in this file.
Uses ido niceness according to `beancount-use-ido'."
(interactive
(list
(if beancount-use-ido
;; `ido-completing-read' does not understand functional
;; completion tables thus directly build a list of the
;; accounts in the buffer
(let ((beancount-accounts
(sort (beancount-collect-unique beancount-account-regexp 0) #'string<)))
(ido-completing-read "Account: " beancount-accounts
nil nil (thing-at-point 'word)))
(completing-read "Account: " #'beancount-account-completion-table
nil t (thing-at-point 'word)))))
(let ((bounds (bounds-of-thing-at-point 'word)))
(when bounds
(delete-region (car bounds) (cdr bounds))))
(insert account-name))
(defmacro beancount-for-line-in-region (begin end &rest exprs)
"Iterate over each line in region until an empty line is encountered."
`(save-excursion
(let ((end-marker (copy-marker ,end)))
(goto-char ,begin)
(beginning-of-line)
(while (and (not (eobp)) (< (point) end-marker))
(beginning-of-line)
(progn ,@exprs)
(forward-line 1)
))))
(defun beancount-align-numbers (begin end &optional requested-currency-column)
"Align all numbers in the given region. CURRENCY-COLUMN is the character
at which to align the beginning of the amount's currency. If not specified, use
the smallest columns that will align all the numbers. With a prefix argument,
align with the fill-column."
(interactive "r")
;; With a prefix argument, align with the fill-column.
(when current-prefix-arg
(setq requested-currency-column fill-column))
;; Loop once in the region to find the length of the longest string before the
;; number.
(let (prefix-widths
number-widths
(number-padding " "))
(beancount-for-line-in-region
begin end
(let ((line (thing-at-point 'line)))
(when (string-match (concat "\\(.*?\\)"
"[ \t]+"
"\\(" beancount-number-regexp "\\)"
"[ \t]+"
beancount-currency-regexp)
line)
(push (length (match-string 1 line)) prefix-widths)
(push (length (match-string 2 line)) number-widths)
)))
(when prefix-widths
;; Loop again to make the adjustments to the numbers.
(let* ((number-width (apply 'max number-widths))
(number-format (format "%%%ss" number-width))
;; Compute rightmost column of prefix.
(max-prefix-width (apply 'max prefix-widths))
(max-prefix-width
(if requested-currency-column
(max (- requested-currency-column (length number-padding) number-width 1)
max-prefix-width)
max-prefix-width))
(prefix-format (format "%%-%ss" max-prefix-width))
)
(beancount-for-line-in-region
begin end
(let ((line (thing-at-point 'line)))
(when (string-match (concat "^\\([^\"]*?\\)"
"[ \t]+"
"\\(" beancount-number-regexp "\\)"
"[ \t]+"
"\\(.*\\)$")
line)
(delete-region (line-beginning-position) (line-end-position))
(let* ((prefix (match-string 1 line))
(number (match-string 2 line))
(rest (match-string 3 line)) )
(insert (format prefix-format prefix))
(insert number-padding)
(insert (format number-format number))
(insert " ")
(insert rest)))))))))
(defun beancount-align-to-previous-number ()
"Align postings under the point's paragraph.
This function looks for a posting in the previous transaction to
determine the column at which to align the transaction, or otherwise
the fill column, and align all the postings of this transaction to
this column."
(interactive)
(let* ((begin (save-excursion
(beancount-beginning-of-directive)
(point)))
(end (save-excursion
(goto-char begin)
(forward-paragraph 1)
(point)))
(currency-column (or (beancount-find-previous-alignment-column)
fill-column)))
(beancount-align-numbers begin end currency-column)))
(defun beancount-beginning-of-directive ()
"Move point to the beginning of the enclosed or preceding directive."
(beginning-of-line)
(while (and (> (point) (point-min))
(not (looking-at
"[0-9][0-9][0-9][0-9][\-/][0-9][0-9][\-/][0-9][0-9]")))
(forward-line -1)))
(defun beancount-find-previous-alignment-column ()
"Find the preceding column to align amounts with.
This is used to align transactions at the same column as that of
the previous transaction in the file. This function merely finds
what that column is and returns it (an integer)."
;; Go hunting for the last column with a suitable posting.
(let (column)
(save-excursion
;; Go to the beginning of the enclosing directive.
(beancount-beginning-of-directive)
(forward-line -1)
;; Find the last posting with an amount and a currency on it.
(let ((posting-regexp (concat
"\\s-+"
beancount-account-regexp "\\s-+"
beancount-number-regexp "\\s-+"
"\\(" beancount-currency-regexp "\\)"))
(balance-regexp (concat
beancount-date-regexp "\\s-+"
"balance" "\\s-+"
beancount-account-regexp "\\s-+"
beancount-number-regexp "\\s-+"
"\\(" beancount-currency-regexp "\\)")))
(while (and (> (point) (point-min))
(not (or (looking-at posting-regexp)
(looking-at balance-regexp))))
(forward-line -1))
(when (or (looking-at posting-regexp)
(looking-at balance-regexp))
(setq column (- (match-beginning 1) (point))))
))
column))
(defun beancount--account-currency (account)
;; Build a regexp that matches an open directive that specifies a
;; single account currencydaaee. The currency is match group 1.
(let ((re (concat "^" beancount-date-regexp " +open"
"\\s-+" (regexp-quote account)
"\\s-+\\(" beancount-currency-regexp "\\)\\s-+")))
(save-excursion
(goto-char (point-min))
(when (re-search-forward re nil t)
;; The account has declared a single currency, so we can fill it in.
(match-string-no-properties 1)))))
(defun beancount--electric-currency ()
(when (and beancount-electric-currency (eq last-command-event ?\n))
(save-excursion
(forward-line -1)
(when (and (beancount-inside-transaction-p)
(looking-at (concat "\\s-+\\(" beancount-account-regexp "\\)"
"\\s-+\\(" beancount-number-regexp "\\)\\s-*$")))
;; Last line is a posting without currency.
(let* ((account (match-string 1))
(pos (match-end 0))
(currency (beancount--account-currency account)))
(when currency
(save-excursion
(goto-char pos)
(insert " " currency))))))))
(defmacro beancount--encode-time (time)
"Compatibility helper.
Impedence match the `encode-time' interface between Emacs-26 and
later Emacs releases. It can be eliminated once support for
Emacs-26 is dropped."
(if (version< emacs-version "27.1")
`(apply #'encode-time ,time)
`(encode-time ,time)))
(defun beancount--parse-date (string)
"Parse the STRING date in the format %Y-%m-%d into a Lisp timestamp."
(save-match-data
(string-match "\\`\\([0-9][0-9][0-9][0-9]\\)-\\([0-9][0-9]\\)-\\([0-9][0-9]\\)\\'" string)
(beancount--encode-time (list 0 0 0
(string-to-number (match-string 3 string))
(string-to-number (match-string 2 string))
(string-to-number (match-string 1 string))
nil -1 nil))))
(defun beancount--format-date (time)
"Format the Lisp timestamp TIME into a date in the format %Y-%m-%d."
(format-time-string "%Y-%m-%d" time))
(defun beancount-insert-date (&optional days)
"Start a new timestamped directive with date DAYS before today."
(interactive "P")
(unless (bolp) (newline))
(insert (beancount--format-date (time-add (current-time) (days-to-time (- (or days 0)))))))
(defun beancount--shift-date-at-point (days)
"Shift the date under point by a specified number of DAYS."
(if (thing-at-point-looking-at beancount-date-regexp 10)
(let ((pos (point))
(date (beancount--parse-date (match-string 0))))
(replace-match (beancount--format-date (time-add date (days-to-time days))) t t)
;; Ensure that point stays in the same position.
(goto-char pos))
(user-error "No date at point")))
(defun beancount-date-up-day (&optional days)
"Increase the date in the current line by one day.
With prefix ARG, change that many days."
(interactive "p")
(beancount--shift-date-at-point (or days 1)))
(defun beancount-date-down-day (&optional days)
"Decrease the date in the current line by one day.
With prefix ARG, change that many days."
(interactive "p")
(beancount--shift-date-at-point (- (or days 1))))
(defvar beancount-install-dir nil
"Directory in which Beancount's source is located.
Only useful if you have not installed Beancount properly in your PATH.")
(defvar beancount-check-program "bean-check"
"Program to run to run just the parser and validator on an
input file.")
(defvar compilation-read-command)
(defun beancount--run (prog &rest args)
(let ((process-environment
(if beancount-install-dir
`(,(concat "PYTHONPATH=" beancount-install-dir)
,(concat "PATH="
(expand-file-name "bin" beancount-install-dir)
":"
(getenv "PATH"))
,@process-environment)
process-environment))
(compile-command (mapconcat (lambda (arg)
(if (stringp arg)
(shell-quote-argument arg) ""))
(cons prog args)
" ")))
(call-interactively 'compile)))
(defun beancount-check ()
"Run `beancount-check-program'."
(interactive)
(let ((compilation-read-command nil))
(beancount--run beancount-check-program
(file-relative-name buffer-file-name))))
(defvar beancount-query-program "bean-query"
"Program to run to run just the parser and validator on an
input file.")
(defun beancount-query ()