Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions CODING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Coding conventions

The code in the repository is the source of truth: match the surrounding code
first. This file collects the conventions that are easy to get wrong.

## Source file layout

### Include block

Keep the include block structured with the standard section comments, in this
order:

1. `// BUGBUG` — `#include "platform.headers.hpp"`, for the files that need the
Windows headers pulled in first. This is a known wart, not a pattern to copy.
2. `// Self` — the file's own header (`.cpp` files only; headers have no `Self`).
3. `// Internal` — other Far core headers.
4. `// Platform` — the `platform.*` OS abstraction headers.
5. `// Common` — `common.hpp` first, then the `common/...` utility headers
(`common/from_string.hpp`, `common/scope_exit.hpp`, ...).
6. `// External` — third-party libraries and their Far wrappers (`format.hpp`
for fmt, `tinyxml.hpp`, `testing.hpp`).

Keep the section comments even when a section is empty, and separate the block
from the code below with the `//----...` line.

## Language features

### Range algorithms

Prefer the C++20 range algorithms (`std::ranges::find`, `std::ranges::any_of`,
`std::ranges::sort`, ...) over `std::begin`/`std::end` combined with the `std::`
algorithms. The codebase is standardized on `std::ranges`; the range form is
shorter, supports projections, and cannot accidentally mix iterators from
different containers:

```
std::ranges::find(Container, Value); // not std::find(std::begin(Container), std::end(Container), Value)
std::ranges::find(Items, Value, &Item::field);
```

### Enums

#### Enumerating values

When an enum has to be enumerated (to fill a combo box, to map the values to
config keys, to size an array, ...), add a `count` enumerator as the last item
and iterate `0 .. std::to_underlying(Type::count)`:

```
enum Mode
{
first,
second,
third,

count
};

for (const auto i: std::views::iota(0, std::to_underlying(Mode::count)))
use(static_cast<Mode>(i));
```

`count` is needed only when the values are actually enumerated; other enums
don't have to define it.

#### switch over an enum

Handle every enumerator explicitly and terminate the switch with
`default: std::unreachable();`.

If only some values need special handling, let the rest share a behaviour
through `default:` (`default: break;` means "do nothing"), or merge `default`
with a fallback case:

```
switch (Value)
{
default:
case Type::unknown: return Fallback;
case Type::a: return ...;
}
```

Use `[[fallthrough]]` when a case intentionally falls through into the next one.

## User interface

### Dialogs and localized labels

Localized text has a different width in each language, so measure labels at
runtime and derive the offsets from the text width. `HiStrlen` accounts for `&`
hotkeys and double-width characters (and returns `size_t`):

```
EditDlg[label].X1 = EditDlg[control].X2 + 2;
EditDlg[field].X1 = EditDlg[label].X1 + static_cast<int>(HiStrlen(msg(lng::Label))) + 1;
```

A control with a drop-down arrow (a combo box with a non-empty list, or an edit
with `DIF_HISTORY`) draws the arrow one column to the right of `X2`. When placing
an item immediately to the right, account for that column (`X2 + 3` keeps a
one-column gap); a control right-aligned to the dialog border needs no
adjustment, the arrow fits into the gap before the border.
6 changes: 5 additions & 1 deletion enc/enc_eng/meta/dialogapi/controls/di_combobox.html
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,11 @@ <h3>Events</h3>

<h3>Remarks</h3>
<div class=descr>
<p></p>
<p>If the combo box has a drop-down arrow (a non-empty list, or an item with
<a href="../flags/dif_history.html">DIF_HISTORY</a>), the arrow is drawn one column
to the right of <b>X2</b>, i.e. the item visually occupies <b>X1</b>..<b>X2+1</b>.
When placing another item to the right, take that column into account and leave a
gap.
</div>


Expand Down
5 changes: 5 additions & 0 deletions enc/enc_eng/meta/dialogapi/dmsg/dn_editchange.html
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ <h3>Remarks</h3>
<li>The <dfn>DN_EDITCHANGE</dfn> event will not be sent in a response to the following messages:
<a href="dm_settextptr.html">DM_SETTEXTPTR</a> and
<a href="dm_settext.html">DM_SETTEXT</a>.
<li>The <dfn>DN_EDITCHANGE</dfn> event is sent even when the item text is set to the
same value (for example, when the current item is re-selected in a
<a href="../controls/di_combobox.html">DI_COMBOBOX</a>). To detect a real change,
compare the new text with the previous one; to detect a list position change, use
<a href="dn_listchange.html">DN_LISTCHANGE</a>.
</ol>
</div>

Expand Down
4 changes: 3 additions & 1 deletion enc/enc_eng/meta/dialogapi/dmsg/dn_listchange.html
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ <h3>Controls</h3>

<h3>Remarks</h3>
<div class=descr>

Unlike <a href="dn_editchange.html">DN_EDITCHANGE</a>, the <dfn>DN_LISTCHANGE</dfn>
event is sent only when the list position actually changes: re-selecting the current
item leaves the position unchanged and does not trigger it.
</div>

<h3>Example</h3>
Expand Down
4 changes: 4 additions & 0 deletions enc/enc_eng/meta/dialogapi/flags/dif_history.html
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ <h3>Remarks</h3>
</tr>
</table>
</li>
<li>An edit control with <dfn>DIF_HISTORY</dfn> shows a drop-down arrow, which is drawn one
column to the right of <b>X2</b> (<b>X2+1</b>). When placing another item immediately to the
right, take that column into account; when the edit is right-aligned to the dialog border,
the arrow fits into the gap before the border and no adjustment is needed.
</ol>
</div>

Expand Down
5 changes: 5 additions & 0 deletions enc/enc_rus/meta/dialogapi/controls/di_combobox.html
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,11 @@ <h3>Замечания</h3>
Ассоциированные данные уничтожаются (если было выделение по памяти)
<br><br>
</ul>
<p>
Если у комбобокса есть стрелка раскрытия списка (непустой список или элемент с
флагом <a href="../flags/dif_history.html">DIF_HISTORY</a>), стрелка рисуется на
одну колонку правее <b>X2</b>, т.е. элемент занимает <b>X1</b>..<b>X2+1</b>.
Размещая правее другой элемент, учитывайте эту колонку и оставляйте отступ.
</div>

<div class=see>Смотрите также:</div>
Expand Down
5 changes: 5 additions & 0 deletions enc/enc_rus/meta/dialogapi/dmsg/dn_editchange.html
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ <h3>Элементы</h3>
<h3>Замечания</h3>
<div class=descr>
В Dialog API нельзя принудительно изменить состояние элемента, изменяя элементы структуры <a href="../../structures/fardialogitem.html">FarDialogItem</a>.
<p>
Событие <code>DN_EDITCHANGE</code> посылается и тогда, когда элементу устанавливается то же самое
значение (например, при повторном выборе текущего элемента в <a href="../controls/di_combobox.html">DI_COMBOBOX</a>).
Чтобы отследить реальное изменение, сравните новое значение с предыдущим; для отслеживания смены
позиции в списке используйте <a href="dn_listchange.html">DN_LISTCHANGE</a>.
</div>

<h3>Пример</h3>
Expand Down
3 changes: 3 additions & 0 deletions enc/enc_rus/meta/dialogapi/dmsg/dn_listchange.html
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ <h3>Элементы</h3>

<h3>Замечания</h3>
<div class=descr>
В отличие от <a href="dn_editchange.html">DN_EDITCHANGE</a>, событие <code>DN_LISTCHANGE</code>
посылается только при реальном изменении позиции в списке: повторный выбор текущего элемента
позицию не меняет и это событие не вызывает.
</div>

<h3>Пример</h3>
Expand Down
4 changes: 4 additions & 0 deletions enc/enc_rus/meta/dialogapi/flags/dif_history.html
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ <h3>Замечания</h3>
<tr><td>L"NewFolder"</td><td>создание каталогов</td></tr>
</table>
</li>
<li>Строка ввода с флагом <code>DIF_HISTORY</code> имеет стрелку раскрытия списка, которая
рисуется на одну колонку правее <b>X2</b> (<b>X2+1</b>). Если справа вплотную размещается
другой элемент, эту колонку нужно учитывать; если строка выровнена по правой границе,
стрелка помещается в промежутке перед границей и ничего подгонять не нужно.
</ol>
</div>

Expand Down
9 changes: 8 additions & 1 deletion far/FarCze.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1555,7 +1555,8 @@ $ #Menu Příkazy#
#Upr. menu uživatele# Umožňuje upravit hlavní nebo lokání
~uživatelské menu~@UserMenu@.
Můžete stisknout Ins pro vložení, Del pro
smazání a F4 pro úpravu záznamu.
smazání, Ctrl+H pro zobrazení filtrovaných položek
a F4 pro úpravu záznamu.

#Závislosti souborů# Zobrazí seznam ~závislosti souborů~@FileAssoc@.
Můžete stisknout Ins pro vložení, Del pro
Expand Down Expand Up @@ -2248,12 +2249,18 @@ přiřazenou danému příkazu.
podmenu, nebo položku v menu můžete klávesou Ins. Upravit existující
podmenu, nebo položku v menu můžete klávesou F4. Pokud chcete menu upravovat
v podobě textového souboru stiskněte Alt+F4.
Stiskněte #Ctrl+H# pro zobrazení položek menu skrytých polem "Zobrazit".

V uživatelském menu je možné použít jako zkratkové klávesy číslice,
písmena a funkční klávezy (#F1#…#F24#). Pokud jsou použity #F1# nebo #F4#, je
jejich původní funkce v menu potlačena. Nicméně, můžete pro úpravu menu
použít #Shift+F4#.

Pole #Zobrazit# zobrazí položku menu pouze tehdy, když je v aktuální
situaci vhodná: #Vždy#, #Existuje výběr#, #Aktuální je soubor# nebo #Aktuální je složka#.
Pro poslední dvě lze zadat volitelnou ~masku souboru~@FileMasks@; položka se
zobrazí, pouze pokud název objektu pod kurzorem odpovídá masce.

Když tvoříte, nebo upravujet položku v menu, měli byste zadat horkou
klávesu, pro rychlý přístup k položce, popis položky, který bude v menu
zobrazen a sekvenci příkazů, která má být vykonána.
Expand Down
11 changes: 9 additions & 2 deletions far/FarEng.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1528,8 +1528,8 @@ $ #Menus: commands menu#
detailed description.

#Edit user menu# Allows to edit main or local ~user menu~@UserMenu@.
You can press #Ins# to insert, #Del# to delete
and #F4# to edit menu records.
You can press #Ins# to insert, #Del# to delete,
#Ctrl+H# to show filtered items and #F4# to edit menu records.

#File associations# Displays the list of ~file associations~@FileAssoc@.
You can press #Ins# to insert, #Del# to delete
Expand Down Expand Up @@ -2215,11 +2215,18 @@ You can also press the hot key assigned to the required menu item.
You can delete a submenu or menu item with the #Del# key, insert new
submenu or menu item with the #Ins# key or edit an existing submenu or menu
item with the #F4# key. Press #Alt+F4# to edit the menu in text file form.
Press #Ctrl+H# to show menu items hidden by the #Show# field.

It is possible to use digits, letters and function keys (#F1#…#F24#) as
hot keys in user menu. If #F1# or #F4# is used, its original function in user
menu is overridden. However, you still can use #Shift+F4# to edit the menu.

The #Show# field makes a menu item visible only when it is applicable in
the current situation: #Always#, #Has selection#, #Current is a file# or
#Current is a folder#. For the last two an optional ~file mask~@FileMasks@ can
be specified; the item is shown only when the name of the object under the
cursor matches the mask.

When you edit or create a menu item, you should enter the hot key for fast
item access, the item title which will be displayed in the menu and the command
sequence to execute when this item will be selected.
Expand Down
11 changes: 9 additions & 2 deletions far/FarGer.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1570,8 +1570,8 @@ $ #Menü Befehle#
#Benutzermenü# Erlaubt das Bearbeiten des Haupt- oder
#bearbeiten# lokalen ~Benutzermenüs~@UserMenu@.
Drücken Sie #Einfg# zum Einfügen, #Entf# zum
Löschen und #F4# zum Bearbeiten von
Menüeinträgen.
Löschen, #Strg+H# zum Anzeigen gefilterter Einträge
und #F4# zum Bearbeiten von Menüeinträgen.

#Dateiverknüpfung# Zeigt die Liste von ~Dateiverknüpfungen~@FileAssoc@.
Drücken Sie #Einfg# zum Einfügen, #Entf# zum
Expand Down Expand Up @@ -2289,11 +2289,18 @@ must switch to file mode with #Alt+F4# key.
Menüpunkte oder Untermenüs können durch die Taste Entf gelöscht werden. Durch Einfg können neue Menüpunkte
oder Untermenüs angelegt werden. Durch #F4# können existierende Menüpunkte und Untermenüs bearbeitet werden.
Mit Alt+F4 kann ein Menü in Form einer Textdatei bearbeitet werden.
Mit #Strg+H# werden durch das Feld "Anzeigen" ausgeblendete Menüeinträge angezeigt.

Es ist möglich, Zahlen, Buchstaben und Funktionstasten (#F1#…#F24#) als Hotkeys in Benutzermenüs einzusetzen.
Bei Benutzung von #F1# oder #F4# wird deren originale Funktion im Benutzermenü übergangen.
#Umsch+F4# können Sie trotzdem weiterhin als Bearbeitungsfunktion nutzen.

Das Feld #Anzeigen# macht einen Menüeintrag nur dann sichtbar, wenn er
in der aktuellen Situation zutrifft: #Immer#, #Auswahl vorhanden#,
#Aktuell ist eine Datei# oder #Aktuell ist ein Ordner#. Für die letzten beiden
kann eine optionale ~Dateimaske~@FileMasks@ angegeben werden; der Eintrag wird
nur angezeigt, wenn der Name des Objekts unter dem Cursor der Maske entspricht.

Wenn Sie einen Menüpunkt anlegen oder bearbeiten, geben Sie einen Hotkey für einen
schnellen Zugriff an, einen Titel, welcher im Menü angezeigt wird sowie eine Befehlssequenz,
die ausgeführt wird, wenn der Menüeintrag ausgewählt wird.
Expand Down
11 changes: 9 additions & 2 deletions far/FarHun.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1565,8 +1565,8 @@ témakör részletezi a funkciót.

#Felhasználói menü# Fő vagy helyi ~felhasználói menüt~@UserMenu@
#szerkesztése# szerkeszthetünk. Az #Ins# billentyű beszúrja,
a #Del# törli, az #F4# pedig szerkeszti a menü
elemeit.
a #Del# törli, a #Ctrl+H# megmutatja a szűrt
elemeket, az #F4# pedig szerkeszti a menü elemeit.

#Fájltársítások# ^<wrap>Megjeleníti a ~fájltársításokat~@FileAssoc@.
Az #Ins# billentyűvel beszúrhatjuk, a #Del#-lel törölhetjük, az #F4#-gyel
Expand Down Expand Up @@ -2292,13 +2292,20 @@ gyorsbillentyű segítségével.
Az #Ins# billentyűvel új menüelemeket, almenüket hozhatunk létre, az #F4#
bilentyűvel szerkeszthetjük a jellemzőiket, a #Del#-lel pedig törölhetjük a
menü elemeit. #Alt+F4#-gyel a menüket szövegfájl formátumban szerkeszthetjük.
A #Ctrl+H# megmutatja a "Megjelenítés" mező miatt elrejtett menüpontokat.

A felhasználói menü elemeinek gyorsbillentyűjeként megadhatunk számokat,
betűket vagy funkcióbillentyűket (#F1#…#F24#), utóbbiakat csak beírás útján
fogadja el. Ha az #F1# vagy #F4# eredetileg más művelethez volt rendelve,
a felhasználói menü felülbírálja eredeti funkcióikat, bár a #Shift+F4#-gyel
ezután is szerkeszthetjük a menüt.

A #Megjelenítés# mező csak akkor teszi láthatóvá a menüpontot, ha az illik az
adott helyzethez: #Mindig#, #Van kijelölés#, #A jelenlegi fájl# vagy
#A jelenlegi mappa#. Az utolsó kettőhöz opcionális ~fájlmaszk~@FileMasks@
adható meg; a menüpont csak akkor jelenik meg, ha a kurzor alatti objektum neve
illik a maszkra.

Ha a szerkesztett menüelemünk parancs, meg kell adnunk a gyorsbillentyűjét,
a nevét (ami majd a menüben jelenik meg) és a végrehajtandó parancs sorát.

Expand Down
10 changes: 8 additions & 2 deletions far/FarPol.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1521,8 +1521,8 @@ $ #Menu: menu polecenia#
Więcej informacji: ~Porównaj foldery~@CompFolders@.

#Edytuj menu# Pozwala na edycję głównego lub lokalnego ~menu użytkownika~@UserMenu@.
#użytkownika# Można wcisnąć #Ins# aby wstawić, #Del# aby usunąć
i #F4# aby edytować pozycję.
#użytkownika# Można wcisnąć #Ins# aby wstawić, #Del# aby usunąć,
#Ctrl+H# aby pokazać odfiltrowane pozycje i #F4# aby edytować pozycję.

#Przypisania plików# Wyświetla listę ~powiązań plików~@FileAssoc@.
Można wcisnąć #Ins# aby wstawić, #Del# aby usunąć
Expand Down Expand Up @@ -2216,11 +2216,17 @@ menu.
podmenu lub pozycję menu za pomocą klawisza #Ins# lub edytować istniejące
podmenu lub pozycję menu za pomocą klawisza #F4#. Należy wcisnąć klawisze #Alt+F4#,
aby edytować menu w formie pliku tekstowego.
Naciśnij #Ctrl+H#, aby pokazać pozycje menu ukryte przez pole "Pokaż".

Do klawiszy skrótu można użyć cyfr, liter i klawiszy funkcyjnych (#F1#…#F24#).
Jeżeli użyto klawiszy #F1# lub #F4# - to zamieniona zostanie oryginalna funkcja
tych klawiszy. Mimo to, skrót #Shift+F4# nadal może być użyty do edycji menu.

Pole #Pokaż# czyni pozycję menu widoczną tylko wtedy, gdy pasuje ona do bieżącej
sytuacji: #Zawsze#, #Jest zaznaczenie#, #Bieżący to plik# lub #Bieżący to folder#.
Dla dwóch ostatnich można podać opcjonalną ~maskę pliku~@FileMasks@; pozycja
jest pokazywana tylko wtedy, gdy nazwa obiektu pod kursorem pasuje do maski.

Podczas edycji lub tworzenia nowej pozycji menu, można (a nawet powinno) dodać
klawisz skrótu dla szybszego dostępu, tytuł który będzie wyświetlany w menu
oraz sekwencję poleceń do wykonania, gdy ta pozycja zostanie wybrana.
Expand Down
9 changes: 8 additions & 1 deletion far/FarRus.hlf.m4
Original file line number Diff line number Diff line change
Expand Up @@ -1564,7 +1564,7 @@ $ #Меню команд#
#Меню пользователя# Позволяет редактировать главное или местное
~меню пользователя~@UserMenu@. Для вставки пункта
используется #Ins#, для удаления - #Del#,
для редактирования - #F4#.
#Ctrl+H# для показа отфильтрованных пунктов, для редактирования - #F4#.

#Ассоциации файлов# Показывает список ~ассоциаций файлов~@FileAssoc@.
Для вставки новой ассоциации может
Expand Down Expand Up @@ -2266,12 +2266,19 @@ $ #Меню пользователя#
вставить новое вложенное меню или пункт меню с помощью #Ins# и редактировать
существующее вложенное меню или пункт меню с помощью #F4#. Нажмите #Alt+F4# для
редактирования меню в виде текстового файла.
Нажмите #Ctrl+H#, чтобы показать пункты меню, скрытые полем "Показывать".

В качестве горячих клавиш для обращения к пунктам меню могут использоваться
цифры, буквы и функциональные клавиши (#F1#…#F24#). Если использованы #F1# и #F4#,
их первоначальные функции теряются. В этом случае для редактирования меню может
применяться #Shift+F4#.

Поле #Показывать# делает пункт меню видимым, только когда он применим в
текущей ситуации: #Всегда#, #Есть выделение#, #Текущий - файл# или
#Текущий - папка#. Для последних двух можно указать необязательную
~маску файла~@FileMasks@; пункт показывается, только если имя объекта под
курсором совпадает с маской.

При редактировании или создании пункта меню нужно ввести заголовок пункта,
который будет отображаться в меню, последовательность команд, выполняющихся при
выбора данного пункта меню, и, при необходимости, горячую клавишу для быстрого
Expand Down
Loading