-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDokuWriter.cpp
More file actions
1376 lines (1203 loc) · 45.7 KB
/
Copy pathDokuWriter.cpp
File metadata and controls
1376 lines (1203 loc) · 45.7 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
// =============================================================================
// DokuWriter.cpp
// A simple single-file WYSIWYG word processor for Windows XP+
// Compiled with Microsoft Visual C++ 2008 (or later)
//
// File format: DokuWiki-style plain text markup
// **bold** -> bold text
// //italic// -> italic text
// __underline__ -> underlined text
// \n\n -> paragraph break (blank line)
// ====== Heading 1 ======
// ===== Heading 2 =====
// ==== Heading 3 ====
// * item -> bullet list item (line starts with " * ")
//
// Build (MSVC 2008 command line):
// cl DokuWriter.cpp /link user32.lib gdi32.lib comctl32.lib comdlg32.lib
//
// Or create a new "Win32 Project" (not console) in MSVC 2008, replace all
// generated .cpp content with this file, and build.
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#define _WIN32_WINNT 0x0501 // Target Windows XP
#define WINVER 0x0501
#include <windows.h>
#include <commdlg.h> // GetOpenFileName / GetSaveFileName
#include <richedit.h> // RichEdit control constants
#include <string>
#include <vector>
#include <sstream>
// =============================================================================
// CONSTANTS & IDs
// =============================================================================
#define IDC_RICHEDIT 1
#define IDM_FILE_NEW 101
#define IDM_FILE_OPEN 102
#define IDM_FILE_SAVE 103
#define IDM_FILE_SAVEAS 104
#define IDM_FILE_EXIT 105
#define IDM_FORMAT_BOLD 201
#define IDM_FORMAT_ITALIC 202
#define IDM_FORMAT_UNDER 203
#define IDM_FORMAT_H1 204
#define IDM_FORMAT_H2 205
#define IDM_FORMAT_H3 206
#define IDM_FORMAT_BULLET 207
#define IDM_HELP_ABOUT 301
#define IDM_VIEW_HIDEMARKUP 401
#define LINK_COLOR RGB(0, 102, 204)
#define IDM_VIEW_WORDWRAP 402
#define IDM_VIEW_ZOOMIN 403
#define IDM_VIEW_ZOOMOUT 404 // Error: not found rofl
// Toolbar button IDs (same as menu IDs for simplicity)
#define ID_TB_NEW IDM_FILE_NEW
#define ID_TB_OPEN IDM_FILE_OPEN
#define ID_TB_SAVE IDM_FILE_SAVE
#define ID_TB_BOLD IDM_FORMAT_BOLD
#define ID_TB_ITALIC IDM_FORMAT_ITALIC
#define ID_TB_UNDER IDM_FORMAT_UNDER
// Twips per point (RichEdit uses twips: 1 point = 20 twips)
#define TWIPS(pt) ((pt) * 20)
// How many milliseconds after typing before we reformat
#define REFORMAT_DELAY_MS 300
// Timer ID for deferred reformatting
#define IDT_REFORMAT 1
// =============================================================================
// GLOBALS
// =============================================================================
static HINSTANCE g_hInst = NULL;
static HWND g_hMainWnd = NULL;
static HWND g_hEdit = NULL;
static HWND g_hToolbar = NULL;
static std::string g_currentFile = ""; // Current open file path (empty = untitled)
static bool g_modified = false; // Has the document been modified?
static bool g_reformatting = false; // Guard against recursive EN_CHANGE
static bool g_hideMarkup = false; // false = show markup tokens, true = hide them
static bool g_wordWrap = false; // false = no word wrapping, true = word wrapping
static int g_baseFontSize = 11; // points; scales up/down with zoom
// =============================================================================
// MARKUP PARSER
// Helper functions that apply DokuWiki-style formatting to the RichEdit control.
// Strategy: after a short idle delay we scan the raw text line by line,
// reset all formatting, then re-apply character formatting for each markup span.
// =============================================================================
// --------------------------------------------------------------------------
// SetCharFmt: Apply a CHARFORMAT2 to a specific character range [start, end)
// --------------------------------------------------------------------------
static void SetCharFmt(int start, int end, CHARFORMAT2 &cf)
{
CHARRANGE cr;
cr.cpMin = start;
cr.cpMax = end;
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
SendMessage(g_hEdit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cf);
}
// --------------------------------------------------------------------------
// MakeCF2: Build a CHARFORMAT2 with common defaults, then let caller adjust
// --------------------------------------------------------------------------
static CHARFORMAT2 MakeCF2()
{
CHARFORMAT2 cf;
ZeroMemory(&cf, sizeof(cf));
cf.cbSize = sizeof(cf);
return cf;
}
// --------------------------------------------------------------------------
// ApplyBold: Apply bold to [start, end)
// --------------------------------------------------------------------------
static void ApplyBold(int start, int end)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_BOLD;
cf.dwEffects = CFE_BOLD;
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyItalic
// --------------------------------------------------------------------------
static void ApplyItalic(int start, int end)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_ITALIC;
cf.dwEffects = CFE_ITALIC;
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyUnderline
// --------------------------------------------------------------------------
static void ApplyUnderline(int start, int end)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_UNDERLINE;
cf.dwEffects = CFE_UNDERLINE;
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyFontSize: Set font size (in points) for [start, end)
// --------------------------------------------------------------------------
static void ApplyFontSize(int start, int end, int points)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_SIZE | CFM_BOLD;
cf.yHeight = TWIPS(points);
cf.dwEffects = CFE_BOLD; // Headings are always bold
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyColor: Set foreground color for [start, end)
// --------------------------------------------------------------------------
static void ApplyColor(int start, int end, COLORREF color)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_COLOR;
cf.crTextColor = color;
cf.dwEffects = 0; // Must clear CFE_AUTOCOLOR
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyHidden: Completely hide the markup formatting text
// --------------------------------------------------------------------------
static void ApplyHidden(int start, int end, bool hidden)
{
CHARFORMAT2 cf = MakeCF2();
cf.dwMask = CFM_HIDDEN;
cf.dwEffects = hidden ? CFE_HIDDEN : 0;
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ApplyBackground: Highlighting (changing the color of the background behind
// the text
// --------------------------------------------------------------------------
static void ApplyBackground(int start, int end, COLORREF color)
{
CHARFORMAT2A cf = MakeCF2();
cf.dwMask = CFM_BACKCOLOR;
cf.crBackColor = color;
SetCharFmt(start, end, cf);
}
// --------------------------------------------------------------------------
// ParseLineCitation: Parse citations
// --------------------------------------------------------------------------
static void ParseLineCitation(const std::string &line, int lineOffset, int lineLen)
{
// Citation block: ((text))
// Must start with (( and end with ))
if (line.size() < 5) return;
if (line.substr(0,2) != "((" ) return;
size_t close = line.rfind("))");
if (close == std::string::npos || close < 2) return;
int contentStart = lineOffset + 2;
int contentEnd = (int)(lineOffset + close);
int tokenEnd = lineOffset + lineLen;
// Style the (( prefix
ApplyColor(lineOffset, lineOffset + 2, RGB(180,180,180));
ApplyHidden(lineOffset, lineOffset + 2, g_hideMarkup);
// Style the content: italic, muted grey
if (contentEnd > contentStart)
{
CHARFORMAT2A cf = MakeCF2();
cf.dwMask = CFM_ITALIC | CFM_COLOR;
cf.dwEffects = CFE_ITALIC;
cf.crTextColor = RGB(100,100,100);
SetCharFmt(contentStart, contentEnd, (CHARFORMAT2A &)cf);
}
// Style the )) suffix
ApplyColor((int)(lineOffset + close), (int)(lineOffset + close + 2), RGB(180,180,180));
ApplyHidden((int)(lineOffset + close), (int)(lineOffset + close + 2), g_hideMarkup);
// Indent the whole line via paragraph formatting
CHARRANGE cr;
cr.cpMin = lineOffset;
cr.cpMax = lineOffset + lineLen;
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
PARAFORMAT2 pf;
ZeroMemory(&pf, sizeof(pf));
pf.cbSize = sizeof(pf);
pf.dwMask = PFM_STARTINDENT | PFM_RIGHTINDENT | PFM_BORDER;
pf.dxStartIndent = 720; // ~0.5 inch left indent
pf.dxStartIndent = 720; // ~0.5 inch right indent
pf.wBorders = 0x001; // left border only
pf.wBorderWidth = 15; // border thickness in twips
SendMessage(g_hEdit, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
}
// --------------------------------------------------------------------------
// ParseLineSpans:
// Scans a single line (given as a std::string) for inline markup tokens
// (**bold**, //italic//, __underline__) and applies formatting.
// lineOffset = character offset of the first character of this line in the
// overall RichEdit document.
// --------------------------------------------------------------------------
static void ParseLineSpans(const std::string &line, int lineOffset)
{
// Tokens: delimiter -> effect function
struct Token {
const char *delim;
int dlen;
void (*apply)(int, int);
};
Token tokens[] = {
{ "**", 2, ApplyBold },
{ "//", 2, ApplyItalic },
{ "__", 2, ApplyUnderline },
};
const int numTokens = 3;
for (int t = 0; t < numTokens; ++t)
{
const char *delim = tokens[t].delim;
int dlen = tokens[t].dlen;
size_t pos = 0;
while (pos < line.size())
{
size_t open = line.find(delim, pos);
if (open == std::string::npos) break;
size_t close = line.find(delim, open + dlen);
if (close == std::string::npos) break;
// Apply formatting to the content between the delimiters.
// We also want to visually dim the delimiter characters themselves.
int contentStart = (int)(lineOffset + open + dlen);
int contentEnd = (int)(lineOffset + close);
if (contentEnd > contentStart)
tokens[t].apply(contentStart, contentEnd);
// Grey out the delimiter tokens so they are visible but unobtrusive
ApplyColor((int)(lineOffset + open), (int)(lineOffset + open + dlen), RGB(180,180,180));
ApplyHidden((int)(lineOffset + open), (int)(lineOffset + open + dlen), g_hideMarkup);
ApplyColor((int)(lineOffset + close), (int)(lineOffset + close + dlen), RGB(180,180,180));
ApplyHidden((int)(lineOffset + close), (int)(lineOffset + close + dlen), g_hideMarkup);
pos = close + dlen;
}
}
// Monospace
{
const char *delim = "''";
const int dlen = 2;
size_t pos = 0;
while (pos < line.size())
{
size_t open = line.find(delim, pos);
if (open == std::string::npos) break;
size_t close = line.find(delim, open + dlen);
if (close == std::string::npos) break;
int contentStart = (int)(lineOffset + open + dlen);
int contentEnd = (int)(lineOffset + close);
if (contentEnd > contentStart)
{
// Red monospaced text with grey background
CHARFORMAT2A cf = MakeCF2();
cf.dwMask = CFM_FACE | CFM_COLOR | CFM_BACKCOLOR;
cf.dwEffects = 0;
cf.crTextColor = RGB(180,0,0);
cf.crBackColor = RGB(220,220,220);
lstrcpyA((char*)cf.szFaceName, "Courier New");
SetCharFmt(contentStart, contentEnd, (CHARFORMAT2A &)cf);
}
// Grey out and optionally hide the '' delimiters
ApplyColor((int)(lineOffset + open), (int)(lineOffset + open + dlen), RGB(180,180,180));
ApplyHidden((int)(lineOffset + open), (int)(lineOffset + open + dlen), g_hideMarkup);
ApplyColor((int)(lineOffset + close), (int)(lineOffset + close + dlen), RGB(180,180,180));
ApplyHidden((int)(lineOffset + close), (int)(lineOffset + close + dlen), g_hideMarkup);
pos = close + dlen;
}
}
}
// --------------------------------------------------------------------------
// ParseLineLinks: Add pseudo support for adding links (so my wiki start page
// looks better
// --------------------------------------------------------------------------
static void ParseLineLinks(const std::string &line, int lineOffset)
{
size_t pos = 0;
while (pos < line.size())
{
// Find opening [[
size_t open = line.find("[[", pos);
if (open == std::string::npos) break;
// Find closing ]]
size_t close = line.find("]]", open + 2);
if (close == std::string::npos) break;
// Everything between [[ and ]]
std::string inner = line.substr(open + 2, close - open - 2);
// Split on | to file URL and label
size_t pipe = inner.find('|');
std::string label;
if (pipe != std::string::npos)
label = inner.substr(pipe + 1); // text after the pipe
else
label = inner; // no pipe: the whole thing is both URL and label
// Character ranges in the document
int tokenStart = (int)(lineOffset + open); // Start of [[
int labelStart = (int)(lineOffset + open + 2); // start of content
int labelEnd = (int)(lineOffset + close); // end of content (before ]])
int tokenEnd = (int)(lineOffset + close + 2); // end of ]]
if (pipe != std::string::npos)
{
// Hide or grey the URL portion and the pipe: [[ url | label ]]
int urlEnd = (int)(lineOffset + open + 2 + (int)pipe + 1); // up to and including |
// Style the [[ prefix
ApplyColor(tokenStart, labelStart, RGB(180,180,180));
ApplyHidden(tokenStart, labelStart, g_hideMarkup);
// Style "url|" - grey/hidden
ApplyColor(labelStart, urlEnd, RGB(180,180,180));
ApplyHidden(labelStart, urlEnd, g_hideMarkup);
// Style the label text - bold, underlined, and blue
int displayStart = urlEnd;
int displayEnd = labelEnd;
if (displayEnd > displayStart)
{
CHARFORMAT cf = MakeCF2();
cf.dwMask = CFM_BOLD | CFM_UNDERLINE | CFM_COLOR;
cf.dwEffects = CFE_BOLD | CFE_UNDERLINE;
cf.crTextColor = LINK_COLOR;
SetCharFmt(displayStart, displayEnd, (CHARFORMAT2 &)cf);
ApplyColor(labelEnd, tokenEnd, RGB(180, 180, 180));
ApplyHidden(labelEnd, tokenEnd, g_hideMarkup);
}
pos = close + 2;
}
}
}
// --------------------------------------------------------------------------
// ReapplyFormatting:
// Called after every typing pause. Resets all formatting to a plain default,
// then walks each line and applies markup-driven formatting.
// --------------------------------------------------------------------------
static void ReapplyFormatting()
{
if (!g_hEdit) return;
// --- 1. Save caret / selection position ---
CHARRANGE savedSel;
SendMessage(g_hEdit, EM_EXGETSEL, 0, (LPARAM)&savedSel);
// --- 2. Freeze redraws to prevent flicker ---
SendMessage(g_hEdit, WM_SETREDRAW, FALSE, 0);
// --- 3. Select all and reset to default character formatting ---
{
CHARRANGE all = {0, -1};
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&all);
CHARFORMAT2 cfDefault = MakeCF2();
cfDefault.dwMask = CFM_BOLD | CFM_ITALIC | CFM_UNDERLINE |
CFM_SIZE | CFM_COLOR | CFM_FACE |
CFM_BACKCOLOR;
cfDefault.crBackColor = RGB(255,255,255);
cfDefault.dwEffects = 0;
cfDefault.yHeight = TWIPS(g_baseFontSize); // Text size
cfDefault.crTextColor = RGB(0, 0, 0);
lstrcpyA(cfDefault.szFaceName, "Times New Roman");
SendMessage(g_hEdit, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&cfDefault);
}
// --- 4. Get the full plain text ---
int textLen = GetWindowTextLength(g_hEdit);
if (textLen == 0)
{
// Restore and unfreeze
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&savedSel);
SendMessage(g_hEdit, WM_SETREDRAW, TRUE, 0);
InvalidateRect(g_hEdit, NULL, TRUE);
return;
}
std::string text(textLen + 1, '\0');
GetWindowTextA(g_hEdit, &text[0], textLen + 1);
text.resize(textLen);
// --- 5. Walk lines ---
// RichEdit uses '\r' as its line separator internally (not '\n').
// GetWindowText returns '\r\n' on some versions; we normalise to '\r'.
// We iterate by finding '\r' boundaries.
int lineOffset = 0; // Character offset of current line's start in RichEdit
size_t pos = 0;
while (pos <= text.size())
{
// Find end of this line
size_t eol = text.find('\r', pos);
if (eol == std::string::npos) eol = text.size();
std::string line = text.substr(pos, eol - pos);
int lineLen = (int)line.size();
// -- Heading detection --
// DokuWiki: ====== H1 ====== (6 = signs), ===== H2 =====, ==== H3 ====
// We detect by counting leading '=' characters.
if (line.size() >= 6 && line[0] == '=')
{
int eqCount = 0;
while (eqCount < (int)line.size() && line[eqCount] == '=') eqCount++;
// Trailing '=' should mirror the leading ones (DokuWiki style).
// We just need at least 4 to treat as a heading.
if (eqCount >= 4)
{
int pts = (eqCount >= 6) ? 22 :
(eqCount >= 5) ? 18 : 15;
ApplyFontSize(lineOffset, lineOffset + lineLen, pts);
ApplyColor(lineOffset, lineOffset + lineLen, RGB(0, 70, 140));
// Grey out the = signs at each end, and if hidden, then hide it
ApplyHidden(lineOffset, lineOffset + eqCount, g_hideMarkup);
ApplyColor(lineOffset, lineOffset + eqCount, RGB(180,180,180));
int trailStart = lineOffset;
// find last non-space, non-'=' position
size_t rpos = line.find_last_not_of("= ");
if (rpos != std::string::npos)
ApplyColor(lineOffset + (int)rpos + 1, lineOffset + lineLen, RGB(180,180,180));
ApplyHidden(lineOffset + (int)rpos + 1, lineOffset + lineLen, g_hideMarkup);
}
}
// -- Bullet list --
else if (line.size() >= 3 &&
(line.substr(0,3) == " *" || line.substr(0,2) == "* "))
{
// Indent the paragraph via PARAFORMAT
CHARRANGE cr;
cr.cpMin = lineOffset;
cr.cpMax = lineOffset + lineLen;
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
PARAFORMAT2 pf;
ZeroMemory(&pf, sizeof(pf));
pf.cbSize = sizeof(pf);
pf.dwMask = PFM_STARTINDENT | PFM_OFFSET | PFM_NUMBERING;
pf.wNumbering = PFN_BULLET;
pf.dxStartIndent = 360; // indent in twips (~0.25 inch)
pf.dxOffset = 360;
SendMessage(g_hEdit, EM_SETPARAFORMAT, 0, (LPARAM)&pf);
// Also tint the bullet marker grey
int markerEnd = (line[0] == ' ') ? 3 : 2;
ApplyColor(lineOffset, lineOffset + markerEnd, RGB(150,150,150));
// If hidden then hide
ApplyHidden(lineOffset, lineOffset + markerEnd, g_hideMarkup);
}
// -- Inline spans (bold/italic/underline) on all lines --
ParseLineSpans(line, lineOffset);
// Links [[url|label]] or [[url]]
ParseLineLinks(line, lineOffset);
// Citations
ParseLineCitation(line, lineOffset, lineLen);
// Advance past this line + the '\r' separator
pos = eol + 1;
// In some builds GetWindowText returns \r\n; skip extra \n
if (pos < text.size() && text[pos] == '\n') pos++;
// lineOffset advances by lineLen + 1 (for the '\r')
lineOffset += lineLen + 1;
}
// --- 6. Restore selection and unfreeze ---
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&savedSel);
SendMessage(g_hEdit, WM_SETREDRAW, TRUE, 0);
InvalidateRect(g_hEdit, NULL, TRUE);
}
// =============================================================================
// FILE I/O
// Plain text read/write. The file is the markup, nothing else.
// =============================================================================
// --------------------------------------------------------------------------
// LoadFile: Read a file and put its contents into the RichEdit control.
// RichEdit wants '\r\n' line endings; we convert '\n' -> '\r\n'.
// --------------------------------------------------------------------------
static bool LoadFile(const std::string &path)
{
HANDLE hFile = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return false;
DWORD fileSize = GetFileSize(hFile, NULL);
std::string raw(fileSize, '\0');
DWORD bytesRead = 0;
ReadFile(hFile, &raw[0], fileSize, &bytesRead, NULL);
CloseHandle(hFile);
raw.resize(bytesRead);
// Normalise line endings: convert \r\n -> \n, then \r -> \n, then \n -> \r\n
std::string normalised;
normalised.reserve(raw.size());
for (size_t i = 0; i < raw.size(); ++i)
{
if (raw[i] == '\r')
{
if (i + 1 < raw.size() && raw[i+1] == '\n') i++; // skip \r in \r\n
normalised += "\r\n";
}
else if (raw[i] == '\n')
{
normalised += "\r\n";
}
else
{
normalised += raw[i];
}
}
g_reformatting = true;
SetWindowTextA(g_hEdit, normalised.c_str());
g_reformatting = false;
// Move caret to start
CHARRANGE cr = {0, 0};
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
ReapplyFormatting();
return true;
}
// --------------------------------------------------------------------------
// SaveFile: Write the RichEdit plain text content to a file.
// We save with '\r\n' line endings (standard Windows).
// --------------------------------------------------------------------------
static bool SaveFile(const std::string &path)
{
int textLen = GetWindowTextLength(g_hEdit);
std::string text(textLen + 1, '\0');
GetWindowTextA(g_hEdit, &text[0], textLen + 1);
text.resize(textLen);
// RichEdit uses '\r' internally; normalise to '\r\n' for the file
std::string out;
out.reserve(text.size() + 256);
for (size_t i = 0; i < text.size(); ++i)
{
if (text[i] == '\r')
{
out += "\r\n";
if (i + 1 < text.size() && text[i+1] == '\n') i++;
}
else
{
out += text[i];
}
}
HANDLE hFile = CreateFileA(path.c_str(), GENERIC_WRITE, 0,
NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return false;
DWORD written = 0;
WriteFile(hFile, out.c_str(), (DWORD)out.size(), &written, NULL);
CloseHandle(hFile);
return true;
}
// =============================================================================
// DIALOGS
// Common file open/save dialogs via commdlg.h
// =============================================================================
static bool ShowOpenDialog(char *outPath, DWORD bufSize)
{
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(ofn));
outPath[0] = '\0';
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hMainWnd;
ofn.lpstrFilter = "DokuWiki Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0\0";
ofn.lpstrFile = outPath;
ofn.nMaxFile = bufSize;
ofn.lpstrTitle = "Open DokuWiki File";
ofn.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
ofn.lpstrDefExt = "txt";
return GetOpenFileNameA(&ofn) != 0;
}
static bool ShowSaveDialog(char *outPath, DWORD bufSize)
{
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(ofn));
outPath[0] = '\0';
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_hMainWnd;
ofn.lpstrFilter = "DokuWiki Text Files (*.txt)\0*.txt\0All Files (*.*)\0*.*\0\0";
ofn.lpstrFile = outPath;
ofn.nMaxFile = bufSize;
ofn.lpstrTitle = "Save DokuWiki File";
ofn.Flags = OFN_OVERWRITEPROMPT;
ofn.lpstrDefExt = "txt";
return GetSaveFileNameA(&ofn) != 0;
}
// =============================================================================
// TITLE BAR
// Shows "DokuWriter - filename [*]" where [*] appears when modified.
// =============================================================================
static void UpdateTitleBar()
{
std::string title = "DokuWriter - ";
if (g_currentFile.empty())
title += "(Untitled)";
else
{
// Show just the filename, not the full path
size_t slash = g_currentFile.find_last_of("\\/");
if (slash != std::string::npos)
title += g_currentFile.substr(slash + 1);
else
title += g_currentFile;
}
if (g_modified) title += " *";
SetWindowTextA(g_hMainWnd, title.c_str());
}
// =============================================================================
// MARKUP INSERTION HELPERS
// When the user clicks Bold/Italic/etc., we wrap the current selection
// (or insert empty tokens at the caret) with the appropriate markup.
// =============================================================================
static void WrapSelectionWith(const char *openToken, const char *closeToken)
{
CHARRANGE cr;
SendMessage(g_hEdit, EM_EXGETSEL, 0, (LPARAM)&cr);
if (cr.cpMin == cr.cpMax)
{
// No selection: insert open+close and park caret between them
// We do this via EM_REPLACESEL
std::string insert = openToken;
insert += closeToken;
SendMessage(g_hEdit, EM_REPLACESEL, TRUE, (LPARAM)insert.c_str());
// Move caret back by length of closeToken
int newPos = cr.cpMin + (int)strlen(openToken);
CHARRANGE newCr = {newPos, newPos};
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&newCr);
}
else
{
// Get selected text
int selLen = cr.cpMax - cr.cpMin;
std::string selText(selLen + 1, '\0');
// EM_GETSELTEXT copies selection into buffer
SendMessage(g_hEdit, EM_GETSELTEXT, 0, (LPARAM)&selText[0]);
selText.resize(selLen);
std::string replacement = openToken;
replacement += selText;
replacement += closeToken;
SendMessage(g_hEdit, EM_REPLACESEL, TRUE, (LPARAM)replacement.c_str());
// Re-select the original content (between the new tokens)
CHARRANGE newCr;
newCr.cpMin = cr.cpMin + (int)strlen(openToken);
newCr.cpMax = newCr.cpMin + selLen;
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&newCr);
}
SetFocus(g_hEdit);
}
// --------------------------------------------------------------------------
// InsertLinePrefix: For headings and bullets, we operate on the whole
// current line. We find the start of the caret's line and insert a prefix,
// or if the prefix is already there, remove it (toggle).
// --------------------------------------------------------------------------
static void InsertHeading(const char *prefix, const char *suffix)
{
// Get caret line index
CHARRANGE cr;
SendMessage(g_hEdit, EM_EXGETSEL, 0, (LPARAM)&cr);
int lineIdx = (int)SendMessage(g_hEdit, EM_EXLINEFROMCHAR, 0, cr.cpMin);
int lineStart = (int)SendMessage(g_hEdit, EM_LINEINDEX, lineIdx, 0);
int lineLen = (int)SendMessage(g_hEdit, EM_LINELENGTH, lineStart, 0);
// Fetch current line text
std::string lineBuf(lineLen + 2, '\0');
// EM_GETLINE requires first WORD of buffer to hold max chars
*((WORD*)&lineBuf[0]) = (WORD)(lineLen + 1);
int copied = (int)SendMessage(g_hEdit, EM_GETLINE, lineIdx, (LPARAM)&lineBuf[0]);
lineBuf.resize(copied);
// Select the whole line and replace it
CHARRANGE lineCr = {lineStart, lineStart + lineLen};
SendMessage(g_hEdit, EM_EXSETSEL, 0, (LPARAM)&lineCr);
std::string replacement = prefix;
replacement += lineBuf;
replacement += suffix;
SendMessage(g_hEdit, EM_REPLACESEL, TRUE, (LPARAM)replacement.c_str());
SetFocus(g_hEdit);
}
// =============================================================================
// COMMAND HANDLER
// Dispatches menu/toolbar commands.
// =============================================================================
static bool CheckSaveModified()
{
if (!g_modified) return true; // Nothing to save, proceed
int result = MessageBoxA(g_hMainWnd,
"The document has unsaved changes. Save now?",
"DokuWriter",
MB_YESNOCANCEL | MB_ICONQUESTION);
if (result == IDCANCEL) return false;
if (result == IDNO) return true;
// IDYES: save
if (g_currentFile.empty())
{
char path[MAX_PATH];
if (!ShowSaveDialog(path, MAX_PATH)) return false;
g_currentFile = path;
}
SaveFile(g_currentFile);
g_modified = false;
UpdateTitleBar();
return true;
}
// =============================================================================
// Word Wrapping
// =============================================================================
static void SetWordWrap(bool wrap)
{
if (wrap)
{
// NULL DC + 0 line width = wrap to window
SendMessage(g_hEdit, EM_SETTARGETDEVICE, (WPARAM)NULL, 0);
// Hide both scroll bars and only show the vertical one
ShowScrollBar(g_hEdit, SB_BOTH, FALSE);
ShowScrollBar(g_hEdit, SB_VERT, TRUE);
}
else
{
// NULL DC + 1 line width = no wrapping
SendMessage(g_hEdit, EM_SETTARGETDEVICE, (WPARAM)NULL, 1);
// Show all the scroll bars since word wrapping is off
ShowScrollBar(g_hEdit, SB_BOTH, FALSE);
ShowScrollBar(g_hEdit, SB_HORZ, TRUE);
ShowScrollBar(g_hEdit, SB_VERT, TRUE);
}
// Force RichEdit to recalculate its line layout be resizing it.
// We do this by briefly toggling its size, which flushes the layout engine.
RECT rc;
GetClientRect(g_hEdit, &rc);
SetWindowPos(g_hEdit, NULL, 0, 0,
rc.right - rc.left, rc.bottom - rc.top,
SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED);
}
static void OnCommand(WPARAM wParam)
{
WORD cmd = LOWORD(wParam);
switch (cmd)
{
// -- File Menu --
case IDM_FILE_NEW:
if (!CheckSaveModified()) break;
g_reformatting = true;
SetWindowTextA(g_hEdit, "");
g_reformatting = false;
g_currentFile = "";
g_modified = false;
UpdateTitleBar();
break;
case IDM_FILE_OPEN:
{
if (!CheckSaveModified()) break;
char path[MAX_PATH];
if (!ShowOpenDialog(path, MAX_PATH)) break;
if (LoadFile(path))
{
g_currentFile = path;
g_modified = false;
UpdateTitleBar();
}
else
{
MessageBoxA(g_hMainWnd, "Could not open file.", "DokuWriter", MB_ICONERROR);
}
break;
}
case IDM_FILE_SAVE:
{
if (g_currentFile.empty())
{
char path[MAX_PATH];
if (!ShowSaveDialog(path, MAX_PATH)) break;
g_currentFile = path;
}
if (SaveFile(g_currentFile))
{
g_modified = false;
UpdateTitleBar();
}
else
{
MessageBoxA(g_hMainWnd, "Could not save file.", "DokuWriter", MB_ICONERROR);
}
break;
}
case IDM_FILE_SAVEAS:
{
char path[MAX_PATH];
if (!ShowSaveDialog(path, MAX_PATH)) break;
g_currentFile = path;
if (SaveFile(g_currentFile))
{
g_modified = false;
UpdateTitleBar();
}
else
{
MessageBoxA(g_hMainWnd, "Could not save file.", "DokuWriter", MB_ICONERROR);
}
break;
}
case IDM_FILE_EXIT:
SendMessage(g_hMainWnd, WM_CLOSE, 0, 0);
break;
// -- Format Menu / Toolbar --
case IDM_FORMAT_BOLD:
WrapSelectionWith("**", "");
break;
case IDM_FORMAT_ITALIC:
WrapSelectionWith("//", "");
break;
case IDM_FORMAT_UNDER:
WrapSelectionWith("__", "");
break;
case IDM_FORMAT_H1:
InsertHeading("====== ", "");
break;
case IDM_FORMAT_H2:
InsertHeading("===== ", "");
break;
case IDM_FORMAT_H3:
InsertHeading("==== ", "");
break;
case IDM_FORMAT_BULLET:
InsertHeading(" * ", "");
break;
// -- Help Menu --
case IDM_HELP_ABOUT:
MessageBoxA(g_hMainWnd,
"DokuWriter v0.2 by vmunix\r\n\r\n"
"A simple WYSIWYG word processor\r\n"
"using DokuWiki-style markup.\r\n\r\n"
"Markup syntax:\r\n"
"\n"
" **bold**\r\n"
" //italic//\r\n"
" __underline__\r\n"
" ====== Heading 1 ======\r\n"
" ===== Heading 2 =====\r\n"
" ==== Heading 3 ====\r\n"
" * Bullet item\r\n"
" (blank line = paragraph break)\r\n"
" [[URL|Label]]\r\n"
" ''monospaced text''\r\n"
" ((Citation/Footnote))\r\n",
"About DokuWriter",
MB_ICONINFORMATION);
break;
case IDM_VIEW_HIDEMARKUP:
{
g_hideMarkup = !g_hideMarkup;
// Update the checkmark on the menu item
HMENU hMenu = GetMenu(g_hMainWnd);
HMENU hView = GetSubMenu(hMenu, 1); // "View" is the second menu item (index 1)
CheckMenuItem(hView, IDM_VIEW_HIDEMARKUP,
MF_BYCOMMAND | (g_hideMarkup ? MF_CHECKED : MF_UNCHECKED));
// Reformat to apply or remove CFE_HIDDEN on all tokens
g_reformatting = true;
ReapplyFormatting();
g_reformatting = false;
break;
}
case IDM_VIEW_WORDWRAP:
{
g_wordWrap = !g_wordWrap;
HMENU hMenu = GetMenu(g_hMainWnd);
HMENU hView = GetSubMenu(hMenu, 1); // View is index 1