-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotes.c
More file actions
2065 lines (1892 loc) · 54.1 KB
/
notes.c
File metadata and controls
2065 lines (1892 loc) · 54.1 KB
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
/*
* notes
*
* command-line notebook application
*
* Copyright (C) 2017-2022 Free Software Foundation, Inc.
*
* This 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.
*
* It 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 it. If not, see <http://www.gnu.org/licenses/>.
*
* Written by Nicholas Christopoulos <nereus@freemail.gr>
*/
#include <stdint.h>
#include <wchar.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <wctype.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <stdbool.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <wordexp.h>
#include <ncurses.h>
#include <locale.h>
#include <time.h>
#include <features.h>
#include <fnmatch.h>
#include "list.h"
#include "str.h"
#include "nc-plus.h"
#if defined(__GNU_GLIBC__)
#define FNM_GLIBC_EXTRA FNM_EXTMATCH
#else
#define FNM_GLIBC_EXTRA 0
#endif
#define OPT_AUTO 0x0001
#define OPT_LIST 0x0002
#define OPT_EDIT 0x0004
#define OPT_VIEW 0x0008
#define OPT_ADD 0x0010
#define OPT_APPD 0x0020
#define OPT_DEL 0x0040
#define OPT_MOVE 0x0080
#define OPT_FILES 0x0100
#define OPT_ALL 0x0200
#define OPT_COMPL 0x0400
#define OPT_STDIN 0x0800
#define OPT_PRINT 0x1000
#define OPT_NOCLOB 0x2000
int opt_flags = OPT_AUTO;
int opt_pv_filestat = 1;
int clr_normal = 0x07;
int clr_select = 0x70;
int clr_status = 0x70;
int clr_status_key = 0x74;
int clr_code = 0x02;
int clr_text = 0x07;
int clr_bold = 0x0f;
int clr_hide = 0x08;
// === configuration & interpreter ==========================================
static char home[PATH_MAX]; // user's home directory
static char ndir[PATH_MAX]; // app data directory (per user)
static char bdir[PATH_MAX]; // backup directory
static char conf[PATH_MAX]; // app configuration file
static bool g_globber = true;
static char sclob[64];
static char current_section[NAME_MAX];
static char current_filter[NAME_MAX];
static char default_ftype[NAME_MAX];
static char onstart_cmd[LINE_MAX];
static char onexit_cmd[LINE_MAX];
static list_t *exclude;
// returns true if the string 'str' is value of true
bool istrue(const char *str) {
const char *p = str;
while ( isblank(*p) ) p ++;
if ( tolower(*p) == 'o' )
if ( strncasecmp(p, "on", 2) == 0 ) return true;
if ( isdigit(*p) )
if ( *p != '0' ) return true;
return (strchr("YT+", toupper(*p)) != NULL);
}
// add pattern to exclude list
void excl_add_pat(const char *pars) {
char *string = strdup(pars);
const char *delim = " \t";
char *ptr = strtok(string, delim);
while ( ptr ) {
list_addstr(exclude, ptr);
ptr = strtok(NULL, delim);
}
m_free(string);
}
// user menu
typedef struct { char label[256]; char cmd[LINE_MAX]; } umenu_item_t;
static list_t *umenu;
void umenu_add(const char *pars) {
char *src = strdup(pars), *p;
umenu_item_t u;
if ( (p = strchr(src, ';')) != NULL ) {
*p ++ = '\0';
while ( isblank(*p) ) p ++;
strcpy(u.cmd, p);
p = src;
while ( isblank(*p) ) p ++;
rtrim(p);
strcpy(u.label, p);
list_add(umenu, &u, sizeof(umenu_item_t));
}
m_free(src);
}
// keymap
// name def-key user-key internal-key
typedef struct { const char *keyword; int id; } keyfunc_t;
static keyfunc_t keyfunc[] = {
{ "backspace", KEY_PRG(KEY_BACKSPACE) },
{ "enter", KEY_PRG(KEY_ENTER) },
{ "cancel", KEY_PRG(KEY_CANCEL) },
{ "quit", KEY_PRG(KEY_EXIT) },
//
{ "up", KEY_PRG(KEY_UP) },
{ "down", KEY_PRG(KEY_DOWN) },
{ "left", KEY_PRG(KEY_LEFT) },
{ "right", KEY_PRG(KEY_RIGHT) },
//
{ "home", KEY_PRG(KEY_HOME) },
{ "end", KEY_PRG(KEY_END) },
{ "pgup", KEY_PRG(KEY_PGUP) },
{ "pgdn", KEY_PRG(KEY_PGDN) },
{ "insmode", KEY_PRG(KEY_IC) },
{ "delchar", KEY_PRG(KEY_DC) },
//
{ "new", KEY_PRG('n') },
{ "add", KEY_PRG('a') },
{ "view", KEY_PRG('v') },
{ "edit", KEY_PRG('e') },
{ "delete", KEY_PRG(KEY_DC) },
{ "rename", KEY_PRG('r') },
{ "help", KEY_PRG(KEY_HELP) },
{ "tag", KEY_PRG(KEY_MARK) },
{ "shell", KEY_PRG('!') },
{ "execute", KEY_PRG('!') },
{ "untag-all", KEY_PRG('u') },
{ "change-section", KEY_PRG('c') },
{ "select-section", KEY_PRG('s') },
{ "umenu", KEY_PRG('m') },
{ "user-menu", KEY_PRG('m') },
{ "search", KEY_PRG(KEY_FIND) },
{ NULL, 0 } };
// setup default keymap
void set_default_keymap() {
nc_use_default_keymap();
nc_addkey("input", KEY_CANCEL, 3);
nc_setkey("nav", KEY_BACKSPACE, 4, 8, 127, 0);
nc_setkey("nav", KEY_ENTER, '\n', '\r', 0);
nc_setkey("nav", KEY_CANCEL, 3, 27, '', 0);
nc_setkey("nav", KEY_EXIT, 3, 'q', '', 0);
nc_setkey("nav", KEY_REFRESH, '', 0);
nc_setkey("nav", KEY_UP, '', 'k', 0);
nc_setkey("nav", KEY_DOWN, '', 'j', 0);
nc_setkey("nav", KEY_LEFT, '', 'h', 0);
nc_setkey("nav", KEY_RIGHT, '', 'l', 0);
nc_setkey("nav", KEY_HOME, 1, 'g', '^', 0);
nc_setkey("nav", KEY_END, '', 'G', '$', 0);
nc_setkey("nav", KEY_HELP, '?', KEY_F(1), 0); // help
nc_setkey("nav", KEY_DC, 'd', KEY_F(8), 0); // delete
nc_setkey("nav", 'v', KEY_F(3), 0); // view
nc_setkey("nav", 'e', KEY_F(4), 0); // edit
nc_setkey("nav", 'n', 0); // new
nc_setkey("nav", 'a', 0); // add
nc_setkey("nav", KEY_MARK, 't', KEY_IC, 0); // tag/untag
nc_setkey("nav", 'u', KEY_F(9), 0); // untag all
nc_setkey("nav", 'r', KEY_F(6), 0); // rename
nc_setkey("nav", KEY_FIND, '/', KEY_F(7), 0); // search
nc_setkey("nav", 'c', 0); // change section (move-to)
nc_setkey("nav", 's', 0); // select section (filter)
nc_setkey("nav", 'm', KEY_F(2), 0); // user-defined menu
nc_setkey("nav", '!', KEY_F(10), 0); // execute
// nc_setkey("nav", 'f', 0); // set filter test
nc_setkey("nav", 'f', 0); // file manager
}
// map key to command
void keymap_add(const char *pars) {
char *src = strdup(pars), *p = src;
char dest[64], *d = dest;
char keycode[64], keycmd[64], kmap[64];
bool sq = false, dq = false;
int wc = 0, c;
char str[16];
while ( isblank(*p) ) p ++;
while ( *p ) {
if ( *p == '\'' )
sq = !sq;
else if ( !sq ) {
if ( *p == '"' )
dq = !dq;
else if ( *p == '\\' ) {
p ++;
switch ( *p ) {
case 't': *d ++ = '\t'; p ++; break;
case 'r': *d ++ = '\r'; p ++; break;
case 'n': *d ++ = '\n'; p ++; break;
case 'v': *d ++ = '\v'; p ++; break;
case 'e': *d ++ = '\033'; p ++; break;
case 'a': *d ++ = '\a'; p ++; break;
case 'b': *d ++ = '\b'; p ++; break;
case 'f': *d ++ = '\f'; p ++; break;
case 'x':
p ++;
str[0] = (isxdigit(*p)) ? *p ++ : 0;
str[1] = (isxdigit(*p)) ? *p ++ : 0;
str[2] = 0;
*d ++ = strtol(str, NULL, 16);
break;
default:
if ( *p >= '0' && *p < '8') {
c = 0;
if ( *p >= '0' && *p < '8' ) { c = (c << 3) | (*p - '0'); p ++; }
if ( *p >= '0' && *p < '8' ) { c = (c << 3) | (*p - '0'); p ++; }
if ( *p >= '0' && *p < '8' ) { c = (c << 3) | (*p - '0'); p ++; }
*d ++ = c;
}
else
*d ++ = *p ++;
}
continue;
}
else if ( !dq ) {
if ( isblank(*p) ) {
*d = '\0';
d = dest;
while ( isblank(*p) ) p ++;
wc ++;
if ( wc == 1 )
strcpy(kmap, dest);
else if ( wc == 2 )
strcpy(keycode, dest);
else if ( wc == 3 ) {
strcpy(keycmd, dest);
break;
}
}
}
}
*d ++ = *p ++;
}
if ( d != dest && wc == 2 ) {
*d = '\0';
strcpy(keycmd, dest);
wc ++;
}
if ( wc > 1 ) {
// convert keynames from C-X or ^X to CTRL, A-X or M-X to ALT, S-X to shift,
// S-C-A combinations are allowed but not by ncurses (man curs_getch)
int key = nc_getkeycode(keycode);
// if wc == 2 delete nodes of the keycode
if ( wc == 2 )
nc_delkey(kmap, key);
// if wc == 3 assign keycode to keycmd
if ( wc == 3 ) {
for ( int i = 0; keyfunc[i].keyword; i ++ ) {
if ( strcasecmp(keyfunc[i].keyword, keycmd) == 0 ) {
nc_addkey(kmap, keyfunc[i].id, key);
break;
}
}
}
}
m_free(src);
}
// === configuration & interpreter ==========================================
// === color ================================================================
//
int digit2i(char c) {
if ( c >= 'a' ) return 10 + (c - 'a');
if ( c >= 'A' ) return 10 + (c - 'A');
return c - '0';
}
//
int isodigit(char c) {
return (c >= '0' && c <= '7');
}
//
int getnum(const char *src) {
const char *p = src;
bool hex = false, oct = false;
int n = 0;
while ( isblank(*p) ) p ++;
if ( *p == '0' ) {
p ++;
if ( *p == 'x' ) { p ++; hex = true; }
else oct = true;
}
if ( hex ) {
while ( isxdigit(*p) ) {
n = (n << 4) | digit2i(*p);
p ++;
}
}
else if ( oct ) {
while ( isodigit(*p) ) {
n = (n << 3) | digit2i(*p);
p ++;
}
}
else {
while ( isdigit(*p) ) {
n = n * 10 + digit2i(*p);
p ++;
}
}
return n;
}
// color normal
void color_setp(const char *pars) {
const char *p = pars;
static struct { const char *key; int *intptr; } ct[] = {
{ "normal", &clr_normal },
{ "text", &clr_text },
{ "status", &clr_status },
{ "select", &clr_select },
{ "key", &clr_status_key },
{ "code", &clr_code },
{ "bold", &clr_bold },
{ "hide", &clr_hide },
{ NULL, NULL } };
while ( isblank(*p) ) p ++;
for ( int i = 0; ct[i].key; i ++ ) {
if ( strncmp(p, ct[i].key, strlen(ct[i].key)) == 0 ) {
*(ct[i].intptr) = getnum(p + strlen(ct[i].key));
break;
}
}
}
// === configuration & interpreter ==========================================
// === rules ================================================================
// rule view *.[0-9] man %f
// rule view *.man man %f
// rule view *.md bat %f
// rule view *.txt less %f
// rule view *.pdf okular %f
// rule edit * $EDITOR %f
typedef struct { int code; char pattern[PATH_MAX], command[LINE_MAX]; } rule_t;
static list_t *rules;
// add rule to list
void rule_add(const char *pars) {
char *destp, pattern[PATH_MAX];
int action = 0;
const char *p = pars;
while ( isblank(*p) ) p ++;
switch ( *p ) {
case 'v': action = 'v'; break;
case 'e': action = 'e'; break;
default: return; }
while ( isgraph(*p) ) p ++;
if ( *p ) {
while ( isblank(*p) ) p ++;
if ( *p ) {
destp = pattern;
while ( isgraph(*p) ) *destp ++ = *p ++;
*destp = '\0';
if ( *p ) {
while ( isblank(*p) ) p ++;
if ( *p ) {
rule_t *rule = (rule_t *) m_alloc(sizeof(rule_t));
rule->code = action;
strcpy(rule->pattern, pattern);
strcpy(rule->command, p);
list_add(rules, rule, sizeof(rule_t));
}
}
}
}
}
//
int note_shell(const char *precmd, const char *files) {
const char *p = precmd, *s;
char dest[LINE_MAX], *d;
bool sq = false, dq = false;
setenv("NOTESDIR", ndir, 1);
setenv("NOTESFILES", files, 1);
d = dest;
while ( *p ) {
if ( *p == '\'' )
sq = !sq;
else if ( !sq ) {
if ( *p == '\"' )
dq = !dq;
else {
if ( *p == '%' ) {
switch ( *(p+1) ) {
case '%': // %%
*d ++ = '%';
p += 2;
continue;
case 'f': // files
for ( s = files; *s; *d ++ = *s ++ );
p += 2;
continue;
}
}
}
}
*d ++ = *p ++;
}
*d = '\0';
return system(dest);
}
// execute rule for the file 'fn'
bool rule_exec(int action, const char *fn) {
const char *base;
size_t root_dir_len = strlen(ndir) + 1;
list_node_t *cur = rules->head;
if ( (base = strrchr(fn, '/')) == NULL )
return false;
base ++;
while ( cur ) {
rule_t *rule = (rule_t *) cur->data;
if ( rule->code == action && fnmatch(rule->pattern, base, FNM_PATHNAME | FNM_PERIOD | FNM_GLIBC_EXTRA) == 0 ) {
char file[PATH_MAX];
if ( fn[0] == '/' )
snprintf(file, PATH_MAX, "'%s'", fn + root_dir_len);
else
snprintf(file, PATH_MAX, "'%s'", fn);
note_shell(rule->command, file);
return true;
}
cur = cur->next;
}
return false;
}
// === configuration & interpreter ==========================================
// table of variables
typedef struct { const char *name; char type; void *value; } var_t;
var_t var_table[] = {
{ "notebook", 's', ndir },
{ "backupdir", 's', bdir },
{ "clobber", 's', sclob },
{ "deftype", 's', default_ftype },
{ "onstart", 's', onstart_cmd },
{ "onexit", 's', onexit_cmd },
{ "pvhead", 'b', &opt_pv_filestat },
{ NULL, '\0', NULL } };
// table of commands
typedef struct { const char *name; void (*func_p)(const char *); } cmd_t;
cmd_t cmd_table[] = {
{ "exclude", excl_add_pat },
{ "rule", rule_add },
{ "umenu", umenu_add },
{ "map", keymap_add },
{ "color", color_setp },
{ NULL, NULL } };
// assign variables
void command_set(int line, const char *variable, const char *value) {
int n;
for ( int i = 0; var_table[i].name; i ++ ) {
if ( strcmp(var_table[i].name, variable) == 0 ) {
switch ( var_table[i].type ) {
case 's':
strcpy((char *)(var_table[i].value), value);
break;
case 'i':
case 'b':
if ( isdigit(*value) )
n = atoi(value);
else {
if ( strcasecmp(value, "off") == 0 ) n = 0;
else if ( strcasecmp(value, "on") == 0 ) n = 1;
else if ( strcasecmp(value, "false") == 0 ) n = 0;
else if ( strcasecmp(value, "true") == 0 ) n = 1;
else n = atoi(value);
}
*((int *)(var_table[i].value)) = n;
break;
case 'f':
*((double *)(var_table[i].value)) = atof(value);
break;
}
return;
}
}
fprintf(stderr, "rc(%d): uknown variable [%s]\n", line, variable);
}
// execute commands
void command_exec(int line, const char *command, const char *parameters) {
for ( int i = 0; cmd_table[i].name; i ++ ) {
if ( strcmp(cmd_table[i].name, command) == 0 ) {
if ( cmd_table[i].func_p )
cmd_table[i].func_p(parameters);
return;
}
}
fprintf(stderr, "rc(%d): uknown command [%s]\n", line, command);
}
// parse string line
void parse(int line, const char *source) {
char name[LINE_MAX], *d = name;
const char *p = source;
while ( isblank(*p) ) p ++;
if ( *p && *p != '#' ) {
while ( *p == '_' || isalnum(*p) )
*d ++ = *p ++;
*d = '\0';
while ( isblank(*p) ) p ++;
if ( *p == '=' ) {
p ++;
while ( isblank(*p) ) p ++;
command_set(line, name, p);
}
else
command_exec(line, name, p);
}
}
// read configuration file
void read_conf(const char *rc) {
int line = 0;
if ( access(rc, R_OK) == 0 ) {
char buf[LINE_MAX];
FILE *fp = fopen(rc, "r");
if ( fp ) {
while ( fgets(buf, LINE_MAX, fp) ) {
line ++;
rtrim(buf);
parse(line, buf);
}
fclose(fp);
}
}
}
// === notes ================================================================
typedef struct {
char file[PATH_MAX]; // full path filename
char name[NAME_MAX]; // name of note (basename)
char section[NAME_MAX]; // section
char ftype[NAME_MAX]; // file type
struct stat st; // just useless data for info
} note_t;
list_t *notes, *sections;
// copy file
bool copy_file(const char *src, const char *trg) {
FILE *inp, *outp, *logf = stderr;
char buf[LINE_MAX], *p;
size_t bytes;
// logf = fopen("/tmp/notes.log", "a");
// fprintf(logf, "copy_file(\"%s\", \"%s\")\n", src, trg);
if ( (inp = fopen(src, "r")) == NULL ) {
fprintf(logf, "%s: errno %d: %s\n", src, errno, strerror(errno));
return false;
}
if ( (p = strrchr(trg, '/')) != NULL ) {
char *dd = strdup(trg);
dd[p - trg] = '\0';
if ( access(dd, W_OK) != 0 ) { // new section ?
if ( mkdir(dd, 0755) != 0 ) {
fprintf(logf, "%s: errno %d: %s (mkdir [%s])\n", trg, errno, strerror(errno), dd);
fclose(inp);
m_free(dd);
return false;
}
}
m_free(dd);
}
if ( (outp = fopen(trg, "w")) == NULL ) {
fprintf(logf, "%s: errno %d: %s\n", trg, errno, strerror(errno));
fclose(inp);
return false;
}
// copy
while ( !feof(inp) ) {
if ( (bytes = f_read(buf, 1, sizeof(buf), inp)) > 0 )
f_write(buf, 1, bytes, outp);
}
// close
fclose(outp);
fclose(inp);
return true;
}
// backup note-file
bool note_backup(const note_t *note) {
char bckf[PATH_MAX];
if ( strlen(bdir) ) {
if ( strlen(note->section) )
snprintf(bckf, PATH_MAX, "%s/%s/%s", bdir, note->section, note->name);
else
snprintf(bckf, PATH_MAX, "%s/%s", bdir, note->name);
return copy_file(note->file, bckf);
}
return true;
}
// prints information about the note
void note_pl(const note_t *note) {
if ( opt_flags & OPT_FILES )
printf("%s\n", note->file);
else {
size_t seclen = 0;
for ( list_node_t *cur = sections->head; cur; cur = cur->next )
seclen = MAX(seclen, strlen((const char *) cur->data));
printf("%-*s (%-3s) - %s\n", seclen, note->section, note->ftype, note->name);
}
}
// simple print (mode --print) of a note
void note_print(const note_t *note) {
FILE *fp;
char buf[LINE_MAX];
printf("=== %s ===\n", note->name);
if ( (fp = fopen(note->file, "rt")) != NULL ) {
while ( fgets(buf, LINE_MAX, fp) )
printf("%s", buf);
fclose(fp);
}
else
fprintf(stderr, "errno %d: %s\n", errno, strerror(errno));
}
// delete a note
bool note_delete(const note_t *note) {
note_backup(note);
return (remove(note->file) == 0);
}
// check filename to add in results list
bool dirwalk_checkfn(const char *fn) {
list_node_t *cur;
if ( strcmp(fn, ".") == 0 || strcmp(fn, "..") == 0 )
return false;
for ( cur = exclude->head; cur; cur = cur->next ) {
if ( fnmatch((const char *) cur->data, fn, FNM_PATHNAME | FNM_PERIOD | FNM_GLIBC_EXTRA | FNM_CASEFOLD) == 0 )
return false;
}
return true;
}
// walk throu subdirs to collect notes
void dirwalk(const char *name) {
DIR *dir;
struct dirent *entry;
char path[PATH_MAX];
size_t root_dir_len = strlen(ndir) + 1;
if ( !(dir = opendir(name)) ) return;
while ( (entry = readdir(dir)) != NULL ) {
if ( !dirwalk_checkfn(entry->d_name) )
continue;
snprintf(path, sizeof(path), "%s/%s", name, entry->d_name);
if ( entry->d_type == DT_DIR )
dirwalk(path);
else {
note_t *note = (note_t *) m_alloc(sizeof(note_t));
char buf[PATH_MAX], *p, *e;
strcpy(note->file, path);
strcpy(buf, path + root_dir_len);
if ( (e = strrchr(buf, '.')) != NULL ) {
*e = '\0';
strcpy(note->ftype, e + 1);
}
if ( (p = strrchr(buf, '/')) != NULL ) {
*p = '\0';
strcpy(note->section, buf);
strcpy(note->name, p + 1);
}
else {
note->section[0] = '\0';
strcpy(note->name, buf);
}
if ( strlen(current_filter) == 0 || fnmatch(current_filter, note->name, FNM_PATHNAME | FNM_PERIOD | FNM_GLIBC_EXTRA | FNM_CASEFOLD) == 0 ) {
stat(note->file, ¬e->st);
list_add(notes, note, sizeof(note_t));
if ( list_findstr(sections, note->section) == NULL )
list_addstr(sections, note->section);
}
else
m_free(note);
}
}
closedir(dir);
}
// copy contents of file to output
bool print_file_to(const char *file, FILE *output) {
FILE *input;
char buf[LINE_MAX];
size_t bytes;
if ( (input = (file) ? fopen(file, "r") : stdin) != NULL ) {
while ( !feof(input) ) {
if ( (bytes = f_read(buf, 1, sizeof(buf), input)) > 0 )
f_write(buf, 1, bytes, output);
}
if ( file ) fclose(input);
return true;
}
else
fprintf(stderr, "%s: errno %d: %s\n", file, errno, strerror(errno));
return false;
}
// expand envirnment variables
void vexpand(char *buf) {
wordexp_t p;
if ( wordexp(buf, &p, 0) == 0 ) {
strcpy(buf, "");
for ( int i = 0; i < p.we_wordc; i ++ )
strcat(buf, p.we_wordv[i]);
wordfree(&p);
}
}
//
void normalize_section_name(char *section) {
list_node_t *cur;
note_t *note;
for ( cur = notes->head; cur; cur = cur->next ) {
note = (note_t *) cur->data;
if ( strcasecmp(note->section, section) == 0 ) {
strcpy(section, note->section);
break;
}
}
}
// if section does not exists, creates it
void make_section(const char *sec) {
char dest[PATH_MAX];
if ( strlen(sec) ) {
snprintf(dest, PATH_MAX, "%s/%s", ndir, sec);
if ( access(dest, X_OK) != 0 ) { // new section ?
if ( mkdir(dest, 0700) != 0 ) {
fprintf(stderr, "mkdir(%s): errno %d: %s\n", dest, errno, strerror(errno));
exit(EXIT_FAILURE);
}
}
}
}
// create a note node
note_t* make_note(const char *name, const char *defsec, int flags) {
note_t *note = (note_t *) m_alloc(sizeof(note_t));
FILE *fp;
const char *p;
if ( (p = strrchr(name, '/')) != NULL ) {
strcpy(note->name, p+1);
strncpy(note->section, name, p - name);
note->section[p - name] = '\0';
normalize_section_name(note->section);
make_section(note->section);
snprintf(note->file, PATH_MAX, "%s/%s/%s", ndir, note->section, note->name);
}
else {
strcpy(note->name, name);
if ( defsec && strlen(defsec) ) {
strcpy(note->section, defsec);
normalize_section_name(note->section);
make_section(note->section);
snprintf(note->file, PATH_MAX, "%s/%s/%s", ndir, note->section, note->name);
}
else {
strcpy(note->section, "");
snprintf(note->file, PATH_MAX, "%s/%s", ndir, note->name);
}
}
if ( strrchr(name, '.') == NULL ) { // if no file extension specified
strcat(note->file, ".");
strcat(note->file, default_ftype);
}
// create the file
if ( flags & 0x01 ) { // create file
if ( (opt_flags & OPT_ADD) && !(opt_flags & OPT_NOCLOB) && !(opt_flags & OPT_APPD) ) {
if ( access(note->file, F_OK) == 0 )
return NULL;
}
if ( (fp = fopen(note->file, "wt")) != NULL )
fclose(fp);
else {
m_free(note);
note = NULL;
}
}
return note;
}
// === explorer =============================================================
static note_t **t_notes;
static int t_notes_count;
static list_t *tagged;
static WINDOW *w_lst, *w_prv, *w_inf;
typedef enum { ex_nav, ex_search } ex_mode_t;
// short date
const char *sdate(const time_t *t, char *buf) {
struct tm *tmp;
tmp = localtime(t);
if ( tmp )
strftime(buf, 128, "%F %H:%M", tmp);
else
strcpy(buf, "* error *");
return buf;
}
// get a string value
bool ex_input(char *buf, const char *prompt_fmt, ...) {
char prompt[LINE_MAX];
va_list ap;
va_start(ap, prompt_fmt);
vsnprintf(prompt, LINE_MAX, prompt_fmt, ap);
va_end(ap);
mvhline(getmaxy(stdscr) - 3, 0, ACS_HLINE, getmaxx(stdscr));
move(getmaxy(stdscr) - 2, 0); clrtoeol();
printw(" %s", prompt);
move(getmaxy(stdscr) - 1, 0); clrtoeol();
printw("> ");
return nc_editstr(buf, getmaxx(stdscr)-4);
}
// print status line
static const char *vrt_ln = "┃";
void ex_status_line(const char *fmt, ...) {
char msg[LINE_MAX];
int short pair;
va_list ap;
va_start(ap, fmt);
vsnprintf(msg, LINE_MAX, fmt, ap);
va_end(ap);
nc_setvgacolor(w_inf, clr_status & 0xf, clr_status >> 4);
wattr_get(w_inf, NULL, &pair, NULL);
wbkgdset(w_inf, COLOR_PAIR(pair));
werase(w_inf);
mvwhline(w_inf, 0, 0, ' ', getmaxx(w_inf));
nc_wprintf(w_inf, "%6d %s %s", list_count(notes), vrt_ln, msg);
wrefresh(w_inf);
}
// display list of notes (list window)
void ex_print_list(int offset, int pos) {
int y = 0, lines = getmaxy(w_lst);
int short pair;
nc_setvgacolor(w_lst, clr_normal & 0xf, clr_normal >> 4);
wattr_get(w_lst, NULL, &pair, NULL);
wbkgdset(w_lst, COLOR_PAIR(pair));
werase(w_lst);
if ( t_notes_count ) {
for ( int i = offset; i < t_notes_count && i < offset + lines; i ++, y ++ ) {
if ( pos == i )
nc_setvgacolor(w_lst, clr_select & 0xf, clr_select >> 4);
mvwhline(w_lst, y, 0, ' ', getmaxx(w_lst));
if ( strlen(t_notes[i]->section) ) {
int l = u8width(t_notes[i]->section);
// wattron(w_lst, A_DIM);
mvwprintw(w_lst, y, getmaxx(w_lst)-l, "%s", t_notes[i]->section);
// wattroff(w_lst, A_DIM);
}
mvwprintw(w_lst, y, 0, "%c%s ",
((list_findptr(tagged, t_notes[i]) ) ? '+' : ' '), t_notes[i]->name);
if ( pos == i )
nc_setvgacolor(w_lst, clr_normal & 0xf, clr_normal >> 4);
}
}
else
mvwprintw(w_lst, 0, 0, "* No notes found! *");
wrefresh(w_lst);
}
// display the contents of the note (preview window)
void ex_print_note(const note_t *note) {
FILE *fp;
char buf[LINE_MAX];
bool inside_code = false;
int short pair;
nc_setvgacolor(w_prv, clr_text & 0xf, clr_text >> 4);
wattr_get(w_prv, NULL, &pair, NULL);
wbkgdset(w_prv, COLOR_PAIR(pair));
werase(w_prv);
wmove(w_prv, 0, 0);
if ( note ) {
if ( opt_pv_filestat ) {
nc_wprintf(w_prv, "Name: $B%s$b", note->name);
if ( strlen(note->section) )
nc_wprintf(w_prv, ", Section: $B%s$b", note->section);
nc_wprintf(w_prv, "\nFile: $B%s$b\n", note->file);
nc_wprintf(w_prv, "Date: $B%s$b\n", sdate(¬e->st.st_mtime, buf));
nc_wprintf(w_prv, "Stat: $B%6d$b bytes, mode $B0%o$b, owner $B%d$b:$B%d$b\n",
note->st.st_size, note->st.st_mode & 0777, note->st.st_uid, note->st.st_gid);
for ( int i = 0; i < getmaxx(w_prv); i ++ ) wprintw(w_prv, "─");
}
if ( (fp = fopen(note->file, "rt")) != NULL ) {
while ( fgets(buf, LINE_MAX, fp) ) {
if ( strcmp(note->ftype, "md") == 0 ) {
int i, color = clr_text;
if ( buf[strlen(buf)-1] == '\n' )
buf[strlen(buf)-1] = '\0';
switch ( buf[0] ) {
case '#': color = ( inside_code ) ? clr_code : clr_bold; break;
case '`': if ( buf[1] == '`' && buf[2] == '`' ) { inside_code = !inside_code; color = clr_hide; } break;
case '\t': color = clr_code; break;
default:
color = ( inside_code ) ? clr_code : clr_text;
}
// nc_setpair(w_prv, color);
nc_setvgacolor(w_prv, color & 0xf, color >> 4);
wprintw(w_prv, "%s", buf);
for ( i = getcurx(w_prv); i < getmaxx(w_prv) ; i ++ ) wprintw(w_prv, " ");
// nc_unsetpair(w_prv, color);
nc_setvgacolor(w_prv, clr_text & 0xf, clr_text >> 4);
}
else
// nc_wprintf(w_prv, "%s", buf);
wprintw(w_prv, "%s", buf);
if ( getcury(w_prv) >= (getmaxy(w_prv)-1) )
break;
}
fclose(fp);
}