-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmarkdownviewer_src.pas
1822 lines (1628 loc) · 53.7 KB
/
markdownviewer_src.pas
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
{
MDPad v1.1
by vhanla
-----------------
This is a desktop version of ShowDown port to javascript
Initial release
2012-06-06
+Everything in executable, no external html files
Changelog:
- 2018-09-23 v1.3.6
- Workaround to borderstyle changing in order to restore WebViewer
- 2018-09-22 v1.3.5
- Migrated code to FreePascal
- Replaced BCEditor with ATSynEdit
- Alternative HTML rendering using HTMLViewer CrossPlatform HTML 4.01 compliant
- Kept ActiveX MSHTML as main rendering on Windows
- 2017-09-30 v1.3.4
- Updated BCEditor
- 2016-07-07 v1.3.3
- Added support for custom theme, css and markdown syntax
- 2016-07-06 v1.3.2
- Fixed erronous method to load markdown files to the new engines
- Fixed error of wordwrap bceditor show (F7) if document was hidden before
and in different width size
// let's disable wordwrap first, otherwise BCEditor will raise error
// it might have to do with resizing width while wordwrap, weird
- Fixed incorrect initialization of textBuffer := BCEditor1.Text; since on
FormCreate wasn't considered, hence Closing, New o Opening was showing that
editor was modified
- 2016-07-02 v1.3.1
Added Native Markdown processor thanks to
Delphi-Markdown - Pavel Stugel
- 2016-07-01 v1.3
Replaced Memo with BCEdit to offer syntax highlighting
Overrided TBCEditor procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU;
procedure MouseUp(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer); override;
to make popup menu work, like notepad's, but no IME and RTL option available on this editor
- 2013-05-19 v1.2
Added more other engines to render MD
MarkdownJS and Marked but needs updating Pagedown
- 2012-06-10 v1.1
Renamed to MDPad since MarkDownPad already exists :(
Status bar
Wordwrap
Sync Editor with Preview
Save to ini
Fixed arrow navitagion on twebbrowser
UTF-8 Encoding support to tmemo
Division by zero bug fixed for sync
Left trying to improve preview time, automatically swtich to slow delay mode if bigger text opened,
not optimized for pasting on new editions. yet :P
Saves window size
html preview zoom
- 2012-06-08
Fixed onfocus event to focus webbrowser after returning to this app it lost focus
Added find text option, not well done yet
- 2012-06-07
Initial release
}
unit markdownviewer_src;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls,
Menus, ExtCtrls, ComCtrls, ActiveXContainer, MSHTML_4_0_TLB,
markdownprocessor, SHDocVw_1_1_TLB, ATSynEdit, UExceptionLogger;
type
TBCEditor = class(ATSynEdit.TATSynEdit)
procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU;
// procedure MouseUp(AButton: TMouseButton; AShift: TShiftState; X, Y: Integer); override;
protected
function GetSelLength: Integer; virtual;
function GetSelStart: Integer;
procedure SetSelLength(const Value: Integer);
procedure SetSelStart(const Value: Integer);
public
property SelLength: Integer read GetSelLength write SetSelLength;
property SelStart: Integer read GetSelStart write SetSelStart;
end;
{ TWebBrowser }
TWebBrowser = class(SHDocVw_1_1_TLB.TEvsWebBrowser)
procedure CNChar(var Message: TWMChar);message CN_CHAR;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
type
{ TForm1 }
TForm1 = class(TForm)
ExceptionLogger1: TExceptionLogger;
OpenDialog1: TOpenDialog;
MainMenu1: TMainMenu;
File1: TMenuItem;
New1: TMenuItem;
Open1: TMenuItem;
Save1: TMenuItem;
Saveas1: TMenuItem;
N1: TMenuItem;
Pageconfig1: TMenuItem;
Print1: TMenuItem;
N2: TMenuItem;
Exit1: TMenuItem;
N3: TMenuItem;
About1: TMenuItem;
View1: TMenuItem;
EditorandResult1: TMenuItem;
Editoronly1: TMenuItem;
Resultonly1: TMenuItem;
FullScreen1: TMenuItem;
N5: TMenuItem;
SaveDialog1: TSaveDialog;
Splitter1: TSplitter;
PrintPreview1: TMenuItem;
TrackBar1: TTrackBar;
tmrHiddenElements: TTimer;
Preferences1: TMenuItem;
N4: TMenuItem;
Registerfilestoopenwith1: TMenuItem;
Edit1: TMenuItem;
SelectAll1: TMenuItem;
FontDialog1: TFontDialog;
Format1: TMenuItem;
Font1: TMenuItem;
N6: TMenuItem;
Undo1: TMenuItem;
N7: TMenuItem;
Cut1: TMenuItem;
Paste1: TMenuItem;
Copy1: TMenuItem;
N8: TMenuItem;
Helponline1: TMenuItem;
ExportHTML1: TMenuItem;
tmrKeyEvent: TTimer;
FindDialog1: TFindDialog;
N9: TMenuItem;
Find1: TMenuItem;
Waitafewsecondsbeforeupdatingthepreview1: TMenuItem;
StatusBar1: TStatusBar;
Wordwrap1: TMenuItem;
Statusbar2: TMenuItem;
N10: TMenuItem;
tmrScrollSyncer: TTimer;
Synceditwithpreview1: TMenuItem;
Engines1: TMenuItem;
engPageDown: TMenuItem;
engMarkDownJS: TMenuItem;
engMarked: TMenuItem;
engShowDown: TMenuItem;
engMarkdownit: TMenuItem;
engNative: TMenuItem;
mnuSyntax: TMenuItem;
mnuTheme: TMenuItem;
mnuCSS: TMenuItem; procedure FormCreate(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure Open1Click(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure New1Click(Sender: TObject);
procedure WebBrowser1BeforeNavigate2(ASender: TObject;pDisp:IDispatch;var URL:OleVariant;var Flags:OleVariant;var TargetFrameName:OleVariant;var PostData:OleVariant;var Headers:OleVariant;var Cancel:WordBool);
procedure FullScreen1Click(Sender: TObject);
procedure EditorandResult1Click(Sender: TObject);
procedure Editoronly1Click(Sender: TObject);
procedure Resultonly1Click(Sender: TObject);
procedure Pageconfig1Click(Sender: TObject);
procedure Print1Click(Sender: TObject);
procedure PrintPreview1Click(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure Splitter1Moved(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure tmrHiddenElementsTimer(Sender: TObject);
procedure Registerfilestoopenwith1Click(Sender: TObject);
procedure WebBrowser1DocumentComplete(Sender: TObject;pDisp:IDispatch;var URL:OleVariant);
procedure Save1Click(Sender: TObject);
procedure Saveas1Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure SelectAll1Click(Sender: TObject);
procedure Font1Click(Sender: TObject);
procedure Undo1Click(Sender: TObject);
procedure Cut1Click(Sender: TObject);
procedure Copy1Click(Sender: TObject);
procedure Paste1Click(Sender: TObject);
procedure Helponline1Click(Sender: TObject);
procedure ExportHTML1Click(Sender: TObject);
procedure Find1Click(Sender: TObject);
procedure FindDialog1Find(Sender: TObject);
procedure tmrKeyEventTimer(Sender: TObject);
procedure Waitafewsecondsbeforeupdatingthepreview1Click(Sender: TObject);
procedure Statusbar2Click(Sender: TObject);
procedure Wordwrap1Click(Sender: TObject);
procedure tmrScrollSyncerTimer(Sender: TObject);
procedure Synceditwithpreview1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BCEditor1Change(Sender: TObject);
procedure BCEditor1DblClick(Sender: TObject);
procedure BCEditor1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure BCEditor1KeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ToggleEngine(Sender: TObject);
procedure mnuSyntaxClick(Sender: TObject);
procedure mnuThemeClick(Sender: TObject);
procedure mnuCSSClick(Sender: TObject);
procedure BCEditor1CaretChanged(ASender: TObject; ACaretPos: TPoint);
private
TrackBar1_Position:integer;
SelectedEngine: Integer;
{ Private declarations }
procedure ToggleFullScreen;
procedure OpenMDFile(const fn: string);
procedure OnFocus(Sender: TObject);
procedure UpdateResult;
// procedure ScrollWheel(var Msg: TMessage);
procedure SyncScrolling;
procedure SaveINI;
procedure LoadINI;
procedure UpdateEngineInMenu;
procedure LoadEngine(const DefaultText: string = '');
procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY;
//procedure WMContextMenu(var message: TWMContextMenu); message WM_CONTEXTMENU;
public
{ Public declarations }
end;
type
Comodin=class(TControl); //for scrolling
const
mdPAGEDOWN = 1;
mdMARKDOWNJS = 2;
mdMARKED = 3;
mdSHOWDOWN = 4;
mdMARKDOWNIT = 5;
mdNATIVE = 6;
const
DELAYTIME = 10;
var
Form1: TForm1;
BCEditor1: TBCEditor;
BrowserContainer: TActiveXContainer;
Browser: TWebBrowser;
PrevWindowState: TWindowState;
CurrentFile: string;
PreviewCSS: string;
textBuffer: widestring;
//para mantener el aspecto al redimensionar
ViewersRatio: integer;
ReadingFromExplorer: Boolean=False;
ReloadingEngine: Boolean=False;
Tryingtoclose: Boolean = False;
SyncPercentage: integer;
FSelPos: Integer;//for find dialog
TDelay: Integer=DELAYTIME; //10 seconds before update changes
needtodelay: boolean = false; //when bigger files are opened we force to slow down
// URLMON para quitar el feo sonido al iniciar cada enlace
const
SET_FEATURE_ON_PROCESS = $00000002;
FEATURE_DISABLE_NAVIGATION_SOUNDS = 21;
function CoInternetSetFeatureEnabled(FeatureEntry: DWORD; dwFlags: DWORD; fEnable: BOOL): HRESULT; stdcall; external 'urlmon.dll';
{$include pagedown.inc}
implementation
uses shellapi, activex, registry, inifiles;
{$R *.lfm}
procedure WBLoadHTML(WebBrowser: TWebBrowser; HTMLCode: string) ;
var
sl: TStringList;
ms: TMemoryStream;
url, vnil: OleVariant;
begin
url := UTF8Encode('about:blank');
vnil := NULL;
WebBrowser.ComServer.Navigate(url, vnil, vnil, vnil, vnil) ;
while WebBrowser.ComServer.ReadyState < READYSTATE_INTERACTIVE do
Application.ProcessMessages;
if Assigned(WebBrowser.ComServer.Document) then
begin
sl := TStringList.Create;
try
ms := TMemoryStream.Create;
try
sl.Text := HTMLCode;
sl.SaveToStream(ms) ;
ms.Seek(0, 0) ;
(WebBrowser.ComServer.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)) ;
finally
ms.Free;
end;
finally
sl.Free;
end;
end;
end;
procedure TWebBrowser.CNChar(var Message: TWMChar);
begin
Message.Result:=0;
end;
constructor TWebBrowser.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
end;
destructor TWebBrowser.Destroy;
begin
// if Assigned(Self) then FreeAndNil(Self);
inherited Destroy;
end;
function LoadFileToStr(const FileName: TFileName): String;
var LStrings: TStringList;
begin
LStrings := TStringList.Create;
try
LStrings.Loadfromfile(FileName);
Result := LStrings.text;
finally
FreeAndNil(LStrings);
end;
end;
procedure ExecuteScript(doc: IHTMLDocument2;script: string; language:string);
begin
if doc<>nil then
begin
if doc.parentWindow<>nil then
doc.parentWindow.execScript(script,olevariant(language));
end;
end;
function GetElementById(const Doc: IDispatch; const Id: string): IDispatch;
var
Document: IHTMLDocument2; // IHTMLDocument2 interface of Doc
Body: IHTMLElement2; // document body element
Tags: IHTMLElementCollection; // all tags in document body
Tag: IHTMLElement; // a tag in document body
I: Integer; // loops thru tags in document body
begin
Result := nil;
// Check for valid document: require IHTMLDocument2 interface to it
if not Supports(Doc, IHTMLDocument2, Document) then
raise Exception.Create('Invalid HTML document');
// Check for valid body element: require IHTMLElement2 interface to it
if not Supports(Document.body, IHTMLElement2, Body) then
raise Exception.Create('Can''t find <body> element');
// Get all tags in body element ('*' => any tag name)
Tags := Body.getElementsByTagName('*');
// Scan through all tags in body
for I := 0 to Pred(Tags.length) do
begin
// Get reference to a tag
Tag := Tags.item(I, EmptyParam) as IHTMLElement;
// Check tag's id and return it if id matches
if AnsiSameText(Tag.id, Id) then
begin
Result := Tag;
Break;
end;
end;
end;
procedure TForm1.About1Click(Sender: TObject);
begin
// ShellAbout(Handle, 'MDPad', 'MDPad v1.1 beta'#13'Written by vhanla - http://apps.codigobit.info', Application.Icon.Handle);
if FileExists(ExtractFilePath(ParamStr(0))+'Readme.md') then
begin
if MessageDlg(ABOUTMDPAD+#13#13'Want to read more about?',mtInformation, mbYesNo, 0) = mrYes then
ShellExecute(0, 'OPEN', PChar(ParamStr(0)),PChar(ExtractFilePath(ParamStr(0))+'Readme.md'),nil,SW_SHOWNORMAL);
end
else
MessageDlg(ABOUTMDPAD,mtInformation, [mbOK], 0);
end;
procedure TForm1.Copy1Click(Sender: TObject);
begin
if BCEditor1.GetSelLength > 0 then
BCEditor1.TextSelected; //CopyToClipboard;
end;
procedure TForm1.Cut1Click(Sender: TObject);
begin
if BCEditor1.GetSelLength > 0 then
BCEditor1.TextSelected; //CutToClipboard;
end;
procedure TForm1.EditorandResult1Click(Sender: TObject);
var
prevwas: boolean;
prevwrdwrp: boolean;
begin
prevwas:=EditorandResult1.Checked;
tmrHiddenElements.Enabled:=True;
Editoronly1.Checked:=False;
Resultonly1.Checked:=False;
EditorandResult1.Checked:=True;
BCEditor1.Visible:=True;
BCEditor1.Align:=alLeft;
BrowserContainer.Visible:=True;
BrowserContainer.Align:=alClient;
Splitter1.Enabled:=True;
// let's disable wordwrap first, otherwise BCEditor will raise error
// it might have to do with resizing width while wordwrap, weird
prevwrdwrp := BCEditor1.OptWrapIndented;
if prevwrdwrp then
BCEditor1.OptWrapIndented := False;
//let's use a variable to keep the position
// Memo1.Width:=ClientWidth div 2;
// WebBrowser1.Width:=ClientWidth div 2;
BCEditor1.Width:=Trunc(ViewersRatio/100*ClientWidth);
BrowserContainer.Width:=ClientWidth-BCEditor1.Width;
Splitter1.Left:=BrowserContainer.Left;
try
if not prevwas then
BCEditor1.SetFocus;
except
end;
if prevwrdwrp then
BCEditor1.OptWrapIndented:= prevwrdwrp;
end;
procedure TForm1.Editoronly1Click(Sender: TObject);
begin
tmrHiddenElements.Enabled:=False;
Editoronly1.Checked:=True;
Resultonly1.Checked:=False;
EditorandResult1.Checked:=False;
BCEditor1.Visible:=True;
BrowserContainer.Align:=alNone;
BCEditor1.Align:=alClient;
Splitter1.Enabled:=False;
BrowserContainer.Visible:=False;
//focus
BCEditor1.SetFocus;
end;
procedure TForm1.Registerfilestoopenwith1Click(Sender: TObject);
var
r: TRegistry;
begin
r:=TRegistry.Create;
try
r.RootKey:=HKEY_CURRENT_USER;
//first let's register the files
if r.OpenKey('\Software\Classes\.md',true) then
begin
r.WriteString('','MDPadFile');
r.WriteString('Content Type','text/plain');
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\.mkd',true) then
begin
r.WriteString('','MDPadFile');
r.WriteString('Content Type','text/plain');
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\.markdown',true) then
begin
r.WriteString('','MDPadFile');
r.WriteString('Content Type','text/plain');
r.CloseKey;
end;
//now let's create the file handler
if r.OpenKey('\Software\Classes\MDPadFile',true) then
begin
r.WriteString('','Mark Down Text');
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\MDPadFile\DefaultIcon',true) then
begin
r.WriteString('',pchar(ExtractFilePath(ParamStr(0))+ExtractFileName(ParamStr(0))+',0'));
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\MDPadFile\shell',true) then
begin
r.WriteString('','Open');
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\MDPadFile\shell\Open',true) then
begin
r.WriteString('','Open');
r.CloseKey;
end;
if r.OpenKey('\Software\Classes\MDPadFile\shell\Open\command',true) then
begin
r.WriteString('',pchar('"'+ExtractFilePath(ParamStr(0))+ExtractFileName(ParamStr(0))+'" "%1"'));
r.CloseKey;
end;
finally
r.Free;
end;
end;
procedure TForm1.Resultonly1Click(Sender: TObject);
begin
tmrHiddenElements.Enabled:=True;
Editoronly1.Checked:=False;
Resultonly1.Checked:=True;
EditorandResult1.Checked:=False;
BCEditor1.Visible:=False;
BrowserContainer.Visible:=True;
Splitter1.Enabled:=False;
BCEditor1.Align:=alNone;
BrowserContainer.Align:=alClient;
//focus
// WebBrowser1.SetFocus;
//good tricks at http://stackoverflow.com/a/918869/537347
// i guess they copied from here http://www.swissdelphicenter.ch/torry/showcode.php?id=1940
with Browser.ComServer do
if Document <> nil then
with Application as IOleObject do
DoVerb(OLEIVERB_UIACTIVATE, nil, BrowserContainer, 0, Handle, GetClientRect);
end;
procedure TForm1.Save1Click(Sender: TObject);
begin
if (CurrentFile <> '') and (FileExists(CurrentFile)) then
begin
BCEditor1.SaveToFile(CurrentFile);
textBuffer:=BCEditor1.Text;
if Tryingtoclose then
close;
end
else begin
//save as
Saveas1Click(Sender);
end;
end;
procedure TForm1.Saveas1Click(Sender: TObject);
begin
//save as
begin
//this is a new edition
with SaveDialog1 do
begin
Filter:='MarkDown files|*.md;*.mkd;*.markdown|*.*|*.*';
if Execute then
begin
//chosen a filename
//but let's make sure the extensions is the correct one
// ShowMessage(ExtractFileExt(FileName));
if (ExtractFileExt(FileName) <>'.md')
and (ExtractFileExt(FileName) <>'.mkd')
and (ExtractFileExt(FileName) <>'.markdown')then
FileName:=FileName+'.md';
if FileExists(FileName) then
if MessageDlg('Overwrite existing file?',mtConfirmation,[mbyes,mbno],0)=mrNo then
exit;
//let's overwrite all
BCEditor1.SaveToFile(FileName);
CurrentFile:=FileName;
Caption:='MDPad - '+FileName;
textBuffer:=BCEditor1.Text;
if Tryingtoclose then
close;
end;
end;
end
end;
procedure TForm1.SelectAll1Click(Sender: TObject);
begin
//TMemo(Memo1).SelectAll;
//TBCEditor(BCEditor1).SelectAll;
BCEditor1.DoSelect_All;
end;
procedure TForm1.Splitter1Moved(Sender: TObject);
begin
ViewersRatio:=Trunc(BCEditor1.Width/ClientWidth*100);
end;
procedure TForm1.Statusbar2Click(Sender: TObject);
begin
StatusBar2.Checked:= not Statusbar2.Checked;
StatusBar1.Visible:=Statusbar2.Checked;
end;
procedure TForm1.UpdateEngineInMenu;
begin
//lets flush all
engMarkDownJS.Checked:=False;
engMarked.Checked:=False;
engPageDown.Checked:=False;
engShowDown.Checked := False;
engMarkdownit.Checked := False;
engNative.Checked := False;
case SelectedEngine of
mdPAGEDOWN: engPageDown.Checked := True;
mdMARKDOWNJS: engMarkDownJS.Checked := True;
mdMARKED: engMarked.Checked := True;
mdSHOWDOWN: engShowDown.Checked := True;
mdMARKDOWNIT: engMarkdownit.Checked := True;
mdNATIVE : engNative.Checked := True;
end;
end;
procedure TForm1.Exit1Click(Sender: TObject);
begin
close;
end;
procedure TForm1.ExportHTML1Click(Sender: TObject);
var
Rel: IHTMLElement;
HTMLText: TMemo;
begin
Rel:=GetElementById(Browser.ComServer.Document,'resultado') as IHTMLElement;
if Assigned(Rel) then
begin
//let's save it to disk
with SaveDialog1 do
begin
Filter:='HTML|*.html';
if FileExists(CurrentFile) then
FileName:=copy(ExtractFileName(CurrentFile),0,pos(ExtractFileExt(CurrentFile),ExtractFileName(CurrentFile)))+'html';
if Execute then
begin
//we have the name now
if FileExists(FileName) then
if MessageDlg('Overwrite existing file?',mtConfirmation,[mbYes, mbNo],0)=mrNo then
Exit;
//let's continue saving the file
HTMLText:=TMemo.Create(Self);
try
HTMLText.Text:='<!DOCTYPE html><html><head><title>MDPad Exported'
+#13' File</title><meta http-equiv="X-UA-Compatible" content="IE=9" ><meta charset="utf-8">'+CSS+'</head><body><div id="readme"><div class="md">'
+Rel.innerHTML+'</div></div><code>Created by <a href="http://apps.codigo'
+'bit.info/2012/06/markdown-pad-markdown-textfile-editor.html" target="_blank">MDPad v1.1</a> Thanks to <a href="https://code.google.com/p/pagedown/" target="_blank">Pagedown</a></code></body></html>';
//HTMLText.Lines.SaveToFile(FileName,TEncoding.UTF8);
HTMLText.Lines.SaveToFile(FileName);
//let's offer the change to open its folder
if MessageDlg('Exported successfully'#13'Would you like to open its location folder?',mtConfirmation,[mbYes,mbNo],0)=mrYes then
ShellExecute(GetDesktopWindow,'OPEN',pchar(ExtractFilePath(FileName)),nil,nil,SW_SHOW);
finally
HTMLText.Free;
end;
end;
end;
end;
end;
procedure TForm1.Find1Click(Sender: TObject);
begin
FSelPos:=0;
// FindDialog1.Execute;
BCEditor1.SelStart := 1;
BCEditor1.SelLength := 2;
BCEditor1.SetFocus;
end;
procedure TForm1.FindDialog1Find(Sender: TObject);
var
S : string;
startpos : integer;
begin
with TFindDialog(Sender) do
begin
{If the stored position is 0 this cannot be a find next. }
if FSelPos = 0 then
Options := Options - [frFindNext];
{ Figure out where to start the search and get the corresponding
text from the memo. }
if frfindNext in Options then
begin
{ This is a find next, start after the end of the last found word. }
StartPos := FSelPos + Length(Findtext);
S := Copy(BCEditor1.Text, StartPos, MaxInt);
end
else
begin
{ This is a find first, start at the, well, start. }
S := BCEditor1.Text;
//BCEditor1.SearchString := FindText;
StartPos := 1;
end;
{ Perform a global case-sensitive search for FindText in S }
FSelPos := Pos(FindText, S);
if FSelPos > 0 then
begin
{ Found something, correct position for the location of the start
of search. }
FSelPos := FSelPos + StartPos - 1;
BCEditor1.SelStart := FSelPos - 1;
BCEditor1.SelLength := Length(FindText);
BCEditor1.SetFocus;
//Memo1.SelStart := FSelPos - 1;
//Memo1.SelLength := Length(FindText);
//Memo1.SetFocus;
end
else
begin
{ No joy, show a message. }
if frfindNext in Options then
S := Concat('There are no further occurences of "', FindText,
'" in Editor.')
else
S := Concat('Could not find "', FindText, '" in Editor.');
MessageDlg(S, mtError, [mbOK], 0);
end;
end;
end;
procedure TForm1.Font1Click(Sender: TObject);
begin
FontDialog1.Font:=BCEditor1.Font;
if FontDialog1.Execute() then
begin
BCEditor1.Font:= FontDialog1.Font;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
confirm: Integer;
begin
Tryingtoclose:=true;
if textBuffer <> BCEditor1.Text then
begin
Action:=caNone;
confirm := MessageDlg('Your document has been modified'#13'Do you want to save those changes?',mtConfirmation,[mbYes,mbNo,mbCancel],0);
if confirm = mrYes then
Save1Click(sender)
else if confirm = mrNo then
Action:= caFree
else if confirm = mrCancel then
begin
Tryingtoclose := False;
Action:=caNone;
end;
end
else
begin
Action:=caFree;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
feditor: string;
st: TStringStream;
begin
Application.OnActivate:=OnFocus;
Caption := 'MDPad';
BCEditor1 := TBCEditor.Create(Self);
BCEditor1.SetParent(Self);
BCEditor1.OnChange := BCEditor1Change;
BCEditor1.OnDblClick := BCEditor1DblClick;
BCEditor1.OnKeyDown := BCEditor1KeyDown;
BCEditor1.OnKeyUp := BCEditor1KeyUp;
{{ BCEditor1.OnChangeCaretPos := BCEditor1CaretChanged;}
// memo1.Visible:=false;
////////////////// BCEditor1.ScrollBars:=ssBoth;
BCEditor1.OptWrapIndented := True;
// Form1.WindowProc:=ScrollWheel;
/// KeyPreview := True;
// SetPriorityClass(GetCurrentProcess, IDLE_PRIORITY_CLASS);
SetPriorityClass(GetCurrentProcess, $4000);//below normal al parecer mejor de IDLE
// Create WebBrowser instance
BrowserContainer := TActiveXContainer.Create(Self);
Browser := TWebBrowser.Create(Self);
//Browser.SetParentComponent(BrowserContainer);
Browser.OnBeforeNavigate2 := WebBrowser1BeforeNavigate2;
Browser.OnDocumentComplete := WebBrowser1DocumentComplete;
BrowserContainer.ComServer := Browser.ComServer;
BrowserContainer.Active := True;
BrowserContainer.Align := alClient;
//disable ugly sounds on internet explorer
CoInternetSetFeatureEnabled(FEATURE_DISABLE_NAVIGATION_SOUNDS, SET_FEATURE_ON_PROCESS, True);
//WebBrowser1.Silent := True;
Browser.ComServer.Set_Silent(True);
//let's load the mdeditor\index.html file
{feditor:= ExtractFilePath(ParamStr(0))+'somdeditor\index.html';
if FileExists(feditor) then
feditor:='file:///'+StringReplace(feditor,'\','/',[rfReplaceAll]);
WebBrowser1.Navigate(feditor);}//good offline tester
//WBLoadHTML(WebBrowser1, PAGEDOWN);
// we need to load the engine prior to update its markdown generated contens
WBLoadHTML(Browser, '');
//
ViewersRatio:= Trunc(BCEditor1.Width / ClientWidth * 100); //averiguamos el porcentaje que vale lo que ocupa memo1.width
Constraints.MinHeight:=200;
Constraints.MinWidth:=300;
//restore zoom of twebbrowser
// WebBrowser1.OleObject.Document.Body.Style.Zoom:=1.0;
//initialize position of our trackbar
TrackBar1.Left:=ClientWidth-TrackBar1.Width;
TrackBar1.Top:=ClientHeight-TrackBar1.Height;
// TrackBar1.Position:=2;
TrackBar1.Visible:=False;
Application.Title:='MDPad';
BCEditor1.Font.Name:='Consolas';
BCEditor1.Font.Size:=11;
BCEditor1.OptWrapIndented:= True;
LoadINI;
if mnuCSS.Checked then
begin
if FileExists(ExtractFilePath(ParamStr(0))+'Style.css') then
PreviewCSS := '<style type="text/css">'+ LoadFileToStr(ExtractFilePath(ParamStr(0))+'Style.css') +'</style></head>';
end
else
PreviewCSS := CSS;
//highlight color and editor color
if not mnuTheme.Checked then
begin
{{st := TStringStream.Create(DEFAULTTHEME);
try
BCEditor1.Highlighter.Colors.LoadFromStream(st);
finally
FreeAndNil(st);
end;}
end
else
begin
{{if FileExists(ExtractFilePath(ParamStr(0))+'Theme.json') then
BCEditor1.Highlighter.Colors.LoadFromFile(ExtractFilePath(ParamStr(0))+ 'Theme.json');}
end;
{{if mnuSyntax.Checked then
if FileExists(ExtractFilePath(ParamStr(0))+'Markdown.json') then
BCEditor1.Highlighter.LoadFromFile(ExtractFilePath(ParamStr(0))+'MarkDown.json');}
textBuffer := BCEditor1.Text;
// let's load the configured engine
LoadEngine;
CurrentFile:=''; //none
//let's open with explorer
if ParamCount>0 then
ReadingFromExplorer:=True
else
ReadingFromExplorer:=False;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
//save ini settings
SaveINI;
BCEditor1.Text := '';
BCEditor1.Free;
FreeAndNil(Browser);
//Browser.Free;
BrowserContainer.Free;
end;
//thanks to http://beensoft.blogspot.com/2007/10/fooling-around-with-twebbrowser-4.html
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
begin
Key := #0;
keybd_event(VK_LCONTROL,0,0,0); //Ctrl key down
keybd_event(Ord('M'), MapVirtualKey(Ord('M'),0),0,0); // m key is down
//let's release those virtual keystrokes
keybd_event(Ord('M'), MapVirtualKey(Ord('M'),0),KEYEVENTF_KEYUP,0);
keybd_event(VK_LCONTROL,0,KEYEVENTF_KEYUP,0); //Ctrl key up
keybd_event(VK_CANCEL, 0,0,0);
end;
// if Key = #116 then
// WebBrowser1.Refresh;
end;
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ReleaseCapture;
Perform(WM_SYSCOMMAND, $F012, 0)
end;
procedure TForm1.FormResize(Sender: TObject);
begin
if EditorandResult1.Checked then
EditorandResult1Click(Sender);
TrackBar1.Left:=ClientWidth-TrackBar1.Width-32;
TrackBar1.Top:=ClientHeight-TrackBar1.Height;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
if BCEditor1.Visible then
BCEditor1.SetFocus;
TrackBar1.Position:=TrackBar1_Position;
end;
procedure TForm1.FullScreen1Click(Sender: TObject);
begin
ToggleFullScreen;
end;
procedure TForm1.Helponline1Click(Sender: TObject);
begin
ShellExecute(GetDesktopWindow,'OPEN','http://daringfireball.net/projects/markdown/syntax',nil,nil,SW_SHOW);
end;
procedure TForm1.tmrHiddenElementsTimer(Sender: TObject);
var
p:TPoint;
begin
try
p:=ScreenToClient(mouse.CursorPos);
if (p.X > TrackBar1.Left) and (p.X< TrackBar1.Left+TrackBar1.Width)
and (p.Y > TrackBar1.Top) and (p.Y< TrackBar1.Top+TrackBar1.Height)
then
TrackBar1.Visible:=True
else
TrackBar1.Visible:=False;
//StatusBar1.Panels[0].Text:=IntToStr(TScrollbar(Memo1).Position);
except
end;
end;
procedure TForm1.tmrKeyEventTimer(Sender: TObject);
begin
if TDelay <= 1 then
begin
UpdateResult;
tmrKeyEvent.Enabled:=False;
TDelay:=DELAYTIME;
end
else dec(TDelay);
end;
procedure TForm1.ToggleFullScreen;
begin
{ TODO: Improve restoring size after fullscreen }
if BorderStyle = bsNone then
begin
//restore
FullScreen1.Checked:=False;
BrowserContainer.Active := False;