Sign in Join
Wiki copytemporary

Extending the IDE/es: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
1+## Contents
2+
3+ * 1 Extendiendo el IDE
4+ * 1.1 Visión general
5+ * 1.2 Paquetes y Dependencias MakeFile
6+ * 2 Elementos del Menú
7+ * 2.1 Añadiendo un elemento al menú
8+ * 3 Atajos (Shortcuts)
9+ * 4 Config files
10+ * 4.1 Cargar/Salvar configuraciones
11+ * 5 Components
12+ * 5.1 Extending existing components
13+ * 5.2 Writing components
14+ * 5.2.1 Giving a new component an icon for the component palette
15+ * 5.2.2 Hiding a component in the component palette
16+ * 5.3 Writing component editors
17+ * 5.4 Writing property editors
18+ * 5.4.1 Hiding a property in the Object Inspector
19+ * 6 Forms
20+ * 7 Designer
21+ * 7.1 Writing a designer mediator
22+ * 7.2 Create a new unique component name
23+ * 7.3 Select a component in the designer/object inspector
24+ * 7.4 Get unit, designer, form of a file
25+ * 7.5 Save unit, designer form
26+ * 8 Event handlers
27+ * 8.1 Designer events
28+ * 8.1.1 Examples for designer events
29+ * 8.1.1.1 Example: When dropping a new component move control to a child
30+ * 8.1.2 Disabling the designer mouse handler
31+ * 8.2 Getting notified when a designer form is modified
32+ * 8.3 Project events
33+ * 8.4 Other IDE events
34+ * 9 Project
35+ * 9.1 Current Project
36+ * 9.2 All units of current project
37+ * 9.2.1 All units of the project inspector
38+ * 9.2.2 All used units of project
39+ * 9.3 The .lpr, .lpi and .lps file of a project
40+ * 9.4 The executable / target file name of a project
41+ * 9.5 Add your own project type
42+ * 9.6 Add your own file type
43+ * 9.6.1 Add a new file type
44+ * 9.6.2 Add a new form type
45+ * 10 Packages
46+ * 10.1 Search in all packages
47+ * 10.2 Search a package with a name
48+ * 10.3 Obtener el nombre de fichero .lpk de un paquete instalado
49+ * 10.4 Instalar paquetes
50+ * 10.5 Abrir un fichero de paquete (lpk)
51+ * 10.6 Find the package(s) of a unit
52+ * 11 Ventanas
53+ * 11.1 Añadiendo una nueva ventana de acoplado en el IDE
54+ * 11.1.1 Como registrar una ventana acoplable del IDE
55+ * 11.1.2 Showing an IDE window
56+ * 11.1.3 Notes about IDEWindowCreators and SimpleLayoutStorage
57+ * 12 CodeTools
58+ * 12.1 Adding a resource directive to a file
59+ * 12.2 Getting the search paths for units and include files
60+ * 13 Source Editor
61+ * 13.1 Active source editor
62+ * 14 SynEdit
63+ * 14.1 Getting the settings for a TSynEdit
64+ * 14.2 Getting the settings for a SynEdit highlighter
65+ * 15 Help
66+ * 15.1 Adding help for sources
67+ * 15.2 Adding lines to the messages window
68+ * 16 Miscellaneous
69+ * 16.1 Adding a macro
70+ * 16.2 Depurando el IDE
71+ * 16.3 See also
72+
173# Extendiendo el IDE
274
375## Visión general
476
5-El IDE de Lazarus soporta varios tipos de plugins:
77+El IDE de Lazarus soporta varios tipos de plugins:
678
7-Componentes
8-Estos son los elementos que se encuentrar en la Paleta de Componentes. Por ejemplo, TButton (que se encuentra en la solapa Standard) que se utiliza para crear Buttons.
79+Componentes
80+ Estos son los elementos que se encuentrar en la Paleta de Componentes. Por ejemplo, TButton (que se encuentra en la solapa Standard) que se utiliza para crear Buttons.
981
10-Component Editors
11-Cuando haces doble click sobre un componente en el Diseñador, se invoka un editor de componente. El editor de componente puede además añadir un elemento extra al menú emergente (accedido cuando haces click en el pulsador derecho en un componente dentro del Diseñador).
82+Component Editors
83+ Cuando haces doble click sobre un componente en el Diseñador, se invoka un editor de componente. El editor de componente puede además añadir un elemento extra al menú emergente (accedido cuando haces click en el pulsador derecho en un componente dentro del Diseñador).
1284
13-Property Editors
14-Cada fila en la sección de la rejilla (grid) del Inspector de Objetos utiliza un editor de propiedades que permite establecer o alterar el valor de su propiedad.
85+Property Editors
86+ Cada fila en la sección de la rejilla (grid) del Inspector de Objetos utiliza un editor de propiedades que permite establecer o alterar el valor de su propiedad.
1587
16-Experts
17-Experts abarca todos los demás tipos de plugin. Pueden registrar nuevos elementos de menú, registrar atajos (short cuts), o extender otras características del IDE.
88+Experts
89+ Experts abarca todos los demás tipos de plugin. Pueden registrar nuevos elementos de menú, registrar atajos (short cuts), o extender otras características del IDE.
1890
19-Hay dos maneras posibles de añadir tus propios plugins al IDE de Lazarus:
91+Hay dos maneras posibles de añadir tus propios plugins al IDE de Lazarus:
2092
21-1. Escribir un paquete, instalarlo y registrar tu plugin(s) en el procedimiento 'Register' procedure de una unit.
22-2. Extender el cógigo de Lazarus, y enviar tu svn diff a la lista de correo de Lazarus.
93+ 1. Escribir un paquete, instalarlo y registrar tu plugin(s) en el procedimiento 'Register' procedure de una unit.
94+ 2. Extender el cógigo de Lazarus, y enviar tu svn diff a la lista de correo de Lazarus.
2395
2496## Paquetes y Dependencias MakeFile
2597
26-Los siguientes pasos son necesarios para añadir nuevas dependencias de paquete.
98+Los siguientes pasos son necesarios para añadir nuevas dependencias de paquete.
2799
28-- Crear/Actualizar el MakeFile para el paquete vía Editor de Paquete / Más ... / Crear Makefile.
29-- Corregir todas las dependencias. Ver tools/updatemakefiles.lpi
100+ * Crear/Actualizar el MakeFile para el paquete vía Editor de Paquete / Más ... / Crear Makefile.
101+ * Corregir todas las dependencias. Ver tools/updatemakefiles.lpi
30102
31103# Elementos del Menú
32104
33-Puedes añadir nuevos elementos al menú, ocultar o mover los existentes y añadir sub menús y secciones. Puedes registrar TMainMenu/TPopupMenu para tus propios formularios de forma que otros paquetes puedan extender más tu formulario. La unidad **MenuIntf** del paquete IDEIntf contiene todos todos los registros para menús y algunos elementos menú estandar del propio IDE.
105+Puedes añadir nuevos elementos al menú, ocultar o mover los existentes y añadir sub menús y secciones. Puedes registrar TMainMenu/TPopupMenu para tus propios formularios de forma que otros paquetes puedan extender más tu formulario. La unidad **MenuIntf** del paquete IDEIntf contiene todos todos los registros para menús y algunos elementos menú estandar del propio IDE.
34106
35107## Añadiendo un elemento al menú
36108
37-Un simple elemento de menú tal como 'View Object Inspector' se llama **TIDEMenuCommand**. Puedes crear uno con **RegisterIDEMenuCommand**, que tiene dos fomas con un montón de parámetros:
38-
39-``` pascal
40-
109+Un simple elemento de menú tal como 'View Object Inspector' se llama **TIDEMenuCommand**. Puedes crear uno con **RegisterIDEMenuCommand** , que tiene dos fomas con un montón de parámetros:
110+```
41111function RegisterIDEMenuCommand(Parent: TIDEMenuSection;
42- const Name, Caption: string;
43- const OnClickMethod: TNotifyEvent = nil;
44- const OnClickProc: TNotifyProcedure = nil;
45- const Command: TIDECommand = nil;
46- const ResourceName: String = ''
47- ): TIDEMenuCommand; overload;
48-function RegisterIDEMenuCommand(const Path, Name, Caption: string;
49- const OnClickMethod: TNotifyEvent = nil;
50- const OnClickProc: TNotifyProcedure = nil;
51- const Command: TIDECommand = nil;
52- const ResourceName: String = ''
53- ): TIDEMenuCommand; overload;
112+ const Name, Caption: string;
113+ const OnClickMethod: TNotifyEvent = nil;
114+ const OnClickProc: TNotifyProcedure = nil;
115+ const Command: TIDECommand = nil;
116+ const ResourceName: String = ''
117+ ): TIDEMenuCommand; overload;
118+ function RegisterIDEMenuCommand(const Path, Name, Caption: string;
119+ const OnClickMethod: TNotifyEvent = nil;
120+ const OnClickProc: TNotifyProcedure = nil;
121+ const Command: TIDECommand = nil;
122+ const ResourceName: String = ''
123+ ): TIDEMenuCommand; overload;
54124```
55125
56-La diferencia entre los dos consiste solamente en como se especifica la sección padre del menú. Puedes dar la sección del menú directamente o bien indirectamente a través de su trayecto. Algunas secciones estandar las puedes encontrar en la unidad *MenuIntf* Por ejemplo, la sección **mnuTools**, la cual es el menú *Tools* de la barra principal del IDE. Contiene una secciónon **itmSecondaryTools**, que es la sección recomendada para utilidades de terceros.
57-
58-Lo siguiente registra un nuevo mandato de menú con el nombre 'MyTool', el caption 'Arranca mi utilidad' y cuando es clickeada ejecuta el procedimiento *StartMyTool*:
126+La diferencia entre los dos consiste solamente en como se especifica la sección padre del menú. Puedes dar la sección del menú directamente o bien indirectamente a través de su trayecto. Algunas secciones estandar las puedes encontrar en la unidad _MenuIntf_ Por ejemplo, la sección **mnuTools** , la cual es el menú _Tools_ de la barra principal del IDE. Contiene una secciónon **itmSecondaryTools** , que es la sección recomendada para utilidades de terceros.
59127
60-``` pascal
128+Lo siguiente registra un nuevo mandato de menú con el nombre 'MyTool', el caption 'Arranca mi utilidad' y cuando es clickeada ejecuta el procedimiento _StartMyTool_ :
129+```
61130procedure StartMyTool;
62-begin
63- ...ejecutada cuando el elemento del menú es clickeado...
64-end;
65-
66-procedure Register;
67-begin
68- RegisterIDEMenuCommand(itmSecondaryTools, 'MyTool','Aranca mi utilidad',nil,@StartMyTool);
69-end;
131+ begin
132+ ...ejecutada cuando el elemento del menú es clickeado...
133+ end;
134+
135+ procedure Register;
136+ begin
137+ RegisterIDEMenuCommand(itmSecondaryTools, 'MyTool','Aranca mi utilidad',nil,@StartMyTool);
138+ end;
70139```
71140
72-If you want to call a method instead of a procedure use the **OnClickMethod** parameter.
73-
74-Este elemento de menú no tiene un atajo. En caso de necesitar uno debes crear un **TIDECommand** y pasarlo en el parámetro **Command**. Por ejemplo:
141+If you want to call a method instead of a procedure use the **OnClickMethod** parameter.
75142
76-``` pascal
143+Este elemento de menú no tiene un atajo. En caso de necesitar uno debes crear un **TIDECommand** y pasarlo en el parámetro **Command**. Por ejemplo:
144+```
77145uses ... IDECommands, MenuIntf;
78-...
79-var
80- Key: TIDEShortCut;
81- Cat: TIDECommandCategory;
82- CmdMyTool: TIDECommand;
83-begin
84- // register IDE shortcut and menu item
85- Key := IDEShortCut(VK_UNKNOWN,[],VK_UNKNOWN,[]);
86- Cat:=IDECommandList.FindCategoryByName(CommandCategoryToolMenuName);
87- CmdMyTool := RegisterIDECommand(Cat,'Start my tool', 'Starts my tool to do some stuff', Key, nil, @StartMyTool);
88- RegisterIDEMenuCommand(itmSecondaryTools, 'MyTool', 'Start my tool', nil, nil, CmdMyTool);
89-end;
146+ ...
147+ var
148+ Key: TIDEShortCut;
149+ Cat: TIDECommandCategory;
150+ CmdMyTool: TIDECommand;
151+ begin
152+ // register IDE shortcut and menu item
153+ Key := IDEShortCut(VK_UNKNOWN,[],VK_UNKNOWN,[]);
154+ Cat:=IDECommandList.FindCategoryByName(CommandCategoryToolMenuName);
155+ CmdMyTool := RegisterIDECommand(Cat,'Start my tool', 'Starts my tool to do some stuff', Key, nil, @StartMyTool);
156+ RegisterIDEMenuCommand(itmSecondaryTools, 'MyTool', 'Start my tool', nil, nil, CmdMyTool);
157+ end;
90158```
91159
92160# Atajos (Shortcuts)
93161
94-Todos los atajos (teclas que invocan alguna acción) se encuentran registradas en el IDECommandList. Este es un ejemplo sobre como encontrar todos los mandatos que reaccionan a la pulsación de Ctrl-D o la combinación de teclas pulsadas que comiencen por Ctrl-D:
95-
96-``` pascal
162+Todos los atajos (teclas que invocan alguna acción) se encuentran registradas en el IDECommandList. Este es un ejemplo sobre como encontrar todos los mandatos que reaccionan a la pulsación de Ctrl-D o la combinación de teclas pulsadas que comiencen por Ctrl-D:
163+```
97164uses
98- Classes, SysUtils, LCLProc, IDECommands;
99-
100-procedure ListCtrlD;
101-// Lista todos los idecommands con el atajo Ctrl-D
102-var
103- i: integer;
104- Cmd: TIDECommand;
105- Commands: TFPList;
106-begin
107- Commands:=IDECommandList.FindCommandsByShortCut(IDEShortCut(VK_D,[],VK_UNKNOWN,[])); // VK = Virtual Key
108- try
109- for i:=0 to Commands.Count-1 do begin
110- Cmd:=TIDECommand(Commands[i]);
111- writeln('Cmd: ',Cmd.Name,
112- ' A=',dbgs(Cmd.ShortcutA.Shift1),'-',Cmd.ShortcutA.Key1,
113- ',',dbgs(Cmd.ShortcutA.Shift2),'-',Cmd.ShortcutA.Key2,
114- ' B=',dbgs(Cmd.ShortcutB.Shift1),'-',Cmd.ShortcutB.Key1,
115- ',',dbgs(Cmd.ShortcutB.Shift2),'-',Cmd.ShortcutB.Key2
116- );
165+ Classes, SysUtils, LCLProc, IDECommands;
166+
167+ procedure ListCtrlD;
168+ // Lista todos los idecommands con el atajo Ctrl-D
169+ var
170+ i: integer;
171+ Cmd: TIDECommand;
172+ Commands: TFPList;
173+ begin
174+ Commands:=IDECommandList.FindCommandsByShortCut(IDEShortCut(VK_D,[],VK_UNKNOWN,[])); // VK = Virtual Key
175+ try
176+ for i:=0 to Commands.Count-1 do begin
177+ Cmd:=TIDECommand(Commands[i]);
178+ writeln('Cmd: ',Cmd.Name,
179+ ' A=',dbgs(Cmd.ShortcutA.Shift1),'-',Cmd.ShortcutA.Key1,
180+ ',',dbgs(Cmd.ShortcutA.Shift2),'-',Cmd.ShortcutA.Key2,
181+ ' B=',dbgs(Cmd.ShortcutB.Shift1),'-',Cmd.ShortcutB.Key1,
182+ ',',dbgs(Cmd.ShortcutB.Shift2),'-',Cmd.ShortcutB.Key2
183+ );
184+ end;
185+ finally
186+ Commands.Free;
187+ end;
117188 end;
118- finally
119- Commands.Free;
120- end;
121-end;
122189```
123190
124191# Config files
125192
126193## Cargar/Salvar configuraciones
127194
128-Todos los ficheros de configuración del IDE se encuentran almacenados en un directorio como ficheros xml. Los paquetes también también pueden añadir sus propios ficheros en dicho directorio. El [[pcp|primary config path]] se puede leer con:
195+Todos los ficheros de configuración del IDE se encuentran almacenados en un directorio como ficheros xml. Los paquetes también también pueden añadir sus propios ficheros en dicho directorio. El [[pcp|primary config path]] se puede leer con:
129196
130-``` pascal
197+
198+
199+```
131200uses LazIDEIntf;
132-...
133- Directory := LazarusIDE.GetPrimaryConfigPath;
201+ ...
202+ Directory := LazarusIDE.GetPrimaryConfigPath;
134203```
135204
136-Los paquetes pueden crear su propios ficheros xml con:
137-
138-``` pascal
139-uses
140- ..., LCLProc, BaseIDEIntf, LazConfigStorage;
141-
142-const
143- Version = 1;
144-var
145- Config: TConfigStorage;
146- SomeValue: String;
147- SomeInteger: Integer;
148- SomeBoolean: Boolean;
149- FileVersion: LongInt;
150-begin
151- SomeValue:='Default';
152- SomeInteger:=3;
153- SomeBoolean:=true;
154-
155- // Salva configuraciones.
156- try
157- Config:=GetIDEConfigStorage('mysettings.xml',false);
158- try
159- // Almacena el número de versión de forma que las extensiones futuras puedan manejar ficheros de configuración antiguos.
160- Config.SetDeleteValue('Path/To/The/Version',Version,0);
161- // Almacena la variable de cadena "SomeValue".
162- // Si SomeValue tiene el valor por defecto entonces la entrada no se almacena,
163- // de forma que únicamente se almacena las diferencias al valor por defecto.
164- // Así el xml se mantiene pequeño y su valor por defecto puede cambiar en el futuro.
165- Config.SetDeleteValue('Path/To/Some/Value',SomeValue,'Default');
166- Config.SetDeleteValue('Path/To/Some/Integer',SomeInteger,3);
167- Config.SetDeleteValue('Path/To/Some/Boolean',SomeBoolean,true);
168- // there are more overloads for SetDeleteValue, find out with Ctrl+Space
169- finally
170- Config.Free;
171- end;
205+Los paquetes pueden crear su propios ficheros xml con:
172206
173- except
174- on E: Exception do begin
175- DebugLn(['Saving mysettings.xml failed: ',E.Message]);
176- end;
177- end;
207+
178208
179- // load settings
180- try
181- Config:=GetIDEConfigStorage('mysettings.xml',true);
182- try
183- // read the version of the config
184- FileVersion:=Config.GetValue('Path/To/The/Version',0);
185- // read a string variable "SomeValue". If the entry does not exist, use
186- // the Default
187- SomeValue:=Config.GetValue('Path/To/Some/Value','Default');
188- SomeInteger:=Config.GetValue('Path/To/Some/Integer',3);
189- SomeBoolean:=Config.GetValue('Path/To/Some/Boolean',true);
190- finally
191- Config.Free;
192- end;
193- except
194- on E: Exception do begin
195- DebugLn(['Loading mysettings.xml failed: ',E.Message]);
209+```
210+uses
211+ ..., LCLProc, BaseIDEIntf, LazConfigStorage;
212+
213+ const
214+ Version = 1;
215+ var
216+ Config: TConfigStorage;
217+ SomeValue: String;
218+ SomeInteger: Integer;
219+ SomeBoolean: Boolean;
220+ FileVersion: LongInt;
221+ begin
222+ SomeValue:='Default';
223+ SomeInteger:=3;
224+ SomeBoolean:=true;
225+
226+ // Salva configuraciones.
227+ try
228+ Config:=GetIDEConfigStorage('mysettings.xml',false);
229+ try
230+ // Almacena el número de versión de forma que las extensiones futuras puedan manejar ficheros de configuración antiguos.
231+ Config.SetDeleteValue('Path/To/The/Version',Version,0);
232+ // Almacena la variable de cadena "SomeValue".
233+ // Si SomeValue tiene el valor por defecto entonces la entrada no se almacena,
234+ // de forma que únicamente se almacena las diferencias al valor por defecto.
235+ // Así el xml se mantiene pequeño y su valor por defecto puede cambiar en el futuro.
236+ Config.SetDeleteValue('Path/To/Some/Value',SomeValue,'Default');
237+ Config.SetDeleteValue('Path/To/Some/Integer',SomeInteger,3);
238+ Config.SetDeleteValue('Path/To/Some/Boolean',SomeBoolean,true);
239+ // there are more overloads for SetDeleteValue, find out with Ctrl+Space
240+ finally
241+ Config.Free;
242+ end;
243+
244+ except
245+ on E: Exception do begin
246+ DebugLn(['Saving mysettings.xml failed: ',E.Message]);
247+ end;
248+ end;
249+
250+ // load settings
251+ try
252+ Config:=GetIDEConfigStorage('mysettings.xml',true);
253+ try
254+ // read the version of the config
255+ FileVersion:=Config.GetValue('Path/To/The/Version',0);
256+ // read a string variable "SomeValue". If the entry does not exist, use
257+ // the Default
258+ SomeValue:=Config.GetValue('Path/To/Some/Value','Default');
259+ SomeInteger:=Config.GetValue('Path/To/Some/Integer',3);
260+ SomeBoolean:=Config.GetValue('Path/To/Some/Boolean',true);
261+ finally
262+ Config.Free;
263+ end;
264+ except
265+ on E: Exception do begin
266+ DebugLn(['Loading mysettings.xml failed: ',E.Message]);
267+ end;
268+ end;
196269 end;
197- end;
198-end;
199270```
200271
201-Notes:
272+Notes:
202273
203-- Every IDE plugin should use its own config file. Especially you must not use the standard IDE option files like [[editoroptions.xml]] or [[environmentoptions.xml]].
204-- GetIDEConfigStorage when loading checks if the file exists and if not it will copy the template from the secondary config directory.
205-- Since 0.9.31 you can use this function to load a file outside the primary config directory.
274+ * Every IDE plugin should use its own config file. Especially you must not use the standard IDE option files like [editoroptions.xml](</index.php?title=editoroptions.xml&action=edit&redlink=1> "editoroptions.xml \(page does not exist\)") or [environmentoptions.xml](</index.php?title=environmentoptions.xml&action=edit&redlink=1> "environmentoptions.xml \(page does not exist\)").
275+ * GetIDEConfigStorage when loading checks if the file exists and if not it will copy the template from the secondary config directory.
276+ * Since 0.9.31 you can use this function to load a file outside the primary config directory.
206277
207278# Components
208279
209280## Extending existing components
210281
211-Source: [1](http://lazarus.freepascal.org/index.php/topic,17733.msg98425.html#msg98425) It is straightforward to customise existing LCL components, e.g. if you want to add properties.
212-
213-Add the properties you need with appropriate setter and getter methods and storage fields.
282+Source: [[1]](<http://lazarus.freepascal.org/index.php/topic,17733.msg98425.html#msg98425>) It is straightforward to customise existing LCL components, e.g. if you want to add properties.
214283
215-Then instantiate them 'by hand', giving an owner component (to handle later destruction), and set Parent and possibly Top and Left and any other defaults your component needs when initialized.
284+Add the properties you need with appropriate setter and getter methods and storage fields.
216285
217-When you are satisfied that your customised component is debugged, add a RegisterComponent() call to stick it on the IDE Component Palette and save you having to do the setup code 'by hand' (look at any component's source to see how to do this).
286+Then instantiate them 'by hand', giving an owner component (to handle later destruction), and set Parent and possibly Top and Left and any other defaults your component needs when initialized.
218287
219-Here is a simple example:
288+When you are satisfied that your customised component is debugged, add a RegisterComponent() call to stick it on the IDE Component Palette and save you having to do the setup code 'by hand' (look at any component's source to see how to do this).
220289
221-``` pascal
290+Here is a simple example:
291+```
222292unit Unit1;
223-
224-{$mode objfpc}{$H+}
225-
226-interface
227-
228-uses
229- Classes, SysUtils, Forms, StdCtrls;
230-
231-type
232- TEdX = class(TEdit)
233- private
234- FNewIntProp: integer;
235- FNewStrProp: string;
236- procedure SetNewIntProp(AValue: integer);
237- procedure SetNewStrProp(AValue: string);
238- public
239- constructor Create(theComponent: TComponent); override;
240- property NewIntProp: integer read FNewIntProp write SetNewIntProp;
241- property NewStrProp: string read FNewStrProp write SetNewStrProp;
242- end;
243-
244- TForm1 = class(TForm)
245- procedure FormCreate(Sender: TObject);
246- private
247- edX: TEdX;
248- public
249- end;
250-
251-var
252- Form1: TForm1;
253-
254-implementation
255-
256-{ TForm1 }
257-
258-procedure TForm1.FormCreate(Sender: TObject);
259-begin
260- edX:= TEdX.Create(Self);
261- edX.Parent:= Self;
262- edX.Caption:= IntToStr(edX.NewIntProp);
263- Caption:= edX.NewStrProp;
264-end;
265-
266-{$R *.lfm}
267-
268-{ TEdX }
269-
270-procedure TEdX.SetNewIntProp(AValue: integer);
271-begin
272- if FNewIntProp=AValue then Exit;
273- FNewIntProp:=AValue;
274- // add custom code here
275-end;
276-
277-procedure TEdX.SetNewStrProp(AValue: string);
278-begin
279- if FNewStrProp=AValue then Exit;
280- FNewStrProp:=AValue;
281- // add custom code here
282-end;
283-
284-constructor TEdX.Create(theComponent: TComponent);
285-begin
286- inherited Create(theComponent);
287- FNewStrProp:= 'new string property value';
288- FNewIntProp:= 99;
289-end;
290-
291-end.
293+
294+ {$mode objfpc}{$H+}
295+
296+ interface
297+
298+ uses
299+ Classes, SysUtils, Forms, StdCtrls;
300+
301+ type
302+ TEdX = class(TEdit)
303+ private
304+ FNewIntProp: integer;
305+ FNewStrProp: string;
306+ procedure SetNewIntProp(AValue: integer);
307+ procedure SetNewStrProp(AValue: string);
308+ public
309+ constructor Create(theComponent: TComponent); override;
310+ property NewIntProp: integer read FNewIntProp write SetNewIntProp;
311+ property NewStrProp: string read FNewStrProp write SetNewStrProp;
312+ end;
313+
314+ TForm1 = class(TForm)
315+ procedure FormCreate(Sender: TObject);
316+ private
317+ edX: TEdX;
318+ public
319+ end;
320+
321+ var
322+ Form1: TForm1;
323+
324+ implementation
325+
326+ { TForm1 }
327+
328+ procedure TForm1.FormCreate(Sender: TObject);
329+ begin
330+ edX:= TEdX.Create(Self);
331+ edX.Parent:= Self;
332+ edX.Caption:= IntToStr(edX.NewIntProp);
333+ Caption:= edX.NewStrProp;
334+ end;
335+
336+ {$R *.lfm}
337+
338+ { TEdX }
339+
340+ procedure TEdX.SetNewIntProp(AValue: integer);
341+ begin
342+ if FNewIntProp=AValue then Exit;
343+ FNewIntProp:=AValue;
344+ // add custom code here
345+ end;
346+
347+ procedure TEdX.SetNewStrProp(AValue: string);
348+ begin
349+ if FNewStrProp=AValue then Exit;
350+ FNewStrProp:=AValue;
351+ // add custom code here
352+ end;
353+
354+ constructor TEdX.Create(theComponent: TComponent);
355+ begin
356+ inherited Create(theComponent);
357+ FNewStrProp:= 'new string property value';
358+ FNewIntProp:= 99;
359+ end;
360+
361+ end.
292362```
293363
294364## Writing components
295365
296-*Main article: [[How To Write Lazarus Component]]*
366+_Main article:[[How To Write Lazarus Component]]_
297367
298-You can create new components via the package editor.
368+You can create new components via the package editor.
299369
300-Create or open a package, click on **add**, click on **New Component**, fill in the items: Ancestor Type = TButton, New class name = TMyButton, palette page = Misc, Unit file name = mybutton.pas (this file will be created), unit name MyButton and click **ok**.
370+Create or open a package, click on **add** , click on **New Component** , fill in the items: Ancestor Type = TButton, New class name = TMyButton, palette page = Misc, Unit file name = mybutton.pas (this file will be created), unit name MyButton and click **ok**.
301371
302372### Giving a new component an icon for the component palette
303373
304-Create an image file of the format .bmp, .xpm or .png with the same name as the component class. For example *tmybutton.png* and save it in the package source directory. The image can be created by any graphic program (e.g. gimp) and should be no bigger than 24x24 pixel. Then convert the image to a resource file with the lazres tool, which can be found in the lazarus/tools directory:
305-
306-``` bash
374+Create an image file of the format .bmp, .xpm or .png with the same name as the component class. For example _tmybutton.png_ and save it in the package source directory. The image can be created by any graphic program (e.g. gimp) and should be no bigger than 24x24 pixel. Then convert the image to a resource file with the lazres tool, which can be found in the lazarus/tools directory:
375+```
307376~/lazarus/tools/lazres mybutton.lrs tmybutton.png
308-# note: Laz trunk/1.4+? uses .res resource files instead of .lrs files:
309-~/lazarus/tools/lazres mybutton.res tmybutton.png
377+ # note: Laz trunk/1.4+? uses .res resource files instead of .lrs files:
378+ ~/lazarus/tools/lazres mybutton.res tmybutton.png
310379```
311380
312-This creates an pascal include file, which is used in the initialization section of mybutton.pas:
313-
314-``` pascal
381+This creates an pascal include file, which is used in the initialization section of mybutton.pas:
382+```
315383initialization
316- {$I mybutton.lrs}
317- // or in newer Lazarus version - to docheck syntax
318- {$R mybutton.res}
384+ {$I mybutton.lrs}
385+ // or in newer Lazarus version - to docheck syntax
386+ {$R mybutton.res}
319387```
320388
321-Install the package.
389+Install the package.
322390
323391### Hiding a component in the component palette
324392
325-Package IDEIntf, unit componentreg:
326-
327-`IDEComponentPalette.FindComponent('TButton').Visible:=false;`
393+Package IDEIntf, unit componentreg:
394+```
395+IDEComponentPalette.FindComponent('TButton').Visible:=false;
396+```
328397
329398## Writing component editors
330399
331-A component editor handles things like double clicking on a component in a designer or adding menu items when right clicking on a component. Writing a component editor is easy. See the unit componenteditors.pas of the package IDEIntf for lots of examples. For instance to show an editor when double clicking see TCheckListBoxComponentEditor.
400+A component editor handles things like double clicking on a component in a designer or adding menu items when right clicking on a component. Writing a component editor is easy. See the unit componenteditors.pas of the package IDEIntf for lots of examples. For instance to show an editor when double clicking see TCheckListBoxComponentEditor.
332401
333402## Writing property editors
334403
335-Each type of property (integer, string, TFont, ...) in the Object Inspector needs a property editor. If your component has a property *Password* of type string, then you can define a property editor for your specific component class, with a property named *Password* of type string. The unit propedits.pp of the package IDEIntf contains many of the standard property editors used by the IDE itself. For example the TStringPropertyEditor is the default property editor for all strings, while TComponentNamePropertyEditor is more specific and handles only TComponent.Name. See the unit for plenty of examples.
404+Each type of property (integer, string, TFont, ...) in the Object Inspector needs a property editor. If your component has a property _Password_ of type string, then you can define a property editor for your specific component class, with a property named _Password_ of type string. The unit propedits.pp of the package IDEIntf contains many of the standard property editors used by the IDE itself. For example the TStringPropertyEditor is the default property editor for all strings, while TComponentNamePropertyEditor is more specific and handles only TComponent.Name. See the unit for plenty of examples.
336405
337406### Hiding a property in the Object Inspector
338407
339-There is a special property editor for hiding: <Code>
340-
341-` RegisterPropertyEditor(TypeInfo(TAnchorSide), TControl, 'AnchorSideLeft', THiddenPropertyEditor);`
342-
343-</Code>
344-
345-# Forms
346-
347-The IDE allows to easily create descendants of forms and frames. These forms can have new published components and new published methods. But you when you add new published properties, they are not accessible via the Object Inspector. They work only at runtime. The methods in the IDE are fake, they can not be executed. The IDE can create the components, because their classes are registered in the component palette. Your new properties only exist in your source code. The IDE can not fake them yet. That's why you have to register the new class. That means:
408+There is a special property editor for hiding: ` `
348409
349-- create a design time package (or extend an existing one)
350-- your form must be in a unit of this package
410+`
411+```
412+RegisterPropertyEditor(TypeInfo(TAnchorSide), TControl, 'AnchorSideLeft', THiddenPropertyEditor);
413+```
351414
352-``` pascal
353-...
354-interface
415+```
355416
356-uses FormEditingIntf, Forms;
417+``
357418
358-type
359- TYourForm = class(TForm)
360- private
361- FYourProperty: integer;
362- published
363- property YourProperty: integer read FYourProperty write FYourProperty;
364- end;
419+# Forms
365420
366-procedure Register;
421+The IDE allows to easily create descendants of forms and frames. These forms can have new published components and new published methods. But you when you add new published properties, they are not accessible via the Object Inspector. They work only at runtime. The methods in the IDE are fake, they can not be executed. The IDE can create the components, because their classes are registered in the component palette. Your new properties only exist in your source code. The IDE can not fake them yet. That's why you have to register the new class. That means:
367422
368-implementation
423+ * create a design time package (or extend an existing one)
424+ * your form must be in a unit of this package
369425
370-procedure Register;
371-begin
372- FormEditingHook.RegisterDesignerBaseClass(TYourForm);
373-end;
426+```
374427...
428+ interface
429+
430+ uses FormEditingIntf, Forms;
431+
432+ type
433+ TYourForm = class(TForm)
434+ private
435+ FYourProperty: integer;
436+ published
437+ property YourProperty: integer read FYourProperty write FYourProperty;
438+ end;
439+
440+ procedure Register;
441+
442+ implementation
443+
444+ procedure Register;
445+ begin
446+ FormEditingHook.RegisterDesignerBaseClass(TYourForm);
447+ end;
448+ ...
375449```
376450
377-- check the "Register" in the package editor for this unit.
378-- Install the package in the IDE
451+ * check the "Register" in the package editor for this unit.
452+ * Install the package in the IDE
379453
380454# Designer
381455
382456## Writing a designer mediator
383457
384-The standard designer allows to visually edit LCL controls, while all others are shown as icons(like TOpenDialog or TDataSource). To visually edit non LCL control, you need to create a **designer mediator**. This can be used to design webpages, UML diagrams or other widgetsets like [[fpGUI]]. There is a complete example in examples/designnonlcl/.
458+The standard designer allows to visually edit LCL controls, while all others are shown as icons(like TOpenDialog or TDataSource). To visually edit non LCL control, you need to create a **designer mediator**. This can be used to design webpages, UML diagrams or other widgetsets like [[fpGUI]]. There is a complete example in examples/designnonlcl/.
385459
386-- Install the example package examples/designnonlcl/notlcldesigner.lpk and restart the IDE. This will register the designer mediator for TMyWidget components and add the new components TMyButton, TMyGroupBox to the component palette.
387-- Open the the example project examples/designnonlcl/project/NonLCL1.lpi.
388-- Open the unit1.pas and show the designer form (F12). You should see the components as red rectangles, which can be selected, moved and resized like LCL controls.
460+ * Install the example package examples/designnonlcl/notlcldesigner.lpk and restart the IDE. This will register the designer mediator for TMyWidget components and add the new components TMyButton, TMyGroupBox to the component palette.
461+ * Open the the example project examples/designnonlcl/project/NonLCL1.lpi.
462+ * Open the unit1.pas and show the designer form (F12). You should see the components as red rectangles, which can be selected, moved and resized like LCL controls.
389463
390464## Create a new unique component name
391-
392-``` pascal
465+```
393466uses FormEditingIntf;
394-
395-...
396-
397-NewName:=FormEditingHook.CreateUniqueComponentName(AComponent);
398-
399-// Or if you need to create the name before creating the component:
400-
401-NewName:=FormEditingHook.CreateUniqueComponentName(ComponentClassName,OwnerComponent);
402-// ComponentClassName will be used as prefix, without a leading T.
403-// OwnerComponent is the new owner of the new component.
467+
468+ ...
469+
470+ NewName:=FormEditingHook.CreateUniqueComponentName(AComponent);
471+
472+ // Or if you need to create the name before creating the component:
473+
474+ NewName:=FormEditingHook.CreateUniqueComponentName(ComponentClassName,OwnerComponent);
475+ // ComponentClassName will be used as prefix, without a leading T.
476+ // OwnerComponent is the new owner of the new component.
404477```
405478
406479## Select a component in the designer/object inspector
407-
408-``` pascal
480+```
409481uses propedits;
410-..
411-GlobalDesignHook.SelectOnlyThis(AComponent);
482+ ..
483+ GlobalDesignHook.SelectOnlyThis(AComponent);
412484```
413485
414486## Get unit, designer, form of a file
415-
416-``` pascal
487+```
417488uses ProjectIntf, LazIDEIntf, ComponentEditors;
418-...
419-// open file
420-if LazarusIDE.DoOpenEditorFile(Filename,-1,-1,[ofAddToRecent])<>mrOk then exit;
421-// get file interface
422-aFile:=LazarusIDE.ActiveProject.FindFile(Filename,[]);
423-// get designer
424-aDesigner:=TComponentEditorDesigner(LazarusIDE.GetDesignerWithProjectFile(AFile,true));
425-if aDesigner=nil then
426- exit; // this unit has no resource (form, frame, datamodule, etc.)
427-// get form
428-aForm:=aDesigner.Form;
489+ ...
490+ // open file
491+ if LazarusIDE.DoOpenEditorFile(Filename,-1,-1,[ofAddToRecent])<>mrOk then exit;
492+ // get file interface
493+ aFile:=LazarusIDE.ActiveProject.FindFile(Filename,[]);
494+ // get designer
495+ aDesigner:=TComponentEditorDesigner(LazarusIDE.GetDesignerWithProjectFile(AFile,true));
496+ if aDesigner=nil then
497+ exit; // this unit has no resource (form, frame, datamodule, etc.)
498+ // get form
499+ aForm:=aDesigner.Form;
429500```
430501
431502## Save unit, designer form
432-
433-``` pascal
503+```
434504uses LazIDEIntf;
435-...
436-if LazarusIDE.DoSaveEditorFile(Filename,[])<>mrOk then exit;
505+ ...
506+ if LazarusIDE.DoSaveEditorFile(Filename,[])<>mrOk then exit;
437507```
438508
439509# Event handlers
440510
441-There are several events in the IDE, for which plugins can add their own handlers.
511+There are several events in the IDE, for which plugins can add their own handlers.
442512
443513## Designer events
444514
445-In propedits.pp there is a "GlobalDesignHook" object, which maintains several events for designing. Each event calls a list of handlers. The default handlers are added by the IDE. You can add your own handlers with the AddHandlerXXX and RemoveHandlerXXX methods. They will be called before the default handlers.
515+In propedits.pp there is a "GlobalDesignHook" object, which maintains several events for designing. Each event calls a list of handlers. The default handlers are added by the IDE. You can add your own handlers with the AddHandlerXXX and RemoveHandlerXXX methods. They will be called before the default handlers.
446516
447-Examples:
517+Examples:
448518
449-- Adding your handler (this is normally done in the constructor of your object):
519+ * Adding your handler (this is normally done in the constructor of your object):
450520
451-` GlobalDesignHook.AddHandlerPersistentAdded(@YourOnPersistentAdded);`
521+```
522+GlobalDesignHook.AddHandlerPersistentAdded(@YourOnPersistentAdded);
523+```
452524
453-- Removing your handler:
525+ * Removing your handler:
454526
455-` GlobalDesignHook.RemoveHandlerPersistentAdded(@YourOnPersistentAdded);`
527+```
528+GlobalDesignHook.RemoveHandlerPersistentAdded(@YourOnPersistentAdded);
529+```
456530
457-- You can remove all handlers at once. For example, it is a good idea to add this line in the destructor of your object:
531+ * You can remove all handlers at once. For example, it is a good idea to add this line in the destructor of your object:
458532
459-` GlobalDesignHook.RemoveAllHandlersForObject(Self);`
533+```
534+GlobalDesignHook.RemoveAllHandlersForObject(Self);
535+```
460536
461-The handlers of GlobalDesignHook:
537+The handlers of GlobalDesignHook:
462538
463-- Lookup root
464- - ChangeLookupRoot - Called when the "LookupRoot" changed. The "LookupRoot" is the owner object of the currently selected components. Normally this is a TForm.
465-- Methods
466- - CreateMethod
467- - GetMethodName
468- - GetMethods
469- - MethodExists
470- - RenameMethod
471- - ShowMethod
472- - MethodFromAncestor
473- - ChainCall
474-- Components
475- - GetComponent
476- - GetComponentName
477- - GetComponentNames
478- - GetRootClassName
479- - AddClicked - Called when the user selected a component class and clicked on the designer to add a new component. You can change the component class and the parent.
480- - ComponentRenamed - Called when a component was renamed
481-- TPersistent objects
482- - PersistentAdded - Called when a new TPersistent was added to the LookupRoot
483- - PersistentDeleting - Called before a TPersistent is freed.
484- - DeletePersistent - Called by the IDE to delete a TPersistent.
485- - GetSelectedPersistents - Called when getting the current selection of TPersistent.
486- - SetSelectedPersistents - Called when setting the current selection of TPersistent.
487- - GetObject
488- - GetObjectName
489- - GetObjectNames
490-- Modifing
491- - Modified
492- - Revert
493- - RefreshPropertyValues
494-- Selection
495- - SetSelection
496- - GetSelection
539+ * Lookup root
540+ * ChangeLookupRoot - Called when the "LookupRoot" changed. The "LookupRoot" is the owner object of the currently selected components. Normally this is a TForm.
541+ * Methods
542+ * CreateMethod
543+ * GetMethodName
544+ * GetMethods
545+ * MethodExists
546+ * RenameMethod
547+ * ShowMethod
548+ * MethodFromAncestor
549+ * ChainCall
550+ * Components
551+ * GetComponent
552+ * GetComponentName
553+ * GetComponentNames
554+ * GetRootClassName
555+ * AddClicked - Called when the user selected a component class and clicked on the designer to add a new component. You can change the component class and the parent.
556+ * ComponentRenamed - Called when a component was renamed
557+ * TPersistent objects
558+ * PersistentAdded - Called when a new TPersistent was added to the LookupRoot
559+ * PersistentDeleting - Called before a TPersistent is freed.
560+ * DeletePersistent - Called by the IDE to delete a TPersistent.
561+ * GetSelectedPersistents - Called when getting the current selection of TPersistent.
562+ * SetSelectedPersistents - Called when setting the current selection of TPersistent.
563+ * GetObject
564+ * GetObjectName
565+ * GetObjectNames
566+ * Modifing
567+ * Modified
568+ * Revert
569+ * RefreshPropertyValues
570+ * Selection
571+ * SetSelection
572+ * GetSelection
497573
498574### Examples for designer events
499575
500576#### Example: When dropping a new component move control to a child
501-
502-``` pascal
503-...
504-type
505- TYourDesignerExtension = class
506- private
507- function AddClicked(ADesigner: TIDesigner;
508- MouseDownComponent: TComponent; Button: TMouseButton;
509- Shift: TShiftState; X, Y: Integer;
510- var AComponentClass: TComponentClass;
511- var NewParent: TComponent): boolean of object;
512- public
513- constructor Create;
514- destructor Destroy; override;
515- end;
516-
577+```
517578...
518-constructor TYourDesignerExtension.Create;
519-begin
520- // register your handler
521- GlobalDesignHook.AddHandlerAddClicked(@AddClicked);
522-end;
523-
524-destructor TYourDesignerExtension.Destroy;
525-begin
526- // remove your handler:
527- GlobalDesignHook.RemoveHandlerAddClicked(@AddClicked);
528-end;
529-
530-function TYourDesignerExtension.AddClicked(ADesigner: TIDesigner;
531- MouseDownComponent: TComponent; Button: TMouseButton;
532- Shift: TShiftState; X, Y: Integer;
533- var AComponentClass: TComponentClass;
534- var NewParent: TComponent): boolean of object;
535-begin
536- // in this example TYourControl is a custom control with a ChildControl.
537- // Whenever the user drops a control on the TYourControl instead of adding
538- // the new control to the TYourControl, the new control is added as child
539- // of ChildControl.
540- // created
541- if MouseDownComponent is TYourControl then
542- NewParent:=TYourControl(MouseDownComponent).ChildControl;
543- Result:=true;
544-end;
579+ type
580+ TYourDesignerExtension = class
581+ private
582+ function AddClicked(ADesigner: TIDesigner;
583+ MouseDownComponent: TComponent; Button: TMouseButton;
584+ Shift: TShiftState; X, Y: Integer;
585+ var AComponentClass: TComponentClass;
586+ var NewParent: TComponent): boolean of object;
587+ public
588+ constructor Create;
589+ destructor Destroy; override;
590+ end;
591+
592+ ...
593+ constructor TYourDesignerExtension.Create;
594+ begin
595+ // register your handler
596+ GlobalDesignHook.AddHandlerAddClicked(@AddClicked);
597+ end;
598+
599+ destructor TYourDesignerExtension.Destroy;
600+ begin
601+ // remove your handler:
602+ GlobalDesignHook.RemoveHandlerAddClicked(@AddClicked);
603+ end;
604+
605+ function TYourDesignerExtension.AddClicked(ADesigner: TIDesigner;
606+ MouseDownComponent: TComponent; Button: TMouseButton;
607+ Shift: TShiftState; X, Y: Integer;
608+ var AComponentClass: TComponentClass;
609+ var NewParent: TComponent): boolean of object;
610+ begin
611+ // in this example TYourControl is a custom control with a ChildControl.
612+ // Whenever the user drops a control on the TYourControl instead of adding
613+ // the new control to the TYourControl, the new control is added as child
614+ // of ChildControl.
615+ // created
616+ if MouseDownComponent is TYourControl then
617+ NewParent:=TYourControl(MouseDownComponent).ChildControl;
618+ Result:=true;
619+ end;
545620```
546621
547622### Disabling the designer mouse handler
548623
549-Normally the designer catches all mouse events of a component. If your custom control should handle the mouse events handle you can either set the **csDesignInteractive** **ControlStyle** or you can fine control it via the message *CM_DESIGNHITTEST* in your control:
550-
551-``` pascal
624+Normally the designer catches all mouse events of a component. If your custom control should handle the mouse events handle you can either set the **csDesignInteractive** **ControlStyle** or you can fine control it via the message _CM_DESIGNHITTEST_ in your control:
625+```
552626type
553- TYourControl = class(TCustomControl)
554- protected
555- procedure CMDesignHitTest(var Message: TLMessage); message CM_DESIGNHITTEST;
556- end;
557-...
558-procedure TYourControl.CMDesignHitTest(var Message: TLMessage);
559-var
560- p: TSmallPoint;
561- aShiftState: TShiftState;
562-begin
563- aShiftState:=KeysToShiftState(PtrUInt(Message.WParam));
564- p:=TSmallPoint(longint(Message.LParam));
565- debugln(['TForm1.CMDesignHitTest ShiftState=',dbgs(aShiftState),' x=',p.x,' y=',p.y]);
566- if SkipDesignerMouseHandler then
567- Message.Result:=1; // now the designer calls the normal MouseUp, MouseMove and MouseDown methods.
568-end;
627+ TYourControl = class(TCustomControl)
628+ protected
629+ procedure CMDesignHitTest(var Message: TLMessage); message CM_DESIGNHITTEST;
630+ end;
631+ ...
632+ procedure TYourControl.CMDesignHitTest(var Message: TLMessage);
633+ var
634+ p: TSmallPoint;
635+ aShiftState: TShiftState;
636+ begin
637+ aShiftState:=KeysToShiftState(PtrUInt(Message.WParam));
638+ p:=TSmallPoint(longint(Message.LParam));
639+ debugln(['TForm1.CMDesignHitTest ShiftState=',dbgs(aShiftState),' x=',p.x,' y=',p.y]);
640+ if SkipDesignerMouseHandler then
641+ Message.Result:=1; // now the designer calls the normal MouseUp, MouseMove and MouseDown methods.
642+ end;
569643```
570644
571645## Getting notified when a designer form is modified
572646
573-Every designed LCL form has a Designer of type TIDesigner. The IDE creates designers of type TComponentEditorDesigner defined in the IDEIntf unit componenteditors. For example:
574-
575-``` pascal
647+Every designed LCL form has a Designer of type TIDesigner. The IDE creates designers of type TComponentEditorDesigner defined in the IDEIntf unit componenteditors. For example:
648+```
576649procedure TYourAddOn.OnDesignerModified(Sender: TObject);
577-var
578- IDEDesigner: TComponentEditorDesigner;
579-begin
580- IDEDesigner:=TComponentEditorDesigner(Sender);
581- ...
582-end;
583-
584-procedure TYourAddOn.ConnectDesignerForm(Form1: TCustomForm);
585-var
586- IDEDesigner: TComponentEditorDesigner;
587-begin
588- IDEDesigner:=TComponentEditorDesigner(Form1.Designer);
589- IDEDesigner.AddHandlerModified(@OnDesignerModified);
590-end;
650+ var
651+ IDEDesigner: TComponentEditorDesigner;
652+ begin
653+ IDEDesigner:=TComponentEditorDesigner(Sender);
654+ ...
655+ end;
656+
657+ procedure TYourAddOn.ConnectDesignerForm(Form1: TCustomForm);
658+ var
659+ IDEDesigner: TComponentEditorDesigner;
660+ begin
661+ IDEDesigner:=TComponentEditorDesigner(Form1.Designer);
662+ IDEDesigner.AddHandlerModified(@OnDesignerModified);
663+ end;
591664```
592665
593666## Project events
594667
595-These events are defined in unit LazIDEIntf.
668+These events are defined in unit LazIDEIntf.
596669
597-- **LazarusIDE.AddHandlerOnProjectClose**: called before a project is closed
598-- **LazarusIDE.AddHandlerOnProjectOpened**: called after the project was completely opened (for example all required packages were loaded, units were opened in the source editor)
599-- **LazarusIDE.AddHandlerOnSavingAll**: called before IDE saves everything
600-- **LazarusIDE.AddHandlerOnSavedAll**: called after IDE saved everything
601-- **LazarusIDE.AddHandlerOnProjectBuilding**: called before IDE builds the project
602-- **LazarusIDE.AddHandlerOnProjectDependenciesCompiling**: called before IDE compiles package dependencies of project
603-- **LazarusIDE.AddHandlerOnProjectDependenciesCompiled**: called after IDE compiled package dependencies of project
604-- **LazarusIDE.AddHandlerOnProjectBuildingFinished**: called after IDE built the project (successful or not) (since 1.5)
670+ * **LazarusIDE.AddHandlerOnProjectClose** : called before a project is closed
671+ * **LazarusIDE.AddHandlerOnProjectOpened** : called after the project was completely opened (for example all required packages were loaded, units were opened in the source editor)
672+ * **LazarusIDE.AddHandlerOnSavingAll** : called before IDE saves everything
673+ * **LazarusIDE.AddHandlerOnSavedAll** : called after IDE saved everything
674+ * **LazarusIDE.AddHandlerOnProjectBuilding** : called before IDE builds the project
675+ * **LazarusIDE.AddHandlerOnProjectDependenciesCompiling** : called before IDE compiles package dependencies of project
676+ * **LazarusIDE.AddHandlerOnProjectDependenciesCompiled** : called after IDE compiled package dependencies of project
677+ * **LazarusIDE.AddHandlerOnProjectBuildingFinished** : called after IDE built the project (successful or not) (since 1.5)
605678
606679## Other IDE events
607680
608-uses LazIDEIntf;
681+uses LazIDEIntf;
609682
610-Call these in the Register procedure of your package:
683+Call these in the Register procedure of your package:
611684
612-- **LazarusIDE.AddHandlerOnIDERestoreWindows**: called when IDE is restores its windows (before opening the first project)
613-- **LazarusIDE.AddHandlerOnIDEClose**: called when IDE is shutting down (after closequery, so no more interactivity)
614-- **LazarusIDE.AddHandlerOnQuickSyntaxCheck**: called when the menu item or the shortcut for Quick syntax check is executed
615-- **LazarusIDE.AddHandlerOnLazarusBuilding**: // called before IDE builds Lazarus IDE (since 1.5)
616-- **LazarusIDE.AddHandlerOnLazarusBuildingFinished**: // called after IDE builds Lazarus IDE (since 1.5)
617-- **LazarusIDE.AddHandlerGetFPCFrontEndParams**: // called when the IDE gets the parameters of the 'fpc' front end tool (since 1.5)
618-- **LazarusIDE.AddHandlerGetFPCFrontEndPath**: // called when the IDE gets the path of the 'fpc' front end tool (since 1.5)
619-- **LazarusIDE.AddHandlerOnUpdateIDEComponentPalette**: ?
620-- **LazarusIDE.AddHandlerOnUpdateComponentPageControl**: ?
621-- **LazarusIDE.AddHandlerOnShowDesignerFormOfSource**: // called after showing a designer form for code editor (AEditor can be nil!) (since 1.5)
622-- **LazarusIDE.AddHandlerOnShowSourceOfActiveDesignerForm**: // called after showing a code of designer form (since 1.5)
623-- **LazarusIDE.AddHandlerOnChangeToolStatus**: //called when IDEToolStatus has changed (e.g. itNone-\>itBuilder etc.) (since 1.5)
685+ * **LazarusIDE.AddHandlerOnIDERestoreWindows** : called when IDE is restores its windows (before opening the first project)
686+ * **LazarusIDE.AddHandlerOnIDEClose** : called when IDE is shutting down (after closequery, so no more interactivity)
687+ * **LazarusIDE.AddHandlerOnQuickSyntaxCheck** : called when the menu item or the shortcut for Quick syntax check is executed
688+ * **LazarusIDE.AddHandlerOnLazarusBuilding** : // called before IDE builds Lazarus IDE (since 1.5)
689+ * **LazarusIDE.AddHandlerOnLazarusBuildingFinished** : // called after IDE builds Lazarus IDE (since 1.5)
690+ * **LazarusIDE.AddHandlerGetFPCFrontEndParams** : // called when the IDE gets the parameters of the 'fpc' front end tool (since 1.5)
691+ * **LazarusIDE.AddHandlerGetFPCFrontEndPath** : // called when the IDE gets the path of the 'fpc' front end tool (since 1.5)
692+ * **LazarusIDE.AddHandlerOnUpdateIDEComponentPalette** : ?
693+ * **LazarusIDE.AddHandlerOnUpdateComponentPageControl** : ?
694+ * **LazarusIDE.AddHandlerOnShowDesignerFormOfSource** : // called after showing a designer form for code editor (AEditor can be nil!) (since 1.5)
695+ * **LazarusIDE.AddHandlerOnShowSourceOfActiveDesignerForm** : // called after showing a code of designer form (since 1.5)
696+ * **LazarusIDE.AddHandlerOnChangeToolStatus** : //called when IDEToolStatus has changed (e.g. itNone->itBuilder etc.) (since 1.5)
624697
625-Call these in the initialization section of one of your units:
698+Call these in the initialization section of one of your units:
626699
627-- **AddBootHandler**
628- - AddBootHandler(**libhTransferMacrosCreated**,@YourProc): called after IDEMacros were created (since 1.3)
629- - AddBootHandler(**libhEnvironmentOptionsLoaded**,@YourProc): called after environment options were loaded (since 1.3)
700+ * **AddBootHandler**
701+ * AddBootHandler(**libhTransferMacrosCreated** ,@YourProc): called after IDEMacros were created (since 1.3)
702+ * AddBootHandler(**libhEnvironmentOptionsLoaded** ,@YourProc): called after environment options were loaded (since 1.3)
630703
631704# Project
632705
633706## Current Project
634707
635-The current main project can be obtained by LazarusIDE.ActiveProject. (unit LazIDEIntf)
708+The current main project can be obtained by LazarusIDE.ActiveProject. (unit LazIDEIntf)
636709
637710## All units of current project
638711
639-Note that the term "units of project" is ambiguous.
712+Note that the term "units of project" is ambiguous.
640713
641-- The project inspector shows the list of the .lpi file. The project might not use all these units on all platforms and maybe the developer forgot to add all used units.
642-- Units from used packages are not project units.
714+ * The project inspector shows the list of the .lpi file. The project might not use all these units on all platforms and maybe the developer forgot to add all used units.
715+ * Units from used packages are not project units.
643716
644717### All units of the project inspector
645718
646-To iterate through all pascal units listed in the project inspector you can use for example:
647-
648-``` pascal
719+To iterate through all pascal units listed in the project inspector you can use for example:
720+```
649721uses
650- LCLProc, FileUtil, LazIDEIntf, ProjectIntf;
651-
652-procedure ListProjectUnits;
653-var
654- LazProject: TLazProject;
655- i: Integer;
656- LazFile: TLazProjectFile;
657-begin
658- LazProject:=LazarusIDE.ActiveProject;
659- if LazProject<>nil then
660- for i:=0 to LazProject.FileCount-1 do
722+ LCLProc, FileUtil, LazIDEIntf, ProjectIntf;
723+
724+ procedure ListProjectUnits;
725+ var
726+ LazProject: TLazProject;
727+ i: Integer;
728+ LazFile: TLazProjectFile;
661729 begin
662- LazFile:=LazProject.Files[i];
663- if LazFile.IsPartOfProject
664- and FilenameIsPascalUnit(LazFile.Filename)
665- then
666- debugln(LazFile.Filename);
730+ LazProject:=LazarusIDE.ActiveProject;
731+ if LazProject<>nil then
732+ for i:=0 to LazProject.FileCount-1 do
733+ begin
734+ LazFile:=LazProject.Files[i];
735+ if LazFile.IsPartOfProject
736+ and FilenameIsPascalUnit(LazFile.Filename)
737+ then
738+ debugln(LazFile.Filename);
739+ end;
667740 end;
668-end;
669741```
670742
671743### All used units of project
672744
673-To find all currently used units of a project/package you can use the following. Note that the IDE needs to parse all units, so it can take some time.
674-
675-``` pascal
745+To find all currently used units of a project/package you can use the following. Note that the IDE needs to parse all units, so it can take some time.
746+```
676747uses
677- LazLoggerBase, LazIDEIntf, ProjectIntf;
678-
679-procedure ListProjectUnits;
680-var
681- LazProject: TLazProject;
682- i: Integer;
683-begin
684- LazProject:=LazarusIDE.ActiveProject;
685- if LazProject<>nil then
686- begin
687- Units:=LazarusIDE.FindUnitsOfOwner(LazProject,[fuooListed,fuooUsed]); // add fuooPackages to include units from packages
688- try
689- for i:=0 to Units.Count-1 do
690- debugln('Filename=',Units[i]);
691- finally
692- Units.Free;
748+ LazLoggerBase, LazIDEIntf, ProjectIntf;
749+
750+ procedure ListProjectUnits;
751+ var
752+ LazProject: TLazProject;
753+ i: Integer;
754+ begin
755+ LazProject:=LazarusIDE.ActiveProject;
756+ if LazProject<>nil then
757+ begin
758+ Units:=LazarusIDE.FindUnitsOfOwner(LazProject,[fuooListed,fuooUsed]); // add fuooPackages to include units from packages
759+ try
760+ for i:=0 to Units.Count-1 do
761+ debugln('Filename=',Units[i]);
762+ finally
763+ Units.Free;
764+ end;
765+ end;
693766 end;
694- end;
695-end;
696767```
697768
698769## The .lpr, .lpi and .lps file of a project
699-
700-``` pascal
770+```
701771uses
702- LCLProc, FileUtil, ProjectIntf, LazIDEIntf;
703-var
704- LazProject: TLazProject;
705-begin
706- LazProject:=LazarusIDE.ActiveProject;
707- // every project has a .lpi file:
708- DebugLn(['Project'' lpi file: ',LazProject.ProjectInfoFile]);
709-
710- // if the project session information is stored in a separate .lps file:
711- if LazProject.SessionStorage<>pssNone then
712- DebugLn(['Project'' lps file: ',LazProject.ProjectSessionFile]);
713-
714- // If the project has a .lpr file it is the main source file:
715- if (LazProject.MainFile<>nil)
716- and (CompareFileExt(LazProject.MainFile.Filename,'lpr')=0) then
717- DebugLn(['Project has lpr file: ',LazProject.MainFile.Filename]);
718-end;
772+ LCLProc, FileUtil, ProjectIntf, LazIDEIntf;
773+ var
774+ LazProject: TLazProject;
775+ begin
776+ LazProject:=LazarusIDE.ActiveProject;
777+ // every project has a .lpi file:
778+ DebugLn(['Project'' lpi file: ',LazProject.ProjectInfoFile]);
779+
780+ // if the project session information is stored in a separate .lps file:
781+ if LazProject.SessionStorage<>pssNone then
782+ DebugLn(['Project'' lps file: ',LazProject.ProjectSessionFile]);
783+
784+ // If the project has a .lpr file it is the main source file:
785+ if (LazProject.MainFile<>nil)
786+ and (CompareFileExt(LazProject.MainFile.Filename,'lpr')=0) then
787+ DebugLn(['Project has lpr file: ',LazProject.MainFile.Filename]);
788+ end;
719789```
720790
721791## The executable / target file name of a project
722792
723-There is a macro \$(TargetFile), which can be used in paths and external tools. You can query the macro in code:
724-
725-``` pascal
793+There is a macro $(TargetFile), which can be used in paths and external tools. You can query the macro in code:
794+```
726795uses MacroIntf;
727-
728-function MyGetProjectTargetFile: string;
729-begin
730- Result:='$(TargetFile)';
731- if not IDEMacros.SubstituteMacros(Result) then
732- raise Exception.Create('unable to retrieve target file of project');
733-end;
796+
797+ function MyGetProjectTargetFile: string;
798+ begin
799+ Result:='$(TargetFile)';
800+ if not IDEMacros.SubstituteMacros(Result) then
801+ raise Exception.Create('unable to retrieve target file of project');
802+ end;
734803```
735804
736-See here for more macros: [[IDE Macros in paths and filenames]].
805+See here for more macros: [[IDE Macros in paths and filenames]].
737806
738807## Add your own project type
739808
740-You can add items to the 'New ...' dialog:
809+You can add items to the 'New ...' dialog:
741810
742-- See the unit ProjectIntf of the package IDEIntf.
743-- See the [[Project Templates]]
811+ * See the unit ProjectIntf of the package IDEIntf.
812+ * See the [[Project Templates]]
744813
814+
815+
745816## Add your own file type
746817
747-You can add items to the 'New ...' dialog:
818+You can add items to the 'New ...' dialog:
748819
749-- See the unit ProjectIntf of the package IDEIntf.
750-- Choose a base class TFileDescPascalUnit for normal units or TFileDescPascalUnitWithResource for a new form/datamodule.
820+ * See the unit ProjectIntf of the package IDEIntf.
821+ * Choose a base class TFileDescPascalUnit for normal units or TFileDescPascalUnitWithResource for a new form/datamodule.
751822
752823### Add a new file type
753-
754-``` pascal
824+```
755825uses ProjectIntf;
756-...
757- { TFileDescText }
758-
759- TFileDescMyText = class(TProjectFileDescriptor)
760- public
761- constructor Create; override;
762- function GetLocalizedName: string; override;
763- function GetLocalizedDescription: string; override;
764- end;
765-...
766-
767-procedure Register;
768-
769-implementation
770-
771-procedure Register;
772-begin
773- RegisterProjectFileDescriptor(TFileDescMyText.Create,FileDescGroupName);
774-end;
775-
776-{ TFileDescMyText }
777-
778-constructor TFileDescMyText.Create;
779-begin
780- inherited Create;
781- Name:='MyText'; // do not translate this
782- DefaultFilename:='text.txt';
783- AddToProject:=false;
784-end;
785-
786-function TFileDescText.GetLocalizedName: string;
787-begin
788- Result:='My Text'; // replace this with a resourcestring
789-end;
790-
791-function TFileDescText.GetLocalizedDescription: string;
792-begin
793- Result:='An empty text file';
794-end;
826+ ...
827+ { TFileDescText }
828+
829+ TFileDescMyText = class(TProjectFileDescriptor)
830+ public
831+ constructor Create; override;
832+ function GetLocalizedName: string; override;
833+ function GetLocalizedDescription: string; override;
834+ end;
835+ ...
836+
837+ procedure Register;
838+
839+ implementation
840+
841+ procedure Register;
842+ begin
843+ RegisterProjectFileDescriptor(TFileDescMyText.Create,FileDescGroupName);
844+ end;
845+
846+ { TFileDescMyText }
847+
848+ constructor TFileDescMyText.Create;
849+ begin
850+ inherited Create;
851+ Name:='MyText'; // do not translate this
852+ DefaultFilename:='text.txt';
853+ AddToProject:=false;
854+ end;
855+
856+ function TFileDescText.GetLocalizedName: string;
857+ begin
858+ Result:='My Text'; // replace this with a resourcestring
859+ end;
860+
861+ function TFileDescText.GetLocalizedDescription: string;
862+ begin
863+ Result:='An empty text file';
864+ end;
795865```
796866
797867### Add a new form type
798-
799-``` pascal
868+```
800869uses ProjectIntf;
801-
802-...
803- TFileDescPascalUnitWithMyForm = class(TFileDescPascalUnitWithResource)
804- public
805- constructor Create; override;
806- function GetInterfaceUsesSection: string; override;
807- function GetLocalizedName: string; override;
808- function GetLocalizedDescription: string; override;
809- end;
810-...
811-
812-procedure Register;
813-
814-implementation
815-
816-procedure Register;
817-begin
818- RegisterProjectFileDescriptor(TFileDescPascalUnitWithMyForm.Create,FileDescGroupName);
819-end;
820-
821-{ TFileDescPascalUnitWithMyForm }
822-
823-constructor TFileDescPascalUnitWithMyForm.Create;
824-begin
825- inherited Create;
826- Name:='MyForm'; // do not translate this
827- ResourceClass:=TMyForm;
828- UseCreateFormStatements:=true;
829-end;
830-
831-function TFileDescPascalUnitWithMyForm.GetInterfaceUsesSection: string;
832-begin
833- Result:='Classes, SysUtils, MyWidgetSet';
834-end;
835-
836-function TFileDescPascalUnitWithForm.GetLocalizedName: string;
837-begin
838- Result:='MyForm'; // replace this with a resourcestring
839-end;
840-
841-function TFileDescPascalUnitWithForm.GetLocalizedDescription: string;
842-begin
843- Result:='Create a new MyForm from example package NotLCLDesigner';
844-end;
870+
871+ ...
872+ TFileDescPascalUnitWithMyForm = class(TFileDescPascalUnitWithResource)
873+ public
874+ constructor Create; override;
875+ function GetInterfaceUsesSection: string; override;
876+ function GetLocalizedName: string; override;
877+ function GetLocalizedDescription: string; override;
878+ end;
879+ ...
880+
881+ procedure Register;
882+
883+ implementation
884+
885+ procedure Register;
886+ begin
887+ RegisterProjectFileDescriptor(TFileDescPascalUnitWithMyForm.Create,FileDescGroupName);
888+ end;
889+
890+ { TFileDescPascalUnitWithMyForm }
891+
892+ constructor TFileDescPascalUnitWithMyForm.Create;
893+ begin
894+ inherited Create;
895+ Name:='MyForm'; // do not translate this
896+ ResourceClass:=TMyForm;
897+ UseCreateFormStatements:=true;
898+ end;
899+
900+ function TFileDescPascalUnitWithMyForm.GetInterfaceUsesSection: string;
901+ begin
902+ Result:='Classes, SysUtils, MyWidgetSet';
903+ end;
904+
905+ function TFileDescPascalUnitWithForm.GetLocalizedName: string;
906+ begin
907+ Result:='MyForm'; // replace this with a resourcestring
908+ end;
909+
910+ function TFileDescPascalUnitWithForm.GetLocalizedDescription: string;
911+ begin
912+ Result:='Create a new MyForm from example package NotLCLDesigner';
913+ end;
845914```
846915
847916# Packages
848917
849-You can perform various actions with [[Lazarus Packages|Packages]]:
918+You can perform various actions with [[Lazarus Packages|Packages]]:
850919
851920## Search in all packages
852921
853-Iterate all packages loaded in the IDE (since 0.9.29).
854-
855-``` pascal
922+Iterate all packages loaded in the IDE (since 0.9.29).
923+```
856924uses PackageIntf;
857-...
858-for i:=0 to PackageEditingInterface.GetPackageCount-1 do
859- writeln(PackageEditingInterface.GetPackages(i).Name);
925+ ...
926+ for i:=0 to PackageEditingInterface.GetPackageCount-1 do
927+ writeln(PackageEditingInterface.GetPackages(i).Name);
860928```
861929
862930## Search a package with a name
863-
864-``` pascal
931+```
865932uses PackageIntf;
866-...
867-var
868- Pkg: TIDEPackage;
869-begin
870- Pkg:=PackageEditingInterface.FindPackageWithName('LCL');
871- if Pkg<>nil then
872933 ...
873-end;
934+ var
935+ Pkg: TIDEPackage;
936+ begin
937+ Pkg:=PackageEditingInterface.FindPackageWithName('LCL');
938+ if Pkg<>nil then
939+ ...
940+ end;
874941```
875942
876-Note: FindPackageWithName does not open the package editor. For that use DoOpenPackageWithName.
943+Note: FindPackageWithName does not open the package editor. For that use DoOpenPackageWithName.
877944
878945## Obtener el nombre de fichero .lpk de un paquete instalado
879-
880-``` pascal
946+```
881947uses PackageIntf;
882-...
883-var
884- Pkg: TIDEPackage;
885-begin
886- Pkg:=PackageEditingInterface.FindPackageWithName('LCL');
887- if Pkg<>nil then
888- LPKFilename:=Pkg.Filename;
889-end;
948+ ...
949+ var
950+ Pkg: TIDEPackage;
951+ begin
952+ Pkg:=PackageEditingInterface.FindPackageWithName('LCL');
953+ if Pkg<>nil then
954+ LPKFilename:=Pkg.Filename;
955+ end;
890956```
891957
892958## Instalar paquetes
893959
894-**Note**: Instalar únicamente paquetes con plugins IDE. Instalar otros paquetes puede hacer el IDE inestable.
895-
896-``` pascal
960+**Note** : Instalar únicamente paquetes con plugins IDE. Instalar otros paquetes puede hacer el IDE inestable.
961+```
897962uses PackageIntf, contnrs;
898-...
899- PkgList:=TObjectList.create(true);
900- try
901- Pkg:=TLazPackageID.Create;
902- Pkg.Name:='Cody';
903- PkgList.Add(Pkg);
904- // Chequear si el IDE puede encontrar cody.lpk y todas las dependencias.
905- // El IDE will muestra algunas advertencias/confirmaciones si algo parece extraño.
906- if not PackageEditingInterface.CheckInstallPackageList(PkgList,[]) then
907- exit;
908- // in this example we have checked already, so skip the warnings
909- // and rebuild the IDE
910- if PackageEditingInterface.InstallPackages(PkgList,[piiifSkipChecks,piiifRebuildIDE])<>mrOK then
911- exit;
912- finally
913- PkgList.Free;
914- end;
963+ ...
964+ PkgList:=TObjectList.create(true);
965+ try
966+ Pkg:=TLazPackageID.Create;
967+ Pkg.Name:='Cody';
968+ PkgList.Add(Pkg);
969+ // Chequear si el IDE puede encontrar cody.lpk y todas las dependencias.
970+ // El IDE will muestra algunas advertencias/confirmaciones si algo parece extraño.
971+ if not PackageEditingInterface.CheckInstallPackageList(PkgList,[]) then
972+ exit;
973+ // in this example we have checked already, so skip the warnings
974+ // and rebuild the IDE
975+ if PackageEditingInterface.InstallPackages(PkgList,[piiifSkipChecks,piiifRebuildIDE])<>mrOK then
976+ exit;
977+ finally
978+ PkgList.Free;
979+ end;
915980```
916981
917982## Abrir un fichero de paquete (lpk)
918-
919-``` pascal
983+```
920984uses PackageIntf, FileUtil;
921-...
922-var
923- pkg: TIDEPackage;
924-begin
925- if PackageEditingInterface.DoOpenPackageFile(LPKFilename,[pofAddToRecent],false)<>mrOk then
926- exit;
927- Pkg:=PackageEditingInterface.FindPackageWithName(ExtractFilenameOnly(LPKFilename));
928- ...
929-end;
985+ ...
986+ var
987+ pkg: TIDEPackage;
988+ begin
989+ if PackageEditingInterface.DoOpenPackageFile(LPKFilename,[pofAddToRecent],false)<>mrOk then
990+ exit;
991+ Pkg:=PackageEditingInterface.FindPackageWithName(ExtractFilenameOnly(LPKFilename));
992+ ...
993+ end;
930994```
931995
932-> **Warning:** El IDE cierra automáticamentes paquetes no utilizados on idle. Nunca mantener referencias a un TIDEPackage.
996+[![Warning-icon.png](/wiki-images/b/b2/Warning-icon.png)](</File:Warning-icon.png>)
933997
934-## Find the package(s) of a unit
998+**Warning:** El IDE cierra automáticamentes paquetes no utilizados on idle. Nunca mantener referencias a un TIDEPackage.
935999
936-You have the file name of a unit, e.g. '/home/user/unit.pas', and you want to know to which package(s) and project(s) it belongs use this:
1000+## Find the package(s) of a unit
9371001
938-``` pascal
1002+You have the file name of a unit, e.g. '/home/user/unit.pas', and you want to know to which package(s) and project(s) it belongs use this:
1003+```
9391004uses Classes, PackageIntf, ProjectIntf;
940-...
941-var
942- Owners: TFPList;
943- i: Integer;
944- o: TObject;
945-begin
946- Owners:=PackageEditingInterface.GetPossibleOwnersOfUnit('/full/path/of/unit.pas',[]);
947- if Owners=nil then begin
948- // unit is not directly associated with a project/package
949- // maybe the unit was for some reason not added, but is reachable
950- // search in all unit paths of all projects/packages
951- // Beware: This can lead to false hits
952- Owners:=PackageEditingInterface.GetPossibleOwnersOfUnit('/full/path/of/unit.pas',
953- [piosfExcludeOwned,piosfIncludeSourceDirectories]);
954- end;
955- if Owners=nil then exit;
956- try
957- for i:=0 to Owners.Count-1 do begin
958- o:=TObject(Owners[i]);
959- if o is TIDEPackage then begin
960- writeln('Owner is package ',TIDEPackage(o).Name);
961- end else if o is TLazProject then begin
962- writeln('Owner is project ',TLazProject(o).ProjectInfoFile);
1005+ ...
1006+ var
1007+ Owners: TFPList;
1008+ i: Integer;
1009+ o: TObject;
1010+ begin
1011+ Owners:=PackageEditingInterface.GetPossibleOwnersOfUnit('/full/path/of/unit.pas',[]);
1012+ if Owners=nil then begin
1013+ // unit is not directly associated with a project/package
1014+ // maybe the unit was for some reason not added, but is reachable
1015+ // search in all unit paths of all projects/packages
1016+ // Beware: This can lead to false hits
1017+ Owners:=PackageEditingInterface.GetPossibleOwnersOfUnit('/full/path/of/unit.pas',
1018+ [piosfExcludeOwned,piosfIncludeSourceDirectories]);
9631019 end;
964- end;
965- finally
966- Owners.Free;
967- end;
1020+ if Owners=nil then exit;
1021+ try
1022+ for i:=0 to Owners.Count-1 do begin
1023+ o:=TObject(Owners[i]);
1024+ if o is TIDEPackage then begin
1025+ writeln('Owner is package ',TIDEPackage(o).Name);
1026+ end else if o is TLazProject then begin
1027+ writeln('Owner is project ',TLazProject(o).ProjectInfoFile);
1028+ end;
1029+ end;
1030+ finally
1031+ Owners.Free;
1032+ end;
9681033```
9691034
9701035# Ventanas
9711036
972-Hay básicamente cuatro tipos de ventandas del IDE:
1037+Hay básicamente cuatro tipos de ventandas del IDE:
9731038
974-- La barra principal del IDE bar que es Application.MainForm. Siempre está presente.
975-- Ventanas flotantes/acoplables tales como el editor del código fuente, the Object Inspectors and Messages.
976-- Fomas modales, tales como los diálogos de búsqueda, opciones y preguntas.
977-- Sugerencias y formas de completado.
1039+ * La barra principal del IDE bar que es Application.MainForm. Siempre está presente.
1040+ * Ventanas flotantes/acoplables tales como el editor del código fuente, the Object Inspectors and Messages.
1041+ * Fomas modales, tales como los diálogos de búsqueda, opciones y preguntas.
1042+ * Sugerencias y formas de completado.
9781043
9791044## Añadiendo una nueva ventana de acoplado en el IDE
9801045
981-Que es una ventana del IDE acoplable: Ventanas tales como el Editor de Código Fuente o el Inspector de Objetos son ventanas flotantes que se pueden acoplar si se instala un paquete de acoplamiento, y su estado, posición y tamaño se almacena y restaura en el siguiente inicio del IDE. En orden a restaurar una ventana el IDE necesita un creador como se definie en la unidad **IDEWindowIntf** del paquete IDEIntf. Cada ventana acoplable debe tener un único nombre. No usar por tanto nombres genéricos como 'FileBrowser' porque haría que entre fácilmente en conflicto con otros paquetes. Y no usar nombres cortos como 'XYZ' porque el creador es responsable de todas las formas que comiencen con dicho nombre.
1046+Que es una ventana del IDE acoplable: Ventanas tales como el Editor de Código Fuente o el Inspector de Objetos son ventanas flotantes que se pueden acoplar si se instala un paquete de acoplamiento, y su estado, posición y tamaño se almacena y restaura en el siguiente inicio del IDE. En orden a restaurar una ventana el IDE necesita un creador como se definie en la unidad **IDEWindowIntf** del paquete IDEIntf. Cada ventana acoplable debe tener un único nombre. No usar por tanto nombres genéricos como 'FileBrowser' porque haría que entre fácilmente en conflicto con otros paquetes. Y no usar nombres cortos como 'XYZ' porque el creador es responsable de todas las formas que comiencen con dicho nombre.
9821047
9831048### Como registrar una ventana acoplable del IDE
9841049
985-Recuerda utilizar un nombre largo única que sea un identificador pascal válido. Tus ventanas pueden tener cualquier caption que necesites.
986-
987-``` pascal
1050+Recuerda utilizar un nombre largo única que sea un identificador pascal válido. Tus ventanas pueden tener cualquier caption que necesites.
1051+```
9881052uses SysUtils, IDEWindowIntf;
989-...
990-var MyIDEWindow: TMyIDEWindow = nil;
991-
992-procedure CreateMyIDEWindow(Sender: TObject; aFormName: string; var AForm: TCustomForm; DoDisableAutoSizing: boolean);
993-begin
994- // check the name
995- if CompareText(aFormName,MyIDEWindowName)<>0 then exit;
996- // create the form if not already done and disable autosizing
997- IDEWindowCreators.CreateForm(MyIDEWindow,TMyIDEWindowm,DoDisableAutosizing,Application);
998- ... init the window ...
999- AForm:=MyIDEWindow;
1000-end;
1001-
1002-procedure Register;
1003-begin
1004- IDEWindowCreators.Add('MyIDEWindow',@CreateMyIDEWindow,nil,'100','50%','+300','+20%');
1005- // the default boundsrect of the form is:
1006- // Left=100, Top=50% of Screen.Height, Width=300, Height=20% of Screen.Height
1007- // when the IDE needs an instance of this window it calls the procedure CreateMyIDEWindow.
1008-end;
1053+ ...
1054+ var MyIDEWindow: TMyIDEWindow = nil;
1055+
1056+ procedure CreateMyIDEWindow(Sender: TObject; aFormName: string; var AForm: TCustomForm; DoDisableAutoSizing: boolean);
1057+ begin
1058+ // check the name
1059+ if CompareText(aFormName,MyIDEWindowName)<>0 then exit;
1060+ // create the form if not already done and disable autosizing
1061+ IDEWindowCreators.CreateForm(MyIDEWindow,TMyIDEWindowm,DoDisableAutosizing,Application);
1062+ ... init the window ...
1063+ AForm:=MyIDEWindow;
1064+ end;
1065+
1066+ procedure Register;
1067+ begin
1068+ IDEWindowCreators.Add('MyIDEWindow',@CreateMyIDEWindow,nil,'100','50%','+300','+20%');
1069+ // the default boundsrect of the form is:
1070+ // Left=100, Top=50% of Screen.Height, Width=300, Height=20% of Screen.Height
1071+ // when the IDE needs an instance of this window it calls the procedure CreateMyIDEWindow.
1072+ end;
10091073```
10101074
10111075### Showing an IDE window
10121076
1013-**Do not use Show**. Use:
1014-
1015-``` pascal
1077+**Do not use Show**. Use:
1078+```
10161079IDEWindowCreators.ShowForm(MyIDEWindow,false);
10171080```
10181081
1019-This will work with docking. The docking system might wrap the form into a docking site. The BringToFront parameter tells the docking system to make the form and all its parent sites visible and bring the top level site to the front.
1082+This will work with docking. The docking system might wrap the form into a docking site. The BringToFront parameter tells the docking system to make the form and all its parent sites visible and bring the top level site to the front.
10201083
10211084### Notes about IDEWindowCreators and SimpleLayoutStorage
10221085
1023-The IDEWindowCreators.SimpleLayoutStorage simply stores the BoundsRect and WindowState of all forms that were once opened. It is used as fallback if no dockmaster is installed. It stores the state even if a DockMaster is installed, so that when the dockmaster is uninstalled the forms bounds are restored.
1086+The IDEWindowCreators.SimpleLayoutStorage simply stores the BoundsRect and WindowState of all forms that were once opened. It is used as fallback if no dockmaster is installed. It stores the state even if a DockMaster is installed, so that when the dockmaster is uninstalled the forms bounds are restored.
10241087
1025-The IDEWindowCreators is used by all dockable forms to register themselves and to show forms. When showing a form the Creator checks if a IDEDockMaster is installed and will delegate the showing to it. If no IDEDockMaster is installed it simply shows the form. The IDEDockMaster can use the information in the IDEWindowCreators to create forms by names and get an idea where to place a form when showing it for the first time. For more details see the packages AnchorDockingDsgn and EasyDockMgDsgn.
1088+The IDEWindowCreators is used by all dockable forms to register themselves and to show forms. When showing a form the Creator checks if a IDEDockMaster is installed and will delegate the showing to it. If no IDEDockMaster is installed it simply shows the form. The IDEDockMaster can use the information in the IDEWindowCreators to create forms by names and get an idea where to place a form when showing it for the first time. For more details see the packages AnchorDockingDsgn and EasyDockMgDsgn.
10261089
10271090# CodeTools
10281091
1029-The CodeTools is a package providing a vast amount of functions to parse, search and change pascal sources and some basic functions for other languages as well. You can use them without the IDE too. It is recommended that you read first about the CodeTools in general before using them in the IDE: [[Codetools]].
1030-
1031-Before calling any of the CodeTools functions in the IDE you should commit the current changes of the source editor to the CodeTools buffers:
1092+The CodeTools is a package providing a vast amount of functions to parse, search and change pascal sources and some basic functions for other languages as well. You can use them without the IDE too. It is recommended that you read first about the CodeTools in general before using them in the IDE: [[Codetools]].
10321093
1033-``` pascal
1094+Before calling any of the CodeTools functions in the IDE you should commit the current changes of the source editor to the CodeTools buffers:
1095+```
10341096uses LazIDEIntf;
1035-...
1036- // save changes in source editor to codetools
1037- LazarusIDE.SaveSourceEditorChangesToCodeCache(-1); // -1: commit all source editors
1097+ ...
1098+ // save changes in source editor to codetools
1099+ LazarusIDE.SaveSourceEditorChangesToCodeCache(-1); // -1: commit all source editors
10381100```
10391101
10401102## Adding a resource directive to a file
10411103
1042-This adds a {\$R example.res} to a pascal unit:
1043-
1044-``` pascal
1104+This adds a {$R example.res} to a pascal unit:
1105+```
10451106procedure AddResourceDirectiveToPascalSource(const Filename: string);
1046-var
1047- ExpandedFilename: String;
1048- CodeBuf: TCodeBuffer;
1049-begin
1050- // make sure the filename is trimmed and contains a full path
1051- ExpandedFilename:=CleanAndExpandFilename(Filename);
1052-
1053- // save changes in source editor to codetools
1054- LazarusIDE.SaveSourceEditorChangesToCodeCache(-1);
1055-
1056- // load the file
1057- CodeBuf:=CodeToolBoss.LoadFile(ExpandedFilename,true,false);
1058-
1059- // add the resource directive
1060- if not CodeToolBoss.AddResourceDirective(CodeBuf,'example.res') then
1061- LazarusIDE.DoJumpToCodeToolBossError;
1062-end;
1107+ var
1108+ ExpandedFilename: String;
1109+ CodeBuf: TCodeBuffer;
1110+ begin
1111+ // make sure the filename is trimmed and contains a full path
1112+ ExpandedFilename:=CleanAndExpandFilename(Filename);
1113+
1114+ // save changes in source editor to codetools
1115+ LazarusIDE.SaveSourceEditorChangesToCodeCache(-1);
1116+
1117+ // load the file
1118+ CodeBuf:=CodeToolBoss.LoadFile(ExpandedFilename,true,false);
1119+
1120+ // add the resource directive
1121+ if not CodeToolBoss.AddResourceDirective(CodeBuf,'example.res') then
1122+ LazarusIDE.DoJumpToCodeToolBossError;
1123+ end;
10631124```
10641125
1065-The codetools provides also functions like FindResourceDirective and RemoveDirective.
1126+The codetools provides also functions like FindResourceDirective and RemoveDirective.
10661127
10671128## Getting the search paths for units and include files
10681129
1069-There are many different search paths in the IDE from projects, packages, the fpc and lazarus directory and there are many types of paths: before or after resolving macros, with or without inherited search paths, as relative or absolute paths. All files in a directory share the same set of search paths. You can get the search paths for each directory fully resolved by asking the codetools:
1070-
1071-``` pascal
1130+There are many different search paths in the IDE from projects, packages, the fpc and lazarus directory and there are many types of paths: before or after resolving macros, with or without inherited search paths, as relative or absolute paths. All files in a directory share the same set of search paths. You can get the search paths for each directory fully resolved by asking the codetools:
1131+```
10721132uses CodeToolManager;
1073-...
1074-
1075-Dir:=''; // the empty directory is for new files and has the same settings as the project directory
1076-
1077-// Getting the search paths for include files:
1078-Path:=CodeToolBoss.GetIncludePathForDirectory(Dir);
1079-
1080-// Getting the search paths for units:
1081-// This search path is passed to the compiler.
1082-// It contains the package output directories, but not the package source directories.
1083-Path:=CodeToolBoss.GetUnitPathForDirectory(Dir);
1084-
1085-// There can be additional unit search paths for the IDE only (not passed to the compiler)
1086-Path:=CodeToolBoss.GetSrcPathForDirectory(Dir);
1087-
1088-// The complete search path contains also all package source paths for units:
1089-Path:=CodeToolBoss.GetCompleteSrcPathForDirectory(Dir);
1133+ ...
1134+
1135+ Dir:=''; // the empty directory is for new files and has the same settings as the project directory
1136+
1137+ // Getting the search paths for include files:
1138+ Path:=CodeToolBoss.GetIncludePathForDirectory(Dir);
1139+
1140+ // Getting the search paths for units:
1141+ // This search path is passed to the compiler.
1142+ // It contains the package output directories, but not the package source directories.
1143+ Path:=CodeToolBoss.GetUnitPathForDirectory(Dir);
1144+
1145+ // There can be additional unit search paths for the IDE only (not passed to the compiler)
1146+ Path:=CodeToolBoss.GetSrcPathForDirectory(Dir);
1147+
1148+ // The complete search path contains also all package source paths for units:
1149+ Path:=CodeToolBoss.GetCompleteSrcPathForDirectory(Dir);
10901150```
10911151
10921152# Source Editor
10931153
10941154## Active source editor
1095-
1096-``` pascal
1155+```
10971156uses SrcEditorIntf;
1098-...
1099-Editor:=SourceEditorManagerIntf.ActiveEditor;
1100-if Editor=nil then exit;
1101-Filename:=Editor.FileName;
1102-ScreenPos:=Editor.CursorScreenXY;
1103-TextPos:=Editor.CursorTextXY;
1157+ ...
1158+ Editor:=SourceEditorManagerIntf.ActiveEditor;
1159+ if Editor=nil then exit;
1160+ Filename:=Editor.FileName;
1161+ ScreenPos:=Editor.CursorScreenXY;
1162+ TextPos:=Editor.CursorTextXY;
11041163```
11051164
11061165# SynEdit
11071166
11081167## Getting the settings for a TSynEdit
11091168
1110-When you have a dialog using a TSynEdit and you want to use the same font and settings like the source editor use:
1111-
1112-``` pascal
1169+When you have a dialog using a TSynEdit and you want to use the same font and settings like the source editor use:
1170+```
11131171uses SrcEditorIntf;
1114-...
1115-SourceEditorManagerIntf.GetEditorControlSettings(ASynEdit);
1172+ ...
1173+ SourceEditorManagerIntf.GetEditorControlSettings(ASynEdit);
11161174```
11171175
11181176## Getting the settings for a SynEdit highlighter
11191177
1120-When you have a dialog using a TSynEdit with a highlighter and you want to use the same colors like the source editor highlighter for this language use:
1121-
1122-``` pascal
1178+When you have a dialog using a TSynEdit with a highlighter and you want to use the same colors like the source editor highlighter for this language use:
1179+```
11231180uses SrcEditorIntf;
1124-...
1125-SourceEditorManagerIntf.GetHighlighterSettings(ASynHighlighter);
1181+ ...
1182+ SourceEditorManagerIntf.GetHighlighterSettings(ASynHighlighter);
11261183```
11271184
1128-See for an example: TSQLStringsPropertyEditorDlg.Create in the unit [SQLStringsPropertyEditorDlg](http://svn.freepascal.org/svn/lazarus/trunk/components/sqldb/sqlstringspropertyeditordlg.pas).
1185+See for an example: TSQLStringsPropertyEditorDlg.Create in the unit [SQLStringsPropertyEditorDlg](<http://svn.freepascal.org/svn/lazarus/trunk/components/sqldb/sqlstringspropertyeditordlg.pas>).
11291186
11301187# Help
11311188
11321189## Adding help for sources
11331190
1134-First create a THelpDatabase:
1135-
1136-``` pascal
1191+First create a THelpDatabase:
1192+```
11371193HelpDB := TFPDocHTMLHelpDatabase(
1138- HelpDatabases.CreateHelpDatabase('ANameOfYourChoiceForTheDatabase',
1139- TFPDocHTMLHelpDatabase,true));
1140-HelpDB.DefaultBaseURL := 'http://your.help.org/';
1141-
1142-FPDocNode := THelpNode.CreateURL(HelpDB,
1143- 'Package1 - A new package',
1144- 'file://index.html');
1145-HelpDB.TOCNode := THelpNode.Create(HelpDB,FPDocNode);// once as TOC
1146-DirectoryItem := THelpDBISourceDirectory.Create(FPDocNode,'$(PkgDir)/lcl',
1147- '*.pp;*.pas',false);// and once as normal page
1148-HelpDB.RegisterItem(DirectoryItem);
1194+ HelpDatabases.CreateHelpDatabase('ANameOfYourChoiceForTheDatabase',
1195+ TFPDocHTMLHelpDatabase,true));
1196+ HelpDB.DefaultBaseURL := 'http://your.help.org/';
1197+
1198+ FPDocNode := THelpNode.CreateURL(HelpDB,
1199+ 'Package1 - A new package',
1200+ 'file://index.html');
1201+ HelpDB.TOCNode := THelpNode.Create(HelpDB,FPDocNode);// once as TOC
1202+ DirectoryItem := THelpDBISourceDirectory.Create(FPDocNode,'$(PkgDir)/lcl',
1203+ '*.pp;*.pas',false);// and once as normal page
1204+ HelpDB.RegisterItem(DirectoryItem);
11491205```
11501206
11511207## Adding lines to the messages window
1152-
1153-``` pascal
1208+```
11541209unit IDEMsgIntf;
1155-...
1156-var Dir: String;
1157-begin
1158- Dir:=GetCurrentDir;
1159- IDEMessagesWindow.BeginBlock;
1160- IDEMessagesWindow.AddMsg('unit1.pas(30,4) Error: Identifier not found "a"',Dir,0);
1161- IDEMessagesWindow.EndBlock;
1162-end;
1210+ ...
1211+ var Dir: String;
1212+ begin
1213+ Dir:=GetCurrentDir;
1214+ IDEMessagesWindow.BeginBlock;
1215+ IDEMessagesWindow.AddMsg('unit1.pas(30,4) Error: Identifier not found "a"',Dir,0);
1216+ IDEMessagesWindow.EndBlock;
1217+ end;
11631218```
11641219
11651220# Miscellaneous
11661221
11671222## Adding a macro
11681223
1169-You can add your own IDE macros:
1170-
1171-``` pascal
1224+You can add your own IDE macros:
1225+```
11721226uses MacroIntf, MacroDefIntf;
1173-
1174-procedure Register;
1175-begin
1176- // registering a Macro with a fixed value:
1177- IDEMacros.Add(TTransferMacro.Create('MyMacro1','Value','Description',nil,[]));
1178-end;
1179-
1180-// registering a Macro with a dynamic value requires a method of an object
1181-procedure TForm1.Init;
1182-begin
1183- IDEMacros.Add(TTransferMacro.Create('MyMacro','Value','Description',@OnResolveMyMacro,[]));
1184-end;
1185-
1186-function TForm1.OnResolveMyMacro(const s: string; const Data: PtrInt;
1187- var Abort: boolean): string;
1188-// s is the parameter. For example $MyMacro(parameter)
1189-// Data is the querying instance. Can be nil.
1190-// If there is an error set Abort to true.
1191-// The result string can contain macros. For example Result:='$(FPCVer)/$(TargetOS)';
1192-begin
1193- Result:='MyValue';
1194-end;
1227+
1228+ procedure Register;
1229+ begin
1230+ // registering a Macro with a fixed value:
1231+ IDEMacros.Add(TTransferMacro.Create('MyMacro1','Value','Description',nil,[]));
1232+ end;
1233+
1234+ // registering a Macro with a dynamic value requires a method of an object
1235+ procedure TForm1.Init;
1236+ begin
1237+ IDEMacros.Add(TTransferMacro.Create('MyMacro','Value','Description',@OnResolveMyMacro,[]));
1238+ end;
1239+
1240+ function TForm1.OnResolveMyMacro(const s: string; const Data: PtrInt;
1241+ var Abort: boolean): string;
1242+ // s is the parameter. For example $MyMacro(parameter)
1243+ // Data is the querying instance. Can be nil.
1244+ // If there is an error set Abort to true.
1245+ // The result string can contain macros. For example Result:='$(FPCVer)/$(TargetOS)';
1246+ begin
1247+ Result:='MyValue';
1248+ end;
11951249```
11961250
11971251## Depurando el IDE
11981252
1199-- Compila el IDE como habitualmente e.g. via Tools/Build de Lazarus. Asegúrate de establecer los flags de depuración tales como -g o -gw2. Lo mejor es utilizar el profile "Debug IDE" que contiene algunos flags útiles para depuración.
1200-- Abre el proyecto ide\lazarus.lpi. No se puede compilar directamente este proyecto.
1201-- Establece los puntos de ruptura (breakpoints) acorde a tus necesidades etc y ejecuta el proyecto.
1253+ * Compila el IDE como habitualmente e.g. via Tools/Build de Lazarus. Asegúrate de establecer los flags de depuración tales como -g o -gw2. Lo mejor es utilizar el profile "Debug IDE" que contiene algunos flags útiles para depuración.
1254+ * Abre el proyecto ide\lazarus.lpi. No se puede compilar directamente este proyecto.
1255+ * Establece los puntos de ruptura (breakpoints) acorde a tus necesidades etc y ejecuta el proyecto.
12021256
12031257## See also
12041258
1205-- [[Creating IDE Help]]
1206-- [[Help protocol]]
1207-- [[How To Write Lazarus Component]]
1259+ * [[Creating IDE Help]]
1260+ * [[Help protocol]]
1261+ * [[How To Write Lazarus Component]]
12081262
12091263---
1210-*From the Free Pascal wiki, page "Extending the IDE/es", as it stood on 2020-02-14 after a change by Trev, 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).*
1264+*From the Free Pascal wiki, page "Extending the IDE/es", as the Internet Archive kept it on 2024-07-25. 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).*

Back to history