KDevelop4/Manual/Working with source code/ru: Difference between revisions

From KDE Wiki Sandbox
No edit summary
(Updating to match new version of source page)
 
(60 intermediate revisions by 5 users not shown)
Line 11: Line 11:
Для работы с проектами в '''KDevelop''' используются ''инструменты''. Инструмент обеспечивает некоторое представление объекта с которым предназначен работать или действий, которые могут быть выполнены над ним. Инструменты представлены в виде кнопок, находящихся по краю окна (вертикально по левому или правому краям, либо горизонтально по нижнему краю). При нажатии на такую кнопку, в главном окне открывается служебная панель с инструментом. Если же нажать на эту кнопку снова — панель скроется.  
Для работы с проектами в '''KDevelop''' используются ''инструменты''. Инструмент обеспечивает некоторое представление объекта с которым предназначен работать или действий, которые могут быть выполнены над ним. Инструменты представлены в виде кнопок, находящихся по краю окна (вертикально по левому или правому краям, либо горизонтально по нижнему краю). При нажатии на такую кнопку, в главном окне открывается служебная панель с инструментом. Если же нажать на эту кнопку снова — панель скроется.  


{{Note/ru|1=Чтобы скрыть служебную панель можно также нажать кнопку <menuchoice>x</menuchoice> в правой части заголовка панели. Однако, по крайней мере в последних версиях '''KDevelop''' 4.2.x, это так же приведёт к исчезновению кнопки, представляющую инструмент на границе окна. Как вернуть потерянную кнопку обратно, равно как и кнопку любого другого инструмента, описано ниже. Данное поведение описано в отчёте об ошибках [http://bugs.kde.org/show_bug.cgi?id=270018 bug 270018]}}  
{{Note|1=To make a subwindow disappear, you can also click at the <menuchoice>x</menuchoice> at the top right of the subwindow.}}  


Изображение, приведённое выше, показывает служебные панели, расположенные по левому и правому краям. Панель '''Classes''' ('''Классы''' в русском переводе) открыта слева, а панель '''Snippets''' ('''Фрагменты''' в русском переводе) — справа от редактора исходного кода, размещённого в середине. На практике Вы вероятнее всего будете пользоваться преимущественно панелями '''Классы''' и '''Навигация по коду''', открытыми слева. Остальные панели вероятнее всего будут открываться на время необходимое для работы с ними, оставляя в основное рабочее время всё свободное пространство редактору кода.
Изображение, приведённое выше, показывает служебные панели, расположенные по левому и правому краям. Панель <menuchoice>Classes</menuchoice> (<menuchoice>Классы</menuchoice> в русском переводе) открыта слева, а панель <menuchoice>Snippets</menuchoice> (<menuchoice>Фрагменты</menuchoice> в русском переводе) — справа от редактора исходного кода, размещённого в середине. На практике Вы вероятнее всего будете пользоваться преимущественно панелями <menuchoice>Классы</menuchoice> и <menuchoice>Code Browser</menuchoice> (<menuchoice>Обозреватель кода</menuchoice> в русском переводе), открытыми слева. Остальные панели вероятнее всего будут открываться на время необходимое для работы с ними, оставляя в основное рабочее время всё свободное пространство редактору кода.


Когда Вы запустите '''KDevelop''', Вы должны увидеть кнопку панели инструментов <menuchoice>Проекты</menuchoice>. Нажав её, откроется окно панели, которая снизу отобразит проекты открытые в существующей сессии, а сверху иерархию директорий и файлов открытых проектов.
Когда Вы запустите '''KDevelop''', Вы должны увидеть кнопку панели инструментов <menuchoice>Проекты</menuchoice>. Нажав её, откроется окно панели, которая снизу отобразит проекты открытые в существующей сессии, а сверху иерархию директорий и файлов открытых проектов.


Есть много иных служебных панелей которые можно использовать в '''KDevelop''', кнопки которых не все изначально присутствуют на границах главного окна. Чтобы добавить интересующую панель следует выбрать пункт меню <menuchoice>Окно -> Добавить служебную панель</menuchoice>. Вот некоторые из тех, что могут оказаться полезными:
Есть много [[Special:myLanguage/KDevelop4/Manual/Tool_list|иных служебных панелей ]] которые можно использовать в '''KDevelop''', кнопки которых не все изначально присутствуют на границах главного окна. Чтобы добавить интересующую панель следует выбрать пункт меню <menuchoice>Окно -> Добавить служебную панель</menuchoice>. Вот некоторые из тех, что могут оказаться полезными:


* '''Classes''': A complete list of all classes that are defined in one of the projects or your session with all of their member functions and variables. Clicking on any of the members opens a source editor window at the location of the item you clicked on.
* '''Классы''': Полный список всех классов, определённых в одном из проектов или всей открытой сессии со всеми их методоми и свойствами. При двойном клике на любой из элементов, откроется редактор кода в месте объявления выбранного элемента.


* '''Documents''': Lists some of the more recently visited files, by kind (e.g. source files, patch files, plain text documents).
* '''Документы''': Список некоторых ранее просматриваемых файлов по видам (например, исходные файлы, патчи, текстовые документы)


* '''Code Browser''': Depending on your cursor position in a file, this tool shows things that are related. For example, if you are on an <code>#include</code> line, it shows information about the file you are including such as what classes are declared in that file; if you are on an empty line at file scope, it shows the classes and functions declared and defined in the current file (all as links: clicking on them brings you to the point in the file where the declaration or definition actually is); if you are in a function definition, it shows where the declaration is and offers a list of places where the function is used.
* '''Обозреватель кода''': в зависимости от положения курсора в файле, этот инструмент показывает вещи, которые связаны между собой. Например, если вы находитесь на <code>#include</code>, он покажет информацию о включаемом файле, вы в том числе, например, какие классы объявленные в том файле. Если вы находитесь на пустой строке, он показывает классы и функции, объявленные и определенных в текущем файле (все они представлены в виде ссылок: нажав на них, вы попадете в точку в файле, где находится их объявление или определение), если вы находитесь в определении функции, он показывает, где она объявлена и предлагает список мест, где функция используется.


* '''File system''': Shows you a tree view of the file system.
* '''Файловая система''': Показывает файловую систему в виде дерева.


* '''Documentation''': Allows you to search for man pages and other help documents.
* '''Документация''': Предлагает поиск man-страниц и другой документации.


* '''Snippets''': This provides sequences of text that one uses over an over and doesn't want to write every time. For example, in the project from which the picture above was created, there is a frequent need to write code like <br />
* '''Фрагменты''': предоставляет последовательности текста, который то и дело используется кем-то, кто не желает этот текст писать каждый раз. Например, в проекте, из которого был создан рисунок выше, существует частая необходимость в коде, как <br />
{{Input|1=<nowiki>for (typename Triangulation&lt; dim&gt;::active_cell_iterator cell
{{Input|1=<nowiki>for (typename Triangulation&lt; dim&gt;::active_cell_iterator cell
      = triangulation.begin_active();
    = triangulation.begin_active();
   cell != triangulation.end();
   cell != triangulation.end();
   ++cell)</nowiki>}}<br />This is an awkward expression but it will look almost exactly like this everytime you need such a loop &mdash; which would make it a good candidate for a snippet.
   ++cell)</nowiki>}}<br />Выражение является громоздким и будет выглядеть фактически именно так всякий раз, когда Вам нужен такой цикл. Для того, чтобы не писать его каждый раз и повторно использовать, это выражение является хорошим кандидатом быть фрагментом (от '''snippet''' (англ.) - фрагмент, отрывок).


* '''Konsole''': Opens a command line window inside '''KDevelop's''' main window, for the occasional command you may want to enter (e.g. to run <code>./configure</code>).
* '''Консоль''': открывает окно командной строки внутри основного окна '''KDevelop''' для ввода команд, которые Вы, может быть, время от времени хотите выполнять (например, запустить <code>./configure</code>)


A complete list of tools and views is given [[Special:myLanguage/KDevelop4/Manual/Tool list|here]].
Для большинства программистов самым важным является вертикальное пространство отображения на экране. В связи с этим Вы можете расположить Ваши инструменты в поле зрения по краям окна слева и справа: чтобы переместить инструмент, нажмите на его обозначение правой кнопкой мыши и выберите новое место для него.
 
For many programmers, vertical screen space is the most important. To this end, you can arrange your
tool views at the left and right margin of the window: to move a tool, click on its symbol with the right mouse button and select a new position for it.
<span id="Exploring source code"></span>
<span id="Exploring source code"></span>
=== Exploring source code ===
=== Анализ исходного кода ===


==== Local information ====
==== Локальные данные ====


'''KDevelop''' ''understands'' source code, and as a consequence it is really good at providing you information about variables or functions that may appear in your program. For example, here is a snapshot of working with a piece of code and hovering the mouse over the symbol <code>cell</code> in line 1316 (if you are working keyboard oriented, you can achieve the same effect by holding down the <keycap>Alt</keycap> key for a while):
'''KDevelop''' ''понимает'' исходный код, и, как следствие, надлежащим образом обеспечивает информацией о переменных и функциях, которые могут появиться в Вашей программе. Например, здесь есть рабочий снимок с фрагментом кода и наведением курсора мыши на символ <code>cell</code> в строке 1316 (если Вы работаете с приспособленной для этого клавиатурой, Вы можете достичь того же эффекта, нажав и удерживая клавишу <keycap>Alt</keycap>):


[[Image:kdevelop-13.png|thumb|600px|center]]
[[Image:kdevelop-13.png|thumb|600px|center]]


'''KDevelop''' shows me a tooltip that includes the type of the variable (here: <code>DoFHandler&lt;dim&gt;active_cell_iterator</code>), where this variable is declared (the ''container'', which here is the surrounding function <code>get_maximal_velocity</code> since it is a local variable), what it is (a variable, not a function, class or namespace) and where it is declared (in line 1314, just a few lines up in the code).
'''KDevelop''' показывает всплывающую подсказку с информацией о типе переменной (здесь: <code>DoFHandler&lt;dim&gt;active_cell_iterator</code>), где эта переменная объявлена (''контейнер'', здесь это выделенная функция <code>get_maximal_velocity</code>, так как это локальная переменная), что это (переменная; не функция, класс или пространство имён) и где это объявлено (в строке 1314, буквально несколько строк выше по тексту).


In the current context, the symbol over which the mouse was hovering has no associated documentation. In this example, had the mouse hovered over the symbol <code>get_this_mpi_process</code> in line 1318, the outcome would have been this:
В данной ситуации символ, на который был наведён курсор мыши, не имеет соотнесённой с ним информации. Если установить курсор мыши на <code>get_this_mpi_process</code> в строке 1318, то в результате получилось бы это:


[[Image:kdevelop-14.png|thumb|600px|center]]
[[Image:kdevelop-14.png|thumb|600px|center]]


Here, '''KDevelop''' has cross-referenced the declaration from an entirely different file (<code>utilities.h</code>, which in fact even resides in a different project of the same session) together with the doxygen-style comment that accompanies the declaration there.
Здесь '''KDevelop''' использовал перекрёстную ссылку на совершенно другой файл (<code>utilities.h</code>, который фактически даже находится в другом проекте того же сеанса) вместе с комментарием в формате doxygen, который там сопутствует объявлению.


What makes these tooltips even more useful is that they are dynamic: I can click on the container to get information about the context in which the variable is declared (i.e. about the namespace <code>System</code>, such as where it is declared, defined, used, or what its documentation is) and I can click on the blue links that will reset the cursor position to the location of the declaration of the Symbol (e.g. in <code>utilities.h</code>, line 289) or give me a list of places where this symbol is used in the current file or throughout all the projects of the current session. The latter is often useful if you want to explore how, for example, a particular function is used in a large code basis.
Ещё более полезными всплывающие подсказки делает то, что они являются динамическими: можно щёлкнуть по контейнеру для получения информации о контексте, где объявлена переменная (то есть данные о пространстве имён <code>System</code>, например то, где это объявлено, определено, использовано, или информацию о документации) и можно щёлкнуть по синим ссылкам, что установит курсор на позицию объявления символа (например, в <code>utilities.h</code>, строка 289) или покажет список мест, где этот символ используется в текущем файле или во всех проектах текущего сеанса. Последняя возможность будет полезной, если Вы хотите изучить, например, как используется отдельная функция в большой кодовой базе.


{{Note|1=The information in a tooltip is fleeting &mdash; it depends on you holding the <keycap>Alt</keycap> key down or hovering your mouse. If you want a more permanent place for it, open the '''Code Browser''' tool view in one of the sub-windows. For example, here the cursor is on the same function as in the example above, and the tool view on the left presents the same kind of information as in the tooltip before:<!--}}-->
{{Note/ru|1=Всплывающая подсказка с информацией быстро исчезает &mdash; всё зависит от удерживания нажатой клавиши <keycap>Alt</keycap> или наведения курсора мыши на фрагмент кода. Если Вы хотите зафиксировать данные из подсказки, откройте панель инструментов <menuchoice>Обозреватель кода</menuchoice>. Например, здесь курсор расположен на той же самой функции, как и раньше, а на панели инструментов слева показана та же информация, что и на подсказке:<!--}}-->


[[Image:kdevelop-15.png|thumb|500px|center]]
[[Image:kdevelop-15.png|thumb|500px|center]]


<!--{{-->Moving the cursor around on the right changes the information presented on the left. What's more, clicking on the <menuchoice>Lock current view</menuchoice> button at the top right allows you to lock this information, making it independent of the cursor movement while you explore the information presented there.}}
<!--{{-->Перемещение курсора в правой части окна будет приводить к изменению данных в его левой части. Нажав на кнопку <menuchoice>Lock current view</menuchoice> наверху справа, Вы сможете зафиксировать данные, оградив их от изменений из-за расположения курсора во время просмотра.}}


{{Note|1=This sort of context information is available in many other places in '''KDevelop''', not just in the source editor. For example, holding down the <keycap>Alt</keycap> key in a completion list (e.g. when doing a quick-open) also yields context information about the current symbol.}}
{{Note/ru|1=Доступ к контекстным данным такого типа можно получить из многих частей '''KDevelop''', не только из редактора текстов программ. Удерживание нажатой клавиши <keycap>Alt</keycap> в словаре для автоматического заполнения при написании кода (например, быстро открыв) также дает контекстную информацию для текущего символа.}}


==== File scope information ====
==== Информация относительно отдельного файла ====


The next level up is to obtain information about the entire source file you are currently working on. To this end, position the cursor at file scope in the current file and look at the what the '''Code Browser''' tool view shows:
Следующим этапом является получение информации о целом файле, содержащем текст программы, над которым Вы в настоящее время работаете. Для этого расположите курсор в области файла и  посмотрите на данные, которые будут показаны на служебной панели '''Обозреватель кода''':


[[Image:kdevelop-16.png|thumb|600px|center]]
[[Image:kdevelop-16.png|thumb|600px|center]]


Here, it shows a list of namespaces, classes and functions declared or defined in the current file, giving you an overview of what's happening in this file and a means to jump directly to any of these declarations or definitions without scrolling up and down in the file or searching for a particular symbol.
Здесь показан список пространств имён, классов и функций, объявленных или определённых в текущем файле. Этот список даёт Вам общее представление о том, какие действия выполняются в этом файле, обеспечивая средством непосредственного перехода к любому из этих объявлений или определений без надобности прокрутки по файлу или поиска определённого символа.


{{Note|1=The information shown for file scope is the same as presented in the "Outline" mode discussed below for navigating source code; the difference is that outline mode is only a temporary tooltip.}}
{{Note/ru|1=Эти данные по всему файлу совпадают с представленными данными в режиме "Обзор", обсуждение которого идёт ниже в разделе навигации в исходном коде. Разница состоит в том, что в режиме обзора информация отображается только на временной панели подсказок.}}


==== Project and session scope information ====
==== Информация относительно проекта и сеанса ====


There are many ways to obtain information about an entire project (or, in fact, about all projects in a session). This sort of information is typically provided through various tool views. For example, the '''Classes''' tool view provides a tree structure of all classes and surrounding namespaces for all projects in a session, together with the member functions and variables of each of these classes:
Существует много способов получить информацию о целом проекте (или, в действительности, обо всех проектах сеанса). Такого типа данные типичны для отображения на различных служебных панелях. Например, служебная панель <menuchoice>Классы</menuchoice> показывает древовидную структуру всех классов и окружающих пространств имён для всех проектов сеанса, вместе со встроенными функциями и переменными каждого из этих классов:


[[Image:kdevelop-17.png|thumb|600px|center]]
[[Image:kdevelop-17.png|thumb|600px|center]]
Line 86: Line 83:
Hovering over an entry provides again information about the symbol, its location of declaration and definition, and its uses. Double-clicking on an entry in this tree view opens an editor window at the location where the symbol is declared or defined.
Hovering over an entry provides again information about the symbol, its location of declaration and definition, and its uses. Double-clicking on an entry in this tree view opens an editor window at the location where the symbol is declared or defined.


But there are other ways of looking at global information. For example, the '''Documents''' tool provides a view of a project in terms of the kinds of files or other documents this project is comprised of:
But there are other ways of looking at global information. For example, the <menuchoice>Documents</menuchoice> tool provides a view of a project in terms of the kinds of files or other documents this project is comprised of:


[[Image:kdevelop-18.png|thumb|600px|center]]
[[Image:kdevelop-18.png|thumb|600px|center]]
==== Rainbow color highlighting explained ====
'''KDevelop''' uses a variety of colors to highlight different objects in source code. If you know what the different colors mean, you can very quickly extract a lot of information from source code just by looking at the colors, without reading a single character. The highlighting rules are as follows:
* Objects of type Class / Struct, Enum (the values and the type), (global) functions, and class members each have their own color assigned (classes are green, enums are dark red, and members are dark yellow or violet, (global) functions are always violet).
* All global variables are colored in dark green.
* Identifiers which are typedefs for another type are colored in teal.
* All declarations and definitions of objects are in bold.
* If a member is accessed from within the context where it is defined (base or derived class) it appears in yellow, otherwise it appears in violet.
* If a member is private or protected, it gets colored in a slightly darker color when used.
* For variables local to a function body scope, rainbow colors are picked based on a hash of the identifier. This includes the parameters to the function. An identifier always will have the same color within its scope (but the same identifier will get a different color if it represents a different object, i.e. if it is redefined in a more nested scope), and you will usually get the same color for the same identifier name in different scopes. Thus, if you have multiple functions taking parameters with the same names, the arguments will all look the same color-wise.
* Identifiers for which '''KDevelop''' could not determine the corresponding declaration are colored in white. This can sometimes be caused by missing <code>#include</code> directives.
* In addition to that coloring, the normal editor syntax highlighting will be applied, as known from '''Kate'''. '''KDevelop's''' semantic highlighting will always override the editor highlighting if there is a conflict.
{{Note| Rainbow coloring of local variables can be turned off in <menuchoice>Settings...->Configure KDevelop...->Language Support->Local colorization intensity</menuchoice> by setting the slider control to its minimum value. Similarly colorization of global variables, global functions, classes, structs, enums, and class members can be turned off in <menuchoice>Settings...->Configure KDevelop...->Language Support->Global colorization intensity</menuchoice> }}
<span id="Navigating in source code"></span>
<span id="Navigating in source code"></span>
=== Navigating in source code ===
=== Navigating in source code ===
Line 106: Line 127:
* '''Outline''': You can get an outline of what's in the current file in at least three different ways:
* '''Outline''': You can get an outline of what's in the current file in at least three different ways:
** Clicking into the <menuchoice>Outline</menuchoice> textbox at the top right of the main window, or hitting <keycap>Alt + Ctrl + N</keycap> opens a drop-down menu that lists all function and class declarations: [[Image:kdevelop-19.png|thumb|600px|center]] You can then just select which one to jump to, or &mdash; if there are a lot &mdash; start typing any text that may appear in the names shown; in that case, as you keep typing, the list becomes smaller and smaller as names are removed that don't match the text already typed until you are ready to select one of the choices.
** Clicking into the <menuchoice>Outline</menuchoice> textbox at the top right of the main window, or hitting <keycap>Alt + Ctrl + N</keycap> opens a drop-down menu that lists all function and class declarations: [[Image:kdevelop-19.png|thumb|600px|center]] You can then just select which one to jump to, or &mdash; if there are a lot &mdash; start typing any text that may appear in the names shown; in that case, as you keep typing, the list becomes smaller and smaller as names are removed that don't match the text already typed until you are ready to select one of the choices.
** Positioning the cursor at file scope (i.e. outside any function or class declarations or definitions) and having the '''Code Browser''' tool open: [[Image:kdevelop-16.png|thumb|600px|center]] This also provides you an outline of what is happening in the current file, and allows you to select where you want to jump to.
** Positioning the cursor at file scope (i.e. outside any function or class declarations or definitions) and having the <menuchoice>Code Browser</menuchoice> tool open: [[Image:kdevelop-16.png|thumb|600px|center]] This also provides you an outline of what is happening in the current file, and allows you to select where you want to jump to.
** Hovering the mouse over the tab for one of the open files also yields an outline of the file in that tab.
** Hovering the mouse over the tab for one of the open files also yields an outline of the file in that tab.


Line 133: Line 154:
* '''Previous/Next use''': Placing the cursor on the name of a local variable and selecting <menuchoice>Navigation -> Next use</menuchoice> (or hitting <keycap>Meta + Shift + Right</keycap>) transports you to the next use of this variable in the code. (Note that this doesn't just search for the next occurrence of the variable name but in fact takes into account that variables with the same name but in different scopes are different.) The same works for the use of function names. Selecting <menuchoice>Navigation -> Previous use</menuchoice> (or hitting <keycap>Meta + Shift + Left</keycap>) transports you to the previous use of a symbol.
* '''Previous/Next use''': Placing the cursor on the name of a local variable and selecting <menuchoice>Navigation -> Next use</menuchoice> (or hitting <keycap>Meta + Shift + Right</keycap>) transports you to the next use of this variable in the code. (Note that this doesn't just search for the next occurrence of the variable name but in fact takes into account that variables with the same name but in different scopes are different.) The same works for the use of function names. Selecting <menuchoice>Navigation -> Previous use</menuchoice> (or hitting <keycap>Meta + Shift + Left</keycap>) transports you to the previous use of a symbol.


{{Note|1=To see the list of all uses of a name through which these commands cycle, place the cursor onto it and open the '''Code Browser''' tool view or press and hold the <keycap>Alt</keycap> button. This is explained in more detail in the section on [[Special:myLanguage/KDevelop4/Manual/Working_with_source_code#File_scope_information|Exploring code]].}}
{{Note|1=To see the list of all uses of a name through which these commands cycle, place the cursor onto it and open the <menuchoice>Code Browser</menuchoice> tool view or press and hold the <keycap>Alt</keycap> button. This is explained in more detail in the section on [[Special:myLanguage/KDevelop4/Manual/Working_with_source_code#File_scope_information|Exploring code]].}}


* The '''context list''': Web browsers have this feature where you can go backward and forward in the list of most recently visited web pages. '''KDevelop''' has the same kind of features, except that instead of web pages you visit ''contexts''. A context is the current location of the cursor, and you change it by navigating away from it using anything but cursor commands &mdash; for example, by clicking on a location provided by a tooltip, in the '''Code Browser''' tool view, one of the options given in the <menuchoice>Navigation</menuchoice> menu, or any other navigation command. Using the <menuchoice>Navigation -> Previous Visited Context</menuchoice> (<keycap>Meta + Left</keycap>) and <menuchoice>Navigation -> Next Visited Context</menuchoice> (<keycap>Meta + Right</keycap>) transports you along this list of visited contexts just like the <menuchoice>back</menuchoice> and <menuchoice>forward</menuchoice> buttons of a browser transports you to the previous or next webpage in the list of visited pages.
{{Note|Some shortcuts might be used already by your window manager (e.g. <keycap>Meta + Left</keycap> is used by LXDE/Openbox); you can either change the key combination for the shortcut in kdevelop <menuchoice>Settings...->Configure Shortcuts</menuchoice> or in the window manager config (e.g. .config/openbox/lubuntu-rc.xml)}}


* Finally, there are tool views that allow you to navigate to different places in your code base. For example, the '''Classes''' tool provides you with a list of all namespaces and classes in all projects of the current session, and allows you to expand it to see member functions and variables of each of these classes: [[Image:kdevelop-17.png|thumb|500px|center]] Double-clicking on an item (or going through the context menu using the right mouse button) allows you to jump to the location of the declaration of the item. Other tools allow similar things; for example, the '''Projects''' tool view provides a list of files that are part of a session: [[Image:kdevelop-13.png|thumb|500px|center]] Again, double-clicking on a file opens it.
* The '''context list''': Web browsers have this feature where you can go backward and forward in the list of most recently visited web pages. '''KDevelop''' has the same kind of features, except that instead of web pages you visit ''contexts''. A context is the current location of the cursor, and you change it by navigating away from it using anything but cursor commands &mdash; for example, by clicking on a location provided by a tooltip, in the <menuchoice>Code Browser</menuchoice> tool view, one of the options given in the <menuchoice>Navigation</menuchoice> menu, or any other navigation command. Using the <menuchoice>Navigation -> Previous Visited Context</menuchoice> (<keycap>Meta + Left</keycap>) and <menuchoice>Navigation -> Next Visited Context</menuchoice> (<keycap>Meta + Right</keycap>) transports you along this list of visited contexts just like the <menuchoice>back</menuchoice> and <menuchoice>forward</menuchoice> buttons of a browser transports you to the previous or next webpage in the list of visited pages.
 
* Finally, there are tool views that allow you to navigate to different places in your code base. For example, the '''Classes''' tool provides you with a list of all namespaces and classes in all projects of the current session, and allows you to expand it to see member functions and variables of each of these classes: [[Image:kdevelop-17.png|thumb|500px|center]] Double-clicking on an item (or going through the context menu using the right mouse button) allows you to jump to the location of the declaration of the item. Other tools allow similar things; for example, the <menuchoice>Projects</menuchoice> tool view provides a list of files that are part of a session: [[Image:kdevelop-13.png|thumb|500px|center]] Again, double-clicking on a file opens it.




Line 183: Line 206:
==== Adding new classes and implementing member functions ====
==== Adding new classes and implementing member functions ====


'''KDevelop''' has a wizard for adding new classes. To add a new class, select <menuchoice>Code -> Create New Class</menuchoice> to get the following dialog box:
'''KDevelop''' has an assistant for adding new classes. The procedure is described in [[Special:myLanguage/KDevelop4/Manual/Code generation with templates#Creating a new class|Creating a new class]].  A simple C++ class can be created by choosing the Basic C++ template from the <tt>Class</tt> category. In the assistant, we can choose some predefined member functions, for example an empty constructor, a copy constructor and a destructor.
 
[[Image:kdevelop-27.png|thumb|400px|center]]
 
Here, we have entered the new class's name <code>Bus</code> (you can also enter here which other classes this class should be derived from). The next page of the dialog allows us to select the standard member functions we will need:


[[Image:kdevelop-28.png|thumb|400px|center]]
After completing the assistant, the new files are created and opened in the editor. The header file already has include guards and the new class has all the member functions we selected. The next two steps would be to document the class and its member functions and to implement them. We will discuss aids for documenting classes and functions below. To implement the special functions already added, simply go to the <menuchoice>bus.cpp</menuchoice> tab where the skeleton of functions are already provided:
 
Here, we want a default constructor, a copy constructor, and a destructor. After the following pages of the dialog that allow you to select a license header and the location for the new files, '''KDevelop''' will generate two new tabs with the header and source files:
 
[[Image:kdevelop-29.png|thumb|500px|center]]
 
 
The header file already has include guards and the new class has all the member functions we selected. The next two steps would be to document the class and its member functions and to implement them. We will discuss aids for documenting classes and functions below. To implement the special functions already added, simply go to the <menuchoice>bus.cpp</menuchoice> tab where the skeleton of functions are already provided:


[[Image:kdevelop-30.png|thumb|500px|center]]
[[Image:kdevelop-30.png|thumb|500px|center]]
Line 227: Line 239:


[[Image:kdevelop-37.png|thumb|500px|center]]
[[Image:kdevelop-37.png|thumb|500px|center]]
{{Note|1=The fact that the tooltip shows the same function twice is fixed in '''KDevelop''' 4.2.2 and later.}}
{{Note|1=In the example, accepting one of the choices the auto-completion tool offers yields the correct signature but unfortunately deletes the <code>inline</code> marker already written. This has been reported as [https://bugs.kde.org/show_bug.cgi?id=274244 KDevelop Bug 274245].}}


==== Documenting declarations ====
==== Documenting declarations ====


Good code is well documented, both at the level of the implementation of algorithms within in functions as well as at the level of the interface &mdash; i.e., classes, (member and global) functions, and (member or global) variables need to be documented to explain their intent, possible values of arguments, pre- and postconditions, etc. As far as documenting the interface is concerned, [http://www.doxygen.org doxygen] has become the de facto standard for formatting comments that can then be extracted and displayed on searchable webpages.
Good code is well documented, both at the level of the implementation of algorithms within functions, as well as at the level of the interface &mdash; i.e., classes, (member and global) functions, and (member or global) variables need to be documented to explain their intent, possible values of arguments, pre- and postconditions, etc. As far as documenting the interface is concerned, [http://www.doxygen.org doxygen] has become the de facto standard for formatting comments that can then be extracted and displayed on searchable webpages.


'''KDevelop''' supports this style of comments by providing a short cut to generate the framework of comments that document a class or member function. For example, assume you have already written this code:
'''KDevelop''' supports this style of comments by providing a short cut to generate the framework of comments that document a class or member function. For example, assume you have already written this code:
Line 293: Line 300:
</syntaxhighlight>}}
</syntaxhighlight>}}


Rather than typing this kind of text over and over again (with all the concomitant typos one introduces), the '''Snippets''' tool of '''KDevelop''' can help here. To this end, open the tool view (see [[Special:myLanguage/KDevelop4/Manual/Working with source code#Tools and views|Tools and views]] if the corresponding button isn't already on the perimeter of your window). Then click on the "Add repository" button (a slight misnomer &mdash; it allows you to create a named collection of snippets for source codes of a particular kind, e.g. C++ sources) and create an empty repository. Then click {{Plus}} to add a snippet, to get a dialog like the following:
Rather than typing this kind of text over and over again (with all the concomitant typos one introduces), the <menuchoice>Snippets</menuchoice> tool of '''KDevelop''' can help here. To this end, open the tool view (see [[Special:myLanguage/KDevelop4/Manual/Working with source code#Tools and views|Tools and views]] if the corresponding button isn't already on the perimeter of your window). Or, go to <menuchoice>Window -> Tool views</menuchoice> in the top menubar, and turn on <menuchoice>Snippets</menuchoice>. Then click on the <menuchoice>Add repository</menuchoice>button (a slight misnomer &mdash; it allows you to create a named collection of snippets for source codes of a particular kind, e.g. C++ sources) and create an empty repository. Then click {{Plus}} to add a snippet, to get a dialog like the following:


[[Image:kdevelop-40.png|thumb|500px|center]]
[[Image:kdevelop-40.png|thumb|500px|center]]


{{Note|1=The name of a snippet may not have spaces or other special characters because it must look like a normal function or variable name (for reasons that will become clear in the next paragraph). If the name of the snippet does contain spaces, the <menuchoice>OK</menuchoice> button will become inactive without any further explanation. This has been reported as [https://bugs.kde.org/show_bug.cgi?id=274299 KDevelop bug 274299].}}
{{Note|1=The name of a snippet may not have spaces or other special characters because it must look like a normal function or variable name (for reasons that will become clear in the next paragraph). If the name of the snippet does contain spaces, the <menuchoice>OK</menuchoice> button will become inactive without any further explanation. This has been fixed in recent versions of KDevelop (see [https://bugs.kde.org/show_bug.cgi?id=274299 KDevelop bug 274299]).}}


To use a snippet so defined, when you are editing code, you can just type the name of the snippet like you would any other function or variable name. This name will become available for auto-completion &mdash; which means that there is no harm in using a long and descriptive name for a snippet such as the one above &mdash; and when you accept the suggestion of the auto-completion tooltip (for example by just hitting <keycap>Enter</keycap>), the already entered part of the snippets' name will be replaced by the full expansion of the snippet and will be properly indented:
To use a snippet so defined, when you are editing code, you can just type the name of the snippet like you would any other function or variable name. This name will become available for auto-completion &mdash; which means that there is no harm in using a long and descriptive name for a snippet such as the one above &mdash; and when you accept the suggestion of the auto-completion tooltip (for example by just hitting <keycap>Enter</keycap>), the already entered part of the snippets' name will be replaced by the full expansion of the snippet and will be properly indented:
Line 303: Line 310:
[[Image:kdevelop-41.png|thumb|500px|center]]
[[Image:kdevelop-41.png|thumb|500px|center]]


Note that for this to work, the '''Snippets''' tool view need not be open or visible: you only ever need the tool view to define new snippets. An alternative, if less convenient, way to expand a snippet is to simply click on it in the respective tool view.
Note that for this to work, the <menuchoice>Snippets</menuchoice> tool view need not be open or visible: you only ever need the tool view to define new snippets. An alternative, if less convenient, way to expand a snippet is to simply click on it in the respective tool view.


{{Note|1=Snippets are much more powerful than just explained. For a full description of what you can do with them, see the [[Special:myLanguage/KDevelop4/Manual/Tool_list/Snippets|detailed documentation of the Snippets tool]].}}<span id="Modes and working sets"></span>
{{Note|1=Snippets are much more powerful than just explained. For a full description of what you can do with them, see the [[Special:myLanguage/KDevelop4/Manual/Tool_list/Snippets|detailed documentation of the Snippets tool]].}}<span id="Modes and working sets"></span>
Line 428: Line 435:


{{Prevnext2
{{Prevnext2
| prevpage=Special:MyLanguage/KDevelop4/Manual/Sessions_and_projects | nextpage=Special:MyLanguage/KDevelop4/Manual/Building_(compiling)_projects_with_custom_Makefiles
| prevpage=Special:MyLanguage/KDevelop4/Manual/Sessions_and_projects | nextpage=Special:MyLanguage/KDevelop4/Manual/Code_generation_with_templates
| prevtext=Sessions and projects | nexttext=Building (compiling) projects with custom Makefiles
| prevtext=Sessions and projects | nexttext=Code generation with templates
| index=Special:MyLanguage/KDevelop4/Manual | indextext=Back to menu
| index=Special:MyLanguage/KDevelop4/Manual | indextext=Back to menu
}}
}}


[[Category:Development]]
[[Category:Разработка/ru]]

Latest revision as of 13:00, 14 July 2018

Other languages:

Работа с исходным кодом

Отладка, чтение и написание исходного кода — это то, на что у Вас будет уходить основное время при разработке программного обеспечения. С этой целью KDevelop предоставляет Вам множество различных возможностей в изучении исходного кода и более продуктивном его написании. В следующих разделах рассказывается что KDevelop является не только редактором исходного кода — он скорее является системой управления исходным кодом, которая даёт Вам различные представления информации о содержимом файлов с исходным кодом, которые в совокупности представляют собой сеансы.

Инструменты и служебные панели

Для работы с проектами в KDevelop используются инструменты. Инструмент обеспечивает некоторое представление объекта с которым предназначен работать или действий, которые могут быть выполнены над ним. Инструменты представлены в виде кнопок, находящихся по краю окна (вертикально по левому или правому краям, либо горизонтально по нижнему краю). При нажатии на такую кнопку, в главном окне открывается служебная панель с инструментом. Если же нажать на эту кнопку снова — панель скроется.

Note
To make a subwindow disappear, you can also click at the x at the top right of the subwindow.


Изображение, приведённое выше, показывает служебные панели, расположенные по левому и правому краям. Панель Classes (Классы в русском переводе) открыта слева, а панель Snippets (Фрагменты в русском переводе) — справа от редактора исходного кода, размещённого в середине. На практике Вы вероятнее всего будете пользоваться преимущественно панелями Классы и Code Browser (Обозреватель кода в русском переводе), открытыми слева. Остальные панели вероятнее всего будут открываться на время необходимое для работы с ними, оставляя в основное рабочее время всё свободное пространство редактору кода.

Когда Вы запустите KDevelop, Вы должны увидеть кнопку панели инструментов Проекты. Нажав её, откроется окно панели, которая снизу отобразит проекты открытые в существующей сессии, а сверху иерархию директорий и файлов открытых проектов.

Есть много иных служебных панелей которые можно использовать в KDevelop, кнопки которых не все изначально присутствуют на границах главного окна. Чтобы добавить интересующую панель следует выбрать пункт меню Окно -> Добавить служебную панель. Вот некоторые из тех, что могут оказаться полезными:

  • Классы: Полный список всех классов, определённых в одном из проектов или всей открытой сессии со всеми их методоми и свойствами. При двойном клике на любой из элементов, откроется редактор кода в месте объявления выбранного элемента.
  • Документы: Список некоторых ранее просматриваемых файлов по видам (например, исходные файлы, патчи, текстовые документы)
  • Обозреватель кода: в зависимости от положения курсора в файле, этот инструмент показывает вещи, которые связаны между собой. Например, если вы находитесь на #include, он покажет информацию о включаемом файле, вы в том числе, например, какие классы объявленные в том файле. Если вы находитесь на пустой строке, он показывает классы и функции, объявленные и определенных в текущем файле (все они представлены в виде ссылок: нажав на них, вы попадете в точку в файле, где находится их объявление или определение), если вы находитесь в определении функции, он показывает, где она объявлена и предлагает список мест, где функция используется.
  • Файловая система: Показывает файловую систему в виде дерева.
  • Документация: Предлагает поиск man-страниц и другой документации.
  • Фрагменты: предоставляет последовательности текста, который то и дело используется кем-то, кто не желает этот текст писать каждый раз. Например, в проекте, из которого был создан рисунок выше, существует частая необходимость в коде, как
for (typename Triangulation< dim>::active_cell_iterator cell
     = triangulation.begin_active();
   cell != triangulation.end();
   ++cell)


Выражение является громоздким и будет выглядеть фактически именно так всякий раз, когда Вам нужен такой цикл. Для того, чтобы не писать его каждый раз и повторно использовать, это выражение является хорошим кандидатом быть фрагментом (от snippet (англ.) - фрагмент, отрывок).

  • Консоль: открывает окно командной строки внутри основного окна KDevelop для ввода команд, которые Вы, может быть, время от времени хотите выполнять (например, запустить ./configure)

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

Анализ исходного кода

Локальные данные

KDevelop понимает исходный код, и, как следствие, надлежащим образом обеспечивает информацией о переменных и функциях, которые могут появиться в Вашей программе. Например, здесь есть рабочий снимок с фрагментом кода и наведением курсора мыши на символ cell в строке 1316 (если Вы работаете с приспособленной для этого клавиатурой, Вы можете достичь того же эффекта, нажав и удерживая клавишу Alt):

KDevelop показывает всплывающую подсказку с информацией о типе переменной (здесь: DoFHandler<dim>active_cell_iterator), где эта переменная объявлена (контейнер, здесь это выделенная функция get_maximal_velocity, так как это локальная переменная), что это (переменная; не функция, класс или пространство имён) и где это объявлено (в строке 1314, буквально несколько строк выше по тексту).

В данной ситуации символ, на который был наведён курсор мыши, не имеет соотнесённой с ним информации. Если установить курсор мыши на get_this_mpi_process в строке 1318, то в результате получилось бы это:

Здесь KDevelop использовал перекрёстную ссылку на совершенно другой файл (utilities.h, который фактически даже находится в другом проекте того же сеанса) вместе с комментарием в формате doxygen, который там сопутствует объявлению.

Ещё более полезными всплывающие подсказки делает то, что они являются динамическими: можно щёлкнуть по контейнеру для получения информации о контексте, где объявлена переменная (то есть данные о пространстве имён System, например то, где это объявлено, определено, использовано, или информацию о документации) и можно щёлкнуть по синим ссылкам, что установит курсор на позицию объявления символа (например, в utilities.h, строка 289) или покажет список мест, где этот символ используется в текущем файле или во всех проектах текущего сеанса. Последняя возможность будет полезной, если Вы хотите изучить, например, как используется отдельная функция в большой кодовой базе.

Примечание
Всплывающая подсказка с информацией быстро исчезает — всё зависит от удерживания нажатой клавиши Alt или наведения курсора мыши на фрагмент кода. Если Вы хотите зафиксировать данные из подсказки, откройте панель инструментов Обозреватель кода. Например, здесь курсор расположен на той же самой функции, как и раньше, а на панели инструментов слева показана та же информация, что и на подсказке:
Перемещение курсора в правой части окна будет приводить к изменению данных в его левой части. Нажав на кнопку Lock current view наверху справа, Вы сможете зафиксировать данные, оградив их от изменений из-за расположения курсора во время просмотра.


Примечание
Доступ к контекстным данным такого типа можно получить из многих частей KDevelop, не только из редактора текстов программ. Удерживание нажатой клавиши Alt в словаре для автоматического заполнения при написании кода (например, быстро открыв) также дает контекстную информацию для текущего символа.


Информация относительно отдельного файла

Следующим этапом является получение информации о целом файле, содержащем текст программы, над которым Вы в настоящее время работаете. Для этого расположите курсор в области файла и посмотрите на данные, которые будут показаны на служебной панели Обозреватель кода:

Здесь показан список пространств имён, классов и функций, объявленных или определённых в текущем файле. Этот список даёт Вам общее представление о том, какие действия выполняются в этом файле, обеспечивая средством непосредственного перехода к любому из этих объявлений или определений без надобности прокрутки по файлу или поиска определённого символа.

Примечание
Эти данные по всему файлу совпадают с представленными данными в режиме "Обзор", обсуждение которого идёт ниже в разделе навигации в исходном коде. Разница состоит в том, что в режиме обзора информация отображается только на временной панели подсказок.


Информация относительно проекта и сеанса

Существует много способов получить информацию о целом проекте (или, в действительности, обо всех проектах сеанса). Такого типа данные типичны для отображения на различных служебных панелях. Например, служебная панель Классы показывает древовидную структуру всех классов и окружающих пространств имён для всех проектов сеанса, вместе со встроенными функциями и переменными каждого из этих классов:

Hovering over an entry provides again information about the symbol, its location of declaration and definition, and its uses. Double-clicking on an entry in this tree view opens an editor window at the location where the symbol is declared or defined.

But there are other ways of looking at global information. For example, the Documents tool provides a view of a project in terms of the kinds of files or other documents this project is comprised of:

Rainbow color highlighting explained

KDevelop uses a variety of colors to highlight different objects in source code. If you know what the different colors mean, you can very quickly extract a lot of information from source code just by looking at the colors, without reading a single character. The highlighting rules are as follows:

  • Objects of type Class / Struct, Enum (the values and the type), (global) functions, and class members each have their own color assigned (classes are green, enums are dark red, and members are dark yellow or violet, (global) functions are always violet).
  • All global variables are colored in dark green.
  • Identifiers which are typedefs for another type are colored in teal.
  • All declarations and definitions of objects are in bold.
  • If a member is accessed from within the context where it is defined (base or derived class) it appears in yellow, otherwise it appears in violet.
  • If a member is private or protected, it gets colored in a slightly darker color when used.
  • For variables local to a function body scope, rainbow colors are picked based on a hash of the identifier. This includes the parameters to the function. An identifier always will have the same color within its scope (but the same identifier will get a different color if it represents a different object, i.e. if it is redefined in a more nested scope), and you will usually get the same color for the same identifier name in different scopes. Thus, if you have multiple functions taking parameters with the same names, the arguments will all look the same color-wise.
  • Identifiers for which KDevelop could not determine the corresponding declaration are colored in white. This can sometimes be caused by missing #include directives.
  • In addition to that coloring, the normal editor syntax highlighting will be applied, as known from Kate. KDevelop's semantic highlighting will always override the editor highlighting if there is a conflict.
Note
Rainbow coloring of local variables can be turned off in Settings...->Configure KDevelop...->Language Support->Local colorization intensity by setting the slider control to its minimum value. Similarly colorization of global variables, global functions, classes, structs, enums, and class members can be turned off in Settings...->Configure KDevelop...->Language Support->Global colorization intensity

Navigating in source code

In the previous section, we have discussed exploring source code, i.e. getting information about symbols, files and projects. The next step is then to jump around your source base, i.e. to navigate in it. There are again various levels at which this is possible: local, within a file, and within a project.

Note
Many of the ways to navigate through code are accessible from the Navigate menu in the KDevelop main window.


Local navigation

KDevelop is much more than an editor, but it is also a source editor. As such, you can of course move the cursor up, down, left or right in a source file. You can also use the PageUp and PageDown keys, and all the other commands you are used from any useful editor.

File scope navigation and outline mode

At the file scope, KDevelop offers many possible ways to navigate through source code. For example:

  • Outline: You can get an outline of what's in the current file in at least three different ways:
    • Clicking into the Outline textbox at the top right of the main window, or hitting Alt + Ctrl + N opens a drop-down menu that lists all function and class declarations:
      You can then just select which one to jump to, or — if there are a lot — start typing any text that may appear in the names shown; in that case, as you keep typing, the list becomes smaller and smaller as names are removed that don't match the text already typed until you are ready to select one of the choices.
    • Positioning the cursor at file scope (i.e. outside any function or class declarations or definitions) and having the Code Browser tool open:
      This also provides you an outline of what is happening in the current file, and allows you to select where you want to jump to.
    • Hovering the mouse over the tab for one of the open files also yields an outline of the file in that tab.
  • Source files are organized as a list of function declarations or definitions. Hitting Alt + Ctrl + PgUp and Alt + Ctrl + PgDown jumps to the previous or next function definition in this file.

Project and session scope navigation: Semantic navigation

As mentioned in other places, KDevelop does not usually consider individual source files but rather looks at projects as a whole (or, rather, at all projects that are part of the current session). As a consequence, it offers many possibilities for navigating through entire projects. Some of these are derived from what we have already discussed in the section on Exploring source code while others are genuinely different. The common theme is that these navigation features are based on a semantic understanding of the code, i.e. they offer you something that requires parsing entire projects and connecting data. The following list shows some ways how to navigate through source code that is scattered throughout a potentially very large number of files:

  • As seen in the section on Exploring source code, you can get a tooltip explaining individual namespace, class, function or variable names by hovering your mouse over it or keeping the Alt key pressed for a while. Here is an example:
    Clicking on the links for the declaration of a symbol or expanding the list of uses allows you to jump to these locations, if necessary opening the respective file and placing the cursor at the corresponding location. A similar effect can be achieved by using the Code Browser tool view also discussed previously.
  • Quick open: A very powerful way of jumping to other files or locations is to use the various quick open methods in KDevelop. There are four versions of these:
    • Quick open class (Navigate -> Quick open class or Alt + Ctrl + C): You will get a list of all classes in this session. Start typing (a part of) the name of a class and the list will continue to whittle down to only those that actually match what you've typed so far. If the list is short enough, select an element using the up and down keys and KDevelop will get you to the place where the class is declared.
    • Quick open function (Navigate -> Quick open function or Alt + Ctrl + M): You will get a list of all (member) functions that are part of the projects in the current session, and you can select from it in the same way as above. Note that this list may include both function declarations and definitions.
    • Quick open file (Navigate -> Quick open file or Alt + Ctrl + O): You will get a list of all files that are part of the projects in the current session, and you can select from it in the same way as above.
    • Universal quick open (Navigate -> Quick open or Alt + Ctrl + Q): If you forget which key combination is bound to which of the above commands, this is the universal swiss army knife — it simply presents you with a combined list of all files, functions, classes, and other things from which you can select.
  • Jump to declaration/definition: When implementing a (member) function, one often needs to switch back to the point where a function is declared, for example to keep the list of function arguments synchronised between declaration and definition, or to update the documentation. To do so, place the cursor onto the function name and select Navigation -> Jump to declaration (or hit Ctrl + .) to get to the place where the function is declared. There are multiple ways to get back to the original place:
    • Selecting Navigation -> Jump to definition (or hitting Ctrl + ,).
    • Selecting Navigation -> Previous visited context (or hit Meta + Left), as described below.
Note
Jumping to the declaration of a symbol is something that does not only work when placing the cursor on the name of the function you are currently implementing. Rather, it also works for other symbols: Putting the cursor on a (local, global, or member) variable and jumping to its declaration also transports you to its location of declaration. Similarly, you can place the cursor on the name of a class, for example in a variable of function declaration, and jump to the location of its declaration.


  • Switch between declaration/definition: In the example above, to jump to the site of the declaration of the current function, you need to first place the cursor on the function name. To avoid this step, you can select Navigation -> Switch definition/declaration (or hit Shift + Ctrl + C) to jump to the declaration of the function within which the cursor currently is. Selecting the same menu entry a second time transports you back to the place where the function is defined.
  • Previous/Next use: Placing the cursor on the name of a local variable and selecting Navigation -> Next use (or hitting Meta + Shift + Right) transports you to the next use of this variable in the code. (Note that this doesn't just search for the next occurrence of the variable name but in fact takes into account that variables with the same name but in different scopes are different.) The same works for the use of function names. Selecting Navigation -> Previous use (or hitting Meta + Shift + Left) transports you to the previous use of a symbol.
Note
To see the list of all uses of a name through which these commands cycle, place the cursor onto it and open the Code Browser tool view or press and hold the Alt button. This is explained in more detail in the section on Exploring code.


Note
Some shortcuts might be used already by your window manager (e.g. Meta + Left is used by LXDE/Openbox); you can either change the key combination for the shortcut in kdevelop Settings...->Configure Shortcuts or in the window manager config (e.g. .config/openbox/lubuntu-rc.xml)


  • The context list: Web browsers have this feature where you can go backward and forward in the list of most recently visited web pages. KDevelop has the same kind of features, except that instead of web pages you visit contexts. A context is the current location of the cursor, and you change it by navigating away from it using anything but cursor commands — for example, by clicking on a location provided by a tooltip, in the Code Browser tool view, one of the options given in the Navigation menu, or any other navigation command. Using the Navigation -> Previous Visited Context (Meta + Left) and Navigation -> Next Visited Context (Meta + Right) transports you along this list of visited contexts just like the back and forward buttons of a browser transports you to the previous or next webpage in the list of visited pages.
  • Finally, there are tool views that allow you to navigate to different places in your code base. For example, the Classes tool provides you with a list of all namespaces and classes in all projects of the current session, and allows you to expand it to see member functions and variables of each of these classes:
    Double-clicking on an item (or going through the context menu using the right mouse button) allows you to jump to the location of the declaration of the item. Other tools allow similar things; for example, the Projects tool view provides a list of files that are part of a session:
    Again, double-clicking on a file opens it.


Writing source code

Because KDevelop understands your projects' source code, it can assist in writing more code. The following outlines some of the ways in which it does that.

Auto-completion

Probably the most useful of all features in writing new code is auto-completion. Consider, for example, the following piece of code:

class Car {
  // ...
  public:
    std::string get_color () const;
};

void foo() 
{
  Car my_ride;
  // ...do something with this variable...
  std::string color = my_ride.ge

In the last line, KDevelop will remember that the variable my_ride is of type Car, and will automatically offer to complete the name of the member function ge as get_color. In fact, all you have to do is to keep typing until the auto-completion feature has reduced the number of matches to one, and then hit the Enter key:

Note that you can click on the tool-tip to get more information about the function apart from its return type and whether it is public:

Auto-completion can save you a lot of typing if your project uses long variable and function names; furthermore, it avoids mis-spelling names (and the resulting compiler errors) and it makes it much simpler to remember the exact names of functions; for example, if all of your getters start with get_, then the auto-completion feature will be able to only present you a list of possible getters when you have typed the first four letters, likely reminding you in the process which of the functions is the correct one. Note that for auto-completion to work, neither the declaration of the Car class nor of the my_ride variable need to be in the same file as where you are currently writing code. KDevelop simply has to know that these classes and variables are connected, i.e. the files in which these connections are made need to be part of the project you are currently working on.

Note
KDevelop doesn't always know when to assist you in completing code. If the auto-completion tooltip doesn't automatically open, hit Ctrl + Space to open a list of completions manually. In general, in order for auto-completion to work, KDevelop needs to parse your source files. This happens in the background for all files that are part of the projects of the current session after you start KDevelop, as well as while after you stop typing for a fraction of a second (the delay can be configured).


Note
KDevelop only parses files that it considers source code, as determined by the MIME-type of the file. This type isn't set before the first time a file is saved; consequently, creating a new file and starting to write code in it will not trigger parsing for auto-completion until after it is saved for the first time.


Note
As in the previous note, for auto-completion to work, KDevelop must be able to find declarations in header files. For this, it searches in a number of default paths. If it doesn't automatically find a header file, it will underline the name of a header file in red; in that case, right click on it to tell KDevelop explicitly where to find these files and the information they provide.


Note
Configuring auto-completion is discussed in this section of this manual.


Adding new classes and implementing member functions

KDevelop has an assistant for adding new classes. The procedure is described in Creating a new class. A simple C++ class can be created by choosing the Basic C++ template from the Class category. In the assistant, we can choose some predefined member functions, for example an empty constructor, a copy constructor and a destructor.

After completing the assistant, the new files are created and opened in the editor. The header file already has include guards and the new class has all the member functions we selected. The next two steps would be to document the class and its member functions and to implement them. We will discuss aids for documenting classes and functions below. To implement the special functions already added, simply go to the bus.cpp tab where the skeleton of functions are already provided:

To add new member functions, go back to the bus.h tab and add the name of a function. For example, let us add this:

Note how I have already started with the implementation. However, in many coding styles, the function shouldn't be implemented in the header file but rather in the corresponding .cpp file. To this end, locate the cursor on the name of the function and select Code -> Move to source or hit Ctrl + Alt + S. This remove the code between curly braces from the header file (and replaces it by a semicolon as necessary to terminate the function declaration) and moves it into the source file:

Note how I have just started typing and that I meant to imply that the students variable should probably be a member variable of class Bus but that I haven't yet added it. Note also how KDevelop underlines it to make clear that it doesn't know anything about the variable. But this problem can be solved: Clicking on the variable name yields the following tooltip:

(The same can be achieved by right clicking on it and selecting Solve: Declare As.) Let me select "3 - private unsigned int" (either by mouse, or by hitting Alt + 3) and then see how it comes out in the header file:

It is worth noting that KDevelop extracts the type of the variable to be declared from the expression used to initialize it. For example, if we had written the addition in the following rather dubious way, it would had suggested to declare the variable as type double:

As a final point: The method using Code -> Move to source does not always insert the new member function where you may want it. For example, you may want it to be marked as inline and place it at the bottom of the header file. In a case like this, write the declaration and the start writing the definition of the function like this:

KDevelop automatically offers all possible completions of what might come here. Selecting one of the two add_students entries yields the following code that already fills in the complete argument list:

Documenting declarations

Good code is well documented, both at the level of the implementation of algorithms within functions, as well as at the level of the interface — i.e., classes, (member and global) functions, and (member or global) variables need to be documented to explain their intent, possible values of arguments, pre- and postconditions, etc. As far as documenting the interface is concerned, doxygen has become the de facto standard for formatting comments that can then be extracted and displayed on searchable webpages.

KDevelop supports this style of comments by providing a short cut to generate the framework of comments that document a class or member function. For example, assume you have already written this code:

class Car {
  public:
    std::string get_color () const;
};

You now want to add documentation to both the class and the member function. To this end, move the cursor onto the first line and select Code -> Document Declaration or hit Alt + Shift + D. KDevelop will respond with the following:

The cursor is already in the grayed out area for you to fill in the short description (after the doxygen keyword @brief) of this class. You can then continue to add documentation to this comment that gives a more detailed overview of what the class does:

While the editor is inside the comment, the comment text is highlighted in green (the highlighting disappears once you move the cursor out of the comment). When you get to the end of a line, hit Enter and KDevelop will automatically start a new line that starts with an asterisk and place the cursor one character indented.

Now let's document the member function, again by putting the cursor on the line of the declaration and selecting Code -> Document Declaration or hitting Alt + Shift + D:

Again, KDevelop automatically generates the skeleton of a comment, including documentation for the function itself, as well as its return type. In the current case, the name of the function is pretty much self-explanatory, but oftentimes function arguments may not be and should be documented individually. To illustrate this, let's consider a slightly more interesting function and the comment KDevelop automatically generates:

Here, the suggested comment already contains all the Doxygen fields for the individual parameters, for example.

Renaming variables, functions and classes

Sometimes, one wants to rename a function, class or variable. For example, let's say we already have this:

We then realize that we're unhappy with the name remove_students and would have rather called it, say, throw_out_students. We could do a search-replace for the name, but this has two drawbacks:

  • The function may be used in more than one file.
  • We really only want to rename this function and not touch functions that may have the same name but are declared in other classes or namespaces.

Both these problems can be solved by moving the cursor on any of the occurrences of the name of the function and selecting Code -> Rename declaration (or right clicking on the name and selecting Rename Bus::remove_students). This brings up a dialog box where you can enter the new name of the function and where you can also see all the places where the function is actually used:

Code snippets

Most projects have pieces of code that one frequently has to write in source code. Examples are: for compiler writers, a loop over all instructions; for user interface writers, checks that user input is valid and if not to open an error box; in the project of the author of these lines, it would be code of the kind

for (typename Triangulation<dim,spacedim>::active_cell_iterator
       cell = triangulation.begin_active();
     cell != triangulation.end(); ++cell)
  ... do something with the cell ...

Rather than typing this kind of text over and over again (with all the concomitant typos one introduces), the Snippets tool of KDevelop can help here. To this end, open the tool view (see Tools and views if the corresponding button isn't already on the perimeter of your window). Or, go to Window -> Tool views in the top menubar, and turn on Snippets. Then click on the Add repositorybutton (a slight misnomer — it allows you to create a named collection of snippets for source codes of a particular kind, e.g. C++ sources) and create an empty repository. Then click to add a snippet, to get a dialog like the following:

Note
The name of a snippet may not have spaces or other special characters because it must look like a normal function or variable name (for reasons that will become clear in the next paragraph). If the name of the snippet does contain spaces, the OK button will become inactive without any further explanation. This has been fixed in recent versions of KDevelop (see KDevelop bug 274299).


To use a snippet so defined, when you are editing code, you can just type the name of the snippet like you would any other function or variable name. This name will become available for auto-completion — which means that there is no harm in using a long and descriptive name for a snippet such as the one above — and when you accept the suggestion of the auto-completion tooltip (for example by just hitting Enter), the already entered part of the snippets' name will be replaced by the full expansion of the snippet and will be properly indented:

Note that for this to work, the Snippets tool view need not be open or visible: you only ever need the tool view to define new snippets. An alternative, if less convenient, way to expand a snippet is to simply click on it in the respective tool view.

Note
Snippets are much more powerful than just explained. For a full description of what you can do with them, see the detailed documentation of the Snippets tool.

Modes and working sets

If you've gotten this far, take a look at the upper right of the KDevelop main window: As shown in the picture, you will see that there are three modes KDevelop can be in: Code (the mode we discuss in the current chapter on working with source code), Debug (see Debugging programs) and Review (see Working with version control systems).

Each mode has its own set of tools that are stacked around the perimeter, and each mode also has a working set of currently open files and documents. Furthermore, each such working set is associated with a current session, i.e. we have the relationship shown above. Note that the files in the working set come from the same session, but they may come from different projects that are part of the same session.

If you open KDevelop the first time, the working set is empty — there are no open files. But as you open files for editing (or debugging, or reviewing in the other modes) your working set grows. The fact that your working set is non-empty is indicated by a symbol in the tab, as shown below. You will notice that whenever you close KDevelop and later start it again, the working set is saved and restored, i.e. you get the same set of open files.

If you hover your mouse over the symbol for the working set, you get a tooltip that shows you which files are currently open in this working set (here: the step-32.cc and step-1.cc files). Clicking on the red minus sign closes the tab for the corresponding file. Maybe more importantly, clicking on the correspondingly named button allows you to close the entire working set at once (i.e. to close all currently open files). The point about closing a working set, however, is that it doesn't just close all files, it actually saves the working set and opens a new, still empty one. You can see this here:

Note the two symbols to the left of the three mode tabs (the heart and the unidentifiable symbol to its left). Each of these two symbols represents a saved working set, in addition to the currently open working set. If you hover your mouse over the heart symbol, you'll get something like this:

It shows you that the corresponding working set contains two files and their corresponding project names: Makefile and changes.h. Clicking Load will close and save the current working set (which as shown here has the files tria.h and tria.cc open) and instead open the selected working set. You can also permanently delete a working set, which removes it from the set of saved working sets.

Some useful keyboard shortcuts

KDevelop's editor follows the standard keyboard shortcuts for all usual editing operations. However, it also supports a number of more advanced operations when editing source code, some of which are bound to particular key combinations. The following are frequently particularly helpful:

Jumping around in code
Ctrl+Alt+O Quick open file: enter part of a filename and select among all the files in the current session's projects' directory trees that match the string; the file will then be opened
Ctrl+Alt+C Quick open class: enter part of a class name and select among all class names that match; the cursor will then jump to the class declaration
Ctrl+Alt+M Quick open function: enter part of a (member) function name and select among all names that match; note that the list shows both declarations and definitions and the cursor will then jump to the selected item
Ctrl+Alt+Q Universal quick open: type anything (file name, class name, function name) and get a list of anything that matches to select from
Ctrl+Alt+N Outline: Provide a list of all things that are happening in this file, e.g. class declarations and function definitions
Ctrl+, Jump to definition of a function if the cursor is currently on a function declaration
Ctrl+. Jump to declaration of a function or variable if the cursor is currently in a function definition
Ctrl+Alt+PageDown Jump to next function
Ctrl+Alt+PageUp Jump to previous function
Ctrl+G Goto line
Searching and replacing
Ctrl+F Find
F3 Find next
Ctrl+R Replace
Ctrl+Alt+F Find-Replace in multiple files
Other things
Ctrl+_ Collapse one level: remove this block from view, for example if you want to focus on the bigger picture within a function
Ctrl++ Expand one level: undo the collapsing
Ctrl+D Comment out selected text or current line
Ctrl+Shift+D Comment in selected text or current line
Alt+Shift+D Document the current function. If the cursor is on a function or class declaration then hitting this key will create a doxygen-style comment pre-populated with a listing of all parameters, return values, etc.
Ctrl+T Transpose the current and the previous character
Ctrl+K Delete the current line (note: this is not just emacs' "delete from here to the end of the line")