Lazarus Tutorial/ru

From Free Pascal wiki
Jump to navigationJump to search

Deutsch (de) English (en) español (es) suomi (fi) français (fr) magyar (hu) italiano (it) 日本語 (ja) македонски (mk) Nederlands (nl) português (pt) русский (ru) slovenčina (sk) shqip (sq) 中文(中国大陆)‎ (zh_CN) 中文(台灣)‎ (zh_TW)

This is the start of a Lazarus Tutorial. Please feel free to add your experiences to it.

Обзор

Lazarus это бесплатный инструмент разработки с открытым кодом, предназначенный для также бесплатного компилятора с открытым кодом Free Pascal (object pascal). IDE Lazarus (screenshot) это стабильная богатая возможностями среда разработки для создания самостоятельных графических и консольных приложений. В настоящее время она работает на Linux, FreeBSD и Win32 и предоставляет настраиваемый редактор кода и визуальную среду создания форм вместе с менеджером пакетов, отладчиком и GUI полноcтью интегрированным с компилятором FreePascal.

Начнем - Ваша первая Lazarus-программа!

(Благодарим User:Kirkpatc)

Найдите, установите(Installing Lazarus) и запустите Lazarus, который кроме того содержит и компилятор FreePascal.

На экране появятся несколько окон: главное окно вверху, Инспектор Объектов (Object Inspector) слева, занимаюший большую часть экрана Редактор Кода Lazarus (Lazarus Source Editor), и готовое к использованию окно Form1 поверх окна Редактора.

В главном окне сверху, под строкой меню располагается строка вкладок. Если вкладка 'Standard' еще не выбрана, выберите ее, щелкнув на ней левой кнопкой мыши. Затем найдите иконку Button (прямоугольник с текстом 'Ok' на нем) и щелкните на ней мышкой. Затем щелкните в окне Form1, где-нибудь слева от середины. Появится затененный прямоугольник с надписью 'Button1'. Вновь щелкните на иконке Button на вкладке Standard и щелкните на Form1 где-нибудь справа от центра: появится прямоугольник с надписью 'Button2'.

Теперь щелкните на Button1 чтобы выбрать ее. Инспектор Объектов отобразит свойства объекта Button1. Не далеко от верхнего края располагается свойство с именем 'Caption', в котором отображается значение 'Button1'. Щелкните в этой строке и измените 'Button1' на 'Нажми меня' (прим.пер.: в оригинальном тексте 'Press'. Далее будет приводиться только русский текст надписей, а оригинальный можно посмотреть на странице с английским текстом). Если вы нажмете клавишу ENTER или щелкнете в другой строке, то увидите, что надпись на первой кнопке Form1 изменилась на 'Нажми меня'. Теперь щелкните в Инспекторе объектов на вкладке Events (События) и вы увидите различные события, на которые может реагировать кнопка. Среди них OnClick, OnEnter, OnExit и так далее. Щелкните в строке справа от OnClick: появится маленькая кнопка с троеточием (...). Если вы ее нажмете, то автоматически перенесетесь в Редактор Кода и курсор окажется в участке кода, начинающегося с:

 procedure TForm1.Button1Click(Sender: TObject);
 begin
   {здесь наберите:}  Button1.caption := 'Нажми еще раз';
   {Редактор уже вставил завершение процедуры}
 end;

Нажмите F12 для переключения от Редактора Кода к окну формы Form1.

Теперь отредактируйте свойства кнопки2 (Button2): щелкните на Button2 для отображения ее свойств в Инспекторе Объектов. Измените свойство Caption на 'Выход' вместо 'Button2'. Теперь перейдите на вкладку событий (Events) и щелкните в строке OnClick. Щелкните на кнопке с троеточием и перенеситесь в Редактор Кода, в тело другой процедуры:

 procedure TForm1.Button2Click(Sender: TObject);
 begin
 {здесь наберите:}   Close;
 {Редактор уже вставил завершение процедуры} 
 end;

Теперь нажмите F12 чтобы увидеть форму Form1 вновь. Теперь вы можете попытаться скомпилировать. Простейшим способом сделать это является выбор в главном меню пункта 'Run' а в появившемся подменю пункта 'Run'. Вы также можете просто нажать клавишу F9. Сначала произойдет компиляция, а затем (если все в порядке) линковка и запуск вашей программы.

Ппромелькнет несколько текстовых окон и будут выведены различные сообщения компилятора, а потом вновь появится окно формы Form1, но уже без точечной сетки; это и есть реальное главное окно вашего приложения, и оно ожидает нажатия кнопок или любого другого вашего действия.

Попробуйте щелкнуть на кнопке 'Нажми меня'. Вы увидите, что надпись на ней сменится на 'Нажми еще раз'. Если вы нажмете еще раз, то на кнопке так и останется надпись 'Нажми еще раз'!!

Теперь щелкните на кнопке с надписью 'Выход'. Окно закроется и программа завершится. Вновь появится окно формы Form1 с точечной сеткой, готовое для редактирования.

Теперь (и вообще почаще) вы можете сохранить свою работу выбрав последовательно пункты меню Project > Save Project As > имя_вашего_файла.pas

Вторая попытка.

Вновь откройте сохраненный вами проект.

На форме Form1 щелкните на кнопке 'Нажми меня' (Button1) чтобы выбрать ее. В Инспекторе Объектов перейдите на вкладку событий (Events), щелкните на строке справа от события OnClick, щелкните на кнопке с многоточием, чтобы перенестись к соответствующему участку кода в Редакторе.

Измените код, на приведенный ниже:

 procedure TForm1.Button1Click(Sender: TObject);
{Используем свойство Tag, устанавливая его в положения 0 или 1}
 begin
   if Button1.tag =0 then
   begin
     Button1.caption := 'Нажми еще раз';
     Button1.tag := 1
   end else
   begin
     Button1.caption := 'Нажми меня';
     Button1.tag := 0
   end
 end;

Сохраните проект, перекомпилируйте и запустите. Левая кнопка теперь циклически меняет свой текст с одного сообщения на другое.

Сделай дело - гуляй смело!

Если вы хотите писать консольные или программы с текстовым интерфейсом на Pascal (например, если вы следуете стандартному курсу изучения программирования на Pascal, или вам нужно написать программу для работы в командном режиме или системную программу) вы также можете использовать Lazarus для написания, компилирования и выполнения ваших программ. Это прекрасная среда для программирования на Pascal. Смотри Console Mode Pascal.

Редактор

Когда вы запускаете Lazarus в первый раз, на вашем рабочем столе появляется набор несвязанных 'плавающих' окошек.

Первое, расположенное в самом верху рабочего стола имеет название Lazarus Editor vXXXXXX - project1 (название зависит от используемой версии и названия открытого проекта). Это главное окно управления проектом и оно содержит Главное Меню и Палитру Компонентов (Component Palette).

Lazmain.jpg

Строкой ниже располагается Главное Меню с обычными пунктами File, Edit, Search, View и некоторыми специфичными для Lazarus. Ниже Слева располагается набор кнопок, предоставляющих быстрый доступ к некоторым функциям главного меню, и справа - Палитра Компонентов. (Примечание переводчика: если при установке вы выбираете русский язык, то весь интерфейс будет на русском, то есть пункты меню, названия окон и вкладок, а также подсказки. В связи с этим далее все названия указаны на русском, а в скобках (на английском) языке. В любой момент можно переключить язык интерфеса в пункте меню Окружение. )

Под окном редактора Lazarus слева располагается окно Инспектора Объектов, а справа Редактор Исходного Кода (Lazarus Source Editor). Могут быть и другое окно меньшего размера, озаглавленное Form1, расположенное поверх Редактора Исходного Кода. Если оно в данный момент не видно, то можно переключиться к нему, нажав клавишу F12, которая позволяет переключаться между Редактором Исходного Кода и Окном Формы. Окно формы это то место, где вы разрабатываете графический интерфейс вашей программы, а в Редакторе Исходного Кода отображается разрабатываемый вами Pascal-код вашего приложения. Использование Инспектора Объектов детально обсуждается ниже после описания Палитры Компонентов.

Когда вы начинаете новый проект (или впервые запускаете Lazarus) по умолчанию создается стандартная форма, состоящая из прямоугольника с точечной сеткой для более легкого позиционирования различных компонентов на форме и системной строка сверху, которая обычно содержит кнопки Свернуть, Развернуть и Закрыть. Если вы щелкните мышкой в любом месте формы, вы увидите ее свойства в Инспекторе Объектов у левого края экрана.

Другие окна, которые могут появиться в процессе работы: Инспектор проектов, содержащий сведения о файлах, включенных в проект, и позволяющий вам добавлять и удалять файлы из проекта; Окно Messages (Сообщения), отображающее сообщения компилятора, ошибки и отчеты по вашему проекту; если Lazarus был запущен из терминала, то это окно остается запущенным и в нем отображаются подробные сообщения компилятора.

Главное меню

Главное текстовое меню содержит следующие пункты: File Edit Search View Project Run Components Tools Environment Windows Help

Как обычно любой пункт можно выбрать если навести на него курсор и нажать левую кнопку мыши или использовать горячие клавиши (например, клавиатурная комбинация Alt+F открывает меню File. Если меню не открылось, то следует нажимать TAB до тех пор, пока не будет активировано желаемое окно.


Меню Файл (File)

  • Создать модуль (New Unit): Создать новый модуль (Unit, исходный код на Pascal).
  • Создать форму (New Form): Создать новую форму. То есть два файла: саму форму и соответствующий ей файл с Pascal-кодом.
  • Создать... (New...): Открывает всплывающее окно (screenshot) в котором приведены различные типы проектов, которые можно создать (screenshot).
  • Открыть (Open): Открывает диалоговое окно, при помощи которого можно найти и открыть существующий файл.
  • Обратный экспорт (Revert): Отменяет сделанные изменения и возвращает файл в исходное состояние.
  • Сохранить (Save): Сохранить текущий файл под этим же именем. Если имя еще не дано, то система скажет об этом (это подобно пункту Сохранить как).
  • Сохранить как (Save As): Позволяет выбрать папку и имя под которым сохранить текущий файл.
  • Закрыть (Close): Закрывает текущий файл, с выводом сообщения о том следует ли сохранить сделанные изменения.
  • Закрыть все файлы редактора (Close all editor files): Закрывает все файлыЮ открытые в данный момент в редакторе. выдается сообщение о сохранении изменений.
  • Очистить каталог (Clean directory): Выводится диалог со строками задания фильтров при помощи которых можно очистить текущий каталог. Полезно для удаления .bak файлов не нужных или устаревших проектов.
  • Выход (Quit): Выход из Lazarus, с выводом запроса на сохранение всех открытых файлов.

Меню Правка (Edit)

  • Отменить (Undo): Отменяет последнее выполненное действие, переводя редактор в состояние до этого действия.
  • Повторить (Redo): Вновь выполняет ранее отмененное действие.
  • Вырезать (Cut): Удаляет выделенный текст или другой элемент и помещает его в буфер обмена.
  • Копировать (Copy): Создает копию выделенного текста, не затрагивая текст, и помещаетт ее в буфер обмена.
  • Вставить (Paste): Помещает содержимое буфера обмена в позицию курсора. Если есть выделенный текст, то он будет заменен содержимым буфера обмена.
  • Сдвинуть блок вправо (Indent selection): Сдвигает выделенный текст вправо на количество позиций, указанных в настройках Окружение -> Настройки редактора -> Общие -> Отступ блока (Environment -> Editor options -> General -> Block indent). Эта опция удобна для форматирования исходного Pascal-кода для создания блочной структуры.
  • Сдвинуть блок влево (Unindent selection): Удаляет один уровень отступа, сдивгая текст влево на количество позиций, указанных в Отступе блока (Block indent).
  • Заключить выделение в (Enclose selection): Открывает всплывающее меню с набором опций для заключения выделенного текста в программные скобки (begin ... end; try ... except; try ... finally; repeat ... until; { ... } и т. д.).
  • Верхний регистр выделения (Uppercase selection): Преобразует выделенный текст в верхний регистр.
  • Нижний регистр выделения (Lowercase selection): Преобразует выделенный текст в нижний регистр.
  • ТАБ сделать пробелами в выделенном (Tabs to spaces in selection): Преобразует все символы табуляции в выделенном тексте в некоторое количество пробелов, настраиваемое посредством Окружение -> Настройки редактора -> Общие -> Ширина ТАБа(Environment -> Editor options -> General -> Tab widths). Вставляется не фиксированное количество пробелов, а только число необходимое для завершения данного табулятора.
  • Разрыв строк в выделенном (Break lines in selection): Если строка выделенного текста длиннее 80 символов или числа указанного в Окружение -> Настройки редактора -> Дисплей -> Правая граница (Environment -> Editor options -> Display -> Right Margin), то строка текста будет разорвана на границе слова и продолжится со следующей строки.
  • Закомментировать (Comment selection): Закомментировать выделенный текст, добавив в начало каждой строки //.
  • Раскомментировать (Uncomment selection): Удалить символы комментария.
  • Сортировка выбранного (Sort selection): Сортирует строки (слова или параграфы) в алфавитном порядке; настраивается порядок сортировки и чувствительность к регистру. Конечно же, в теле программы это не нужно, но если у вас есть некий список и вам нужно его отсортировать, то можете использовать этот трюк.
  • Выделить (Select): Позволяет выделить текстовый блок. Имеются опции для выделения всего, до скобки, выделить абзац или строку и т. д.
  • Вставить из таблицы символов (Insert from character map): Позволяет вставить специальные символы, такие как символы с акцентами, которые берутся из всплывающей таблицы символов.
  • Вставить текст (Insert text): Вызывает всплывающее меню, позволяющее вставить шаблоны текста, такие как ключи CVS (Author, Date, Header и т. д.) или заметку о GPL, имя пользователя или текущую дату и время.
  • Завершить код (Complete code): Завершает код под курсором. Действия зависят от контекста и позволяют сохранить кучу времени. Например, можно завершить классы, добавив private переменные, Get и Set методы для доступа к свойствам и тела методов. Если переменной присваивается значение (например, i:=3), то будет добавлено описание переменной. Для процедур описанных с ключом forward будет добавлено тело процедуры. Если имеется присвоение событию (OnClick:=), то будут добавлены описание метода и тело метода. Смотри Lazarus IDE Tools.
  • Выделить процедуру (Extract procedure): Использует выделенный текст (один или несколько операторов) для построения новой процедуры.

Меню Поиск (Search)

  • Найти (Find): То же самое, что и в большинстве графических текстовых редакторов: появляется всплывающее диалоговое окно позволяющее вам ввести строку поиска, а также опции поиска, такие как чувствительность к регистру, искать целые слова, целые выражения, область и направление поиска.
  • Найти впереди (Find Next), Найти сзади (Find previous): искать далее указанную ранее строку в соответствующем направлении.
  • Найти в файлах (Find in files): Искать строку в файлах: всплывающее окно с опциями во всех открытых файлах, во всех файлах проекта или поиск в каталогах; можно задать маску-фильтр для типов файлов.
  • Замена (Replace): Подобна Найти; появляется диалоговое окно со областью ввода искомой строки и текста для замены, а также опций чувствительности к регистру, направления и т. д.
  • Поиск с нарастанием (Incremental find): Поиск строки в то время, пока вы вводите ее. Например, после того, как вы выберете "Поиск с нарастанием" и нажмете "l" будет подсвечена ближайшая буква "l". Если затем вы нажмете "a", редактор найдет следующее "la" и так далее.
  • Переход к строке (Goto line): Перемещает курсор в указанную строку файла.
  • Переход назад (Jump back): Перемещается по файлу назад, к предыдущей закладке (необходимо использовать ДОбавить точку перехода в историю). Может перемещаться к закладкам в других файлах, открытых в редакторе.
  • Переход вперед (Jump forward): Переместиться к следующей закладке.
  • Добавить точку перехода в историю (Add jump point to history): Добавляет закладку или точку перехода в файл.
  • Просмотр истории перехода (View Jump-History): Просмотреть список закладок в файле: Еще не реализовано.
  • Найти другой конец блока кода (Find other end of code block): Если курсор стоит на begin, то осуществляется поиск соответствующего end и наоборот.
  • Найти начало блока кода (Find code block start): Перемещается к begin процедуры или функции в теле которой находится курсор.
  • Найти описание под курсором (Find Declaration at cursor): Поиск участка кода, где описан выбранный идентификатор. Оно может быть в этом же файле или в любом другом, открытом в редакторе; Если файл еще не открыт, то он будет открыт (скажем если процедура или функция описана в classesh.inc этот файл будет открыт в Редакторе).
  • Открыть имя файла под курсором (Open filename at cursor): Открывает файл, имя которого выделено курсором. Полезно для просмотра Include файлов или файлов, содержащих другие модули Units, используемые в проекте.
  • Перейти к директиве include (Goto include directive): Если курсор помещен в файле, который включен Included в другой файл, то происходит перемещение в то место другого файла, из которого вызывается включенный.

Меню Просмотр (View)

Управляет отображением на экране различных окон и панелей.

  • Инспектор Объектов (Object Inspector): Окно, обычно расположенное по левому краю рабочего стола и отображающее фичи текущей формы. Щелчок на любом из компонентов формы приведет к отображению в Инспекторе Объектов деталей компонента (свойств и событий). Чуть выше располагается окно, отображающее древовидную структуру текущего проекта, в этом окне можно также выбрать компоненты формы, что также приведет к отображению их свойств в Инспекторе Объектов. Нижняя, главная, панель имеет две вкладки, позволяющих выбрать режим отображения Свойств (Properties) или Событий (Events). Вкладка Свойства отображает такие свойства, как имя (name), цвет (color), надпись (caption), шрифт (font), размер (size) и т. д.: она содержит два столбца - левый содержит имена свойств, а правый - их текущие значения. Щелкнув на значении свойства, можно изменить его значение через меню или окно настройки.

Вкладка События также имеет два столбца: левый содержит возможные события, типа нажатия кнопки мыши, ассоциированные с данным компонентом, а правый показывает действия, предусмотренные для этих событий. Если действие не определено, то нажатием на кнопку с точками

...

открывается Редактор Исходных текстов, где курсор уже находится в области объявления процедуры, ожидая ввода программы обработки данного события.

  • Редактор исходников (Source Editor): Основное окно для редактирования исходных текстов. Этот редактор очень похож на другие графические текстовые редакторы: мышью можно перемещать курсор по тексту, а нажав левую кнопку мыши и перемещая указатель, можно выделить участок текста. Нажатие правой кнопки вызывает меню, имеющее обычные функции редактирования: Вырезать, Копировать или Вставить, Найти объявление и Открыть файл. В верхней части окна Редактора может иметься несколько вкладок, соответствующих файлам, открытым в текущем проекте; нажатием на вкладку выбирается нужный файл. Так можно легко перемещаться по файлам, копировать и вставлять куски текста, выполняя обычные функции редактирования. Редактор исходных текстов выполняет цветовое выделение текста программы, отображая разными цветами метки пунктуации, комментарии, строковые константы и т. д. Он также сохраняет размер отступа от строки к строке, пока его не изменить вручную. Функции и вид Редактора исходников имеют настройки, вызываемые из основного меню выбором Окружение -> Параметры -> Опции Редактора выбором одной или нескольких вкладок в диалоговом окне.
  • Обозреватель кода (Code Explorer): Это окно обычно расположено справа и отображает в древовоидной форме структуру кода в текущем блоке или программе. Структура обычно открывается в виде только имен модулей и ветвей для секций интерфейса и реализации, но нажатием на рамку
    +
    слева от ветви открываются ее подветви, достигая более подробной детализации о константах, типах и переменных, а также объявлениях процедур и функций. Если сменить файл, отображаемый в окне Редактора Исходников, нужно нажать кнопку Обновить в обозревателе кода для просмотра структуры нового файла.
  • Модули ... (Units...): Открывается диалоговое окно с перечислением файлов модулей текущего проекта. Щелчком мыши на имени файла выбирается файл; Щелчком на ОК он открывается в Редакторе Исходников. Флажок Множественное выделение позволяет открывать одновременно несколько файлов (но только один будет отображен в окне Редактора Исходников). Эта опция меню очень похожа на опцию Проект -> Инспектор Проекта, но только отображает список файлов модулей и позволяет их открывать.
  • Формы... (Forms...): Opens a pop-up dialog window with a list of the Forms in the current project, and allows the selection of one or more of them for display.
  • Показать зависимости модулей (View Unit Dependencies): Opens a pop-up dialog window that shows, in a tree-like manner, the structure of dependencies of the currently open unit file. Most of the files listed as dependencies will have their own
    +
    boxes, which allow the dependencies of the individual files to be explored, often in a highly recursive manner.
  • Toggle form / unit view F12: Toggles whether the Source Editor or the current Form is placed on the top layer of the Desktop, and given focus. If the Source Editor has focus, then you can edit the source code; if the Form is given focus, you can manipulate the components on the desktop and edit the appearance of the Form. The easiest way to toggle the display between Editor and Form is to use the F12 key on the keyboard, but the same effect is achieved by selecting this option on the Main Menu.
  • Messages: A window that displays compiler messages, showing the progress of a successful compilation or listing the errors found.
  • Результат поиска (Search Results): Окно, которое отображает результаты поиска в файлах.
  • Debug windows: Opens a pop-up menu with several options for operating and configuring the Debugger. See below where the debugger is described.

The Project sub-menu

  • New Project: Create a new project. A pop-up dialog window appears offering a choice of types of project to create.
  • New Project from file: A Navigation dialog window appears, alowing selection of a file from which to create a new project.
  • Open Project Open a project which has already been created and saved. A navigation dialog appears with a list of Lazarus Project Information (.lpi) files from which a project may be chosen.
  • Open Recent Project: Displays a pop-up list of recent projects on which you have been working, and allows selection of one of these.
  • Save Project: Similar to File -> Save: all the files of the current project are saved; if they have not previously been saved, there is a prompt for filename(s)- similar to Save Project As...
  • Save Project As...: Prompts for filename to save project. A default filename of Project1.lpi is offered, but you should choose your own filename. Lazarus will not permit you to use the same name for the Project file and the Unit File (see below).
  • Publish Project: Creates a copy of the whole project. If you want to send someone just the sources and compiler settings of your code, this function is your friend. A normal project directory contains a lot of information. Most of it is not needed to be published: the .lpi file contains session information (like caret position and bookmarks of closed units) and the project directory contains a lot of .ppu, .o files and the executable. To create a lpi file with only the base information and only the sources, along with all sub directories use "Publish Project". In the dialog you can setup the exclude and include filter, and with the command after you can compress the output into one archive. See Lazarus IDE Tools
  • Project Inspector: Opens a pop-up dialog with a tree-like display of the files in the current project. Allows you to add, remove or open selected files, or change options of the project.
  • Project Options...: Opens a pop-up dialog window with tabs for setting options for Application (Title, Output Target file name), Forms (allowing you to select among the available forms, make them Auto-create at start of application) and Info (specifying whether editor information should be saved for closed files, or only for project files).
  • Compiler options ...: (Recently moved here from the Run Menu). Opens a multi-page tabbed window which allows configuration of the compiler. Tabs include Paths which allows definition of search paths for units, include files, libraries etc, as well as allowing choice of widget type for the forms (gtk, gnome, win32); Parsing which allows choice of rules for parsing source programs, Code which allows choice of optimisation for faster or smaller programs, choice of target processor, types of checks, heap size etc; Linking allowing choice of whether or how to use debugging, static or dynamic libraries, and whether to pass options through to the linker; Messages to define what type of messages should be generated during error conditions; Other which allows decision to use default configuration file (fpc.cfg) or some other file; Inherited which shows a tree structure diagram to indicate how options have been inherited from units already incorporated; Compilation which allows definition of commands to be executed before or after the compiler is launched and can allow use of Make files.
  • Add editor file to Project: Add the file currently being edited to the Project
  • Remove from Project: Gives a pop-up menu of files available for removal from project.
  • View Source: No matter which file you are editing, takes you back to the main program file (.lpr)or the main .pas file if there is no .lpr.
  • View ToDo List:Opens a dialog box with a list of ToDo items associated with this project. This will list any ToDo comments in your project (lines commencing //TODO), and any others in the Lazarus units you have used. You need to Refresh the ToDo items in the dialog (using arrow symbol button of toolbar) before new 'ToDos' appear. The first column of the ToDo list contains numbers you have allocated to your ToDo comments; a simple //TODO comment will appear as a zero, but a comment of //TODO999 (for example) will place the number 999 in the first column. Remember there should be no spaces on the line before //TODO and ToDo comments added after the last save will not be shown!

The Run sub-menu

  • Build: Causes Lazarus to build (ie compile) any files in the project that have been changed since the last build.
  • Build all: Builds all files in the project, whether or not there have been any changes.
  • Abort build: Stop the build process once it is running - either you have remembered that you did something silly and want to stop the build, or the system seems to be taking far too long and something is obviously wrong.
  • Run: This is the usual way to launch the compiler and, if compilation is successful, to start execution of the application. What actually happens is that Lazarus saves a copy of your files, then starts the compiler and linker, then begins execution of the final linked binary program.
  • Pause: Suspend execution of the currently running program. This may allow you to inspect any output that has been generated; execution may be resumed by selecting Run again.
  • Step into: Used in conjunction with the debugger, causes execution of the program one step at a time up to a bookmarked point in the source.
  • Step over: Causes stepwise execution up to the statement marked, then skips the marked statement, and continues execution at normal speed. Useful in trying to isolate a statement that introduces a logical error.
  • Run to cursor: Causes execution at normal speed (ie NOT one statement at a time) until the statement is reached where the cursor is located; then stops. Resume execution at normal speed by selecting Run.
  • Stop: Cease execution of the running program. Cannot be resumed by selecting Run; this will start the program again from the beginning (re-compiling if necessary).
  • Run Parameters: Opens a multi-page pop-up window which allows command-line options and parameters to be passed to the program to be executed; allows selection of display to run program (eg a remote X terminal may be used in Linux); some system Environment variables may be overridden.
One very important use of this sub-menu is to activate a terminal window in which conventional Pascal console input/output is displayed. If you are developing a console-mode Pascal program (ie one that doesn't use the Graphical User Interface with its forms, buttons and boxes) then you should check the box for "Use launching application". The first time you do this and try the Compile/Run sequence, you will probably get a rude message to say
"xterm: Can't execvp /usr/share/lazarus//tools/runwait.sh: Permission denied".  
If this happens, you need to change the permissions on the appropriate file (for example using chmod +x filename, or using the Windows utility for changing permissions); you might have to do this as root. After this, each time you launch you program, a console box will appear and all your text i/o (readln, writeln etc) will appear in it.
After your program has finished execution, a message "Press enter" appears on the screen. Thus any output your program generated will remain on the screen until you have had a chance to read it; after you press 'enter' the console window closes.
See the separate tutorial on Console Mode Pascal programming.
  • Reset debugger: Restores the debugger to its original state, so that breakpoints and values of variables etc are forgotten.
  • Build file: Compile (build) just the file that is currently open in the Editor.
  • Run file: Compile, link and execute just the currently open file.
  • Configure Build + Run File: Opens a multi-page tabbed window with options to allow for build of just this file when Build Project is selected, allows selection of the working directory, the use of various Macros, etc. Then Builds and Runs the file.
These last three options enable you to open (and maintain) a test project. Use File -> Open to open an .lpr file, pressing cancel on the next dialog to open this file as "normal source" file.

The Components sub-menu

  • Open Package: Displays a list of installed packages, with an invitation to open one or more of them, or to select various general or compiler options.
  • Open Package File: Open one of the files in the selected package.
  • Open Recent Package: Open a package that was opened recently.
  • Add Active Unit to Package: Place the unit file (currently in the editor) into a package.
  • Package Graph: Displays a graph showing the relationships of the packages currently being used (if you aren't using any other packages, the Lazarus package and the FCL and LCL will be displayed).
  • Configure custom components: If you have created some components, allows you to configure them.

The Tools sub-menu

  • Configure custom tools: Allows the user to add various external tools (usually macros) to the toolkit
  • Quick syntax check: Perform a quick check of the syntax in your source file without actually compiling anything. Essential step in developing long or complicated programs, where you don't want to waste time compiling if the code is wrong.
  • Guess unclosed block: useful utility if you have a complex nested block structure and you have left out an 'end' somewhere
  • guess misplaced IFDEF/ENDIF: useful if there is a complex or nested macro structure and you think you have left out an ENDIF directive
  • Make resource string: Makes the selected string a resource string by placing it in the resourcestrings section. An advantage of resource strongs is you can change them without the need to recompile your project!
  • Diff: Allows comparison between two files (or, usually, two versions of the same file) to find differences. Options to ignore white space at beginning or end of lines or differences in line termination: CR+LF versus LF). Useful for checking if there have been changes since last CVS update etc.
  • Check LFM file in editor: Allows inspection of the LFM file which contains the settings that describe the current form
  • Convert Delphi unit to Lazarus unit: Helps in porting Delphi applications to Lazarus; makes the necessary changes to the source file. See Lazarus For Delphi Users and Code Conversion Guide.
  • Convert DFM file to LFM: For porting from Delphi to Lazarus: converts the Form Description files from Delphi to Lazarus. See Lazarus For Delphi Users and Code Conversion Guide.
  • Build Lazarus: Launches a re-build of Lazarus from the most recently downloaded or updated CVS files. Hit the button and sit back to watch it happen! (track the process on your Messages window).
  • Configure "Build Lazarus": Allows the user to determine which parts of Lazarus should be re-built, and how. For example, you could select to have just the LCL re-built, or to have everything except the examples built; you can select which LCL interface to use (ie which set of widgets), and you can select the target operating system and specify a different target directory.

The Environment sub-menu

  • Environment options: Displays a multi-page window with tabs for
    • Files - allowing the user to specify path to default directory, compiler, source directory and temporary directory for compilation;
    • Desktop - options for Language, Auto save behaviour, saving desktop properties, hints for component palette and speed buttons;
    • Windows, to allow specification of size and behaviour of the various windows;
    • Form Editor - choose colours for editing forms;
    • Object Inspector - choose colour and height of items;
    • Backup - specify how to backup files when editing;
    • Naming - specify what extension to use in naming pascal files ('.pp' or '.pas'), whether to save files with names in lowercase, whether to perform auto-delete or auto-rename.
  • Editor options: Multi-page window, with tabs for
    • General - determines behaviour like auto-indent, bracket highlighting, drag-drop editing, scrolling, syntax highlighting, showing hints, size of block indent and tabs, limit of Undo;
    • Display - options for showing line numbers, presence of gutters, size and type of font for editor, and contains a preview panel showing the colours of the various syntax features such as comments, directives, punctuation, errors and breakpoints;
    • Key Mappings - options to select Lazarus or Turbo Pascal scheme;
    • Color - allows choice of colour scheme for text features, for a number of language types such as Object Pascal, C++, Perl, HTML, XML and shell scripts. It shows preview panel again (for whichever language is selected);
    • Code Tools - allows selection of features like Identifier Completion, tooltips, specification of template file names, specific templates for code completion.
  • Debugger Options: Multi-page window with tabs for
    • General - choose debugger: none, GNU debugger (gdb) or gdb through SSH, specify search paths for debuggers,and specific options for chosen debugger;
    • Event log - specify whether to clear log on run, and which messages to display;
    • Language Exceptions - select which exceptions can be ignored;
    • OS Exceptions - allows user to add certain signals which apply to current operating system (not implemented).
  • Code Tool Options: Multi-page window, tabs for
    • General - Allows entry of additional source search paths, specify Jumping Method;
    • Code Creation - determines whether created code is added before or after certain features;
    • Words - determines whether Pascal keywords are to be entered in upper or lower case, or as Capitalised Words;
    • Line Splitting - establish rules about where lines are allowed to be split (before or after punctuation, after keywords etc);
    • Space - decide whether a space is to be added automatically before or after certain syntactic features such as keywords or punctuation marks.
  • Code Tools Defines Editor: Here you can see all IDE internal definitions to parse sources. You will see all the defines, unit, source, include paths for all source directories. Beginning with the settings of the current FPC, the defines for the Lazarus Source directory, all package directories and project directories.

Most of these settings are auto generated and read only.


  • Re-scan FPC Source directory Looks through the directory again. Lazarus uses the fpc sources to generate correct event handlers and while looking for declarations. If somebody changes the directory in the environment options, then this directory is rescanned, to make sure lazarus uses the version stored in that location. But if this directory has changed without lazarus noticing, then you may get some errors when designing forms or doing "Find declaration". If you get such an error, you can do two things:
    1. Check the fpc source directory setting in the environment option.
    2. Re-scan FPC source directory.

The Windows sub-menu

Contains a list of the currently opened files and the available windows such as Source Editor, Object Inspector and Project Inspector. Clicking on the name of one of the windows brings it to the foreground and gives it focus.

The Help sub-menu

At present this has three selections:

  • Online Help which at present opens a browser window that contains a picture of the running cheetah and a few links to the Lazarus, FreePascal and WiKi websites
  • Configure Help which opens a pop-up menu with options to select viewers and databases from which to read Help information. This option allows the user to specify either the on-line documents section of the Lazarus-CCR website, some other website containing the documents, or a local store for the documentation (this would eventually become the default, when the Help system is fully developed).

At present by default, if you place your Editor cursor over any keyword from the FreePascal Components Library FCL or the RunTime Library RTL (but not the Lazarus Components Library LCL) and then press <<F1>> you will be taken to the appropriate definition on the website. THIS SECTION STILL REPRESENTS WORK IN PROGRESS

  • About Lazarus Displays a pop-up box with some information about Lazarus.

Eventually there will be a full on-line Help service, with information about Pascal syntax, the use of the IDE, how to use, modify or create Components, and hints on how to perform certain tasks. This part of the Documentation section (the thing you are currently reading) represents the beginning of the process. We need contributions from anyone who feels able to provide them: the WiKi is very easy to edit.

The Button bar

A small toolbar area on the left of the main editor window, just below the Main Menu and to the left of the Component Palette, contains a set of buttons which replicate frequently-used Main Menu selections:

New unit, Open (with a down-arrow to display a drop-down list of recently used files), Save, Save all, New Form, Toggle Form/Unit (ie show either form or source code of Unit), View Units, View Forms, Run (ie compile and Run), Pause, Step Into, Step over (the last two are Debugger functions).

The Component Palette

A Tabbed toolbar which displays a large number of icons representing commonly used components for building Forms.

Each tab causes the display of a different set of icons, representing a functional group of components. The left-most icon in each tabbed group is an obliquely leftward-facing arrow, called the Selection Tool.

If you allow the mouse cursor to hover over any of the icons on the Component Palette, without clicking on the icon, the title of that component will pop-up. Note that each title begins with a 'T' - this signifies 'Type' or more accurately 'Class' of the component. When you select a component for inclusion in a form, the Class is added to the type section of the interface part of the Unit (usually as part of the overall TForm1), and an instance of that class is added to the var section (usually as the variable Form1). Any Methods that you design to be used by the Form or its Components (ie Procedures or Functions) will be placed in the implementation part of the Unit

In the following list of the Components, you will find links to files that contain descriptions of the Units in which they are found. If you want to find out about the properties of a particular component, it is often worth looking at the Inheritance of that component and then inspecting the properties of the base type from which it is derived. For example, to understand TMaskEdit it is also useful to examine TCustomMaskEdit.

TABS (the names are largely self-explanatory):

Component Palette Standart.png
Frequently used components: TMainMenu, TPopupMenu, TButton, TLabel, TEdit, TMemo, TToggleBox, TCheckBox, TRadioButton, TListBox, TComboBox, TScrollBar, TGroupBox, TStaticText, TRadioGroup, TCheckGroup, TPanel, TActionList
Component Palette Additional.png
More, often-used components: TBitBtn, TSpeedButton, TImage, TShape, TBevel, TPaintBox, TNotebook, TLabeledEdit, TSplitter, TMaskEdit, TCheckListBox, TScrollBox, TApplicationProperties, TStringGrid, TDrawGrid, TPairSplitter
Component Palette Common Controls.png
TTrackBar, TProgressBar, TTreeView, TListView, TStatusBar, TToolBar, TUpDown, TPageControl, TImageList
Component Palette Dialogs.png
TOpenDialog, TSaveDialog, TSelectDirectoryDialog, TColorDialog, TFontDialog, TOpenPictureDialog, TSavePictureDialog, TCalendarDialog, TCalculatorDialog

Several useful Dialog procedures or functions don't appear on the Palette, but are easily used as direct calls from your source program.

For several good examples of the use of Components see the $LazarusPath/lazarus/examples subdirectory of your source installation. Many of the programs show how to use dialogs and other components directly without using the IDE and component palette or having a separate form definition file: all the components are fully and explicitly defined in the main Pascal program. Other example programs make full use of the IDE.

Some examples don't work straight away: you may need to play about with paths and permissions of files or directories. If you want to compile any of the examples, make sure that you have read/write/execute permissions for the files and directories, or copy the files to a directory where you do have the appropriate permissions.

Try running the 'testall' program to see a menu of the available components together with small example test forms for most of them; then inspect the code to find out how they work!

  • Misc
Component Palette Misc.png
TColorButton, TSpinEdit, TArrow, TCalendar, TEditButton, TFileNameEdit, TDirectoryEdit, TDateEdit, TCalcEdit, TFileListBox
  • Data Controls
Component Palette DataControls.png
Data-aware components, which largely replicate the Standard and Additional groups but are applicable to Databases: TDBNavigation, TDBText, TDBEdit, TDBMemo, TDBImage, TDBListBox,TDBComboBox, TDBCheckBox, TDBRadioGroup, TDBCalendar, TDBGroupBox, TdbGrid
  • Data Access
Component Palette DataAccess.png
TDatasource
  • System
Component Palette System.png
TTimer, TIdleTimer, TProcess
  • SynEdit
Component Palette SynEdit.png
A group of components to help interfacing with other languages and software tools. SynEdit is an advanced multi-line edit control, for Borland Delphi, Kylix and C++Builder. It supports Syntax Highlighting and code completion, and includes exporters for html, tex and rtf. It is a full-VCL/CLX control, meaning it is not a wrapper for Microsoft Windows controls, and no run-time library is required; this make SynEdit a crossplatform component. Compatibility with FreePascal is also planned, and SynEdit is the edit component in Lazarus IDE. see synedit at sourceforge. TSynEdit, TSynAutoComplete, TSynExporterHTML, TSynMacroRecorder, TSynMemo, TSynPasSyn, TSynCppSyn, TSynJavaSyn, TSynPerlSyn, TSynHTMLSyn, TSynXMLSyn, TSynLFMSyn, TSynUNIXShellScriptSyn, TSynCssSyn, TSynPHPSyn, TSynTeXSyn, TSynSQLSyn, TSynMultiSyn

To use the Palette, there must be an open form on view in the editor (if there isn't one, select File -> New Form). Click on the icon in the appropriate tab of the Palette for the component you want to use, then click on the Form, near where you want the component to appear. When the desired component appears, you can select it by clicking with the mouse, then move it to the exact place on the Form where you want it and adjust its size. Adjustments can be made to the appearance either by altering the picture itself on the Form using the mouse, or by changing the relevant Property in the Object Editor for that component.

If you install additional components, either those you have written yourself, or some coming as a package from some other source, then extra tabs with the relevant icons will appear in your Component Palette. These new components can be selected and used on your forms in the same way as those supplied by default.

The Debugger

Still to be written.

Файлы Lazarus

   (Благодарим Kevin Whitefoot.)
   (ДОбавления от Giuseppe Ridinò, User:Kirkpatc и Tom Lisjac)

Когда вы выполняете сохранение на самом деле вы сохраняете два файла:

  xxx.pas и yyy.lpr 

(Вы сохраняете и больше, но это те файлы, которым вы даете имена). Файл проекта (lpr) и файл модуля (pas) должны иметь разные имена, потому что Lazarus присваивает имя модулю (в исходном коде) также, как и имя файла модуля, а программе по имени файла проекта (это необходимо сделать иначе компилятор может впоследствии не найти модуль по ссылке на него в файле проекта). Во избежание противоречий (ошибок) следует изменить все упоминания Unit1 на xxx.

Итак, если вы сохранили проект под именем again, то попытка сохранить again.pas и again.lpr приведет к ошибке, потому что имена модуля и программы одинаковы, что приводит к ошибке двойного именования.

Ниже приведен пример именования:

e:/lazarus/kj/lazhello:

total 4740  free 76500
-rwxrwxrwx   1 kjwh     root  4618697 Mar 24 11:19 again.exe
-rw-rw-rw-   1 kjwh     root     3002 Mar 24 11:21 again.lpi
-rw-rw-rw-   1 kjwh     root      190 Mar 24 11:18 again.lpr
-rw-rw-rw-   1 kjwh     root      506 Mar 24 11:08 againu.lfm
-rw-rw-rw-   1 kjwh     root      679 Mar 24 11:08 againu.lrs
-rw-rw-rw-   1 kjwh     root      677 Mar 24 11:08 againu.pas
-rw-rw-rw-   1 kjwh     root     2124 Mar 24 11:08 againu.ppu
-rwxrwxrwx   1 kjwh     root      335 Mar 24 11:07 ppas.bat

Заметьте, что появилось более двух файлов, как следовало бы ожидать.

Ниже приведена краткая справка по каждому файлу:

again.exe: Основной исполняемый файл программы. Win32 добавляет расширение "exe". Linux этого не делает. В Linux это файл будет иметь большой размер вследствие того, что включает отладочную информацию. Запустите утилиту "strip" чтобы удалить ее и значительно снизить размер исполняемого файла.

again.lpi: Это основной файл проекта Lazarus (Lazarus Project Information); эквивалент основного файла приложения в Delphi с расширением .dpr. Он сохраняется в XML формате.

again.lpr: Исходный код основной программы. Не смотря на специфичноое для Lazarus расширение на самом деле это обычный Pascal-код. Он содержит строку Uses, помогающую компилятору найти все необходимые модули Отметим, что программа называется не аналогично имени данного файла.

againu.lfm: Это файл, в котором Lazarus хранит описание формы. Lazarus использует его для создания файла ресурсов, который включает секцию инициализации модуля againu.pas. Файл Delphi с расширением .dfm может быть преобразован в lfm-формат в IDE Lazarus из главного меню: Tools->Convert DFM file.

again.lrs: Это автоматически генерируемый файл ресурсов. Заметьте, что это не файл ресурсов Windows.

againu.pas: Модуль, содержащий код формы.

again.ppu: Это скомпилированный модуль.

ppas.bat: Это простой скрипт, связывающий программу для создания выполняемого файла. Если компиляция успешна, он удаляется компилятором.

Original contributors and changes

This page has been imported from the epikwiki version.

  • Created initial page and template. T. Lisjac - 11/04/2003 VlxAdmin
  • Inserted a note containing instructions for writing your first Lazarus Program. Suggest an administrator places it in the appropriate place on the Tutorial menu. 3/09/2004 User:Kirkpatc
  • Per above, moved Chris's writeup to the main body of the tutorial VlxAdmin
  • Began to insert text describing the Lazarus Editor - more to follow! 24 Mar 2004 User:Kirkpatc
  • Added some more to Lazarus Editor section of Tutorial. 25 Mar 2004 User:Kirkpatc
  • Added screenshots and revised some of the page formatting VlxAdmin 3/25/2004
  • Moved some of kwhitefoot's comments into Tutorial section. Formatting not quite right, but have to go to bed now! 26 Mar 2004 User:Kirkpatc
  • Formatted, added credits and comments. Removed original notes. VlxAdmin 3/26/2004
  • More material added to Editor section of tutorial. 26 Mar 2004 User:Kirkpatc
  • More material added describing the Main Menu. Renamed 'Hello World' to 'Getting Started' and moved it to nearer the top. 31 March 2004 User:Kirkpatc
  • Inserted section on Run sub-menu. Some general editing (eg ended each entry with a period to ensure consistency). 9 Apr 2004 User:Kirkpatc
  • Inserted a new section on How to get started with MySQL in FPC/Lazarus. 13 Apr 2004 User:Kirkpatc
  • Deleted the section on MySQL from here: it has been copied to Lazarus Database section of tutorial. 14 Apr 2004 User:Kirkpatc
  • Added some more to the description of the Editor Main Menu. 18 Apr 2004 User:Kirkpatc
  • Added section on Environment sub-menu. 19 Apr 2004 User:Kirkpatc
  • Added section on Components sub-menu. 4 May 2004 User:Kirkpatc
  • Adding Tools sub-menu description (incomplete). 7 May 2004 User:Kirkpatc
  • Added some screenshots to Menu descriptions. 9 May 2004 User:Kirkpatc
  • Fixed a bit in Environment Options - thanks VincentSnijders. 14 May 2004 User:Kirkpatc
  • More additions to Tools sub-menu. 19 May 2004 User:Kirkpatc
  • Added a section on the Button Bar and started work on The Component Palette. 20 May 2004 User:Kirkpatc
  • Posted a description file for the StdCtrls unit of the LCL, in the hope that people will add comments. 26 May 2004 User:Kirkpatc
  • Edited the StdCtrls file, removing a lot of repetitive material and doing some formatting. It is still far too long. 28 May 2004 User:Kirkpatc
  • Expanding on the Components Palette. 5 June 2004 User:Kirkpatc
  • Added a lot to the DialogExamples page. 10 June 2004 User:Kirkpatc
  • Considerable revision of the StdCtrls page, hopefully making it clearer and encouraging people to contribute - particularly in the 'Description' sections. 14 June 2004 User:Kirkpatc
  • Added pages for Menus and Dialogs units (linked to Component Palette description) - please feel free to add to these pages. 14 June 2004 User:Kirkpatc
  • Added page for Common Controls (linked to Component Palette). 16 June 2004 User:Kirkpatc
  • Added MaskEdit page (linked to Component Palette). 17 June 2004 User:Kirkpatc
  • Added Buttons, ExtCtrls pages (linked to Component Palette). 17 June 2004 User:Kirkpatc
  • Edited MainMenu component description page. 23 June 2004 User:Kirkpatc
  • Some additions to Common Controls. 28 June 2004 User:Kirkpatc
  • A new tutorial on Text-mode Pascal programming has been added. 5 July 2004 User:Kirkpatc
  • Minor changes to ComCtrls, ExtCtrls, Environment Menu. 10 July User:Kirkpatc
  • Added FormsTxt, component description page for Component Palette. 20 July 2004 User:Kirkpatc
  • Some corrections to ConsoleModePascal. 21 July 2004 User:Kirkpatc
  • Some small changes to ComponentPalette. 22 July 2004 User:Kirkpatc