Simon Volpert bean-add / master bean-add
master

Tree @master (Download .tar.gz)

bean-add @masterraw · history · blame

   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
#!/usr/bin/env python3
# bean-add - A beancount transaction entry assistant
# Author: Simon Volpert <simon@simonvolpert.com>
# Project page: https://simonvolpert.com/bean-add/
# This program is free software, released under the Apache License, Version 2.0. See the LICENSE file for more information
# Consult the README file for usage instructions and other helpful hints

import readline
import sys
import datetime
import subprocess
import os

# Set global constants
tempfile = '/tmp/bean-add.%s.tmp.bnct' % os.environ['USER']

usage = '''Usage: bean-add [-n] FILENAME
Add or edit transactions in the beancount journal FILENAME.

  -n           immediately enter a new transaction with today's date
  -h, --help   show this help message

See the README file for more information.'''


# Init transaction data
class data(object):
	# Journal/transactions
	journal = []
	saved = []
	external_journal = []
	file_name = ''
	defaults = {}
	restore = []
	mtime = 0
	# Completion
	accounts = []
	currencies = []
	tags = []
	vocab = []
	history = {
		'command': [],
		'date': [],
		'description': [],
		'account': [],
		'amount': [],
		'tag': [],
		'seek': [],
		'lookup': [],
		'note': [],
		'txids': []
	}
	history_context = 'command'
	# Current transaction
	description = ''
	cur = ''
	balance = 0
	known_balances = {}
	tag = 'bean-add'
	txid = -1
	date = datetime.date.today().isoformat()
	date_prompt = '%Y-%m-%d'
	lookup_string = ''
	eof = False
	# Statements
	statement = []
	statement_pattern = ' ! '
	statement_replacement = ' * '
	target = 0
	statement_currency = ''
	transaction_account = ''
	funding_account = ''
	# Options
	sort_by_date = True
	date_delimiter = '-'
	use_defaults = None
	paranoid_write = False
	external_write = False
	date_preview = True
	context = 10
	auto_flag = []
	lookup_seek = None
	max_expr_length = 40
	auto_new = False


# Ask for confirmation: str(prompt) -> bool(result)
def confirm(prompt='', default_yes=None):
	# Unset completion
	data.vocab = []
	readline.set_completer_delims('')
	# Get a valid confirmation
	while True:
		ch = input(prompt).lower()
		if ch == '':
			if default_yes is None:
				continue
			ch = 'y' if default_yes else 'n'
		if ch == 'y':
			return True
		elif ch == 'n':
			return False


# Cast a number into the appropriate format: number -> int or rounded float
def cast_number(number):
	number = float(number)
	return int(number) if number.is_integer() else round(number, 2)


# Condense whitespace and return a list
def condense(line):
	line = line.strip().split(' ')
	_data = []
	for i in line:
		if i.strip() != '':
			_data.append(i)
	return _data


# Naive word pluralization
def pluralize(number, word):
	number = str(number)
	return '%s %s' % (number, word if number.endswith('1') and not number.endswith('11') else word + 's')


# Completion
def complete(text, state):
	results = [x for x in data.vocab if x.startswith(text)] + [None]
	return results[state]


# Set up histories
def set_history_context(context):
	data.history[data.history_context] = []
	for i in range(readline.get_current_history_length()):
		data.history[data.history_context].append(readline.get_history_item(i + 1))
	readline.clear_history()
	for i in data.history[context]:
		readline.add_history(i)
	data.history_context = context


# Insert a transaction in an appropriate place in the file: str(transaction) -> int(index)
def insert_transaction(tx):
	_found = False
	for _txid, jtx in enumerate(data.journal):
		# Ignore records that don't start with a date
		if jtx[0] not in '0123456789':
			continue
		# Insert balance statements in as the first transaction of the date
		if tx[10:19] == ' balance ' and jtx[0:10] == tx[0:10]:
			_found = True
			break
		# Seek forward to first bigger date
		if jtx[0:10] > tx[0:10]:
			_found = True
			break
	if _found and data.sort_by_date:
		data.journal.insert(_txid, tx)
	else:
		# If not found, insert at the end of file
		_txid = len(data.journal)
		data.journal.append(tx)
	print('\nTransaction added as record %s\n\n%s' % (_txid, tx))
	data.txid = _txid
	update_statement_refs(_txid, True)


# Date from string wrapper: str(date) -> date(date)
def strpdate(d):
	return datetime.datetime.strptime(d, data.date_prompt).date()


# Figure out the full date from a day-only input
def sliding_window(day):
	today = strpdate(data.date)
	if today.day == day:
		return today
	future = today
	for future_delta in range(32):
		future = future + datetime.timedelta(days=1)
		if future.day == day:
			break
	past = today
	for past_delta in range(32):
		past = past - datetime.timedelta(days=1)
		if past.day == day:
			break
	if past_delta <= future_delta and past_delta < 31:
		return past
	elif future_delta < past_delta:
		return future
	elif past_delta == future_delta == 31:
		return None


# Read and validate a date: str(default) -> str(date)
def read_date(default):
	# Unset completion
	data.vocab = []
	readline.set_completer_delims('')
	set_history_context('date')
	# Get a valid date
	while True:
		reading = input('Enter transaction date (%s, or %%d, or +/-days) [%s]: ' % (data.date_prompt, default))
		# Accepting the default
		if reading == '':
			return default
		date = strpdate(default)
		# Relative date
		if reading.startswith('+') or reading.startswith('-'):
			try:
				date += datetime.timedelta(int(reading))
			except ValueError:
				continue
		# Partial notation (day only)
		elif len(reading) == 1 or len(reading) == 2:
			try:
				date = sliding_window(int(reading))
			except ValueError:
				continue
			if date is None:
				continue
		# Absolute date
		else:
			try:
				date = strpdate(reading)
			except ValueError:
				continue
		date = date.isoformat()
		if data.date_preview:
			default = date
			continue
		return date


# Read a description -> str(description)
def read_description():
	# Set completion
	data.vocab = data.defaults.keys()
	readline.set_completer_delims('')
	set_history_context('description')
	# Get a non-empty description
	while True:
		reading = input('Enter transaction description [%s]: ' % data.description).strip(' "')
		if reading == '':
			if data.description != '':
				return data.description
			else:
				return None
		else:
			data.description = reading
			return reading


# Read a valid account name
def read_account():
	while True:
		# Set completion
		data.vocab = data.accounts
		readline.set_completer_delims('')
		set_history_context('account')
		# Read a valid account
		reading = input('Enter an account name (tab to complete, enter to fininsh): ')
		if reading == '':
			return None
		# Add new account option
		if reading not in data.accounts:
			if not confirm('The account `%s` is not in the journal file. Add it? (Y/n) ' % reading, True):
				continue
			insert_transaction('%s open %s' % (data.date, reading))
			print()
			data.accounts.append(reading)
		return reading


# Normalize amounts with unnecessary decimal places
# number, rounding precision -> string
def undecimal(number, precision=2):
	try:
		number = cast_number(number)
	except ValueError:
		print('\nThis is not a valid number.')
		raise KeyboardInterrupt
	if type(number) == float:
		number = round(number, precision)
		if len(str(number).split('.')[1]) == 1:
			number = str(number) + '0'
	return str(number)


# Calculate simple arithmetic expressions
def evaluate(expression):
	try:
		expression = str(expression)
		# Restrict to nothing but numbers and basic arithmetic operators and attempt to limit computation cost
		if len(expression) > data.max_expr_length:
			raise ValueError
		if '**' in expression:
			raise ValueError
		for n in expression:
			if n not in '0123456789.+-*/()':
				raise ValueError
		return eval(expression)
	except (SyntaxError, ValueError, ArithmeticError):
		print('\nInvalid arithmetic expression.')
		raise KeyboardInterrupt


# Read and normalize transaction amount
def read_amount(account):
	# Set completion
	data.vocab = data.currencies
	readline.set_completer_delims(' ')
	set_history_context('amount')
	# Read an amount
	if account in data.accounts:
		account = '`%s`' % account
	amount = input('Enter the amount for %s (including currency symbol) [%s %s]: ' % (account, undecimal(data.balance), data.cur))
	if amount == '':
		amount = [data.balance, data.cur]
	else:
		amount = amount.split()
	# Process currency sign
	if len(amount) == 1:
		amount.append(data.cur)
	else:
		data.cur = amount[-1]
		if data.cur not in data.currencies:
			data.currencies.append(data.cur)
	# Normalize numbers and process conversion rate
	amount[0] = undecimal(evaluate(amount[0]))
	if '@' in amount:
		amount[-2] = undecimal(evaluate(amount[-2]), 3)
		data.balance -= float(amount[0]) * float(amount[-2])
	else:
		data.balance -= float(amount[0])
	data.balance = cast_number(data.balance)
	# Finalize and return
	return ' '.join(amount)


# Toggle transaction flag
def toggle_flag():
	if data.txid < 0:
		print('\nNothing to flag, no current record.')
		return
	if ' * ' in data.journal[data.txid]:
		data.journal[data.txid] = data.journal[data.txid].replace(' * ', ' ! ')
		flagged = True
	elif ' ! ' in data.journal[data.txid]:
		data.journal[data.txid] = data.journal[data.txid].replace(' ! ', ' * ')
		flagged = False
	else:
		print('\nRecord type does not support flags.')
		return
	print('\nTransaction flag %sset.\n' % ('un' if not flagged else ''))
	print(data.journal[data.txid])


# Toggle the flags on individual transaction legs
def toggle_flag_with_legs():
	if ' * ' not in data.journal[data.txid] and ' ! ' not in data.journal[data.txid]:
		print('\nRecord type does not support flags.')
		return
	if ' * ' in data.journal[data.txid]:
		print('\nFlag which transaction legs?')
		account = read_account()
		data.journal[data.txid] = data.journal[data.txid].replace(account, '! %s' % account).replace('! !', '!')
	else:
		data.journal[data.txid] = data.journal[data.txid].replace('	! ', '	')
	toggle_flag()


# Add or remove transaction tags
def add_remove_tag():
	if data.txid < 0:
		print('\nNothing to tag, no current record.')
		return
	# Set completion
	data.vocab = data.tags
	readline.set_completer_delims('')
	set_history_context('tag')
	# Get and normalize a tag
	try:
		_tag = input('Enter a tag [%s]: ' % data.defaults['__tag__'])
	except KeyboardInterrupt:
		print('\nTagging cancelled.')
		return
	except EOFError:
		data.eof = True
		return
	_tag = _tag.strip('# ')
	if _tag == '':
		_tag = data.defaults['__tag__']
	else:
		data.defaults['__tag__'] = _tag
	# If the tag is already there, offer to remove it instead
	if '#' + _tag in data.journal[data.txid]:
		if confirm('\nThe transaction already has this tag. Remove it? (Y/n) ', True):
			data.journal[data.txid] = data.journal[data.txid].replace(' #%s' % _tag, '')
		else:
			print('\nTagging cancelled.')
			return
	# Apply the tag (using two different methods)
	else:
		_transaction = data.journal[data.txid].replace('"\n', '" #%s\n' % _tag)
		if _transaction == data.journal[data.txid]:
			_transaction = data.journal[data.txid].replace('" #', '" #%s #' % _tag)
		if _transaction == data.journal[data.txid]:
			print('\nCannot add tags to special transactions.')
			return
		data.journal[data.txid] = _transaction
	print()
	print(data.journal[data.txid])


# Seek to a specific record in the journal file
def seek_to_transaction(autoseek=None):
	while True:
		# Early return
		if data.journal == []:
			print('\nThe journal is empty.')
			return
		last_tx = len(data.journal) - 1
		if autoseek is None:
			# Manual seeking input
			set_history_context('seek')
			# Unset completion
			data.vocab = []
			readline.set_completer_delims('')
			if data.txid >= 0:
				print('\nCurrently at record %s.' % data.txid)
				or_count = ', or +/-COUNT'
			else:
				print('\nNo current record.')
				or_count = ''
			try:
				reading = input('Enter record number (0-%s%s): ' % (last_tx, or_count))
			except KeyboardInterrupt:
				print('\nSeeking cancelled.')
				return
			except EOFError:
				data.eof = True
				return
		else:
			# Scripted seeking
			reading = str(autoseek)
		try:
			_txid = int(reading)
		except ValueError:
			print('\nSeeking cancelled.')
			return
		# Relative value
		if reading.startswith('+') or reading.startswith('-'):
			if data.txid == -1:
				if autoseek is not None:
					print('\nNo current record.')
					return
				else:
					print('\nSeeking cancelled.')
					return
			else:
				_txid += data.txid
		# Beginning of journal
		if _txid <= 0:
			if data.txid == 0:
				print('\nYou are at the first record.')
				return
			else:
				_txid = 0
				break
		# End of journal
		elif _txid >= last_tx:
			if data.txid == last_tx:
				print('\nYou are at the last record.')
				return
			else:
				_txid = last_tx
				break
		# Explicit and absolute value
		elif _txid == data.txid:
			print('\nSeeking cancelled.')
			return
		else:
			break
	# Change to the specified record
	print('\nRecord %s:\n' % _txid)
	print(data.journal[_txid])
	data.txid = _txid


# Return a list of txids which contain all of the passed strings
def tx_lookup(patterns, prune_txids=[]):
	if type(patterns) == str:
		patterns = [patterns]
	patterns = [x.lower() for x in patterns]
	results = []
	for i, tx in enumerate(data.journal):
		if i not in prune_txids:
			match = True
			record = tx.lower()
			for pattern in patterns:
				# Use an AND keyword joining
				if pattern not in record:
					match = False
					break
			if match:
				results.append(i)
	return results


# Find transactions that contain a string
def find_transactions(autoseek=None):
	# Unset completion
	data.vocab = []
	readline.set_completer_delims('')
	set_history_context('lookup')
	# Autoseeking without doing a lookup first
	if autoseek is not None and data.lookup_string == '':
		print('\nNo lookup pattern.')
		return
	# Get a lookup pattern or reuse the previous one if autoseeking
	if autoseek is None:
		try:
			reading = input('Enter a search string: ').strip('\n')
		except KeyboardInterrupt:
			print('\nLookup cancelled.')
			return
		except EOFError:
			data.eof = True
			return
	else:
		reading = data.lookup_string
	if reading == '':
		print('\nLookup cancelled.')
		return
	results = tx_lookup(reading)
	# Use default lookup-seek option
	if autoseek is None and reading != data.lookup_string:
		autoseek = data.lookup_seek
		data.lookup_string = reading
	if results == []:
		print('\nNo results.')
		return
	# Check for autoseek
	_txid = -1
	if autoseek is not None:
		# Last result
		if autoseek is True:
			_txid = results[-1]
		# First result
		elif autoseek is False:
			_txid = results[0]
		# Next and previous results
		elif autoseek == 1 or autoseek == -1:
			_txid = data.txid
			while _txid >= 0 and _txid < len(data.journal):
				_txid += autoseek
				if _txid in results:
					break
			if _txid == len(data.journal):
				if data.txid > results[-1]:
					print('\nNo more results.')
				else:
					print('\nYou are on the last result.')
				return
			elif _txid == -1:
				if data.txid < results[0]:
					print('\nNo more results.')
				else:
					print('\nYou are on the first result.')
				return
	else:
		_txid = data.txid
	# Print the transaction list
	for i in results:
		if _txid == i:
			print('>>>>>>>	%s' % (data.journal[i].split('\n')[0]))
		else:
			print('[%s]	%s' % (i, data.journal[i].split('\n')[0]))
	# Seek to the proper record
	if autoseek is not None:
		seek_to_transaction(_txid)
	return results


# Get default accounts for a transaction
def get_default_accounts(description):
	if description in data.defaults:
		print('Previously used accounts for this transaction:')
		for _account in data.defaults[description]:
			print('\t%s' % _account)
		print()
		_use = confirm('Use these accounts? (Y/n) ', True) if data.use_defaults is None else data.use_defaults
		if _use:
			return data.defaults[description].copy()
		else:
			return []
	else:
		return []


# Enter a normal transaction
def read_normal_transaction(description=None):
	output = ''
	_transaction = []
	data.balance = 0
	if not data.auto_new:
		data.date = read_date(data.date)
	if description is None:
		description = read_description()
	if description is None:
		raise KeyboardInterrupt
	else:
		output += '%s * "%s"\n' % (data.date, description)
	defaults = get_default_accounts(description)
	while True:
		# Use defaults, if available, then proceed to manual account input
		if len(defaults) > 0:
			account = defaults.pop(0)
		else:
			account = read_account()
			if account is None:
				if data.balance != 0:
					if not confirm('\nThe transaction is unbalanced! Really finish? (y/N) ', False):
						continue
				break
		_transaction.append(account)
		amount = read_amount(account)
		# Zero amounts are meaningless in this context
		if amount.startswith('0 '):
			print('Removing zero-amount `%s` from transaction.' % account)
			del(_transaction[-1])
		else:
			output += '	%s %s\n' % (account, amount)
	# The transaction is empty, no money moved anywhere
	if _transaction == []:
		raise KeyboardInterrupt
	else:
		# Update defaults and insert the transaction
		data.defaults[description] = _transaction
		insert_transaction(output.strip())
		# Auto-flag if appropriate
		for _account in data.auto_flag:
			if _account in output:
				toggle_flag()
				break


# Read a balance assertion transaction
def read_balance_transaction():
	print('\nAdding a new balance assertion.')
	data.date = read_date(data.date)
	defaults = get_default_accounts('__balance__')
	if defaults == []:
		account = read_account()
		data.defaults['__balance__'] = [account]
	else:
		account = defaults[0]
	data.balance = 0
	amount = read_amount(account)
	output = '%s balance %s %s' % (data.date, account, amount)
	insert_transaction(output)


# Read a pad statement
def read_pad_transaction():
	print('\nAdding a new pad statement.')
	data.date = read_date(data.date)
	# Print a helpful hint
	if '__pad__' not in data.defaults:
		print('\nEnter the source and destination accounts.')
	defaults = get_default_accounts('__pad__')
	if defaults == []:
		account1 = read_account()
		account2 = read_account()
		data.defaults['__pad__'] = [account1, account2]
	else:
		account1, account2 = defaults
	output = '%s pad %s %s' % (data.date, account1, account2)
	insert_transaction(output)


# Read a note statement
def read_note_transaction():
	# Unset completion
	data.vocab = []
	readline.set_completer_delims('')
	set_history_context('note')
	print('\nAdding a new note statement.')
	data.date = read_date(data.date)
	defaults = get_default_accounts('__note__')
	if defaults == []:
		account = read_account()
		data.defaults['__note__'] = [account]
	else:
		account = defaults[0]
	description = input('Enter the note text: ').strip(' "')
	output = '%s note %s "%s"' % (data.date, account, description)
	insert_transaction(output)


# Remove a transaction
def remove_transaction(silent_drop):
	if data.txid >= 0:
		if silent_drop:
			del(data.journal[data.txid])
		else:
			data.restore.append(data.journal.pop(data.txid))
			print('\nRemoved record %s' % data.txid)
		if data.txid in data.statement:
			data.statement.remove(data.txid)
		update_statement_refs(data.txid, False)
		if data.txid >= len(data.journal):
			data.txid -= 1
	else:
		print('\nNothing to remove, no current record.')


# Edit the current transaction with an external editor
def edit_transaction():
	if 'EDITOR' not in os.environ or os.environ['EDITOR'] == '':
		print('\nThe $EDITOR environmental variable is not set, editing unavailable.')
		return
	if data.txid < 0:
		print('\nNothing to edit, no current record.')
		return
	# Save the transaction in a temp file
	with open(tempfile, 'w') as tmp_file:
		tmp_file.write(data.journal[data.txid])
	try:
		subprocess.call([os.environ['EDITOR'], tempfile])
	except Exception as exc:
		print('\nCould not start the editor: %s\n' % exc)
	# Reload the transaction from the file
	with open(tempfile, 'r') as tmp_file:
		_tx = ''.join(tmp_file.readlines()).strip('\n')
	if _tx == data.journal[data.txid]:
		print('Nothing changed.')
	else:
		# Update the record
		if data.journal[data.txid][0:10] != _tx[0:10]:
			# Reinsert the transaction where appropriate if the date changed...
			remove_transaction(True)
			insert_transaction(_tx)
		else:
			# ...Update in-place otherwise
			data.journal[data.txid] = _tx
		print('Record updated.')
	os.unlink(tempfile)


# Print the context to the current transaction (default: +-10 transactions)
def print_journal():
	if data.txid == -1:
		print('\nNo current record.')
		return
	start = max(data.txid - data.context, 0)
	end = min(data.txid + data.context, len(data.journal))
	for tx in range(start, end):
		tx_string = data.journal[tx].split('\n')[0]
		tx_number = '>>>>>>>' if tx == data.txid else '[%s]' % tx
		print('%s	%s' % (tx_number, tx_string))


# Attempt to deduce an implied amount: int txid -> bool transaction is correct
def deduce_implied_amount(txid):
	_tx = data.journal[txid].split('\n')
	lineid = -1
	amount = 0
	cur = ''
	for lineno, line in enumerate(_tx):
		line = condense(line)
		# Ignore anything that isn't a transaction leg
		if line[0] == '!':
			del(line[0])
		if line[0] not in data.accounts:
			continue
		# Find the leg that needs to be deduced
		if len(line) == 1:
			if lineid != -1:
				print('\nError: More than one implied amount in record %s.' % txid)
				return False
			else:
				lineid = lineno
		else:
			# FIXME multiple currencies are not supported
			if cur != line[-1] and cur != '':
				print('\nWarning: Multiple transactional currencies in record %s.' % txid)
				return True
			cur = line[-1]
			if '@' in line and len(line) == 5:
				line[-2] = undecimal(line[-2], 3)
				amount -= float(line[1]) * float(line[-2])
			else:
				amount -= float(line[1])
			amount = cast_number(amount)
	# The record is perfectly fine as-is
	if lineid == -1:
		return True
	# Something needs to be done
	if amount != 0:
		_tx[lineid] = _tx[lineid] + ' %s %s' % (undecimal(amount), cur)
	else:
		print('\nCould not figure out implied amount in record %s.' % txid)
		return False
	# Update the record
	data.journal[txid] = '\n'.join(_tx)
	print('Implied amounts corrected in record %s.' % txid)
	return True


# Calculate the balance of an account
def calculate_balance(account, txlist=None, statement_verification_quirks=False):
	# If no list of transactions to consider is given, default to the entire journal
	if txlist is None:
		txlist = list(range(len(data.journal)))
	amounts = {}
	for currency in data.currencies:
		amounts[currency] = 0
	# Go through the transaction list
	for tx in txlist:
		# See if it need corrections
		if account in data.journal[tx]:
			if not deduce_implied_amount(tx):
				continue
		lines = data.journal[tx].split('\n')
		for _line in lines:
			if account in _line and len(_line) < 3:
				if not deduce_implied_amount(tx):
					continue
		# If the record is a balance statement, use that
		line = condense(lines[0])
		if len(line) == 5 and line[1] == 'balance' and line[2] == account:
			amounts[line[4]] = cast_number(line[3])
			continue
		# If statement verification, look for the first flagged leg
		if statement_verification_quirks:
			flagid = -1
			for _line in lines[1:]:
				line = condense(_line)
				if line[0] == '!' and flagid == -1:
					flagid = lines.index(_line)
					break
			if flagid > -1:
				if len(line) < 3:
					print('Missing amount ignored in record %s.' % tx)
					continue
				line = condense(data.journal[tx].split('\n')[flagid])[1:]
				amounts[line[2]] = cast_number(amounts[line[2]] + float(line[1]))
				continue
		# Else, just add the amount to the balance
		for _line in lines[1:]:
			line = condense(_line)
			if line[0] == '!':
				del(line[0])
			if line[0] == account:
				if len(line) < 3:
					print('Missing amount ignored in record %s.' % tx)
					continue
				amounts[line[2]] = cast_number(amounts[line[2]] + float(line[1]))
	return amounts


# Count and print the balances for an account
def print_account_balances():
	try:
		account = read_account()
		if account is None:
			raise KeyboardInterrupt
	except KeyboardInterrupt:
		print('\nCancelled.')
		return
	except EOFError:
		data.eof = True
		return
	balances = data.known_balances[account].copy() if account in data.known_balances else None
	data.known_balances[account] = calculate_balance(account)
	if balances is None:
		balances = data.known_balances[account].copy()
	print('\nBalances for %s:' % account)
	for currency in data.currencies:
		difference = data.known_balances[account][currency] - balances[currency]
		if difference == 0:
			if data.known_balances[account][currency] != 0:
				print('%s %s' % (undecimal(data.known_balances[account][currency]), currency))
		else:
			difference = '%s%s' % ('+' if difference > 0 else '', undecimal(difference))
			print('%s %s (%s %s)' % (undecimal(data.known_balances[account][currency]), currency, difference, currency))


# Nudge txids in the statement following a journal modification
def update_statement_refs(txid, insertion):
	for tx, statement in enumerate(data.statement):
		if insertion:
			if statement >= txid:
				data.statement[tx] += 1
		else:
			if statement > txid:
				data.statement[tx] -= 1


# Verify a statement
def verify_statement():
	# If wasn't working on a statement before
	if data.target == 0 or not confirm('Continue ongoing statement verification? (Y/n) ', True):
		# Get some general information
		try:
			data.statement = []
			print('\nEnter the account the statement refers to.')
			data.transaction_account = read_account()
			print('\nEnter the account which funds the statement.')
			data.funding_account = read_account()
			print()
			amount = read_amount('the statement')
			data.target = cast_number(amount.split()[0])
			if data.target == 0:
				raise KeyboardInterrupt
			data.statement_currency = amount.split()[1]
		except KeyboardInterrupt:
			print('\nCancelled.')
			return
		except EOFError:
			data.eof = True
			return
	neg = -1 if data.transaction_account.startswith('Liabilities:') or data.transaction_account.startswith('Income:') else 1
	set_history_context('txids')
	while True:
		# Tally the balance
		balance = calculate_balance(data.transaction_account, data.statement, True)[data.statement_currency] * neg
		print('\nTotal: %s %s (target: %s %s, difference: %s %s)' % (undecimal(balance), data.statement_currency, undecimal(data.target), data.statement_currency, undecimal(balance - data.target), data.statement_currency))
		if balance == data.target:
			break
		transactions = tx_lookup([data.transaction_account, data.statement_pattern], data.statement)
		# List matching records neatly justified
		width = 10
		for tx in data.statement + transactions:
			width = max(width, len(data.journal[tx].split('\n')[0]))
		for title, txlist in [
			['Statement Records', data.statement],
			['Available Records', transactions]
		]:
			print('\n------- %s '.ljust(width, '-') % title)
			if txlist == []:
				print('	(nothing)')
				continue
			for tx in txlist:
				desc = data.journal[tx].split('\n')[0].ljust(width)
				_amount = undecimal(calculate_balance(data.transaction_account, [tx], True)[data.statement_currency] * neg)
				print('[%s]	%s  %s	%s' % (tx, desc, _amount, data.statement_currency))
		# Select records to add or remove
		print('\nSelect records to add to the statement. Type a record number already on the statement to remove it.')
		try:
			reading = int(input('Enter a record number: ').strip())
			if reading < 0 or reading > len(data.journal) - 1:
				raise ValueError
		except ValueError:
			print('\nInvalid record number.')
			continue
		except KeyboardInterrupt:
			print('\nPostponing statement verification.')
			return
		except EOFError:
			data.eof = True
			return
		# Add or remove records
		if reading in data.statement:
			data.statement.remove(reading)
		elif reading in transactions:
			data.statement.append(reading)
			data.statement.sort()
		else:
			print('\nThis record is not relevant to the statement.')
			continue
	# Modify the journal
	if confirm('Commit statement to journal? (Y/n) ', True):
		try:
			data.date = read_date(data.date)
			desc = read_description()
		except KeyboardInterrupt:
			print('\nPostponing statement verification.')
			return
		except EOFError:
			data.eof = True
			return
		print('\nSetting transaction flags.')
		lookup_string = '! %s' % data.transaction_account
		for tx in data.statement:
			# Unflag one of the legs first
			if lookup_string in data.journal[tx]:
				data.journal[tx] = data.journal[tx].replace(lookup_string, data.transaction_account, 1)
			# And if it was the last one, unflag the transaction also
			if lookup_string not in data.journal[tx]:
				data.journal[tx] = data.journal[tx].replace(data.statement_pattern, data.statement_replacement)
		# Add the statement transaction
		output = '%s * "%s"\n	%s %s %s\n	%s %s %s' % (data.date, desc, data.funding_account, undecimal(balance * -1), data.statement_currency, data.transaction_account, undecimal(balance), data.statement_currency)
		insert_transaction(output)
		# Mark the verification as finished
		data.target = 0


# Move any new transactions to the external journal
def externalize_transactions():
	journal = []
	for _tx in data.journal:
		if _tx not in data.saved:
			journal.append(_tx)
	return journal


# Duplicate the current transaction at another date
def duplicate_transaction():
	if data.txid == -1:
		print('\nNo current record.')
		return
	_tx = data.journal[data.txid]
	# If the record does not start with a date, just copy it to the end of the file
	if _tx[0] not in '0123456789':
		print('\nTransaction added as record %s\n\n%s' % (len(data.journal), _tx))
		data.journal.append(_tx)
	else:
		data.date = read_date(data.date)
		new_tx = data.date + data.journal[data.txid][10:]
		insert_transaction(new_tx)


# Process command line arguments
if len(sys.argv) < 2:
	print(usage)
	sys.exit(1)
elif sys.argv[1] == '-h' or sys.argv[1] == '--help':
	print(usage)
	sys.exit()
elif '-n' in sys.argv:
	sys.argv.remove('-n')
	data.auto_new = True

# Read and process journal file
data.file_name = sys.argv[1]
try:
	with open(data.file_name, 'r') as source_file:
		tx_file = source_file.read()
		data.mtime = os.stat(data.file_name).st_mtime
except FileNotFoundError:
	tx_file = ''
except Exception as exc:
	print('Could not open the file: %s' % exc)
	sys.exit(2)

description = ''
lastdate = '0'
for line in tx_file.split('\n'):
	line = line.strip()
	if line == '':
		# Transaction came out empty
		if description in data.defaults and data.defaults[description] == []:
			del(data.defaults[description])
		description = ''
		continue
	# Skip comments, but make use of the option strings
	elif line.startswith(';'):
		if line.startswith(';*bean-add* '):
			_auto_flag = False
			for i in line.split()[1:]:
				if i == 'a':
					data.use_defaults = True
				elif i == 'aa':
					data.use_defaults = False
				elif i == 's':
					data.sort_by_date = False
				elif i == 'w':
					data.paranoid_write = True
				elif i == 'e':
					data.external_write = True
				elif i == 'd':
					data.date_preview = False
				elif i == 'l':
					data.lookup_seek = True
				elif i == 'll':
					data.lookup_seek = False
				elif i == 'f':
					_auto_flag = True
					continue
				elif _auto_flag:
					data.auto_flag.append(i)
					_auto_flag = False
				else:
					print('Unrecognized option: %s' % i)
			print('Loaded options from journal file.')
		continue
	_data = condense(line)
	try:
		# Attach transaction legs to previous description
		if _data[0] in data.accounts:
			data.defaults[description].append(_data[0])
			# Transaction leg has a currency sign
			if len(_data) == 3:
				_cur = _data.pop()
				if _cur not in data.currencies:
					data.currencies.append(_cur)
		# Add account name to account list
		elif _data[1] == 'open':
			data.accounts.append(_data[2])
		# Remove closed accounts from completion
		elif _data[1] == 'close' and _data[2] in data.accounts:
			data.accounts.remove(_data[2])
		# Cache command data
		elif _data[1] == 'balance':
			data.defaults['__balance__'] = [_data[2]]
		elif _data[1] == 'pad':
			data.defaults['__pad__'] = [_data[2], _data[3]]
		# Record a description
		elif _data[1] in '!*':
			_date = _data[0][0:10]
			if data.sort_by_date and _date < lastdate:
				print('Sorting by date disabled due to inconsistent ordering at %s.' % _date)
				data.sort_by_date = False
			else:
				lastdate = _date
			data.date_delimiter = _data[0][4]
			description = line[13:].split('#')[0].strip('" ')
			data.defaults[description] = []
			# Cache any tags present
			if '#' in line:
				for word in _data:
					if word.startswith('#'):
						if not word[1:] in data.tags:
							data.tags.append(word[1:])
						data.defaults['__tag__'] = word[1:]
	# Pass through malformed (or unrecognized) lines without stopping
	except IndexError:
		continue

# Prepare file for transaction insertion
data.journal = tx_file.split('\n\n')
data.journal = [i.strip() for i in data.journal]
# Initialize modification tracking
data.saved = data.journal.copy()
# Remove empty records
while '' in data.journal:
	data.journal.remove('')
# Move balance statements to the beginning of each day
for i, jtx in enumerate(data.journal):
	if jtx[0] in '0123456789' and jtx[10:19] == ' balance ':
		_date = jtx[0:10]
		_tx = i
		while True:
			# Seek backwards until the first non-comment transaction or another balance statement with an earlier date
			_tx -= 1
			if data.journal[_tx][0] not in '0123456789':
				continue
			if not data.journal[_tx].startswith(_date) or data.journal[_tx][10:19] == ' balance ':
				# Attempt to move the balance statement up
				if _tx == i - 1:
					break
				data.journal.insert(_tx + 1, data.journal[i])
				del(data.journal[i + 1])
				break

# Notify that some trivial fixes were made
if data.journal != data.saved:
	print('Automatic normalizations applied.')
	data.saved = data.journal.copy()

# Set up the completer
readline.parse_and_bind('tab: complete')

readline.set_completer(complete)

# Print some statistics
print('\n%s processed' % pluralize(len(data.journal), 'record'))
if len(data.accounts) > 0:
	print('%s, %s, %s and %s loaded' % (
		pluralize(len(data.accounts), 'account name'),
		pluralize(len(data.defaults), 'unique description'),
		pluralize(len(data.currencies), 'currency sign'),
		pluralize(len(data.tags), 'tag')))
else:
	# Empty file
	if tx_file == '':
		print('File does not exist, or is empty.')
	# Not empty, but un-useful file
	else:
		print('File contains no account definitions.')
	if not confirm('Proceed with editing? (y/N) ', False):
		sys.exit()

# Date delimiter handling
if data.date_delimiter != '-':
	print('\nWarning: Non-standard date delimiter.')
	data.date = data.date.replace('-', data.date_delimiter)
	data.date_prompt = data.date_delimiter.join(['%Y', '%m', '%d'])

# Init date and currencies
data.cur = 'USD' if data.currencies == [] else data.currencies[0]

# Main data entry loop
print('\nChanges stay in memory until you [w]rite them out.')
print('Type `h` or `?` for a list of available commands.')

while True:
	# Check journal modifications for paranoid write mode
	if data.paranoid_write and not data.external_write and data.journal != data.saved:
		cmd = 'w'
	elif data.paranoid_write and data.external_write and externalize_transactions() != data.external_journal:
		cmd = 'w'
	elif data.eof:
		cmd = 'q'
		print()
		data.eof = False
	# Pass-through transaction entry
	elif data.auto_new:
		print('\nAdding a new transaction with today\'s date.\n')
		cmd = 'n'
	# Get a command
	else:
		# Unset completion
		data.vocab = []
		# Set history
		set_history_context('command')
		try:
			cmd = input('\nEnter command (h for help) ')
		except (KeyboardInterrupt, EOFError):
			print()
			cmd = 'q'
	# Write the journal
	if cmd in ['w', 'wq']:
		if data.mtime != os.stat(data.file_name).st_mtime:
			print('\nWARNING: The journal file was modified on disk after opening; The journal is most likely inconsistent.')
			if not data.external_write and not confirm('Do you really want to overwrite it? (y/N) ', False):
				continue
		if data.external_write:
			file_name = data.file_name + '.new'
			data.external_journal = externalize_transactions()
			journal = data.external_journal
		else:
			file_name = data.file_name
			journal = data.journal
		try:
			with open(file_name, 'w') as source_file:
				source_file.write('\n\n'.join(journal) + '\n')
				print('\n%s written' % pluralize(len(journal), 'record'))
				data.mtime = os.stat(data.file_name).st_mtime
		except Exception as exc:
			print('\nCould not write the file: %s' % exc)
			continue
		else:
			if not data.external_write:
				data.saved = data.journal.copy()
		if cmd == 'wq':
			sys.exit()
	# Quit
	elif cmd == 'q':
		try:
			if not data.external_write and data.journal != data.saved:
				if not confirm('The journal file was modified. Do you really want to DESTROY ALL CHANGES and quit? (y/N) ', False):
					continue
			elif data.external_write:
				journal = externalize_transactions()
				modified = False
				for _tx in journal:
					if _tx not in data.external_journal:
						modified = True
						break
				if modified:
					if not confirm('There are unsaved records in the external file buffer. Do you really want to DESTROY ALL CHANGES and quit? (y/N) ', False):
						continue
			elif data.target != 0:
				if not confirm('Statement verification in progress. Do you really want to DESTROY ALL CHANGES and quit? (y/N) ', False):
					continue
		# Treat a second CTRL-C as a confirmation
		except (KeyboardInterrupt, EOFError):
			pass
		sys.exit()
	# Run bean-check
	elif cmd == 'c':
		with open(tempfile, 'w') as tmp_file:
			tmp_file.write('\n\n'.join(data.journal) + '\n')
		try:
			subprocess.call(['bean-check', tempfile])
		except Exception as exc:
			print('\nCould not start the validator: %s' % exc)
		else:
			print('\nValidation finished.')
		os.unlink(tempfile)
	# New transaction
	elif cmd == 'n':
		try:
			read_normal_transaction()
		except KeyboardInterrupt:
			print('\nTransaction entry cancelled.')
		except EOFError:
			data.eof = True
		# Unset pass-through transaction entry
		if data.auto_new:
			data.auto_new = False
	# New transaction sequence
	elif cmd == 'nn':
		tx_count = 0
		defaults = data.use_defaults
		try:
			read_normal_transaction()
			# Set to auto-accept as much as possible
			data.use_defaults = True
			while True:
				tx_count += 1
				print('\nAdding transaction #%s\n' % (tx_count + 1))
				read_normal_transaction(data.description)
		except KeyboardInterrupt:
			print('\nTransaction entry cancelled.')
		except EOFError:
			data.eof = True
		finally:
			print('\n%s added.' % pluralize(tx_count, 'transaction'))
			# Restore original behavior
			data.use_defaults = defaults
	# New balance assertion
	elif cmd == 'B':
		try:
			read_balance_transaction()
		except KeyboardInterrupt:
			print('\nTransaction entry cancelled.')
		except EOFError:
			data.eof = True
	# New padding transaction
	elif cmd == 'P':
		try:
			read_pad_transaction()
		except KeyboardInterrupt:
			print('\nTransaction entry cancelled.')
		except EOFError:
			data.eof = True
	# New note transaction
	elif cmd == 'N':
		try:
			read_note_transaction()
		except KeyboardInterrupt:
			print('\nTransaction entry cancelled.')
		except EOFError:
			data.eof = True
	# Toggle flag
	elif cmd == 'f':
		toggle_flag()
	# Toggle deep flag
	elif cmd == 'ff':
		try:
			toggle_flag_with_legs()
		except KeyboardInterrupt:
			print('\nCancelled.')
		except EOFError:
			data.eof = True
	# Edit tags
	elif cmd == 't':
		add_remove_tag()
	# Seeking
	elif cmd == 's':
		seek_to_transaction()
	elif cmd == 'sa':
		seek_to_transaction(-1)
	elif cmd == 'sd':
		seek_to_transaction('+1')
	elif cmd == 'sq':
		seek_to_transaction(0)
	elif cmd == 'se':
		seek_to_transaction(len(data.journal) - 1)
	# Lookup
	elif cmd == 'l':
		find_transactions()
	elif cmd == 'ld':
		find_transactions(1)
	elif cmd == 'la':
		find_transactions(-1)
	elif cmd == 'le':
		find_transactions(True)
	elif cmd == 'lq':
		find_transactions(False)
	# Remove record
	elif cmd == 'r':
		remove_transaction(False)
	# Unremove record
	elif cmd == 'u':
		if len(data.restore) > 0:
			insert_transaction(data.restore.pop())
		else:
			print('\nNothing to undo, the restore buffer is empty.')
	# Duplicate record
	elif cmd == 'd':
		try:
			duplicate_transaction()
		except KeyboardInterrupt:
			print('\nCancelled.')
		except EOFError:
			data.eof = True
	# External edit
	elif cmd == 'e':
		edit_transaction()
	# Show context
	elif cmd == 'j':
		print_journal()
	# Tally account balances
	elif cmd == 'b':
		print_account_balances()
	# Begin statement verification
	elif cmd == 'v':
		verify_statement()
	# Show options
	elif cmd == 'o':
		print('Available option commands:')
		print('oo	write current options to the journal')
		print('os	sort transactions by date (%s)' % ('enabled' if data.sort_by_date else 'disabled'))
		print('oa	reuse last used accounts in new transactions (%s)' % ('ask' if data.use_defaults is None else 'always' if data.use_defaults else 'never'))
		print('ow	write journal after every change (%s)' % ('enabled' if data.paranoid_write else 'disabled'))
		print('oe	write changes to an external file (%s)' % ('enabled' if data.external_write else 'disabled'))
		print('od	preview non-absoulute dates during input (%s)' % ('enabled' if data.date_preview else 'disabled'))
		print('of	automatically flag transactions containing (%s)' % (None if data.auto_flag == [] else ', '.join(data.auto_flag)))
		print('ol	lookup result to seek to (%s)' % ('none' if data.lookup_seek is None else 'last' if data.lookup_seek else 'first'))
	# Option: sort by date
	elif cmd == 'os':
		data.sort_by_date = not data.sort_by_date
		print('\nSorting by date %s.' % ('enabled' if data.sort_by_date else 'disabled'))
	# Option: accept defaults
	elif cmd == 'oa':
		data.use_defaults = True if data.use_defaults is None else False if data.use_defaults else None
		print('\nThe policy on reusing accounts for new transactions is now `%s`.' % ('ask' if data.use_defaults is None else 'always' if data.use_defaults else 'never'))
	# Option: paranoid write
	elif cmd == 'ow':
		data.paranoid_write = not data.paranoid_write
		print('\nWriting journal after every change is %s.' % ('enabled' if data.paranoid_write else 'disabled'))
	# Option: external write
	elif cmd == 'oe':
		data.external_write = not data.external_write
		print('\nWriting changes to an external file is now %s.' % ('enabled' if data.external_write else 'disabled'))
	# Option: date preview
	elif cmd == 'od':
		data.date_preview = not data.date_preview
		print('\nPreviewing of non-absolute dates during input is now %s.' % ('enabled' if data.date_preview else 'disabled'))
	elif cmd == 'of':
		try:
			_account = read_account()
			if _account is None:
				raise KeyboardInterrupt
			if _account in data.auto_flag:
				print('Removed from auto-flag list.')
				data.auto_flag.remove(_account)
			else:
				print('Added to auto-flag list.')
				data.auto_flag.append(_account)
				data.auto_flag.sort()
			print('\nAccounts to trigger automatic flagging:\n	%s' % (None if data.auto_flag == [] else '\n	'.join(data.auto_flag)))
		except KeyboardInterrupt:
			print('\nCancelled.')
		except EOFError:
			data.eof = True
	elif cmd == 'ol':
		data.lookup_seek = True if data.lookup_seek is None else False if data.lookup_seek else None
		print('\nSeeking to lookup result is set to %s.' % ('none' if data.lookup_seek is None else 'last' if data.lookup_seek else 'first'))
	# Save options to the journal
	elif cmd == 'oo':
		# Generate the option string
		optstring = ';*bean-add*'
		optstring += '' if data.sort_by_date else ' s'
		optstring += '' if data.use_defaults is None else ' a' if data.use_defaults else ' aa'
		optstring += ' w' if data.paranoid_write else ''
		optstring += ' e' if data.external_write else ''
		optstring += '' if data.date_preview else ' d'
		optstring += '' if data.lookup_seek is None else ' l' if data.lookup_seek else ' ll'
		for _account in data.auto_flag:
			optstring += ' f %s' % _account
		# Apply the option string
		if data.journal[0].startswith(';*bean-add* '):
			data.journal[0] = optstring
		else:
			data.journal.insert(0, optstring)
		# Delete all other option strings
		for _tx in data.journal[1:]:
			if _tx.startswith(';*bean-add* '):
				data.journal.remove(_tx)
		print('\nOptions saved to the journal as record 0.')
	# Help
	elif cmd == 'h' or cmd == '?':
		print('''Available commands:
n	new transaction
nn	add a sequence of near-identical transactions
d	duplicate the current transaction at another date
f	toggle transaction flag
ff	flag a transaction including its legs
t	add or remove tags
s	seek to another record
sa	seek one record forward
sd	seek one record backwards
sq	seek to the first record
se	seek to the last record
l	look up records containing a string
ld	go one lookup result forward
la	go one lookup result backwards
le	go to the last lookup result
lq	go to the first lookup result
j	show the context of the current record
b	show the balance of an account
r	remove the current record
u	undo record removal
e	edit the current record with your preferred editor
v	verify a statement
B	new balance assertion
P	new pad statement
N	new note statement
c	run bean-check on the journal file
o	view or change options
w	write journal file
q	quit
wq	write journal file and quit immediately
h,?	show this help message''')
	# Say what
	else:
		print('Unknown command.')