/
kn_LinksMng.pas
2526 lines (2119 loc) · 88 KB
/
kn_LinksMng.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
unit kn_LinksMng;
(****** LICENSE INFORMATION **************************************************
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------------------
(c) 2000-2005 Marek Jedlinski <marek@tranglos.com> (Poland)
(c) 2007-2015 Daniel Prado Velasco <dprado.keynote@gmail.com> (Spain) [^]
[^]: Changes since v. 1.7.0. Fore more information, please see 'README.md'
and 'doc/README_SourceCode.txt' in https://github.com/dpradov/keynote-nf
*****************************************************************************)
{.$DEFINE DEBUG_HISTORY}
interface
uses
Winapi.Windows,
Winapi.Messages,
Winapi.ShellAPI,
Winapi.RichEdit,
System.Classes,
System.SysUtils,
System.StrUtils,
System.IOUtils,
System.Math,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.Clipbrd,
RxRichEd,
TreeNT,
gf_misc,
gf_miscvcl,
gf_files,
gf_strings,
gf_streams,
kn_Const,
kn_Info,
kn_Ini,
kn_RTFUtils,
kn_NoteObj,
kn_NoteFileMng,
kn_NodeList,
kn_TreeNoteMng,
kn_LocationObj,
kn_URL,
kn_History
;
// Links related routines
procedure GetKNTLocation (var Location: TLocation; Simplified: Boolean= false);
procedure InsertFileOrLink( const aFileName : string; const AsLink : boolean; Relative: boolean= false );
procedure InsertOrMarkKNTLink( aLocation : TLocation; const AsInsert : boolean ; TextURL: string; NumBookmark09: integer= 0);
function BuildKNTLocationText( const aLocation : TLocation) : string;
function BuildKNTLocationFromString( LocationStr : string ): TLocation;
function BuildBookmark09FromString( LocationStr : AnsiString ): TLocation;
procedure JumpToKNTLocation( LocationStr : string );
function JumpToLocation( Location: TLocation; IgnoreOtherFiles: boolean = true; AdjustVisiblePosition: boolean = true): boolean;
function SearchCaretPos (myNote : TTabNote; myTreeNode: TTreeNTNode;
CaretPosition: integer; SelectionLength: integer; PlaceCaret: boolean;
AdjustVisiblePosition: boolean = true): integer;
function PositionInImLinkTextPlain (myNote: TTabNote; myTreeNode: TTreeNTNode; CaretPosition: integer; ForceCalc: boolean = false): integer;
procedure ClickOnURL(const URLstr: string; chrgURL: TCharRange; myURLAction: TURLAction; EnsureAsk: boolean = false);
procedure InsertURL(URLStr : string; TextURL : string; Note: TTabNote);
function PathOfKNTLink (myTreeNode: TTreeNTNode; myNote : TTabNote; position: Integer; ForceShowPosition: boolean; RelativeKNTLink: boolean;
forUseInFindResults: boolean = false): string;
procedure GetTreeNodeFromLocation (const Location: TLocation; var Note: TTabNote; var myTreeNode: TTreeNTNode);
procedure NavigateToTreeNode(myTreeNode: TTreeNTNode);
// Navigation history
procedure AddHistoryLocation( const aNote : TTabNote; const AddLocalMaintainingIndex: boolean;
aLocation: TLocation= nil; const AddToGlobalHistory: boolean= true);
procedure NavigateInHistory( const Direction: THistoryDirection);
procedure UpdateHistoryCommands;
function TypeURL (var URLText: string; var KNTlocation: boolean): TKntURL;
function URLFileExists (var URL: string): boolean;
function DeleteBookmark09 (Location: TLocation): boolean;
var
_Executing_History_Jump : boolean;
_Executing_JumpToKNTLocation_ToOtherNote : boolean;
_LastMoveWasHistory : boolean;
implementation
uses
kn_Global,
kn_Main,
kn_EditorUtils,
kn_FindReplaceMng,
kn_ImagesMng,
kn_ImageForm;
resourcestring
STR_01 = 'Note ID not found: %d';
STR_02 = 'Note name not found: %s';
STR_03 = 'Node ID not found: %d';
STR_04 = 'Node name not found: %s';
STR_05 = 'Select file to link to';
STR_06 = 'Select file to insert';
STR_07 = 'The file you selected is not a plain-text or RTF file and cannot be inserted.';
STR_08 = 'Cannot insert link to a KeyNote location, because no location has been marked. First, mark a location to which you want to link.';
STR_09 = ' Location inserted';
STR_10 = ' Current location marked';
STR_11 = ' Failed to open location';
STR_12 = 'Location does not exist or file cannot be opened: "%s"';
STR_13 = 'Invalid location string: %s';
STR_14 = ' Invalid location';
STR_15 = 'Error executing hyperlink: %s';
// STR_16 = ' Hold down SHIFT while clicking the URL: ';
STR_17 = ' URL modified';
STR_18 = ' URL action canceled';
STR_19 = ' URL copied to clipboard';
STR_20 = 'Error %d executing hyperlink "%s": "%s"';
STR_21 = ' History error';
STR_22 = ' Cannot navigate to history location';
STR_23 = ' History navigation error';
STR_24 = 'Navigate backwards in history';
STR_25 = 'Navigate backwards in note (''local'') history';
STR_26 = 'Navigate backwards in global history';
STR_27 = 'Navigate forward in history';
STR_28 = 'Navigate forward in note (''local'') history';
STR_29 = 'Navigate forward in global history';
STR_30 = ' (Ctrl+click: only in note history)';
STR_31 = ' [Mark: %d]';
STR_32 = ' (Undo to remove new hidden markers)';
type
EInvalidLocation = Exception;
var
INVALID_CHARS_FN : array[0..8] of string = (
'*', '?', '"', '<', '>', '|',
'=', ';', ','); // this ones are not invalid but very unusual..
const
IMAGE_GOBACK_IN_NOTE: integer = 53;
IMAGE_GOFORWARD_IN_NOTE: integer = 54;
IMAGE_GOBACK_OTHER_NOTE: integer = 38;
IMAGE_GOFORWARD_OTHER_NOTE: integer = 39;
procedure ClickOnURLImage(const URLstr: string; chrgURL: TCharRange; myURLAction: TURLAction; EnsureAsk: boolean = false); forward;
//=========================================
// PathOfKNTLink
//=========================================
function PathOfKNTLink (myTreeNode: TTreeNTNode; myNote : TTabNote; position: Integer; ForceShowPosition: boolean; RelativeKNTLink: boolean;
forUseInFindResults: boolean = false): string;
var
path, pathInsertionPoint : string;
i, j, n, m: integer;
pDelim: integer;
ShowFullPath: boolean;
PathTopToBottom: boolean;
begin
PathTopToBottom:= TreeOptions.PathTopToBottom;
ShowFullPath:= TreeOptions.ShowFullPath;
if forUseInFindResults then begin
ShowFullPath:= TreeOptions.ShowFullPathSearch;
PathTopToBottom:= true;
end;
if assigned(myTreeNode) then begin
if ShowFullPath then
path:= GetNodePath( myTreeNode, TreeOptions.NodeDelimiter, PathTopToBottom ) // {N}
else
path:= myTreeNode.Text; // {N}
if PathTopToBottom then
path:= myNote.Name + TreeOptions.NodeDelimiter + path
else
path:= path + TreeOptions.NodeDelimiter + myNote.Name;
end
else
path := myNote.Name;
// Hide common part of the path (common ancestors), if RelativeKNTLink=True
if RelativeKNTLink then begin
pathInsertionPoint:= PathOfKNTLink(GetCurrentTreeNode, ActiveNote, -1, false, false);
if path = pathInsertionPoint then
path:= ''
else begin
i:= 1;
n:= Length(path);
m:= Length(pathInsertionPoint);
if TreeOptions.PathTopToBottom then begin
pDelim:= 0;
while (i < Min(n, m)) and (path[i] = pathInsertionPoint[i]) do begin
if path[i] = TreeOptions.NodeDelimiter then
pDelim:= i;
i:= i + 1;
end;
if (i = m + 1) and (path[i] = TreeOptions.NodeDelimiter) then
pDelim:= i;
path:= Copy(path, pDelim+1, Length(path));
end
else begin
i:= n;
j:= m;
pDelim:= n+1;
while (i >= 1) and (j >= 1) and (path[i] = pathInsertionPoint[j]) do begin
if path[i] = TreeOptions.NodeDelimiter then
pDelim:= i;
i:= i - 1;
j:= j - 1;
end;
if (j = 0) and (path[i] = TreeOptions.NodeDelimiter) then
pDelim:= i;
path:= Copy(path, 1, pDelim-1);
end;
end;
end;
if (position >= 0) and (ForceShowPosition or TreeOptions.CaretInKNTLinks or (path = '')) then begin
if path = '' then
path:= 'Pos.'
else
path := path + ' - ';
path := path + IntToStr(position);
end;
Result:= path;
end; // PathOfKNTLink
//=========================================
// GetTreeNode
//=========================================
procedure GetTreeNodeFromLocation (const Location: TLocation; var Note: TTabNote; var myTreeNode: TTreeNTNode);
begin
with Location do begin
// obtain NOTE
Note := nil;
if (NoteID <> 0) then // new format
begin
Note := notefile.GetNoteByID( NoteID );
if (Note = nil ) then
raise EInvalidLocation.Create(Format( STR_01, [NoteID] ));
end
else begin
Note := notefile.GetNoteByName( NoteName );
if (Note = nil) then
raise EInvalidLocation.Create(Format( STR_02, [NoteName] ));
end;
// obtain NODE
myTreeNode := nil;
if ( Note.Kind = ntTree ) and ((NodeID > 0) or (NodeName <> '')) then begin // If NodeID <= 0 and NodeName = '' -> Node will be ignored
if ( NodeID <> 0 ) then begin // new format
myTreeNode := TTreeNote( Note ).GetTreeNodeByID( NodeID );
if (myTreeNode = nil) then
raise EInvalidLocation.Create(Format( STR_03, [NodeID] ));
end
else begin
myTreeNode := TTreeNote( Note ).TV.Items.FindNode( [ffText], NodeName, nil );
if (myTreeNode = nil) then
raise EInvalidLocation.Create(Format( STR_04, [NodeName] ));
end;
end;
end;
end;
//----------------------------------------
// Insertlink
//----------------------------------------
procedure InsertLink(URLStr: string; TextURL : string; FileLink: Boolean; Note: TTabNote; FromInsertURL: Boolean= false);
var
SelL: integer;
SelR: integer;
sepL, sepR: string;
UseHyperlink, ShowTextAndURL: boolean;
cad: string;
begin
UseHyperlink:= False;
if (RichEditVersion >= 4) and (not Note.PlainText) then
UseHyperlink:= True;
if ImagesManager.StorageMode <> smEmbRTF then begin
if Note.Editor.SelLength > 0 then
CheckToSelectLeftImageHiddenMark (Note.Editor);
end;
// URLFileEncodeName: Default=False URLFilePrefNoHyp: Default=False
if UseHyperlink and (not FromInsertURL) and FileLink and KeyOptions.URLFilePrefNoHyp then
if ((not KeyOptions.URLFileEncodeName) and (TextURL = StripFileURLPrefix(URLStr))) or
((KeyOptions.URLFileEncodeName) and (TextURL = StripFileURLPrefix(FileNameToURL(URLStr)))) then
UseHyperlink:= false;
with Note.Editor do begin
SelL := SelStart;
SelR := SelL + SelLength;
sepL:= '';
SetSelection(SelL-1, SelL, false);
cad:= Trim(SelText);
if SelAttributes.Link or (not UseHyperlink and (cad <> '') and not (AnsiChar(cad[1]) in ['<','(','[','{']) ) then
sepL:= ' ';
SetSelection(SelR, SelR+1, false);
cad:= Trim(SelText);
if SelAttributes.Link or (not UseHyperlink and (cad <> '') and not (AnsiChar(cad[1]) in ['>',')',']','}']) ) then
sepR:= ' ';
SetSelection(SelL, SelR, false);
{$IFDEF KNT_DEBUG}Log.Add('Insert HyperLink', 4 ); {$ENDIF}
if UseHyperlink then begin
Note.Editor.PutRtfText(Format('{\rtf1\ansi{\colortbl ;\red0\green0\blue255;}{\fonttbl}%s{\field{\*\fldinst{HYPERLINK "'
+ '%s"}}{\fldrslt{\cf1\ul %s}}}%s\cf0\ulnone}',
[sepL, URLToRTF(URLStr, false ), URLToRTF(TextURL, true), sepR]), true);
end
else begin
if FileLink and KeyOptions.URLFileEncodeName then
URLStr := FileNameToURL( URLStr );
ShowTextAndURL:= (TextURL <> '') and (TextURL <> StripFileURLPrefix(URLStr));
if pos(' ', URLStr) > 0 then
URLStr:= '<' + URLStr + '>';
if ShowTextAndURL then
SelText := sepL + '''' + TextURL + '''' + ' (' + URLStr + ') '
else
SelText := sepL + URLStr + #32;
if sepR = ' ' then
SelStart:= SelStart + SelLength
else begin
SelStart:= SelStart + SelLength-1;
SelLength:= 1;
SelText:= '';
end;
end;
SelLength := 0;
end;
end;
//===============================================================
// InsertFileOrLink
//===============================================================
procedure InsertFileOrLink( const aFileName : string; const AsLink : boolean; Relative: boolean= false );
var
FN : string;
oldFilter : string;
ImportFileType : TImportFileType;
ext : string;
RTFAux: TRxRichEdit;
begin
if ( not ( Form_Main.HaveNotes( true, true ) and assigned( ActiveNote ))) then exit;
if Form_Main.NoteIsReadOnly( ActiveNote, true ) then exit;
if ( aFileName = '' ) then begin
with Form_Main.OpenDlg do begin
oldFilter := Filter;
if AsLink then
Filter := FILTER_FILELINK
else
Filter := FILTER_RTFFILES + '|' +
FILTER_TEXTFILES + '|' +
FILTER_ALLFILES;
FilterIndex := 1;
if AsLink then
Title := STR_05
else
Title := STR_06;
Options := Options - [ofAllowMultiSelect];
Form_Main.OpenDlg.FileName := '';
if ( KeyOptions.LastImportPath <> '' ) then
InitialDir := KeyOptions.LastImportPath
else
InitialDir := GetFolderPath( fpPersonal );
end;
try
if ( not Form_Main.OpenDlg.Execute ) then exit;
FN := Form_Main.OpenDlg.FileName;
KeyOptions.LastImportPath := properfoldername( extractfilepath( FN ));
Relative:= AltDown;
finally
Form_Main.OpenDlg.Filter := oldFilter;
Form_Main.OpenDlg.FilterIndex := 1;
end;
end
else
FN := aFileName;
if Relative then
FN:= ExtractRelativePath(NoteFile.File_Path, FN);
if AsLink then begin
if pos( 'FILE:', AnsiUpperCase(FN) ) = 0 then
FN := 'file:///' + FN;
InsertLink(FN, StripFileURLPrefix(FN), true, ActiveNote);
end
else begin
ext := extractfileext( FN );
ImportFileType := itText;
if ( ext = ext_RTF ) then
ImportFileType := itRTF
else
if ExtIsHTML( ext ) then
ImportFileType := itHTML
else
if ExtIsText( ext ) then
ImportFileType := itText
else begin
DoMessageBox( STR_07, mtError, [mbOK]);
exit;
end;
ActiveNote.Editor.Lines.BeginUpdate;
try
try
if ImagesManager.StorageMode <> smEmbRTF then begin
if ActiveNote.Editor.SelLength > 0 then
CheckToSelectLeftImageHiddenMark (ActiveNote.Editor);
end;
case ImportFileType of
itText, itHTML : begin
ActiveNote.Editor.SelText := TFile.ReadAllText(FN);
ActiveNote.Editor.SelLength := 0;
end;
itRTF:
ActiveNote.Editor.PutRtfText(TFile.ReadAllText(FN), true);
end;
except
on E : Exception do begin
DoMessageBox( E.Message, mtError, [mbOK] );
exit;
end;
end;
finally
ActiveNote.Editor.Lines.EndUpdate;
end;
end;
NoteFile.Modified := true;
UpdateNoteFileState( [fscModified] );
end; // InsertFileOrLink
//===============================================================
// GetKNTLocation
//===============================================================
procedure GetKNTLocation (var Location: TLocation; Simplified: Boolean= false);
var
tNote: TTreeNote;
begin
{$IFDEF DEBUG_HISTORY}
Simplified:= false;
{$ENDIF}
if not assigned(Location) then
Location:= TLocation.Create;
with Location do begin
if not Simplified then begin
FileName := normalFN( NoteFile.FileName );
NoteName := ActiveNote.Name;
end;
NoteID := ActiveNote.ID;
NodeName := '';
NodeID := 0;
if (ActiveNote.Kind = ntTree) then begin
tNote:= TTreeNote(ActiveNote);
if TTreeNote(ActiveNote).SelectedNode <> nil then begin
NodeID := TTreeNote(ActiveNote).SelectedNode.ID;
if not Simplified then
NodeName := TTreeNote(ActiveNote).SelectedNode.Name;
end;
end;
CaretPos := ActiveNote.Editor.SelStart;
SelLength := ActiveNote.Editor.SelLength;
Mark := 0;
end;
end;
//===============================================================
// GetLastTargetMarker
//===============================================================
function GetLastTargetMarker(const Str: string): integer;
var
p, pF, N, Num: integer;
TargetMarker: String;
begin
TargetMarker:= KNT_RTF_HIDDEN_MARK_L_CHAR + KNT_RTF_HIDDEN_BOOKMARK; // \v\'11B999\'12\v0 HB999H
Num:= 0;
try
p:= 1;
repeat
p:= pos(TargetMarker, Str, p);
if (p > 0) then begin
pF:= pos(KNT_RTF_HIDDEN_MARK_R_CHAR, Str, p+1);
if (pF > 0 ) and ((pF - p) <= 5) then begin
N:= StrToInt(Copy(Str, P + 2, (pF - p)-2));
if N > Num then
Num:= N;
end;
p:= pF + 1;
end;
until (p = 0);
except
end;
Result:= Num;
end;
//===============================================================
// InsertOrMarkKNTLink
//===============================================================
(*
New KNT Links, vinculated to markers, not only to caret position
Until now, KNT links only included, in addition to the note and node, the caret position. If the note
was edited, the absolute position we were pointing to, would have changed and therefore our link would no longer point
to the intended position.
When marking a KNT location (Ctr+F6) the app will now insert a small hidden bookmark next to the text
identified as target. When inserting the link (Shift+F6) the new hyperlink will refer to the created bookmark,
and will locate it even though all the text could have been relocated (within the same note/node). If the marker
were eliminated, the caret position would be used, as before.
Note: The bookmark will only be inserted if the destination is a note or RTF node, other than virtual node.
The format used internally to register these markers is of the form. Ex:
{\rtf1\ansi \v\'11B5\'12\v0 Target of a KNT link}
Once retrieved as plain text: '#$11'B5'#$12'Target of a KNT link
B: Bookmark "5" 5º bookmark in the note / node.
To achieve this, it has been necessary for KNT to be able to handle RTF texts with this type of hidden text from any
functionality.
Among other things, it has been necessary to replace the mechanism that has been used to carry out the searches, where
the rich control (RxRichEdit.FindText) had been called directly iteratively. All the hidden texts are considered
in the search by RichEdit control, and would prevent finding the patterns that include them inside.
Now the search is done directly in Delphi, on a text string previously retrieved from the control.
A new method has been added to the RichEdit control, TextPlain, which is supported by the EM_GETTEXTEX message,
making use of the option GT_RAWTEXT:
<<Text is retrieved exactly as it appears in memory. This includes special structure characters for table row and cell delimiters
(see Remarks for EM_INSERTTABLE) as well as math object delimiters (start delimiter U+FDD0, argument delimiter U+FDEE, and end
delimiter U+FDDF) and object markers (U+FFFC). This maintains character-position alignment between the retrieved text and the
text in memory.>>
This way, position identified looking for a pattern text in a string returned by this function can be used to move caret to that position.
As an advantage, the new search mechanism is much faster. Once initialized [*] new plain text variables (NoteTextPlain / NodeTextPlain),
searches will now be almost instantaneous, whereas currently each search incurs the same amount of time, which on a large file can easily
be 5 or 6 seconds.
[*] With TNoteFile.UpdateTextPlainVariables, called by TForm_Main.TimerTimer, or on demand by RunFindAllEx (in kn_FindReplaceMng)
Subsequently, a modification will be included to try to ensure that these initial data are obtained at times when
the application is idle, so even the first search is instantaneous.
It has been necessary to revise many other points in the application to ensure that these hidden characters are 'transparent'.
For example, when copying (cutting or pasting is not necessary) to the clipboard, we must remove our possible hidden characters
(not others like hyperlinks). It is also needed to discard those hidden characters when exporting to other files, or when creating
templates. It has also been necessary to keep them in mind when performing operations such as changing to uppercase, lowercase, etc.
Once these changes have been made, the management of this new hidden text format will allow the implementation of other functionalities
in which it is necessary to mark or tag any text within a note.
*)
procedure InsertOrMarkKNTLink( aLocation : TLocation; const AsInsert : boolean; TextURL: string; NumBookmark09: integer= 0);
var
Note: TTabNote;
TreeNode: TTreeNTNode;
TargetMarker: integer;
str, strTargetMarker: string;
RTFMarker: AnsiString;
KEY_Marker: Char;
function GetActualTargetMarker (Editor: TRxRichEdit): integer;
var
SS, L, Len: integer;
Str: String;
begin
// *1 By the check made from TForm_Main.RxRTFKeyDown, when the Left cursor is pressed, if it is already next to
// an existing marker, we'll be just to the left
// *2 But if we insert a marker (CTR+F6) several times without moving the position, there would be a mark just in the left
Result:= 0;
Str:= '';
try
with Editor do begin
SS:= SelStart;
SelStart:= SS + 1;
L:= SelStart; // *1
if L <> SS + 1 then // It will have been placed to the left of the first non-hidden character, to the right (L > SS )
Str:= GetTextRange(SS, L) // HB999H
else begin
SelStart:= SS - 1;
L:= SelStart; // *2
if L <> SS - 1 then // It will have been placed to the left of the first non-hidden character, to the left (L < SS)
Str:= GetTextRange(L, SS);
end;
if Str <> '' then begin
Len:= Length(Str); // HB999H
if (Str[1]=KNT_RTF_HIDDEN_MARK_L_CHAR) and (Str[2]=KNT_RTF_HIDDEN_BOOKMARK) and (Str[Len]=KNT_RTF_HIDDEN_MARK_R_CHAR) then
Result:= StrToInt(Copy(Str, 3, (Len)-3));
end;
SelStart:= SS;
end;
except
end;
end;
begin
if ( not Form_Main.HaveNotes( true, true )) then exit;
if ( not assigned( ActiveNote )) then exit;
if ( aLocation = nil ) then
aLocation := _KNTLocation;
if AsInsert then begin
// insert link to previously marked location
if Form_Main.NoteIsReadOnly( ActiveNote, true ) then exit;
if aLocation.Bookmark09 then exit;
if ( aLocation.NoteName = '') and (aLocation.NoteID = 0) then begin
showmessage( STR_08 );
exit;
end;
if TextURL = '' then
if NoteFile.FileName = aLocation.FileName then begin
GetTreeNodeFromLocation (aLocation, Note, TreeNode);
TextURL:= PathOfKNTLink(TreeNode, Note, aLocation.CaretPos, false, TreeOptions.RelativeKNTLinks);
end
else
TextURL:= Format('%s: %s/%s %d', [ExtractFileName(aLocation.FileName),
aLocation.NoteName, aLocation.NodeName,
aLocation.CaretPos]);
InsertLink(BuildKNTLocationText(aLocation), TextURL, false, ActiveNote);
if aLocation.Mark <> 0 then
strTargetMarker:= Format(STR_31, [aLocation.Mark]);
Form_Main.StatusBar.Panels[PANEL_HINT].Text := STR_09 + strTargetMarker;
end
else begin
// mark caret position as TLocation
GetKNTLocation (aLocation);
// If we are pointing to the start of a node or a note (CaretPos = 0), we will not create any new markers. We will always aim for that position 0.
strTargetMarker:= '';
if (aLocation.CaretPos <> 0) and (not ActiveNote.PlainText)
and ((ActiveNote.Kind <> ntTree) or (TTreeNote(ActiveNote).SelectedNode.VirtualMode in [vmNone, vmRTF, vmKNTNode]) ) then begin // Allow the mark (hidden) although Note is ReadOnly
if NumBookmark09 <= 0 then
TargetMarker:= GetActualTargetMarker(ActiveNote.Editor); // If a marker already exists at that position, we will use it
if TargetMarker = 0 then begin
{$IFDEF KNT_DEBUG}Log.Add('Insert Marker for HyperLink', 4 ); {$ENDIF}
if NumBookmark09 >= 1 then begin // Bookmark0-9 -> [1-10]
TargetMarker:= NumBookmark09;
aLocation.Bookmark09:= true;
KEY_Marker:= KNT_RTF_HIDDEN_Bookmark09;
end
else begin
TargetMarker:= 1 + GetLastTargetMarker(ActiveNote.Editor.TextPlain);
KEY_Marker:= KNT_RTF_HIDDEN_BOOKMARK;
end;
// {\rtf1\ansi {\v\'11B5\'12}}; => {\rtf1\ansi \v\'11B5\'12\v0}; // Finally they will be inserted directly with \v...\v0 (see comment *2 next to KNT_RTF_BMK_HIDDEN_MARK in kn_const.pas)
RTFMarker:= Format('\v' + KNT_RTF_HIDDEN_MARK_L + KEY_Marker + '%d'+ KNT_RTF_HIDDEN_MARK_R + '\v0', [TargetMarker]);
ActiveNote.Editor.PutRtfText('{\rtf1\ansi' + RTFMarker + '}', true);
end;
strTargetMarker:= Format(STR_31 + STR_32, [TargetMarker]);
aLocation.Mark:= TargetMarker;
end;
Form_Main.StatusBar.Panels[PANEL_HINT].Text := STR_10 + strTargetMarker;
end;
end; // InsertOrMarkKNTLink
//===============================================================
// BuildKNTLocationText
//===============================================================
function BuildKNTLocationText( const aLocation : TLocation) : string;
var
LocationString : string;
NoteId, NodeId, LocationMark: string;
begin
if ( aLocation.FileName = normalFN( NoteFile.FileName )) then
LocationString := ''
else
LocationString := FileNameToURL( aLocation.FileName );
// [x] this does not handle files on another computer, i.e.
// we cannot do file://computername/pathname/file.knt
if (RichEditVersion >= 4) then begin
LocationMark:= KNTLOCATION_MARK_NEW;
NoteId:= inttostr( aLocation.NoteID );
NodeId:= inttostr( aLocation.NodeID );
end
else begin
LocationMark:= KNTLOCATION_MARK_OLD;
NoteId:= FileNameToURL( aLocation.NoteName );
NodeId:= FileNameToURL( aLocation.NodeName );
end;
LocationString := 'file:///' + LocationString + LocationMark +
NoteId + KNTLINK_SEPARATOR +
NodeId + KNTLINK_SEPARATOR +
inttostr( aLocation.CaretPos ) + KNTLINK_SEPARATOR +
inttostr( aLocation.SelLength );
if aLocation.Mark > 0 then
LocationString := LocationString + KNTLINK_SEPARATOR + inttostr( aLocation.Mark);
result := LocationString;
end; // BuildKNTLocationText
//---------------------------------------------------------------
// BuildKNTLocationFromString
//---------------------------------------------------------------
function BuildKNTLocationFromString( LocationStr : string ): TLocation;
var
p, pold, pnew : integer;
Location : TLocation;
NewFormatURL : boolean;
origLocationStr : string;
Note: TTabNote;
myTreeNode: TTreeNTNode;
begin
// Handles links that point to a "KNT location" rather than normal file:// URLs.
// We may receive two types of links:
// the old style link: file:///?filename.knt...
// the new style link: file:///*filename.knt...
p := 0;
origLocationStr := LocationStr;
Location := TLocation.Create;
LocationStr := StripFileURLPrefix( LocationStr );
pold := pos( KNTLOCATION_MARK_OLD, LocationStr );
pnew := pos( KNTLOCATION_MARK_NEW, LocationStr );
if (( pold = 0 ) and ( pnew = 0 )) then
raise EInvalidLocation.Create( origLocationStr );
// see which marker occurs FIRST
// (both markers may occur, because '?' and '*' may occur within note or node names
if ( pnew < pold ) then begin
if ( pnew > 0 ) then begin
NewFormatURL := true;
p := pnew;
end
else begin
NewFormatURL := false;
p := pold;
end;
end
else begin
if ( pold > 0 ) then begin
NewFormatURL := false;
p := pold;
end
else begin
NewFormatURL := true;
p := pnew;
end;
end;
// extract filename
case p of
0 : raise EInvalidLocation.Create( origLocationStr );
1 : Location.FileName := ''; // same file as current
else begin
Location.FileName := HTTPDecode( copy( LocationStr, 1, pred( p )));
if ( Location.FileName = NoteFile.FileName ) then
Location.FileName := '';
end;
end;
delete( LocationStr, 1, p ); // delete filename and ? or * marker
// extract note name or ID
p := pos( KNTLINK_SEPARATOR, LocationStr );
case p of
0 : begin
if NewFormatURL then
Location.NoteID := strtoint( LocationStr ) // get ID
else
Location.NoteName := HTTPDecode( LocationStr ); // get name
LocationStr := '';
end;
1 : raise EInvalidLocation.Create( origLocationStr );
else
begin
if NewFormatURL then
Location.NoteID := strtoint( copy( LocationStr, 1, pred( p )))
else
Location.NoteName := HTTPDecode( copy( LocationStr, 1, pred( p )));
delete( LocationStr, 1, p );
end;
end;
if Location.NoteID <> 0 then
Note := notefile.GetNoteByID( Location.NoteID )
else
Note := notefile.GetNoteByName( Location.NoteName );
if assigned(Note) then begin
Location.NoteID:= Note.ID;
Location.NoteName:= Note.Name;
end;
p := pos( KNTLINK_SEPARATOR, LocationStr );
case p of
0 : begin
if NewFormatURL then
Location.NodeID := StrToIntDef( LocationStr, -1)
else
Location.NodeName := HTTPDecode( LocationStr );
LocationStr := '';
end;
1 : begin
Location.NodeName := '';
Location.NodeID := -1;
end;
else
begin
if NewFormatURL then
Location.NodeID := StrToIntDef( copy( LocationStr, 1, pred( p )), -1)
else
Location.NodeName := HTTPDecode( copy( LocationStr, 1, pred( p )));
end;
end;
delete( LocationStr, 1, p );
if assigned(Note) then
if ( Note.Kind = ntTree ) and (Location.NodeID >= 0) then begin
if ( Location.NodeID <> 0 ) then
myTreeNode := TTreeNote( Note ).GetTreeNodeByID( Location.NodeID )
else
myTreeNode := TTreeNote( Note ).TV.Items.FindNode( [ffText], Location.NodeName, nil );
if assigned(myTreeNode) then
if assigned( myTreeNode.Data ) then begin
Location.NodeID:= TNoteNode( myTreeNode.Data ).ID;
Location.NoteName:= TNoteNode( myTreeNode.Data ).Name;
end;
end;
if ( LocationStr <> '' ) then begin
p := pos( KNTLINK_SEPARATOR, LocationStr );
if p <= 0 then
p:= 99;
try
Location.CaretPos := strtoint( copy( LocationStr, 1, pred( p )));
except
Location.CaretPos := 0;
end;
delete( LocationStr, 1, p );
end;
if ( LocationStr <> '' ) then begin
p := pos( KNTLINK_SEPARATOR, LocationStr );
Location.SelLength := 0;
if ( p > 0 ) then begin // selLenght|mark
try
Location.SelLength := strtoint(copy(LocationStr, 1, pred(p)));
except
end;
delete( LocationStr, 1, p );
if ( LocationStr <> '' ) then
try
Location.Mark := strToInt( LocationStr );
except
Location.Mark := 0;
end;
end
else // selLenght
try
Location.SelLength := strtoint(LocationStr);
except
end;
end;
Result:= Location;
end; // BuildKNTLocationFromString
function BuildBookmark09FromString( LocationStr : AnsiString ): TLocation;
var
Strs: TStrings;
s: AnsiString;
begin
// file:///*NoteID|NodeID|CursorPosition|SelectionLength|MarkID
// Ex: file:///*8|2|4|0|1
Result:= nil;
if Pos('file:///*', LocationStr) <> 1 then exit;
Strs:= TStringList.Create;
Result:= TLocation.Create;
try
try
s:= Copy(LocationStr, Length('file:///*')+1);
SplitString(Strs, s, '|', false);
with Result do begin
NoteID:= StrToInt(Strs[0]);
NodeID:= StrToInt(Strs[1]);
CaretPos:= StrToInt(Strs[2]);
SelLength:= StrToInt(Strs[3]);
Mark:= StrToInt(Strs[4]);
Bookmark09:= true;
end;
except
end;
finally
Strs.Free;
end;
end;
//===============================================================
// NavigateToTreeNode
//===============================================================
procedure NavigateToTreeNode(myTreeNode: TTreeNTNode);
var
myNote: TTabNote;
begin
if assigned(myTreeNode) then begin
myNote:= NoteFile.GetNoteByTreeNode(myTreeNode);
if ( myNote <> ActiveNote ) then begin
Form_Main.Pages.ActivePage := myNote.TabSheet;
Form_Main.PagesChange( Form_Main.Pages );
end;
if assigned( myTreeNode ) then begin
myTreeNode.MakeVisible;
TTreeNote( ActiveNote ).TV.Selected := myTreeNode;
end;
end;
end;
function GetPositionOffset (myNote : TTabNote; myTreeNode: TTreeNTNode; Pos_ImLinkTextPlain: integer; CaretPosition: integer; ForceCalc: boolean = false): integer;
var
Stream: TMemoryStream;
imLinkTextPlain: String;
Offset: integer;
RtfModified: boolean;