Sign in Join
Wiki copytemporary

Codetools: what changed

Revision 4 to 5. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11# What are the codetools?
22
33Codetools is a Lazarus package providing tools to parse, explore, edit and refactor Pascal sources. The codetools have been packaged in their own module and are licensed under GPL. Many examples showing how to use the codetools in your own programs can be found under components/codetools/examples.
44
55svn:
66
77- Lazarus: <http://svn.freepascal.org/svn/lazarus/trunk>
88- Only CodeTools: <http://svn.freepascal.org/svn/lazarus/trunk/components/codetools>
99
1010# Using the codetools without the IDE
1111
1212You can use the codetools without the IDE. This can be used to test a new tool. An easy example is
1313
14-```
14+```text
1515 <lazarusdir>/components/codetools/examples/methodjumping.lpi
1616```
1717
1818To test find declaration, the codetools need to parse sources. Especially the RTL and FCL sources. The examples use the following environment variables:
1919
2020- FPCDIR: path to the FPC sources, the default is *~/freepascal/fpc*.
2121- PP: path to the compiler executable (/usr/bin/fpc or /usr/bin/ppc386 or C:\lazarus\ppc386.exe). The codetools need to ask the compiler for the settings. The default is to search for 'fpc' via the PATH variable.
2222- FPCTARGETOS: tell the codetools to scan for another operating system (cross compiling). For example: linux, freebsd, darwin, win32, win64, wince
2323- FPCTARGETCPU: when scanning for another CPU. For example: i386, powerpc, x86_64, arm, sparc
2424- LAZARUSDIR: path of the lazarus sources. Only needed if you want to scan them.
2525
2626FPC is a very complex project with lots of search paths, include files and macros. The codetools need to know all these paths and macros in order to parse this jungle. To setup all this easily the codetools contain predefined templates for FPC, Lazarus, Delphi and Kylix source directories. See for a find declaration example
2727
28-```
28+```text
2929 <lazarusdir>/components/codetools/examples/finddeclaration.lpi
3030```
3131
3232Because the FPC sources contain multiple versions of some units, and the FPC sources change often, the codetools do not use a fixed table of paths, but rather scan the whole FPC directory structure on first use, applying a set of rules specifying what is the correct source for the current TargetOS and TargetCPU. This scan may take a while depending on your disk speed. All examples save the result in **codetools.config**, so that the next time Lazarus is started this possibly lengthy scan is skipped.
3333
3434Whenever the FPC sources are changed or a unit is renamed, just delete the **codetools.config** file. The Lazarus IDE has its own config file and does a rescan whenever the compiler executable changes (or when the user forces a 'Tools \> Rescan FPC source directory').
3535
3636## Defining search paths and macros
3737
3838Important: Codetools assumes that you have multiple directories with different compiler settings, e.g. the FPC sources have different search paths than your sources. You can have FPC, Delphi and pas2js directories - all at the same time.
3939
4040The codetools uses "define templates" to generate search paths and macros. Define templates are trees of rules.
4141
4242### Example: Expand IncPath for a directory and/or its sub directories
4343
4444The following demo demonstrate various ways to expand the IncPath for a directory and/or its sub directories:
4545
4646``` pascal
4747program SetIncludePath;
4848
4949{$mode objfpc}{$H+}
5050
5151uses
5252 SysUtils, CodeToolManager, DefineTemplates, LazFileUtils;
5353
5454var
5555 Directory: String;
5656 DirectoryTemplate: TDefineTemplate;
5757 IncPathTemplate: TDefineTemplate;
5858 SubDirectory: String;
5959begin
6060 // create a template for the current directory
6161 // all child nodes of this template are only valid for this directory.
6262 Directory:=ExpandFileNameUTF8(GetCurrentDirUTF8);
6363 DirectoryTemplate:=TDefineTemplate.Create('Current working directory',
6464 'Example template for current working directory','',Directory,da_Directory);
6565
6666 // Example 1:
6767 // Add a sub template to extend the include search path #IncPath
6868 // only for the current directory, not its sub directories.
6969 // Note: 'myincludes' is a relative path, so it won't work for sub directories.
7070 IncPathTemplate:=TDefineTemplate.Create('Add myincludes to the IncPath',
7171 'Add myincludes to the include search path',
7272 IncludePathMacroName, // variable name: #IncPath
7373 IncludePathMacro+';myincludes' // new value: $(#IncPath);myincludes
7474 ,da_Define // da_Define extends the IncPath only for this directory
7575 );
7676 DirectoryTemplate.AddChild(IncPathTemplate);
7777
7878 // Example 2:
7979 // Add a sub template to extend the include search path #IncPath
8080 // with an absolute path for the current directory and all its sub directories.
8181 // Note: '/tmp/myincludes' is an absolute path, so works for sub directories.
8282 IncPathTemplate:=TDefineTemplate.Create('Add /tmp/myincludes to the IncPath',
8383 'Add /tmp/myincludes to the include search path',
8484 IncludePathMacroName, // variable name: #IncPath
8585 IncludePathMacro+';'+SetDirSeparators('/tmp/myincludes') // new value: $(#IncPath);/tmp/myincludes
8686 ,da_DefineRecurse // da_DefineRecuse extends the IncPath for this directory and all sub directories
8787 );
8888 DirectoryTemplate.AddChild(IncPathTemplate);
8989
9090 // Example 3:
9191 // Using the #DefinePath macro you can use the current directory to create absolute paths.
9292 IncPathTemplate:=TDefineTemplate.Create('Add ./myincludes to the IncPath',
9393 'Add ./myincludes to the include search path',
9494 IncludePathMacroName, // variable name: #IncPath
9595 IncludePathMacro+';'+DefinePathMacro+'/myincludes' // new value: $(#IncPath);$(#DefinePath)/myincludes
9696 ,da_DefineRecurse // da_DefineRecuse extends the IncPath for this directory and all sub directories
9797 );
9898 DirectoryTemplate.AddChild(IncPathTemplate);
9999
100100 // add the directory template to the tree
101101 CodeToolBoss.DefineTree.Add(DirectoryTemplate);
102102
103103 writeln('Directory="',Directory,'"',
104104 ' IncPath="',CodeToolBoss.GetIncludePathForDirectory(Directory),'"');
105105 SubDirectory:=AppendPathDelim(Directory)+'sub';
106106 writeln('SubDirectory="',SubDirectory,'"',
107107 ' IncPath="',CodeToolBoss.GetIncludePathForDirectory(SubDirectory),'"');
108108end.
109109```
110110
111111### Example: Expand global UnitPath
112112
113113Here is an example how to extend the global (all directories) unit search path and query the unit path of one directory. This might be useful for single minded command line tools.
114114
115115``` pascal
116116uses
117117 Classes, SysUtils, CodeToolManager, DefineTemplates, FileProcs;
118118
119119var
120120 Directory: String;
121121 UnitPathTemplate: TDefineTemplate;
122122begin
123123 // add a sub template to extend the include search path #UnitPath.
124124 UnitPathTemplate:=TDefineTemplate.Create(
125125 'Add myunits to the UnitPath', // optional: an arbitrary name of the template, useful for finding it later
126126 'Add /tmp/myunits to the unit search path', // optional: a description
127127 UnitPathMacroName, // variable name: #UnitPath
128128 UnitPathMacro+';/tmp/myunits' // new value: $(#UnitPath);/tmp/myunits
129129 ,da_DefineRecurse
130130 );
131131 // add the unit path template to the tree
132132 CodeToolBoss.DefineTree.Add(UnitPathTemplate);
133133
134134 Directory:=ExpandFileNameUTF8(GetCurrentDirUTF8);
135135 writeln('Directory="',Directory,'"',
136136 ' UnitPath="',CodeToolBoss.GetUnitPathForDirectory(Directory),'"');
137137end.
138138```
139139
140140## Define Template Macros
141141
142142Macros defined by define templates are used by the Pascal parser. The Codetools have functions to query the Free Pascal Compiler for its macros and convert them to define templates. This is done by CodeToolBoss.Init(Options); which you can find in many examples.
143143
144144Additionally there some predefined macros, which start with a hash (#). See unit definetemplates for the full list. Here are some important ones:
145145
146146``` pascal
147147 ExternalMacroStart = '#';
148148 // Standard macros
149149 DefinePathMacroName = ExternalMacroStart+'DefinePath'; // the current directory
150150 UnitPathMacroName = ExternalMacroStart+'UnitPath'; // unit search path separated by semicolon (same as given to FPC)
151151 IncludePathMacroName = ExternalMacroStart+'IncPath'; // include file search path separated by semicolon (same as given to FPC)
152152 SrcPathMacroName = ExternalMacroStart+'SrcPath'; // unit source search path separated by semicolon (not given to FPC)
153153```
154154
155155For example the **IncludePathMacroName** is **\#IncPath** and is used to define the include file search path. Keep in mind that macro values depend on the directory.
156156
157157Define templates values can contain macros. The macro has to be enclosed in dollar and brackets: **\$(macro)**.
158158
159159In the above example the value was *'\$('+IncludePathMacroName+');/tmp/myincludes'*, which is *'\$(#IncPath);/tmp/myincludes'*, which executes to the old include search path plus *';/tmp/myincludes'*, which means a path is appended. For readability you can use the constant IncludePathMacro instead of *'\$('+IncludePathMacroName+')'*:
160160
161161``` pascal
162162 DefinePathMacro = '$('+DefinePathMacroName+')'; // the path of the define template
163163 UnitPathMacro = '$('+UnitPathMacroName+')';
164164 IncludePathMacro = '$('+IncludePathMacroName+')';
165165 SrcPathMacro = '$('+SrcPathMacroName+')';
166166```
167167
168168## Define Template Actions
169169
170170A define template has a name, an optional description, a variable, a value and an action. The name and description are optional. The meaning of variable and value depends on the action. You can add define templates as children of define templates - creating a tree of define templates. You can see many examples for define templates in the Lazarus' dialog *Tools / CodeTools Defines Editor*.
171171
172172- da_Block - Used for grouping templates. When the block is executed all children are executed.
173173- da_Directory - Use this to define all rules of a directory. If this is a root directory set Value to the full expanded directory path (use function CleanAndExpandDirectory). If this is a sub directory (parent template is a directory) Value is the sub path. Can contain macros. Children are only executed if directory fits.
174174- da_Define - sets a macro (Variable) value (Value) of the current directory. The value can contain macros. Note that when a macro value is set to empty string *it is still defined, that means*{\$IFDEF variable}*will still result in*true''. Children are not executed.
175175- da_Undefine - clears a macro (Variable) of the current directory. *{\$IFDEF macro}* results in *false*. Children are not executed.
176176- da_DefineRecurse - as da_Define, but for current directory and sub directories.
177177- da_UndefineRecurse - as da_Undefine, but for current directory and sub directories.
178178- da_UndefineAll - clear all macro values.
179179- da_IfDef - if macro *Variable* is defined then execute children and skip following da_Else and da_ElseIf.
180180- da_IfNDef - if macro *Variable* is not defined then execute children and skip following da_Else and da_ElseIf.
181181- da_If,daElseIf - if the boolean expression *Value* executes to true then execute children and skip following da_Else and da_ElseIf. Value can contain macros.
182182- da_Else - When this template is executed then execute all children.
183183
184184## How to extend the include path of a directory
185185
186186See the example lazarus/components/codetools/examples/setincludepath.lpr. It demonstrates the use of relative paths, absolute paths, how to use the DefinePathMacro and the difference between da_Define and da_DefineRecurse.
187187
188188# Using the codetools in the IDE with the IDEIntf
189189
190190See \<lazarusdir\>/examples/idequickfix/quickfixexample.lpk package. It demonstrates:
191191
192192- How to write an IDE package. When you install this package it will register a Quick Fix item in the IDE.
193193- How to write a Quick Fix item for the compiler message: 'Parameter "Sender" not used'
194194- How to use the codetools to:
195195 - parse a unit
196196 - convert Filename, Line, and Column data into a codetools source position
197197 - find a codetools node at a cursor position
198198 - find a procedure node, and the begin..end node
199199 - create a nice insertion position for a statement at the beginning of the begin..end block
200200 - obtain line indentation information so that a new line will work in a sub-procedure as well
201201 - insert code using the codetools
202202
203203# Codetools rules for FPC sources
204204
205205When the codetools searches the source of a fpc ppu it uses a set of rules. You can write your own rules, but normally you will use the standard rules, which are defined in the include file components/codetools/fpcsrcrules.inc. You can test the rules with the command line utility: components/codetools/examples/testfpcsrcunitrules.lpi.
206206
207207## Usage of testfpcsrcunitrules
208208
209209 Usage: lazarus/components/codetools/examples/testfpcsrcunitrules -h
210210
211211 -c <compiler file name>, --compiler=<compiler file name>
212212 Default is to use environment variable PP.
213213 If this is not set, search for fpc
214214
215215 -T <target OS>, --targetos=<target OS>
216216 Default is to use environment variable FPCTARGET.
217217 If this is not set, use the default of the compiler.
218218
219219 -P <target CPU>, --targetcpu=<target CPU>
220220 Default is to use environment variable FPCTARGETCPU.
221221 If this is not set, use the default of the compiler.
222222
223223 -F <FPC source directory>, --fpcsrcdir=<FPC source directory>
224224 Default is to use environment variable FPCDIR.
225225 There is no default.
226226
227227 -u <unit name>, --checkunit=<unit name>
228228 Write a detailed report about this unit.
229229
230230## Example for testfpcsrcunitrules
231231
232232Open the testfpcsrcunitrules.lpi in the IDE and compile it. Then run the utility in a terminal/console:
233233
234-```
234+```text
235235./testfpcsrcunitrules -F ~/fpc/sources/2.5.1/fpc/
236236```
237237
238238This will tell you which compiler is used, which compiler executes, which config files were tested and parsed, and it warns you about duplicate units in the FPC search path and about duplicated unit source files. **Note:** This example caches results in the file *codetools.config*. You should delete *codetools.config* when you update the compiler or your fpc.cfg file.
239239
240240## Duplicate source files
241241
242242You find out that the codetools opens for target wince/arm the wrong source of the unit *mmsystem*. Run the tool with the -u parameter:
243243
244244./testfpcsrcunitrules -F ~/fpc/2.5.1/fpc/ -T wince -P arm -u mmsystem
245245
246246This will give you a detailed report where this unit was found and what score each source file got. For example:
247247
248248``` pascal
249249Unit report for mmsystem
250250 WARNING: mmsystem is not in PPU search path
251251GatherUnitsInFPCSources UnitName=mmsystem File=packages/winunits-base/src/mmsystem.pp Score=11
252252GatherUnitsInFPCSources UnitName=mmsystem File=packages/winceunits/src/mmsystem.pp Score=11 => duplicate
253253```
254254
255255This means there are two source files with the same score, so the codetools took the first. The last one in winceunits is for target wince and the first one is for win32 and win64.
256256
257257Now open the rules file fpcsrcrules.inc.
258258
259259Rules work like this:
260260
261261``` pascal
262262Score:=10;
263263Targets:='wince';
264264Add('packages/winceunits');
265265```
266266
267267The **Add** adds a rule for all files beginning with 'packages/winceunits' that adds a score of 10 to all these files. The **Targets** is a comma separated list of target operating systems and/or target processors. For example Targets='wince,linux,i386' means: apply this rules to TargetOS wince or linux and to all TargetCPU i386.
268268
269269# How the codetools parses sources differently from the compiler
270270
271271A compiler is optimized to parse code linearly and to load needed units and include files as soon as it parses a uses section or a directive. The codetools are optimized to parse only certain code sections. For example jumping from the method declaration to the method body only needs the unit and its include files. When a codetool searches a declaration it searches backwards. That means it starts searching in the local variables, then upwards from the implementation. When it finds a uses section it searches the identifiers in the interface section of the units. When the identifier is found it stops. The result and some intervening steps are cached. Because it often only needs to parse a few interface sections it finds an individual identifier very quickly.
272272
273273The codetools do not parse a source in a single step (as the compiler does) but in several steps, which depend on what the current codetool needs:
274274
275275- First a source file is loaded in a TCodeBuffer. The IDE uses this step to change the encoding to UTF8. The files are kept in memory and only reloaded if the modification date changes or if a file is manually reverted. There are several tools and functions which work directly on the buffer.
276276- The next step is to parse the unit (or include file). A unit must be parsed from the beginning, so the codetools tries to find the main file, the first file of a unit. It does that by looking for a directive in the first line like {%MainUnit ../lclintf.pp}. If that does not exist, it searches in the includelink cache. The IDE saves this cache to disk, so the IDE learns over time.
277277- After finding the main file a TCodeTool is created and a TLinkScanner parses the source. It handles compiler directives, such as include directives and conditional directives. The scanner can be given a range, so it might, for instance, parse only a unit's interface. The scanner creates the **clean source**. The clean source is put together from all include files, having been stripped of code in the *else* part of conditional directives, which is skipped. It also creates a list of **links** which map the clean source to the real source files. The clean source is now Pascal containing no *else* code. Note: there are also tools designed to scan a single source for all directives. These tools create a tree of directives.
278278- After creating the clean source a TCodeTool parses it and creates a tree of TCodeTreeNode. It can also be given a range. This parser skips a few parts, for example class members, begin..end blocks and parameter lists. Many tools don't need them. These sub nodes are created on demand. A TCodeTreeNode has a range StartPos..EndPos which are clean positions, that means positions in the clean source. There are only nodes for the important parts. Creating nodes for every detail would need more memory than the source itself and is seldom needed. There are plenty of functions to find out the details. For example if a function has the 'cdecl' calling convention.
279279- When searching for an identifier the search stores the base types it finds and creates caches for all identifiers in the interface section.
280280
281281Every level has its own caches, which need to be checked and updated before calling a function. Many high level functions accessible via the CodeToolBoss do that automatically. For others it is the responsibility of the caller.
282282
283283Example for:
284284
285285unit1.pas:
286286
287287``` pascal
288288unit Unit1;
289289{$I settings.inc}
290290interface
291291uses
292292 {$IFDEF Flag}
293293 unix,
294294 {$ELSE}
295295 windows,
296296 {$ENDIF}
297297 Classes;
298298```
299299
300300settings.inc:
301301
302302``` pascal
303303{%MainUnit unit1.pas}
304304{$DEFINE Flag}
305305```
306306
307307clean source:
308308
309309``` pascal
310310unit Unit1;
311311{$I settings.inc}{%MainUnit unit1.pas}
312312{$DEFINE Flag}
313313interface
314314uses
315315 {$IFDEF Flag}
316316 unix,
317317 {$ELSE}{$ENDIF}
318318 Classes;
319319```
320320
321321Hint: To easily parse a unit and build the nodes, use **CodeToolBoss.Explore**.
322322
323323# Tool, Node, LinkScanner
324324
325325## Tool
326326
327327A tool is a TCodeTool. For Pascal files every unit, program and package gets its own TCodeTool. These are automatically created by the CodetoolBoss when parsing sources. A tool has a Scanner (TLinkScanner) and a Root (TCodeTreeNode), which is the root node of the tree of Pascal nodes of the module (e.g. unit).
328328
329329## LinkScanner
330330
331331Every TCodeTool creates a TLinkScanner to scan the files and creates the CleanedSrc, which is the parsed unit source, include files included and code in skipped \$IF directives removed. When only the unit interface was parsed, the CleanedSrc may not be complete. TLinkScanner is not shared between TCodeTools. There is a 1:1 mapping between TLinkScanner and TCodeTool.
332332
333333## Node
334334
335335- A TCodeTreeNode is part of a tree of such nodes. The root node is stored in a TCodeTool.Root. Nodes are not shared between tool. Every node is associated with exactly one TCodeTool.
336336- When a function returns a Node, it always returns the associated Tool as well.
337337- Node.StartPos/EndPos are positions 1-based in the Scanner.CleanedSrc.
338338- To get from the cleaned postion to the file, line, column use Tool.CleanPosToCaret(Node.StartPos,xyp).
339339
340340# CleanPos and CursorPos
341341
342342There are several methods to define a position in the codetools.
343343
344344The codetools Absolute position is related to the source as a continuous string starting at character 1. For example a TCodeBuffer holds the file contents as a single string in its Source property. Caret or cursor positions are given as X,Y where X is the column number and Y the line number. Each value (X and Y) starts at 1. A TCodeBuffer provides the member functions **LineColToPosition** and **AbsoluteToLineCol'' to convert between (X,Y) values and the Absolute codetools position. When working with multiple source files (such as a unit which may contain several include files), the clean position relates to the absolute position in the stripped code**Src**. Here Src is a string whose clean positions start at 1. Cursor positions are specified as TCodeXYPosition (Code,X,Y). A TCodeTool provides the functions**CaretToCleanPos**and**CleanPosToCaret''' to convert between them.
345345
346346# Inserting, deleting, replacing - the TSourceChangeCache
347347
348348When making changes to the source code of a unit (or its include files) you should use the CodetoolBoss.SourceChangeCache instead of altering the source directly.
349349
350350- Simple usage: Connect, Replace, Replace, ... Apply. See below.
351351- You can use cleanpos as given by the node tree OR you can use direct position in a file.
352352- You can use Replace to insert and delete, which automatically calls events, so connected editors are notified of changes.
353353- It can automatically insert needed spaces, line breaks or empty lines in front or behind each Replace. For example you define that there should be an empty line in front. The SourceChangeCache checks what is inserted and how much space there is already and will insert needed space.
354354- It checks if the replaced/deleted span is writable.
355355- You can do multiple Replaces and you control when they are applied. Keep in mind that inserting code means that the parsed tree becomes invalid and needs rebuilding.
356356- Multiple replaces are checked for intersection. For example an insert in the middle of deleted code gives an error.
357357- Mutiple insertions at the same place are added FIFO - first at the top.
358358- You can combine several functions altering code to one bigger function. See below.
359359
360360## Usage
361361
362362The SourceChangeCache works on a unit, so you need to get a TCodeTool and scan a unit/include file. For example:
363363
364364``` pascal
365365 // Step 1: load the file and parse it
366366 Code:=CodeToolBoss.LoadFile(Filename,false,false);
367367 if Code=nil then
368368 raise Exception.Create('loading failed '+Filename);
369369 if not CodeToolBoss.Explore(Code,Tool,false) then
370370 ...;// parse error ...
371371
372372 // Step 2: connect the SourceChangeCache
373373 CodeToolBoss.SourceChangeCache.MainScanner:=Tool.Scanner;
374374
375375 // Step 3: use Replace to insert and/or delete code
376376 // The first two parameters are the needed spaces in front and behind the insertion
377377 // The FromPos,ToPos defines the deleted/replaced range in CleanPos positions.
378378 // The NewCode is the string of new code. Use '' for a delete.
379379 if not CodeToolBoss.SourceChangeCache.Replace(gtNone,gtNone,FromPos,ToPos,NewCode) then
380380 exit; // e.g. source read only or a former Replace has deleted the place
381381 ...do some more Replace...
382382
383383 // Step 4: Apply the changes
384384 if not CodeToolBoss.SourceChangeCache.Apply then
385385 exit; // apply was aborted
386386```
387387
388388## BeginUpdate/EndUpdate
389389
390390BeginUpdate/EndUpdate delays the Apply. This is useful when combining several code changing functions. For example:
391391
392392You want to scan the unit, add a unit to the interface uses section, and remove the unit from the implementation uses section. The two functions AddUnitToMainUsesSection and RemoveUnitFromUsesSection use Apply, altering the source, so the second function would rescan the unit a second time. But since the two functions are independent of each other (they change different parts of the source) you can combine them and do it with one scan:
393393
394394``` pascal
395395 // Step 1: parse unit and connect SourceChangeCache
396396 if not CodeToolBoss.Explore(Code,Tool,false) then
397397 ...;// parse error ...
398398 CodeToolBoss.SourceChangeCache.MainScanner:=Tool.Scanner;
399399
400400 // Step 2: delay Apply
401401 CodeToolBoss.SourceChangeCache.BeginUpdate;
402402
403403 // Step 3: add unit to interface section
404404 // AddUnitToMainUsesSection would apply and change the code
405405 // Because of the BeginUpdate the change is not yet done, but stored in the SourceChangeCache
406406 if not Tool.AddUnitToMainUsesSection('Classes','',CodeToolBoss.SourceChangeCache) then exit;
407407
408408 // Step 4: remove unit from implementation section
409409 // Without the BeginUpdate the RemoveUnitFromUsesSection would rescan the unit
410410 if Tool.FindImplementationUsesSection<>nil then
411411 if not Tool.RemoveUnitFromUsesSection(Tool.FindImplementationUsesSection,'Classes',CodeToolBoss.SourceChangeCache) then exit;
412412
413413 // Step 5: apply all changes
414414 if not CodeToolBoss.SourceChangeCache.EndUpdate then
415415 exit; // apply was aborted
416416```
417417
418418BeginUpdate/EndUpdate work with a counter, so if you call BeginUpdate twice you need to call EndUpdate twice. This means you can put the above example in a function and combine that with another function.
419419
420420## Saving changes to disk
421421
422422The above changes are made to the code buffers and the buffers are marked modified. To save the changes to disk, you have to call Save for each modified buffer.
423423
424424- The buffers that will be modified in the next Apply/EndUpdate are in SourceChangeCache.BuffersToModify and BuffersToModifyCount.
425425- The events SourceChangeCache.OnBeforeApplyChanges/OnAfterApplyChanges are used by the CodeToolBoss, which connects it to its own OnBeforeApplyChanges/OnAfterApplyChanges. The Lazarus IDE sets these events and automatically opens modified files in the source editor, so all changes go into the undo list of synedit.
426426
427427# Hints/Tips/Guide Lines
428428
429429- BuildTree checks the current state and will only parse if needed. If a former call has parsed the interface and you need the interface again, BuildTree will not do anything. If you need the full unit, only the implementation will be parsed. Nodes are only freed if some files have changed on disk or some settings have changed (initial macros). BuildTree does not check all files on every call. Instead it uses the directory cache of the codetools. So, if nothing has changed it will return very quickly. You should call it before any search operation.
430430- Do **not** call BuildTree **after** an operation. That is a waste of CPU.
431431- BuildTree raises an exception when there are missing include files or syntax errors. You should enclose your code into
432432
433433``` pascal
434434try
435435 Tool.BuildTree(lsrEnd);
436436 ... search ... replace
437437except
438438 on E: Exception do
439439 CodeToolBoss.HandleException(E);
440440end;
441441```
442442
443443- After calling SourceChangeCache.Replace (multiple times) the sources (TCodeBuffers) have not changed immediately. You must call SourceChangeCache.Apply to change the sources. This will not save the changes to file.
444444
445445# Test suite
446446
447447The codetools test suite can be found here:
448448
449-```
449+```text
450450lazarus/components/codetools/tests/runtestscodetools
451451```
452452
453453Compile it and run it:
454454
455-```
455+```text
456456cd lazarus/components/codetools/tests
457457./runtestscodetools
458458```
459459
460460# Links
461461
462462- [[Lazarus IDE Tools]] - A tutorial about the built-in tools of the standard IDE
463463- [[Cody]] - IDE package adding advanced code tools to the IDE
464464- [[Extending the IDE]] - How to write your own codetools plugins for the IDE.
465465
466466---
467467*From the Free Pascal wiki, page "Codetools", as it stood on 2020-12-31 after a change by Mattias2, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
468468Category: Components

Back to history