-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathNotesEditorTab__.pas
3037 lines (2650 loc) · 89.9 KB
/
NotesEditorTab__.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
//
// TNotesEditorTab - Componente que modifica os comportamentos
// do SynEdit para que fique de acordo com as idéias da equipe
// do Notes :)
//
// Notes, https://github.com/jonasraoni/notes
// Copyright (C) 2003-2004, Equipe do Notes.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
//
// The Original Code is: SynEditPythonBehaviour.pas, released 2000-06-23.
// The Original Code is based on odPythonBehaviour.pas by Olivier Deckmyn, part
// of the mwEdit component suite.
//
// Contributors to the SynEdit and mwEdit projects are listed in the
// Contributors.txt file. See http://synedit.sf.net for info.
//
(*
@abstract(NotesEditorTab - componente que agrupa tab, synedit e unighilighter além de adicionar novos comportamentos ao editor.)
@author(Anderson R. Barbieri <notesnr@ig.com.br>)
@author(Denner Bizarria Branco <dennerbb@yahoo.com.br>)
@author(Baseado no componente de Olivier Deckmyn e David Muir <dhm@dmsoftware.co.uk>)
*)
unit NotesEditorTab;
interface
uses
SysUtils, Classes, Windows, Messages, Graphics,
Controls, Forms, Dialogs, SynEdit, SynEditKeyCmds,
NotesHighlighter, ComCtrls, StdCtrls, NotesUtils,
NotesEditorTabPosList, SynEditTypes;
type
{ Guarda os últimos símbolos coloridos no editor.}
TLastColoredSymbols = record
P1: TPoint;
P2: Tpoint;
Cleared: boolean;
end;
type
TNotesLoadFromFileResult = (lfCancel, lfError, lfOk);
type
TNotesMarksList= class(TObject)
private
fItems: array of Integer;
fCount: integer;
fSorted: boolean;
function get(index: integer): integer;
procedure put(index: integer; value: integer);
procedure QuickSort(lowerPos, upperPos: integer);
public
function Add(atLine: integer): Integer;
function IndexOf(Value: integer): integer;
function Remove(atLine: integer): Integer;
function getNextMark(Line: integer): integer;
function getPreviousMark(Line: integer): integer;
procedure Sort;
procedure AdjustToLineAdded(Line: integer);
procedure AdjustToLineRemoved(Line: integer);
procedure Clear;
destructor destroy; override;
public
property Items[Index: Integer]: Integer read Get write Put; default;
property Count: integer read fCount;
end;
type
// Guarda as posições de um escopo
TNotesEscopePos = record
EscopeBegin,
EscopeEnd: TPoint;
EscopeStart: integer;
end;
{ Tipo de um indicador de escopo
@code(eiNone) - não mostra o indicador
@(eiGutter) - mostra uma linha com braços na gutter
@(eiEditor) - mostra o indicador no editor }
TNotesEscopeIndicatorType = (eiNone, eiGutter, eiEditor);
TNotesEditorTab = class;
// plugin para poder pegar linhas inseridas e removidas corretamente
TNotesSynPlugin = class(TSynEditPlugin)
private
fEdTab: TNotesEditorTab;
protected
procedure AfterPaint(ACanvas: TCanvas; const AClip: TRect;
FirstLine, LastLine: integer); override;
procedure LinesInserted(FirstLine, Count: integer); override;
procedure LinesDeleted(FirstLine, Count: integer); override;
public
property EditorTab: TNotesEditorTab read fEdTab write fEdTab;
end;
{ A classe TNotesEditorTab agrupa o synedit, a tab, a classe de coloração
e adiciona novos comportamentos ao editor permitindo manipular tudo isto em
conjunto.}
TNotesEditorTab = class(TObject)
private
FTag: Integer;
FEditor: TSynEdit;
FHighlighter: TNotesHighlighter;
FTab: TTabSheet;
FPlugin: TNotesSynPlugin;
FFileName: string;
fFileType: string;
FLastHS: TLastColoredSymbols;
FIndent: Integer;
FCloseHTMLTags: boolean;
FAutoclose: boolean;
FNoBackspaceAtLineStart: boolean;
FCanVKLeftGoUp: boolean;
FBlockIndent: boolean;
FHighlightSymbols: boolean;
FSymbolscolor: TColor;
FHLineColor: TColor;
FBlockStart: TStringArray;
FBlockEnd: TStringArray;
FBreakType: TNotesBreakType;
FFullPath: string;
fLinesCount: integer;
fMarks: TNotesMarksList;
fErrorLine: integer;
fEscopePos : TNotesEscopePos;
fEscopeIndicator: TNotesEscopeIndicatorType;
fEscopeIndicatorColor: TColor;
fEscopeStart: TStringArray;
fEscopeEnd: TStringArray;
fLineComment: string;
fMultilineCommentStart: string;
fMultilineCommentEnd: string;
fErrorColor: TColor;
function GetTabAsSpace: boolean;
function GetTabIndent: boolean;
function GetTabSize: integer;
function GetAutoIndent: boolean;
function GetCursorPastEof: boolean;
function GetCursorPastEol: boolean;
function GetBlockEndTokens: string;
function GetBlockStartTokens: string;
procedure SetCloseHTMLTags(const Value: boolean);
procedure SetTabAsSpace(const Value: boolean);
procedure SetTabIndent(const Value: boolean);
procedure SetAutoIndent(const Value: boolean);
procedure setBlockEndTokens(const Value: string);
procedure SetBlockIndent(const Value: boolean);
procedure setBlockStartTokens(const Value: string);
procedure SetCursorPastEof(const Value: boolean);
procedure SetHighlightLine(const Value: boolean);
procedure SetHLineColor(const Value: TColor);
procedure SetSymbolsColor(const Value: TColor);
procedure SetCursorPastEol(const Value: boolean);
procedure SetTabSize(const Value: integer);
procedure InsertSpaces(const NumberOfSpaces: integer);
function GetCloseHTMLStr: string;
function getEscopeEndTokens: string;
function getEscopeStartTokens: string;
procedure setEscopeendTokens(const Value: string);
procedure setEscopeStartTokens(const Value: string);
function getHighlightLine: boolean;
procedure setFileType(const Value: string);
protected
procedure SetEditor(Value: TSynEdit); virtual;
procedure doKeyPress(Sender: TObject; var Key: Char); virtual;
procedure doProcessCommand(Sender: TObject; var Command: TSynEditorCommand; var AChar: Char; Data: Pointer); virtual;
procedure doAfterProcessCmd(Sender: TObject; var Command: TSynEditorCommand; var AChar: Char; Data: Pointer); virtual;
procedure doSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor); virtual;
procedure doPaintTransient(Sender: TObject; Canvas: TCanvas; TransientType: TTransientType);
procedure doPaint(Sender: TObject; ACanvas: TCanvas);
procedure doMouseMoves(Sender: TObject; Shift: TShiftState; X, Y: Integer);
procedure doKeyUP(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure CalcEscopeIndicator;
function getLineY(const Line: integer): integer;
public
{ Cria um novo objeto da classe.<BR>
@code(aOwner) - o componente que vai "ter" a classe e seus componentes.<BR>
@code(aPgControl) - passe o PageControl no qual a nova tab será inserida.}
constructor Create(aOwner: TComponent; aPgControl: TPageControl);
destructor Destroy; override;
{ Carrega o texto de um arquivo. A caption da tab correspondente será atualizada
automaticamente. A propriedade EolStyle armazenará o tipo de fim de linha do arquivo. }
function LoadFromFile( const AFile: string ): TNotesLoadFromFileResult;
{ Retorna uma string com o tipo de fim de linha do arquivo.}
function GetFileBreakType: string;
{ Pega a próxima chave. Por exemplo, se no valor de APoint estiver um "(" ele
vai retornar onde está o próximo ")".}
function GetMatchingBracket(const APoint: TBufferCoord): TBufferCoord;
{ Permite pegar as opções do synedit mais facilmente.}
function IsEditorOptionSetted( Option: TSynEditorOption ): Boolean;
procedure AttachEvents;
{ Salva o texto para um arquivo. Se EolStyle não for do tipo windows, o texto
terá seus fins de linhas convertidos para o tipo especificado em EolStyle.}
procedure SaveToFile( const AFile: string );
{ Desfazer }
procedure Undo;
{Copia o texto selecionado para a clipboard. Use este procedimento no lugar
do procedimento do SynEdit.}
procedure CopyToClipBoard;
{Cola o texto da clipboard. Use este procedimento no lugar
do procedimento do SynEdit.}
procedure PasteFromClipboard;
{Recorta o texto selecionado para a clipboard. Use este procedimento no lugar
do procedimento do SynEdit.}
procedure CutToClipboard;
{ Deleta o texto selecionado. Use este procedimento no lugar
do procedimento do SynEdit.}
procedure Delete;
{ Vai para a linha. }
procedure GoToLine(const Line: Integer);
{ Vai para a coluna.}
procedure GoToCol(const Col: Integer);
{ Insere o conteúdo de um arquivo no texto.}
procedure InsertTextFromFile(const AFile: string);
{ A feature "envolver com" do notes.}
procedure InsertNCLItem( const FileName: string );
{ Comenta o bloco.}
procedure CommentBlock;
{ Descomnenta o bloco.}
procedure UnCommentBlock;
{ Aumenta a indentação.}
procedure IndentBlock;
{ Diminuí a indentação.}
procedure UnIndentBlock;
{ Seleciona a linha.}
procedure SelectLine;
{ Duplica a linha.}
procedure DuplicateLine;
{ Deleta a linha.}
procedure DeleteLine;
{ Vai para o próximo braço. }
procedure GoToMatchingBracket;
{ Permite setar as opções do synedit mais facilmente.}
procedure SetEditorOption( Option: TSynEditorOption; Enable: Boolean );
// Recarrega as confiruações para o tipo de arquivo atual
procedure ReloadConfig;
procedure ToogleMark;
procedure NextMark;
procedure PreviousMark;
procedure GoToMark(MarkNumber: integer);
// Lista de marcadores.
property Marks: TNotesMarksList read fMarks write fMarks;
published
{ Permite acessar o SynEditor.}
property Editor: TSynEdit read FEditor write SetEditor;
{ Permite acessar o UniHighlighter.}
property Highlighter: TNotesHighlighter read FHighlighter write FHighlighter;
{ Guarda o caminho completo do arquivo que está sendo editado.}
property FullPath: string read FFullPath write FFullPath;
{ Guarda o nome do arquivo que está sendo editado.}
property FileName: string read fFileName write fFileName;
{ Guarda o tipo de arquivo do arquivo atual.}
property FileType: string read fFileType write setFileType;
{ Tamanho em espaços da indentação.}
property IndentSize: integer read fIndent write fIndent default 4;
{ Tamanho em espaços do caracter tab.}
property TabSize: integer read GetTabSize write SetTabSize;
{ Se true, as tabs serão sempre convertidas para espaços.}
property TabAsSpace: boolean read GetTabAsSpace write SetTabAsSpace;
{ Permite indentar o código teclando tab.}
property TabIndent: boolean read GetTabIndent write SetTabIndent;
{ Fecha tags HTML automaticamente.}
property CloseHTMLTags: boolean read fCloseHTMLTags write SetCloseHTMLTags;
{ Fecha os símbolos de programação automaticamente.}
property AutoClose: boolean read fAutoclose write fAutoclose;
{ Se true, colore de forma especial símbolos como (, [, etc.}
property highlightSymbols: boolean read fHighlightSymbols write fHighlightSymbols;
{ Colore a linha atual.}
property highlightLine: boolean read getHighlightLine write SetHighlightLine;
property highlightSymbolsColor: TColor read fSymbolscolor write SetSymbolsColor;
property highlightLineColor: TColor read fHLineColor write SetHLineColor;
{ Se true, permite que o usuário posicione o cursor após o fim da linha.}
property CursorPastEol: boolean read GetCursorPastEol write SetCursorPastEol;
{ Se true, o Notes deixa o cursor passar do fim do arquivo. Ele vai inserir
novas linhas no arquivo se necessário.}
property CursorPastEof: boolean read GetCursorPastEof write SetCursorPastEof;
{ Se true o usuário pode voltar a linha anterior usando a seta equerda (VK_LEFT).
Do contrário, se for false, o cusor irá parar ao chegar no início da linha.}
property CanVKLeftGoUp: boolean read fCanVKLeftGoUp write fCanVKLeftGoUp;
{ Proibe, se true, o usuário de usar backspace ao início da linha.}
property NoBackspaceAtLineStart: boolean read fNoBackspaceAtLineStart write fNoBackspaceAtLineStart;
{ Se true, ao teclar "enter" a próxima linha terá a mesma identação
que a linha atual.}
property AutoIndent: boolean read GetAutoIndent write SetAutoIndent;
{ Se true o Notes vai fazer uam espécie de "SmartIndent" usando
os valores das propriedades @link(BlockStartTokens) e @link(BlockEndTokens).}
property BlockIndent: boolean read fBlockIndent write SetBlockIndent;
{ Lista de tokens separados por espaço. Se o usuário teclar Enter
após um dos tokens desta lista, a próxima linha ganhará uma indentação
a mais do que a linha atual.}
property BlockStartTokens: string read GetBlockStartTokens write setBlockStartTokens;
{ Lista de tokens separados por espaço. Se o usuário teclar Enter
após um dos tokens desta lista, a linha atual perderá uma indentação
e então a próxima linha terá a mesma indentação que a linha atual.}
property BlockEndTokens: string read GetBlockEndTokens write setBlockEndTokens;
{ Tipo de fim de linha.}
property BreakType: TNotesBreakType read FBreakType write FBreakType;
{ Permite acessar a tab.}
property Tab: TTabSheet read FTab write FTab;
// linha a ser marcada com a cor de erros
property ErrorLine: integer read fErrorLine write fErrorLine;
// cor de erro
property ErrorsColor: TColor read fErrorColor write fErrorColor;
// Tipo de indicador de escopo. Vide @link(TNotesEscopeIndicatorType).
property EscopeIndicator: TNotesEscopeIndicatorType read fEscopeIndicator write fEscopeIndicator;
// Cor do indicador de escopo
property EscopeIndicatorColor: TColor read fEscopeIndicatorColor write fEscopeIndicatorColor;
// Tokens que iniciam um escopo
property EscopeStartTokens: string read getEscopeStartTokens write setEscopeStartTokens;
// Tokens que finalizam um escopo
property EscopeEndTokens: string read getEscopeEndTokens write setEscopeendTokens;
// Tag
property Tag: integer read fTag write fTag;
property LineComment: string read fLineComment write fLineComment;
property MultilineCommentStart: string read fMultilineCommentStart write fMultilineCommentStart;
property MultilineCommentEnd: string read fMultilineCommentEnd write fMultilineCommentEnd;
end;
function DisplayCoordToPoint(const Coord: TDisplayCoord): TPoint;
function PointToDisplayCoord(const APoint: TPoint): TDisplayCoord;
function BufferCoordToPoint(const Coord: TBufferCoord): TPoint;
function PointToBufferCoord(const APoint: TPoint): TBufferCoord;
Var
ProblemsList: TNotesEditorTabPosList;
EditLocationsList: TNotesEditorTabPosList;
implementation
// resource com os ícones dos marcadores/problemas
{$R NotesEditorTab.res}
uses
ShellAPI, FastStrings, SynEditHighlighter, NotesXML, NotesGlobals,
NotesToolTip, NotesFileTypeOptions, SynEditTextBuffer, StrUtils, Math;
Var
MarkIco: HICON;
ProblemIco: HICON;
fProblemIcon: TIcon;
fMarkIcon: TIcon;
tip: TNotesToolTip;
Const
(* Tags HTML que não devem ser fechadas *)
ExcludeTags: Array[0..86] of string = ('br', 'img', 'hr', '!DOCTYPE',
'meta', 'link', 'frame', '!--', '--', '', ' ', '?xml', 'AREA',
'BGSOUND', 'OVERLAY', 'BASE', 'RANGE', 'INPUT', 'MULTICOL',
'BASEFONT', 'TEXTFLOW', 'PARAM', 'SPACER', 'WBR', 'ISINDEX',
(* Tags do ColdFusion que não devem ser fechadas *)
'cfset', 'cfelse', 'cfelseif', 'cflocation', 'cfabort', 'cfapplet', 'cfapplication',
'cfargument', 'cfreturn', 'cfassociate', 'cfbreak','cfcache', 'cfchartdata','cfcol',
'cfcollection','cfcontent', 'cfcookie','cfdirectory', 'cfdump','cferror', 'cfexit',
'cffile', 'cfflush','cfftp', 'cfgridcolumn', 'cfgridrow','cfgridupdate', 'cfheader',
'cfhtmlhead', 'cfhttpparam','cfimport', 'cfinclude','cfindex', 'cfinput','cfinsert',
'cfinvokeargument', 'cfldap','cflocation', 'cflog','cfloginuser', 'cflogout',
'cfmailparam', 'CFMODULE','cfobject', 'cfobjectcache','cfparam', 'cfpop', 'cfprocparam',
'cfprocresult','cfproperty', 'cfqueryparam','cfregistry', 'cfrethrow','cfschedule',
'cfsearch','cfsetting', 'cfslider','cftextinput', 'cftreeitem', 'cfupdate','cfwddx',
'cfauthenticate');
//
// FUNÇÕES UTEÍS
//
//-----------------------------------------------------------------
(**
* Procedimento: IsInStrArray
* Descrição: Retorna true se a string ASearch estiver contida no
* Array de String passado em ASource
* Autor: Anderson R. Barbieri
* Data: 25-nov-2003
* Argumentos: ASearch: string; ASource: Array of String
* Resultado: boolean
*)
function IsInStrArray(const ASearch: string; const ASource: TStringArray): boolean; overload;
Var
I: integer;
begin
Result:= false;
for I:= 0 to high(ASource) do
if SameText(ASource[I], ASearch) then begin
Result:= true;
Break;
Exit;
end;
end;
function IsInStrArray(const ASearch: string; const ASource: array of string): boolean; overload;
Var
I: integer;
begin
Result:= false;
for I:= 0 to high(ASource) do
if SameText(ASource[I], ASearch) then begin
Result:= true;
Break;
Exit;
end;
end;
function DisplayCoordToPoint(const Coord: TDisplayCoord): TPoint;
begin
Result.X:= Coord.Column;
Result.Y:= Coord.Row;
end;
function PointToDisplayCoord(const APoint: TPoint): TDisplayCoord;
begin
Result.Column:= APoint.X;
Result.Row:= APoint.Y;
end;
function BufferCoordToPoint(const Coord: TBufferCoord): TPoint;
begin
Result.X:= Coord.Char;
Result.Y:= Coord.Line;
end;
function PointToBufferCoord(const APoint: TPoint): TBufferCoord;
begin
Result.Char:= APoint.X;
Result.Line:= APoint.Y;
end;
function GetLastWord(const S: string): String;
Var
I: integer;
begin
I:= length(S);
if I < 1 then Exit;
while (S[I] <> #32) and (S[I] <> #9) and (I > 1) do
Dec(I);
Result:= Copy(S, I, length(S));
end;
function TabsToSpaces(const S: string; const TabSize: integer): string;
begin
Result:= StringReplace(S, #9, StringOfChar(#32, TabSize), [rfReplaceAll]);
end;
function SpacesToTabs(const S: string; const TabSize: integer): string;
begin
Result:= StringReplace(S, StringOfChar(#32, TabSize), #9, [rfReplaceAll]);
end;
//-----------------------------------------------------------------
(**
* Procedimento: IsInTag
* Descrição: Retorna true se a posição passada em YourPas
* estiver dentro do trecho especificado por
* StartTag e EndTag.
* Autor: Anderson R. Barbieri
* Data: 26-nov-2003
* Argumentos: const S, StartTag, EndTag: string; const YourPos, StartTagLen, EndTagLen: integer
* Resultado: boolean
*)
function IsInTag(const S, StartTag, EndTag: string;
const YourPos, StartTagLen, EndTagLen: integer): boolean;
var
DangerousTagsBegin, DangerousTagsEnd, Len: integer;
begin
Result:= false;
Len:= length(S);
DangerousTagsBegin:= FastPosBackNoCase(S, StartTag,
Len, StartTagLen, YourPos);
if DangerousTagsBegin > 0 then begin
DangerousTagsEnd:= FastPosBackNoCase(S, EndTag,
Len, EndTagLen, YourPos);
// se a tag de fim for anterior a de início,
// então estamos dentro da tag
if DangerousTagsEnd < DangerousTagsBegin then
Result:= true;
end;
end;
{ TNotesEditorTab }
//-----------------------------------------------------------------
(**
* Procedimento: TNotesEditorTab.AttachEvents
* Descrição: Anexa-se aos eventos do SynEdit
* Autor: Anderson R. Barbieri
* Data: 23-nov-2003
* Argumentos: None
* Resultado: None
*)
procedure TNotesEditorTab.AttachEvents;
begin
if assigned(FEditor) then
begin
FEditor.OnProcessCommand := doProcessCommand;
FEditor.OnCommandProcessed := doAfterProcessCmd;
FEditor.OnKeyPress := doKeyPress;
FEditor.OnPaintTransient := doPaintTransient;
FEditor.OnSpecialLineColors := doSpecialLineColors;
FEditor.OnKeyUp := doKeyUP;
fEditor.OnMouseMove := doMouseMoves;
fEditor.OnPaint := doPaint;
end;
end;
constructor TNotesEditorTab.Create(aOwner: TComponent; aPgControl: TPageControl);
begin
FTab := TTabSheet.Create(nil);
FTab.Parent:= aPgControl;
FTab.PageControl := aPgControl;
FTab.Tag := Integer( Self );
FEditor := TSynEdit.Create(nil);
// Limpamos as keystrokes, os atalhos serão gerenciados pelo Notes.
FEditor.Keystrokes.Clear;
FHighlighter:= nil;
FEditor.Align:= alClient;
FEditor.ScrollHintFormat:= shfTopToBottom;
FEditor.ScrollBars:= ssBoth;
FEditor.TabOrder:= 0;
FEditor.WantTabs:= true;
SetEditorOption(eoAutoSizeMaxScrollWidth, true);
SetEditorOption(eoDisableScrollArrows, true);
SetEditorOption(eoDragDropEditing, true);
SetEditorOption(eoDropFiles, true);
SetEditorOption(eoGroupUndo, true);
SetEditorOption(eoRightMouseMovesCursor, true);
SetEditorOption(eoShowScrollHint, true);
SetEditorOption(eoKeepCaretX, true);
SetEditorOption(eoSpecialLineDefaultFg, true);
SetEditorOption(eoHideShowScrollbars, false);
SetEditorOption(eoAltSetsColumnMode, true);
//OnSpecialLineColors: TSpecialLineColorsEvent
fIndent := 4;
fLastHS.Cleared:= true;
fCloseHTMLTags:= true;
fAutoclose:= true;
fNoBackspaceAtLineStart:= false;
fCanVKLeftGoUp:= true;
fBlockIndent:= true;
fHighlightSymbols:= true;
fSymbolscolor:= clLtGray;
fHLineColor:= clSilver;
fMarks:= TNotesMarksList.Create;
BreakType:= btWin;
fEscopeIndicator:= eiGutter;
fEscopeIndicatorColor:= clLtGray;
FEditor.Parent:= FTab;
// plugins são distruídos pelo próprio synedit
FPlugin:= TNotesSynPlugin.Create(FEditor);
FPlugin.EditorTab:= self;
AttachEvents;
end;
destructor TNotesEditorTab.Destroy;
begin
if FEditor <> nil then
FreeAndNil( FEditor );
if FHighlighter <> nil then
FreeAndNil( FHighlighter );
if FTab <> nil then
FreeAndNil( FTab );
fMarks.Free;
inherited Destroy;
end;
//-----------------------------------------------------------------
(**
* Procedimento: TNotesEditorTab.SetEditor
* Descrição: Seta o SynEdit ao qual estará anexado
* Autor: Anderson R. Barbieri
* Data: 23-nov-2003
*)
procedure TNotesEditorTab.SetEditor(Value: TSynEdit);
begin
if FEditor <> Value then begin
FEditor := Value;
AttachEvents;
end;
end;
//-----------------------------------------------------------------
(**
* Procedimento: TNotesEditorTab.doAfterProcessCmd
* Descrição: Acionado depois q um comando é processado
*)
procedure TNotesEditorTab.doAfterProcessCmd(Sender: TObject;
var Command: TSynEditorCommand; var AChar: Char; Data: Pointer);
begin
if ((Command = ecDeleteLastChar) or (Command = ecDeleteChar)) and (fLinesCount > fEditor.Lines.Count) then
begin
fMarks.AdjustToLineRemoved(fEditor.CaretY);
ProblemsList.AdjustToLineRemoved(fEditor.CaretY, self.FullPath);
end;
if (Command > 500) and (Command > 605) then
begin
if (FullPath <> '') and (EditLocationsList.Count > 0) and (((EditLocationsList.Last.Line > fEditor.CaretY + 8) or
(EditLocationsList.Last.Line < fEditor.CaretY - 8)) or (EditLocationsList.Last.FileName <> FullPath)) then
EditLocationsList.Add(fEditor.CaretY, fEditor.CaretX, FFullPath, '');
if (EditLocationsList.Count = 0) then
EditLocationsList.Add(fEditor.CaretY, fEditor.CaretX, FFullPath, '');
end;
if not ((GetKeyState(VK_UP) < 0) or (GetKeyState(VK_DOWN) < 0)) then
CalcEscopeIndicator;
if (fEditor.CaretY < fEscopePos.EscopeBegin.Y) or (fEditor.CaretY > fEscopePos.EscopeEnd.Y) then
begin
fEscopePos.EscopeBegin:= Point(0,0);
fEscopePos.EscopeEnd:= Point(0,0);
end;
case fEscopeIndicator of
eiGutter: fEditor.InvalidateGutter;
eiEditor: fEditor.Repaint;
end;
end;
//----------------------------------------------------------------
// Mostra uma tooltip com o problema que ocorreu na linha qdo a
// linha tem um problema
procedure TNotesEditorTab.doMouseMoves(Sender: TObject; Shift: TShiftState; X, Y: Integer);
Var
CL, I: integer;
begin
if fEditor.Dragging then Exit;
if tip.isShowing then Exit;
// O mouse está na gutter?!
if (X > 0) and (X < fEditor.Gutter.Width-6+16) then
begin
// Se o botão do mouse estiver sendo pressionado, saímos
if (ssRight in Shift) or (ssLeft in Shift) or (ssMiddle in Shift) then Exit;
if ProblemsList.Count = 0 then Exit;
if (X < fEditor.Gutter.Width - 6 +16) and (x > fEditor.Gutter.Width -6) then
begin
// CL --> linha em que está o mouse
CL:= Y div fEditor.LineHeight;
CL:= CL + fEditor.TopLine;
CL:= FEditor.RowToLine(CL);
// vemos se na linha CL há um ícone de erro
for I:= 0 to ProblemsList.Count-1 do
begin
if (ProblemsList.Items[I].Line = CL) and (SameText(self.FullPath, ProblemsList.Items[I].FileName)) then
begin
tip.Title:= 'Problema:';
tip.Text:= ProblemsList.Items[I].Info;
tip.Show;
Exit;
end;
end;
end;
end;
end;
//-----------------------------------------------------------------
(**
* Procedimento: TNotesEditorTab.doSpecialLineColors
* Descrição: Colore a linha fErrorLine com fErrorColor
* Autor: Josimar Silva
*)
procedure TNotesEditorTab.doSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG, BG: TColor);
begin
if Line = fErrorLine then
begin
Special:= true;
BG:= fErrorColor;
FG:= clWhite;
end;
end;
//-----------------------------------------------------------------
(**
* Procedimento: TNotesEditorTab.doKeyPress
* Descrição: Recebe os KeyPress do editor
* (e implementa Autoclose, closeHTMLTags, etc.)
* Autor: Anderson R. Barbieri
*)
procedure TNotesEditorTab.doKeyPress(Sender: TObject; var Key: Char);
var
I: integer;
function CheckIsShouldAutoCompleteChars(Key: Char): boolean;
Var
Len: integer;
S: string;
I, C: integer;
begin
S:= FEditor.LineText;
Len:= length(S);
Result:= false;
// Se o cursor estiver no final da linha sempre autocompletamos
if (Len < 2) or (FEditor.CaretX > Len -1) then
begin
Result:= true;
end else
begin
// usamos C para guardar a posição do caracter na tabela ASCII
C:= Ord(S[FEditor.CaretX]);
if (C < 48) and ((C > 57) and (C < 65)) and ( (C > 90) and
(C < 97) ) and ( (C > 122) and (C < 192) )
and (C <> 32) and (C <> 9) then
Result:= true;
end;
{ Os caracteres " e ' precisam de um tratamento especial
por que o seu caracter de fechamento é ele mesmo. Se o usuário
estiver fechando um trecho com ' ou ", não devemos completar.
Para isto contamos o número dele na linha. Se o número for
ímpar, então NÂO autocompletamos. }
if (Result) and (Key in [#34, #39]) then
begin
// Guardamos a contagem em C - iniciado como 2 para evitar division by zero
C:= 2;
for I:= 1 to Len do
if S[I] = Key then
inc(C);
if (C mod 2 <> 0) then
Result:= false;
end;
end;
begin
if fErrorLine > 0 then
begin
fErrorLine:= -1;
fEditor.Invalidate;
end;
if (fAutoclose) and (CheckIsShouldAutoCompleteChars(Key)) then
begin
Case Key of
'(':
begin
Key:= #0;
FEditor.ExecuteCommand(ecChar, '(', nil);
FEditor.ExecuteCommand(ecChar, ')', nil);
FEditor.CaretX:= FEditor.CaretX - 1;
end;
'[':
begin
Key:= #0;
FEditor.ExecuteCommand(ecChar, '[', nil);
FEditor.ExecuteCommand(ecChar, ']', nil);
FEditor.CaretX:= FEditor.CaretX - 1;
end;
'"':
begin
Key:= #0;
FEditor.ExecuteCommand(ecChar, '"', nil);
FEditor.ExecuteCommand(ecChar, '"', nil);
FEditor.CaretX:= FEditor.CaretX - 1;
end;
#39:
begin
Key:= #0;
FEditor.ExecuteCommand(ecChar, #39, nil);
FEditor.ExecuteCommand(ecChar, #39, nil);
FEditor.CaretX:= FEditor.CaretX - 1;
end;
'{':
begin
Key:= #0;
FEditor.ExecuteCommand(ecChar, '{', nil);
FEditor.ExecuteCommand(ecChar, '}', nil);
FEditor.CaretX:= FEditor.CaretX - 1;
end;
end;
end;
if (Key = '>') and (fCloseHTMLTags) and (length(FEditor.LineText) > 1)
and (FEditor.CaretX > 1) and
// EM XML e XHTML as tags que acabam em / não devem ser fechadas
(FEditor.LineText[FEditor.CaretX-1] <> '/') then
begin
Key:= #0;
I:= FEditor.SelStart;
FEditor.SelText:= GetCloseHTMLStr;
FEditor.SelStart:= I + 1;
end;
end;
//-----------------------------------------------------------------
(**
* Descrição: O SynEdit tem uma coisa maravilhosa chamada "comandos".
* Basicamente, tudo que ele faz (mudar a posição do cursor,
* deletar o próximo caracter, inserir uma linha) é traduzido
* para algum comando. Então nada melhor para modificar o
* comportamento do SynEdit do que receber os comandos que
* chegam e transformaá-los para aquilo que a gente quer fazer.
* Praticamente todos os comportamentos novos estão
* implementados neste procedure.
* Autor: Anderson R. Barbieri
*)
procedure TNotesEditorTab.doProcessCommand(Sender: TObject;
var Command: TSynEditorCommand; var AChar: Char; Data: Pointer);
var
S: string;
I: integer;
begin
fLinesCount:= FEditor.Lines.Count;
if fErrorLine > 0 then
begin
fErrorLine:= -1;
fEditor.Invalidate;
end;
Case command of
ecClearAll:
begin
fMarks.Clear;
ProblemsList.ClearItemsForFile(self.FullPath);
fEditor.InvalidateGutter;
end;
{ Possibilita que o cursor passe de verdade do Eof }
ecDown:
if IsEditorOptionSetted( eoScrollPastEof ) and ( ( FEditor.CaretXY.Line = fLinesCount ) or ( fLinesCount = 0 ) ) then begin
FEditor.BeginUpdate;
I := FEditor.CaretX;
FEditor.ExecuteCommand( ecLineEnd, #0, nil );
FEditor.ExecuteCommand( ecInsertLine, #0, nil );
FEditor.CaretX:= I;
FEditor.EndUpdate;
end;
ecLineBreak:
begin
fMarks.AdjustToLineAdded(fEditor.CaretY-1);
ProblemsList.AdjustToLineAdded(fEditor.CaretY-1, self.FullPath);
if Not fBlockIndent then Exit;
S:= FEditor.LineText;
if Length(S)+1 > FEditor.CaretX then
Exit;
S:= trim(S);
if S = EmptyStr then Exit;
// início de bloco: aumentar identação da próxima linha
if isInStrArray(GetLastWord(S), fBlockStart) then begin
// paramos a quebra de linha
Command:= ecNone;
// descobrimos quantos espaços tem a linha atual
I:= 1;
S:= FEditor.LineText;
while (S[I] in [#32, #9]) and (I < length(S)) do
if S[I] = #32 then
inc(I)
else
inc(I, FEditor.TabWidth);
// inserimos a nova linha
FEditor.ExecuteCommand(ecInsertLine, #0, nil);
// Mandamos o cursor para a nova linha
FEditor.CaretXY:= BufferCoord( 0, FEditor.CaretY + 1);
// inserimos os espaços mais uma indentação
InsertSpaces(I + fIndent);
// mandamos o cursor para o fim da linha
FEditor.CaretXY:= BufferCoord( I + fIndent , FEditor.CaretY);
end
// fim de bloco: diminuí a identação da linha atual e manda
// o cursor para a próxima linha
else if isInStrArray(GetLastWord(S), fBlockEnd) then begin
// paramos a quebra de linha
Command:= ecNone;
// descobrimos quantos espaços tem a linha atual
I:= 1;
S:= FEditor.LineText;
while (S[I] in [#32, #9]) and (I < length(S)) do begin
if S[I] = #32 then
inc(I)
else
inc(I, FEditor.TabWidth);
end;
// no caso da identação da linha estar pequena demais
// apenas colocamos tudo no ínicio da linha
if I - fIndent < 0 then begin
FEditor.LineText:= Trim(FEditor.LineText);
Command:= ecLineBreak;
Exit;
end;
// tiramos uma identação da linha atual
FEditor.LineText:= Copy(FEditor.LineText, fIndent+1, length(FEditor.LineText));
// inserimos a nova linha
FEditor.ExecuteCommand(ecInsertLine, #0, nil);
// Mandamos o cursor para a nova linha
FEditor.CaretXY:= BufferCoord( 0, FEditor.CaretY + 1);
// inserimos os espaços com menos uma indentação
InsertSpaces(I - fIndent);
// mandamos o cursor para o fim da linha
FEditor.CaretXY:= BufferCoord( I - fIndent , FEditor.CaretY);
end;
end;
ecSelLeft..ecSelGotoXY, ecSelectAll:
begin
// Não pintamos o escopo qdo há txt selecionado
fEscopePos.EscopeBegin:= Point(0,0);
fEscopePos.EscopeEnd:= Point(0,0);
fEscopePos.EscopeStart := 0;
end;
ecLeft:
begin
if fCanVKLeftGoUp then begin
if FEditor.CaretX = 1 then
if FEditor.CaretY > 1 then begin
FEditor.ExecuteCommand(ecUp, #0, nil);
Command:= ecLineEnd;
end;
end
else if FEditor.CaretX = 1 then
Command:= ecNone;
end;
// opção para proibir backspace no início da linha
{ ecDeleteLastChar:
begin
if fNoBackspaceAtLineStart and ( FEditor.CaretX = 1 ) then
Command:= ecnone;}