Документация по системе CharChem 2.0+ CharChem 2.0+ documentation

Как читать данный документ How to read this document

Рекомендуется полностью прочесть раздел "Описание химических формул". При этом не стоит пытаться сразу всё понять и запомнить. Достаточно в общих чертах представлять основные возможности CharChem.

It is recommended to read the entire section "Description of chemical formulas". However, you should not try to understand and remember everything at once. It is enough to have a general idea of the main features of CharChem.

Затем Вы можете использовать раздел Подсказки чтобы быстро находить решения для тех ситуаций, которые могут возникнуть в процессе кодирования формул.

You can then use the Hints section to quickly find solutions to situations that may arise while coding formulas.

Справочник не предназначен для чтения. К нему стоит обращаться по мере необходимости для получения подробной информации по тем или иным аспектам системы CharChem.

The Reference is not intended to be read. It should be consulted as needed to obtain detailed information on various aspects of the CharChem system.

Автор документа: PeterWin. Версия от 2025-04-08

Author of the document: PeterWin. Version from 2025-04-08

Описание химических формул Description of chemical formulas

Для описания химических формул в CharChem используются текстовые строки. В следующей таблице представлены примеры. CharChem uses text strings to describe chemical formulas. The following table provides examples.

Текстовое описание Text description
Полученная формула Result formula
CuSO4*5H2O
CuSO4*5H2O
2H^+ + SO4^2- <=> H^+ + HSO4^-
2H^+ + SO4^2- <=> H^+ + HSO4^-
CH3-CH2-CH<|CH3>-OH
CH3-CH2-CH<|CH3>-OH
H3C/\<|CH3>/OH
H3C/\<|CH3>/OH
`/O`\<`/~HO>`|<`\wHO>/<`|wOH>\</dOH>|\wCH3
`/O`\<`/~HO>`|<`\wHO>/<`|wOH>\</dOH>|\wCH3
CH2OH|_(x-1,y1)<|HO>_(x1,y1,W+)<`|OH>_(x1.4)<|OH>_(x1,y-1,W-)<`|OH>_(x-1,y-1)O_#2
CH2OH|_(x-1,y1)<|HO>_(x1,y1,W+)<`|OH>_(x1.4)<|OH>_(x1,y-1,W-)<`|OH>_(x-1,y-1)O_#2

Здесь можно видеть, что сложность описания зависит от сложности формулы. Хотя здесь представлен далеко не все возможности, которые можно использовать при помощи системы CharChem.

Here you can see that the complexity of the description depends on the complexity of the formula. Although this does not present all the possibilities that can be used with the CharChem system.

Для описания химических формул рекомендуется использовать тестовый стенд. Там можно сразу видеть результат. А если появится какая-то ошибка, то об этом будет соответствующее сообщение.

To describe chemical formulas, it is recommended to use the test stand. There you can immediately see the result. And if any error occurs, there will be a corresponding message about it.

В данном разделе расматриваются правила, с помощью которых выполняеются текстовые описания формул CharChem

This section discusses the rules by which textual descriptions of CharChem formulas are performed.

Из чего состоит химическая формула CharChem Components of CharChem chemical formula

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

In general, a formula consists of several reagents that can be separated by operations.

Например, в следуюшей формуле три реагента и две операции (они обозначены красным).

For example, in the following formula there are three reagents and two operations (they are marked in red).

2H2$color(red) + $color()O2$color(red) -> $color()2H2O

Следующая формула состоит из одного реагента и не имеет операций. Но реагент состоит из трёх узлов. В то время как в предыдущей формуле у каждого из реагентов по одному узлу.

The following formula consists of one reagent and has no operations. But the reagent consists of three nodes. While in the previous formula each of the reagents has one node.

CH3-CH2-OH

Узлы обычно соединяются химическими связями. И хотя в реальности каждый атом водорода тут имеет ковалентную связь с соответствующим атомом, но в формуле явно указаны только две. Поэтому здесь получается три узла. Но если то же самое вещество записать в виде другой формулы CH3CH2OH - то в ней всего один узел, т.к. отсутствуют разделители. То есть, узел - это понятие никак не связано с химическими свойствами. Оно нужно только для графического представления.

The nodes are usually connected by chemical bonds. And although in reality each hydrogen atom here has a covalent bond with the corresponding atom, only two bonds are clearly indicated in the formula. Therefore, there are three nodes here. But if the same substance is written as another formula CH3CH2OH, then there is only one node, because there are no separators.

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

The following formula (left) shows one reagent that has 7 chemical bonds. (These are the bonds that are clearly shown in the formula.)

||`/`\\`|//\/CH2OH
||@:n(t,a,d:0.4)<_(A&a,N0,L&d)$itemColor1(blue)"&t">@(1,30)`/@n(2,90)`\\@n(3,150)`|@n(4,-150)//@n(5,-90)\@n(6,-89,0.6)/CH2OH@n(7,-90,0.6)

Можно подумать, что у него только один узел (CH2OH). Но по правилам скелетных формул, каждый угол соответствует атому углерода. Поэтому здесь 7 узлов, которые обозначены справа. Такие узлы (кроме 7) в системе CharChem называются автоузлами.

You might think that it has only one node (CH2OH). But according to the rules of skeletal formulas, each corner corresponds to a carbon atom. Therefore, there are 7 nodes, which are indicated on the right. Such nodes (except 7) are called autonodes in the CharChem system.

Общие правилаGeneral rules

При описании формул важно соблюдать регистр. Потому что например CO - это угарный газ, а Co - кобальт.

When describing formulas, it is important to observe the register. Because, for example, CO is carbon monoxide, and Co is cobalt.

Пробелы можно вставлять только в определённых местах. Например, пробелом необходимо отделять реагент от операции. Но там где разрешено (или требуется) один пробел, можно вставлять и несколько пробелов. И даже можно использовать переход на следующую строку.

Полный список правил, связанных с пробелом

Spaces can only be inserted in certain places. For example, a space must separate a reagent from an operation. But where one space is allowed (or required), multiple spaces can be inserted. And you can even use a line break.

Complete list of space related rules

Описание узлов Description of nodes

Прежде чем переходить к сложным формулам, желательно разобраться с простыми. Давайте рассмотрим такие формулы, где реагенты состоят из одного узла. К ним относятся классические рациональные формулы, такие как H2SO4 и т.п.

Before moving on to complex formulas, it is advisable to understand simple ones. Let's consider such formulas, where the reactants consist of one node. These include classical rational formulas, such as H2SO4, etc.

Элементы узлов Node items

Каждый узел состоит из одного или нескольких элементов узлов. Ими обычно являются атомы химических элементов, но есть и другие варианты.

Each node consists of one or more node items. These are usually atoms of chemical elements, but there are other options.

.
Элемент узлаNode item НазначениеPurpose ПримерыExamples
АтомAtom То есть, символ любого элемента из периодической системы. That is, the symbol of any element from the periodic table.
Li2SO4
Li2SO4
Специальные изотопы Special isotopes Их всего два: D — Дейтерий и T — Тритий. There are only two of them: D — Deuterium and T — Tritium.
D + T -> {n} + $M(4)He
$itemColor(var(--select-color))D + T$itemColor() -> {n} + $M(4)He
Абстрактный элемент Abstract element Иногда бывает нужно использовать не определённый химический элемент, а обозначение функциональной группы. Для этого в фигурных скобках можно указать нужное обозначение.
Если в формуле появляется хотя бы один абстрактный элемент, то вся формула считается абстрактной. Функциональность таких формул снижается. Например, для них нельзя вычислить массу.
Sometimes it is necessary to use not a specific chemical element, but a designation of a functional group. For this purpose, the required designation can be specified in curly brackets.
If at least one abstract element appears in a formula, the entire formula is considered abstract. The functionality of such formulas is reduced. For example, mass cannot be calculated for them.
{M}2SO4
$itemColor1(var(--select-color)){M}2SO4
{R^1}-O-{R^2}
$itemColor1(var(--select-color)){R^1}-O-$itemColor1(var(--select-color)){R^2}
РадикалRadical Описание радикала выглядит точно так же, как абстрактный элемент - аббревиатура в фигурных скобках. Разница в том, что только определённые аббревиатуры воспринимаются как радикалы. Их список есть в справочнике.
Основное отличие радикала от абстрактного элемента - формула с радикалом не становится абстрактной. Для неё правильно считается атомная масса.
The description of a radical looks exactly the same as an abstract element - an abbreviation in curly brackets. The difference is that only certain abbreviations are perceived as radicals. Their list is in the reference.
The main difference between a radical and an abstract element is that a formula with a radical does not become abstract. The atomic mass is calculated correctly for it.
EtOH = C2H5OH
$itemColor1(var(--select-color))EtOH = C2H5OH
Me2O = CH3OCH3
$itemColor1(var(--select-color))Me2O = CH3OCH3
КомментарийComment Бывает необходимость снабдить какие-то части формулы комментариями. Комменарий обозначается двойными кавычками.
В отличие от абстрактных элементов, комментарий не делает формулу абстрактной.
Sometimes it is necessary to provide some parts of a formula with comments. A comment is indicated by double quotes.
Unlike abstract elements, a comment does not make a formula abstract.
{M}2SO4", M=Li,Na,K"
{M}2SO4", M=Li,Na,K"
GeH4 + 2H2O ->
GeO2"|v" + 4H2"|^"
GeH4 + 2H2O -> GeO2"|v" + 4H2"|^"
ЗапятаяComma Используется для формул минералов с непостоянным составом. Превращает формулу в абстрактную The comma is used for formulas of minerals with variable composition. It turns the formula into an abstract one.
(Fe,Mn)WO4
(Fe,Mn)WO4
Ca(Mg,Fe)[CO3]2
Ca(Mg,Fe)[CO3]2

Возможности элементов узлов Features of node items

Числовой коэффициент Numerical coefficient

Самый типичный случай - целое число после элемента.

The most typical case is an integer after the element.

{R}2SO4
{R}2SO4

Абстрактный коэффициент Abstract coefficient

Записывается сразу после элемента в одинарных кавычках.

The abstract coefficient is written immediately after the element in single quotes.

Так же может употребляться для эмпирических формул минералов.

It can also be used for empirical formulas of minerals.

C'n'H'2n+2'
C'n'H'2n+2'
Fe(OH)'3-x'O'x/2'
Fe(OH)'3-x'O'x/2'
(Na'0,88'Ca'0,1'K'0,02')[(Si'1,95'Al'0,05')'2,0'O6]
(Na'0,88'Ca'0,1'K'0,02')[(Si'1,95'Al'0,05')'2,0'O6]

Если в формуле встречается абстрактный коэффициент, то вся формула считается абстрактной.

If an abstract coefficient is found in a formula, the entire formula is considered abstract.

Степень окисленияOxidation state

Записывается как заряд сразу после элемента в круглых скобках. (Способы описания зарядов перечислены в справочнике) Если у элемента есть коэффициент, то записывать их можно в любом порядке.

The oxidation state is written as a charge immediately after the element in parentheses. (The methods of describing charges are listed in the reference) If the element has a coefficient, then they can be written in any order.

K(+1)Mn(+7)O4(-2)
K(+1)Mn(+7)O4(-2)
(N(-3)H4(+1))2S(+6)O4(-2)
(N(-3)H4(+1))2S(+6)O4(-2)
KFe(iii)[Fe(ii)(CN)6]
KFe(iii)[Fe(ii)(CN)6]

Атомная масса изотопа Atomic mass of isotope

Записывается в виде функции $M(m). Функции обсуждаются в следующем разделе

The atomic mass of an isotope is written as a function $M(m). The functions are discussed in the next section.

$M(4)He
$M(4)He
$M(235)U
$M(235)U

Атомный номер и масса изотопа Atomic number and mass of the isotope

Также известно как AZE-нотация. Записывается функцией $nM(m[,n]).

Also known as AZE notation. It written with the function $nM(m[,n]).

$nM(232)Th + $nM(1,0){n} -> $nM(233)Th
$nM(232)Th + $nM(1,0){n} -> $nM(233)Th

Структуры Льюиса Lewis structures

Описываются функцией $dots()

Lewis structures are described by the $dots() function.

H$dots(!)OH
H$dots(!)OH
H-$dots(TB)O-H
H-$dots(TB)O-H

Функции CharChem CharChem functions

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

Since chemical formulas can have quite a lot of different features, it is not possible to come up with some special syntactic constructions for all of them. Therefore, for such featutes that are not needed too often, there is a universal construction called a "function". (The term is borrowed not from mathematics, but from programming languages.)

Функция всегда начинается со знака доллара, затем идёт название, затем параметры в скобках. Параметры перечисляются через запятую, без пробелов. Скобки указываются обязательно, даже если параметров нет.

A function always starts with a dollar sign, then the name, then the parameters in brackets. The parameters are listed separated by commas, without spaces. Brackets are required, even if there are no parameters.

В общем виде описание выглядит так: In general, the description looks like this: $name(params)

Полный список функций есть в справочнике.

The full list of functions is in the reference.

Функция всегда ставится перед тем объектом, к которому она должна применяться. Есть функции, которые действуют только на ближайший объект. А есть такие, которые действуют на все следующие подходящие объекты. Это называется областью действия, которая для каждой функции указана в описании.

A function is always placed before the object it is to be applied to. There are functions that act only on the closest object. And there are those that act on all subsequent suitable objects. This is called the scope, which is specified in the description for each function.

В предыдущем разделе мы уже видели несколько функций, который действуют на элементы узлов. Кратко рассмотрим их ещё раз.

In the previous section we have already seen several functions that act on node items. Let's briefly review them again.

Масса изотопаIsotope mass $M(235)U
$M(235)U
Масса и атомный номер Mass and atomic number $nM(238)U + $nM(1,0){n} -> $nM(239)U
$nM(238)U + $nM(1,0){n} -> $nM(239)U
Структуры Льюиса Lewis structures H-$dots(TB)O-H
H-$dots(TB)O-H

А в следующем разделе представлены цветовые функции.

And the next section presents the color functions.

Цветовые функции Color functions

В CharChem существует возможность выделять цветами отдельные части формул. Для этого есть несколько функций.

CharChem has the ability to highlight individual parts of formulas with colors. There are several functions for this.

НазваниеName Краткое описаниеBrief description Область действияScope
color Цвет всех частей формулы, которые следуют за функцией The color of all parts of the formula that follow the function До конца формулы. Или до следующей функции $color() Until the end of the formula. Or until the next $color() function.
itemColor Цвет элементов узлов, которые следуют за функцией. The color of the node items that follow the function. До конца формулы. Или до следующей функции $itemColor() Until the end of the formula. Or until the next $itemColor() function.
itemColor1 Цвет следующего элемента узла. The color of the next node item. Только один следующий элемент узла. Only one next node item.
atomColor Цвет атомов, которые следуют за функцией. The color of the atoms that follow the function. До конца формулы. Или до следующей функции $atomColor() Until the end of the formula. Or until the next $atomColor() function.
atomColor1 Цвет следующего атома. The color of the next atom. Только один следующий атом. Only one next atom.

Правила описания цветов есть в справочнике

The rules for describing colors are in the reference.

Самая простая из цветовых функций - color. Всё что за ней следует - окрашивается в указанный цвет. А чтобы поменять цвет - надо в нужном месте включить новую функцию color.

The simplest of the color functions is $color. Everything that follows it is painted in the specified color. And to change the color, you need to turn on the new $color function in the right place.

$color(green)2H2 + $color(red)O2 = $color(blue)2H2O
$color(green)2H2 + $color(red)O2 = $color(blue)2H2O

Но в данном примере не очень хорошо выглядит то, что плюс окрашен в зелёный цвет, а равенство - в красный. Чтобы вернуть цвет по-умолчанию, используется та же функция, но без параметра: $color().

But in this example it doesn't look very good that the plus is colored green and the equality is colored red. To return the default color, the same function is used, but without the parameter: $color().

$color(green)2H2$color() + $color(red)O2$color() = $color(blue)2H2O$color()
$color(green)2H2$color() + $color(red)O2$color() = $color(blue)2H2O$color()

Хотелось бы отметить, почему рекомендуется вызывать именно $color(), а не, например, $color(black).

I would like to note why it is recommended to call $color(), and not, for example, $color(black).

Дело в том, что внешний вид формул обычно должен соответствовать дизайну того документа, где они используются. В следующем примере демонстрируется тёмная тема. Цвет по-умолчанию там белый. Именно конструкция $color() восстанавливает тот цвет, который используется по-умолчанию.

The point is that the appearance of formulas should usually match the design of the document where they are used. The following example demonstrates a dark theme. The default color there is white. It is the $color() construct that restores the color that is used by default.

2H2 + $color(lightgreen)O2$color() = $color(aqua)2H2O$color()
2H2 + $color(lightgreen)O2$color() = $color(aqua)2H2O$color()

Цвет элементов узла Color of node items

Это функции $itemColor() и $itemColor1(), которые отличаются лишь областью действия.

These are the $itemColor() and $itemColor1() functions, which differ only in their scope.

Они влияют на цвет элементов узлов, включая коэффициент и другие возможности, ранее перечисленные в одном из разделов. Но не влияют на то, что к узлам не относится - химические связи, операции, скобки и т.п. А так же не влияют на заряд узла, т.к. он не является элементом узла.

They affect the color of the node items, including the coefficient and other features previously listed in one of the sections. But they do not affect what does not apply to nodes - chemical bonds, operations, brackets, etc. And they also do not affect the charge of the node, since it is not a node item.

$itemColor(blue)Ca(OH)2 <=> Ca^2+ + 2OH^-
$itemColor(blue)Ca(OH)2 <=> Ca^2+ + 2OH^-
[Pt$itemColor(blue)(NH3)4$itemColor()](NO3)2
[Pt$itemColor(blue)(NH3)4$itemColor()](NO3)2
K2(+1)$itemColor1(magenta)Cr(+6)2O(-2)7
K2(+1)$itemColor1(magenta)Cr(+6)2O(-2)7

Как видно, $itemColor() без параметров прекращает действие ранее указанного цвета. Так же как и $color().

As you can see, $itemColor() without parameters cancels the previously shown color. Same as $color().

Цвет атомовColor of atoms

Это функции $atomColor() и $atomColor1(), которые отличаются лишь областью действия.

These are the $atomColor() and $atomColor1() functions, which differ only in their scope.

Они влияют только на атомы. То есть, на такие элементы узла, которые представлены символами химических элементов из периодической системы: H, He, Li и т.д.

They affect only atoms. That is, such node items that are represented by symbols of chemical elements from the periodic table: H, He, Li, etc.

$atomColor(blue)Ca(OH)2 <=> Ca^2+ + 2OH^-
$atomColor(blue)Ca(OH)2 <=> Ca^2+ + 2OH^-
[Pt$atomColor(blue)(NH3)4$atomColor()](NO3)2
[Pt$atomColor(blue)(NH3)4$atomColor()](NO3)2
K2(+1)$atomColor1(magenta)Cr(+6)2O(-2)7
K2(+1)$atomColor1(magenta)Cr(+6)2O(-2)7

Заряд узла Node charge

Типичная ситуация, где требуется заряд узла - формулы анионов и катионов.

A typical situation where a node charge is required is the formulas of anions and cations.

3H^+ + PO4^3- <=> 2H^+ + HPO4^2-
3H^+ + PO4^3- <=> 2H^+ + HPO4^2-

Заряд узла начинается со знака ^ после описания узла. В некоторых языках программирования так обозначается возведение в степень. Да и сам вид такого значка как бы говорит о том, что следующие символы должны располагаться выше.

The node charge starts with the ^ sign after the node description. In some programming languages, this is how raising to a power is denoted. And the very appearance of such a symbol seems to indicate that the following symbols should be located above.

Существует несколько способов описания заряда, которые перечислены в справочнике.

There are several ways to describe charge, which are listed in the reference.

Изменение положения заряда Changing the position of the charge

Иногда бывают ситуации, когда нужно вывести заряд не справа, а слева. Для этого достаточно поставить символ ` (обратный апостроф) перед знаком ^.

Sometimes there are situations when you need to output the charge not from the right, but from the left. To do this, simply put the symbol ` (backtick) before the ^ sign.

Mg`^+2
Mg`^+2

Существует и боле сложный вариант при помощи функции $pos. Но он бывает нужен довольно редко.

There is a more complex option using the $pos function. But it is rarely needed.

Текстовые возможности Text features

Текстовые возможности применимы к таким элементам узла как комментарии и абстрактные элементы. А так же к операциям.

Text capabilities apply to node items such as comments and abstract elements, as well as to operations.

CharChem не предназначен для вывода сложных текстов. Предполагается, что комментарии будут короткие и без какого-то сложного форматирования

CharChem is not intended for displaying complex texts. Comments are expected to be short and without any complex formatting.

Специальные символы Special characters

Есть несколько "магических" сочетаний для часто используемых специальных символов

There are several "magic" combinations for commonly used special characters.

ОписаниеDescription Исходное обозначениеOriginal designation Выводимый результатOutput result
ГрадусDegree^o°
Стрелка вверхUp arrow |^ илиor ArrowUp
Стрелка внизDown arrow |v илиor ArrowDown

Примеры

Examples

GeS2 + 2H2O "100°C"--> GeO2"|v" + 2H2S"|^"
GeS2 + 2H2O "100°C"--> GeO2"|v" + 2H2S"|^"

Греческие буквы Greek letters

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

Greek letters can be used in comments and abstract items by entering the letter name in square brackets.

Полный список греческих букв есть в справочнике.

A complete list of Greek letters is available in the reference.

$nM(27)Al + {[gamma]} -> $nM(27)Al"*"
$nM(27)Al + {[gamma]} -> $nM(27)Al"*"
C + H2O "[Delta]"-> CO + H2
C + H2O "[Delta]"-> CO + H2

Надстрочные и подстрочные символы Superscript and subscript characters

Надстрочный символ следует после ^, подстрочный - после _. Если нужно не один, а несколько символов, то они заключаются в фигурные скобки.

The superscript symbol comes after ^, the subscript symbol comes after _. If you need more than one symbol, they are enclosed in curly brackets.

{R^A} {R^ABC} {R^{ABC}}
{R^A} {R^ABC} {R^{ABC}}
{R_A} {R_ABC} {R_{ABC}}
{R_A} {R_ABC} {R_{ABC}}

Цвет текста Text color

Обсуждавщиеся ранее цветовые функции могут указывать цвет только для всего текстового элемента.
Но если нужно менять цвета внутри текста, то нужно использовать конструкцию {\color{код-цвета}текст}.
Возможные коды цветов перечислены в справочнике.

The color functions discussed earlier can only specify a color for the entire text element.
But if you need to change colors within the text, you need to use the {\color{color-code}text} construct.
Possible color codes are listed in the reference.

-"AB{\color{red}CD}EF"
-"AB{\color{red}CD}EF"

Можно использовать \color{код-цвета}, если нужно указать цвет для всего оставшегося текста.

You can use \color{color-code} if you want to specify a color for all remaining text.

-"AB\color{red}CDEF"
-"AB\color{red}CDEF"

PS. Синтаксис для цвета и надстрочных/подстрочных символов заимствован из достаточно известной системы TeX

P.S. The syntax for color and superscript/subscript characters is borrowed from the well-known TeX system.

Локализованные фразы Localized phrases

Система CharChem предоставляет возможность использовать разные языки. Для этого существует словарь. Его можно пополнять программно. Но в нём уже есть ряд зарезервированных фраз.

The CharChem system provides the ability to use different languages ​​using a special dictionary. It can be replenished programmatically. But it already contains a number of reserved phrases.

Чтобы в тексте использовать фразу на текущем языке, нужно указать ключ фразы в обратных апострофах.

To use a phrase in the current language in the text, you must specify the phrase key in backticks.

Следующие примеры демонстрируют вывод на языке пользователя названия химического элемента и агрегатные состояния реагентов

The following examples demonstrate the output in the user's language of the name of a chemical element and the states of aggregation of reagents.

H-Br$color(gray)|h"`Br`"
H-Br$color(gray)|h"`Br`"
2Na"`(s)`" + Cl2"`(g)`"
2Na"`(s)`" + Cl2"`(g)`"

Гидраты, сольваты и аддукты Hydrates, solvates and adducts

Записываются при помощи знака *, без пробелов

They are written using the * sign, without spaces.

CuSO4*5H2O
CuSO4*5H2O
LiCl*4CH3OH
LiCl*4CH3OH
K2O*Al2O3*'x'SiO2*'у'H2O
K2O*Al2O3*'x'SiO2*'у'H2O

Первый коэффициент First coefficient

Коэффициент перед реагентом всегда относится ко всему реагенту.

The coefficient in front of a reagent always refers to the entire reagent.

2KMnO4 + 10KCl + 8H2SO4 = 5Cl2 + 2MnSO4 + 6K2SO4 + 8H2O
2KMnO4 + 10KCl + 8H2SO4 = 5Cl2 + 2MnSO4 + 6K2SO4 + 8H2O

Поэтому, если нужен коэффициент для первого сегмента, то нужно брать реагент в скобки.

Therefore, if you need a coefficient for the first segment, you need to put the reagent in brackets.

[2Ca(OH)2*3Mg(OH)2]
[2Ca(OH)2*3Mg(OH)2]

В таком виде 2 относится только к Ca(OH)2. А без скобок это был бы коэффициент всего реагента.

In this form, 2 refers only to Ca(OH)2. Without the brackets, it would be the coefficient of the entire reagent.

Химические операции Chemical operations

Полный список операций представлен в справочнике.

A complete list of operations is presented in the reference.

Операции принято использовать для разделения реагентов в химических реакциях.

Operations are commonly used to separate reagents in chemical reactions.

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

Before and immediately after the operation code, without a space, you can specify text labels in quotation marks. The same text features that were discussed in the previous section apply to these labels.

C + 2S "t^oC"--> CS2
C + 2S "t^oC"--> CS2
CCl3CO2H "Na(Hg)"-->"H_3O^+" CH3CO2H
CCl3CO2H "Na(Hg)"-->"H_3O^+" CH3CO2H
$C()H/`|$C()O|\NH2 "\color{red}160-120 ^oC"--|>"\color{blue}71%" $C()`|$C()N//\|_qNH_q_qqN_q|`/`\\
$C()H/`|$C()O|\NH2 "\color{red}160-120 ^oC"--|>"\color{blue}71%" $C()`|$C()N//\|_qNH_q_qqN_q|`/`\\

Химические связи Chemical bonds

Мы уже рассмотрели относительно простые возможности CharChem. Пора переходить к более серьёзным формулам.

We have already looked at the relatively simple capabilities of CharChem. It is time to move on to more serious formulas.

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

There are quite a few different ways to describe chemical bonds.

Краткие описания химических связей Short descriptions of chemical bonds

Начнём с самого простого способа описания химических связей.

Let's start with the simplest way to describe chemical bonds.

CH3-CH2-OH
CH3-CH2-OH

Здесь одинарные ковалентные связи между атомами углерода и кислорода указаны при помощи знака "минус".

Here, single covalent bonds between carbon and oxygen atoms are indicated by a "minus" sign.

Тот же принцип можно использовать для двойных и тройных связей:

The same principle can be used for double and triple bonds:

H2C=CH-CH3
H2C=CH-CH3
HC%C-CH3
HC%C-CH3

Здесь знак "равно" используется для двойных связей. А вот для тройных - знак процента.

Here the "equal" sign is used for double bonds. But for triple bonds - the percent sign.

Последовательность узлов, соединённых химическими связями будем называть цепочками.

A sequence of nodes connected by chemical bonds will be called a chains.

Теперь перейдём от горизонтальных цепочек к вертикальным.

Now let's move from horizontal chains to vertical ones.

CH3|CH2|OH CH2||CH|CH3 CH|||C|CH3
CH3|CH2|OH
CH2||CH|CH3
CH|||C|CH3

Для этого понадобилось заменить минус на вертикальную черту, знак "равно" - на две вертикальные черты, а процент - на три.

To do this, it was necessary to replace the minus with a vertical bar, the "equal" sign with two vertical bars, and the percentage with three.

Следующий шаг - замена вертикальной черты на наклонную. Точнее символы "слэш" или "обратный слэш".

The next step is to replace the vertical bar with a slash. More precisely, the "slash" or "backslash" symbols.

H3C\O\CCl3 H2C\\N\CH3 HC\\\C\CH3
H3C\O\CCl3
H2C\\N\CH3
HC\\\C\CH3
H3C/O/CCl3 H2C//N/CH3 HC///C/CH3
H3C/O/CCl3
H2C//N/CH3
HC///C/CH3

Таким образом, мы можем использовать следующие символы для описания химических связей: Thus, we can use the following symbols to describe chemical bonds: - = % | \ /

Такие описания в CharChem называются краткими связями.

Such descriptions are called short bonds in CharChem.

Но пока мы можем строить цепочки только в 4 направления. Этого недостаточно для структурных формул.

But for now we can only build chains in 4 directions. This is not enough for structural formulas.

Однако, достаточно добавить перед описанием символ обратного апострофа, чтобы поменять направление на противоположное.

However, it is enough to add a backtick before the description to change the direction to the opposite.

CH3`\O`\Cl3C CH2`\\N`\H3C CH`\\\C`\H3C
CH3`\O`\Cl3C
CH2`\\N`\H3C
CH`\\\C`\H3C
CH3`/O`/Cl3C CH2`//N`/H3C CH`///C`/H3C
CH3`/O`/Cl3C
CH2`//N`/H3C
CH`///C`/H3C

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

Note that the bonds are drawn in the opposite direction, but the node items always go from left to right. So sometimes you have to rearrange the items to make the formula look better.

Теперь мы можем строить цепочки, используя 8 направлений.

Now we can build chains using 8 directions.

{A}`\{B} {A}`|{B} {A}/{B} {A}`-{B}
{A}-{B} {A}`/{B} {A}|{B} {A}\{B}
{A}`\{B}
{A}`|{B}
{A}/{B}
{A}`-{B}
{A}-{B}
{A}`/{B}
{A}|{B}
{A}\{B}

Скелетные формулы Skeletal formulas

Чтобы получить скелетные формулы, можно записывать подряд описания связей без узлов

To obtain skeletal formulas, you can write down descriptions of chemical bonds in a row without nodes.

\/\//
\/\//
/\OH
/\OH

И вот как выглядит описание формулы бензола

And here is what the description of the benzene formula looks like:

/\\|`//`\`||
/\\|`//`\`||

Тут стоит отметить, что CharChem понимает, что последняя связь соединяется с первой.

It is worth noting here that CharChem understands that the last chemical bond is connected to the first.

Благодаря этому возможен даже такой приём - повторная прорисовка связи поверх существующей.

Thanks to this, even such a technique is possible - re-drawing a connection over an existing one.

|\|`/`\`|/\/
|$color(var(--select-color))\$color()|`/`\`|/\/

В этом случае две одинарных связи превращаются в одну двойную.

In this case, two single bonds are converted into one double bond.

Система координат и углы Coordinate system and angles

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

In the previous section we got acquainted with the description of chemical bonds. It is clear that they are simply geometric figures.

Вообще, при составлении химических формул больше нужна геометрия, чем химия.

In general, when composing chemical formulas, geometry is needed more than chemistry.

Поэтому стоит познакомиться с системой координат, которая используется в CharChem.

Therefore, it is worth getting acquainted with the coordinate system used in CharChem.

$L(2)$color(gray)_(x%w:6,H)_(x-%w,y4,N0)_(x%w,H)_(x-%w,y2,N0)_(x%w,H)_(y-%w,H)_(x-2,y%w,N0)_(y-%w,H)_(x-4,y%w,N0)_(y-%w,H)_(x2,y-1,N0)$color(blue)_(y8,>)@:y(n)<_(x.35,y-.4,N0){&n}>@(y)_(y-1,N0)@y(2)_(y-2,N0)@y(1)_(y-2,N0)@y(0)_(y-2,N0)@y(-1)_(x-3,y2,N0)_(x8,>)@:x(n)<_(x.25,y-.4,N0){&n}>@(x)_(x-1,N0)@x(2)_(x-2,N0)@x(1)_(x-4,N0)@x(-1)$color(black)_(x2)_(A30,W2)_(A90)_(A150)_(A-150)_(A-90)_(A-30)

Здесь на систему координат наложена формула циклогексана \|`/`\`|/, которая представляет правильный шестиугольник.

Here the formula of cyclohexane \|`/`\`|/, which represents a regular hexagon, is superimposed on the coordinate system.

Ось Y направлена вниз. Это может быть непривычно для математоков, но является типичным для машинной графики.

The Y axis points downwards. This may be unusual for math majors, but is typical for computer graphics.

Для CharChem стандартными направлениями являются слева направо и сверху вниз.

For CharChem, the default directions are left to right and top to bottom.

Начало координат всегда совпадает с первым узлом.

The origin always coincides with the first node.

Ещё тут хорошо видно, что стандартная длина химической связи равна единице.

It is also clearly visible here that the standard length of a chemical bond is equal to one.

Кроме того, угол между осью X и наклонной связью составляет 30°

In addition, the angle between the X axis and the inclined bond is 30°

На следующем изображении можно видеть, что высота шрифта по-умолчанию равна 0.5

In the following image you can see that the default font height is 0.5

$color(black)O$color(silver)_(x-1,y-1,N0)_(x3,H)_(x-3,y1,N0)_(x3,H)_(x-3,y1,N0)_(x3,H)_(x-3,y1,N0)_(x3,H)_(x-2,y-2,N0)$color(black)|O--CH2`|CH2`--$color(silver)_(y-2,N0)_(y5,H)_(x1,N0)_(y-5,H)

Так как тут узлы содержат текст, то видимая длина химических связей становится короче. Например, вертикальные связи между двумя атомами кислорода и между двумя двумя атомами углерода имеют длину 0.5.

Since the nodes here contain text, the apparent length of chemical bonds becomes shorter. For example, vertical bonds between two oxygen atoms and between two carbon atoms have a length of 0.5.

Ширина текстовых узлов зависит от того, какие там используются символы. Это создаёт некоторые трудности, которые мы рассмотрим далее.

The width of text nodes depends on the characters used there. This creates some difficulties, which we will look at next.

УглыAngles

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

In the following image you can see which angles are used for the most typical formulas that form hexagonal cells.

$L(2)_(A0,>)"0^o"; #1_(A30,>)"3""0^o"; #1_(A90,>)"90^o"; #1_(A150,>)"15"`"0^o"; #1_(A180,>)"18"`"0^o"; #1_(A-150,>)"-15"`"0^o"; #1_(A-90,>)"-90^o"; #1_(A-30,>)"-3""0^o"

ВетвленияBranching

Большинство структурных формул не являются простыми цепочками, а содержат ответвления.

Most structural formulas are not simple chains but contain branches.

Иногда в литературе можно встретить вот такую формулу ацетона:

Sometimes in literature you can find the following formula for acetone:

CH3-C(=O)-CH3

(Кстати, это описание формулы совпадает с получаемой формулой.) Здесь скобками обозначено, что атом кислорода не является частью основной цепи.

(By the way, this description of the formula coincides with the resulting formula.) Here, the brackets indicate that the oxygen atom is not part of the main chain.

Примерно тот же принцип положен в основу веток CharChem. Для этого используются угловые скобки (то есть пара символов < > "меньше" и "больше").

CharChem branches are based on roughly the same principle. For this, angle brackets are used (i.e. a pair of < > "less than" and "greater than" symbols).

CH3-C<||O>-CH3
CH3-C<||O>-CH3

Тут всего лишь произошла замена круглых скобок на угловые, а горизонтальная двойная связь в виде знака = поменялась на вертикальную в виде ||

Here, all that has happened is that the round brackets have been replaced with angle brackets, and the horizontal double bond in the form of the = sign has been replaced with a vertical one in the form of the || signs.

Другими словами, после знака > нужно вернуться к соответствующему знаку < и продолжать цепочку от этого места.

In other words, after the > sign, you need to return to the corresponding < sign and continue the chain from this place.

CH3-C"<"C:a"||"O_(h)">"-CH3; #a_(x.3,y-.4,N0){}$color(magenta)_(x1.5,>)_(x.2,N0)_m(y-1)_m(x-2)_(y1,>)_(y0.8,N0)_m(y.8)_m(x2.4)_(y-1,>)

Конечно же, ветка может состоять из нескольких узлов, которые образуют боковую цепь. Например, вот так можно описать рацемическую формулу лизина:

Of course, a branch can consist of several nodes that form a side chain. For example, this is how the racemic formula of lysine can be described:

H2N-CH<|CH2|CH2|CH2|CH2|NH2>-COOH
H2N-CH<|CH2|CH2|CH2|CH2|NH2>-COOH

Более того, можно делать ветки внутри ветки. Например, чтобы изобразить рацемическую формулу валина (2 варианта):

Moreover, you can make branches within a branch. For example, to depict the racemic formula of valine (2 options):

H2N-CH<|CH<`-H3C>-CH3>-COOH
H2N-CH<|CH<`-H3C>-CH3>-COOH
H2N\<|<`/>\>/COOH
H2N\<|<`/>\>/COOH

Кроме того, из одного узла можно делать несколько веток. Например, такой вариант формулы D-фруктозы:

In addition, several branches can be made from one node. For example, this variant of the D-fructose formula:

CH2OH|C<=O>|C<-H><`-HO>|C<-OH><`-H>|C<-OH><`-H>|CH2OH
CH2OH|C<=O>|C<-H><`-HO>|C<-OH><`-H>|C<-OH><`-H>|CH2OH

Рекомендуется выбирать в качестве ветки тот участок, который короче основной цепи. Но это не обязательно.

It is recommended to choose as a branch the section that is shorter than the main chain. But this is not necessary.

Ещё одной важной особенностью является то, что ветка может сливаться с ранее созданными узлами. Например, если надо изобразить цикл из двух колец, то ветки не нужны. Вот пример, где начинаем цепь из точки А и завершаем в точке B.

Another important feature is that a branch can merge with previously created nodes. For example, if you need to depict a cycle of two rings, then branches are not needed. Here is an example where we start the chain from point A and end at point B.

{A}|{B}`/`\`|/\/\|`/`\
{A}|{B}`/`\`|/\/\|`/`\

Но если нужно объединить три цикла, то уже потребуется ветвление.

But if you need to combine three cycles, then branching will be required.

{A}|{B}`/`\`|/\/\{D}|{C}<`/`\>\/`|`\`/
{A}|{B}`/`\`|/\/\{D}|{C}$color(var(--select-color))<`/`\$color()>\/`|`\`/

Тут цепь начинается в точке А, заканчивается в точке D, но в процессе ветка замыкает средний цикл веткой из С в В

Here the chain starts at point A, ends at point D, but in the process the branch closes the middle cycle with a branch from C to B

Альтернативный вариант ветвления Alternative branching option

Одной из главных целей CharChem является использование формул в HTML-документах. Однако, там символы < и > являются служебными, т.к. используются для обозначения тегов. Если вставить такое описание формулы в HTML-документ, то это скорее всего приведёт к ошибке.

One of the main purposes of CharChem is to use formulas in HTML documents. However, the < and > symbols are special characters there, as they are used to denote tags. If you insert such a formula description into an HTML document, it will most likely lead to an error.

-</>\
-</>\

Чтобы не было ошибок, необходимо экранировать служебные символы. Это значит что в HTML-документе это описание должно быть таким: To avoid errors, special characters must be escaped. This means that in an HTML document, this description should be as follows:
-&lt;/&gt;\

Конечно, это сильно усложняет ввод формул, если это делается вручную.

Of course, this makes entering formulas much more difficult if done manually.

Поэтому можно использовать альтернативную конструкцию ветвления при помощи (* и *)

Therefore, an alternative branching construct using (* and *) can be used.

-(*/*)\
-(*/*)\

То есть (* является точной заменой для <, а *) - для >

That is, (* is an exact replacement for <, and *) is an exact replacement for >.

Но это работает только для ветвлений. Есть и другие ситуации, где требуется использовать служебные символы. Например, для операций:

But this only works for branches. There are other situations where you need to use service symbols. For example, for operations:

H2O <=> H^+ + OH^-
H2O <=> H^+ + OH^-

Здесь альтернативы нет. Только экранирование.

There is no alternative here. Only escaping.

Поэтому рекомендуется набирать описания формул на тестовом стенде. Там есть специальная возможность: Коды для вставки в документ.
Рекомендуется вставлять описания химических формул именно оттуда, т.к. там уже выполнено экранирование всех специальных символов.

Therefore, it is recommended to type the formula descriptions on the test stand. There is a special option there: Codes for insertion into the document.
It is recommended to insert the descriptions of chemical formulas from there, because all special characters are already escaped there.

Нумерация узлов, соединение цепочек, ссылки и метки Node numbering, chain connection, links and labels

Иногда проще разделить сложную структуру на несколько более простых, а затем их соединить.

Sometimes it is easier to divide a complex structure into several simpler ones and then connect them.

Например, формулу метана можно представить как пересечение двух цепей.

For example, the formula for methane can be represented as the intersection of two chains.

H-C-H; H|#C|H
H-C-H; H|#C|H

Первая цепь из трёх узлов H-C-H заканчивается точкой с запятой. После неё можно добавить пробел или перенос строки.

The first chain of three nodes H-C-H ends with a semicolon. After that, you can add a space or a line break.

Точка соединения цепей обозначена #C. Такая конструкция называется ссылкой на узел.

The connection point of the chains is marked #C. This construction is called a link to node.

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

Links always start with a hash sign, and then there can be different options. In this case, the carbon symbol is used, because such a node is already in the formula.

Это работает так: когда в цепи встречается ссылка, то происходит поиск узла среди ранее созданных. Затем текущая цепочка соединяется с найденным узлом.

It works like this: when a link is encountered in a chain, a node is searched for among previously created ones. Then the current chain is connected to the found node.

Ссылки можно делать только на те узлы, которые уже созданы. То есть, те, которые находятся в тексте описания слева от ссылки.

Links can only be made to nodes that have already been created. That is, those that are in the description text to the left of the link.

Сама ссылка узлом не является. То есть, в предыдущем примере формула содержит только один атом углерода. А ссылка всего лишь сообщает, что к нему надо присоединить еще одну цепь.

The link itself is not a node. That is, in the previous example, the formula contains only one carbon atom. And the link only says that another chain should be attached to it.

Номера узлов Node numbers

Но давайте рассмотрим формулу этана, где потребуется три цепочки.

But let's look at the formula for ethane, which requires three chains.

H-C-C-H; H|#2|H; H|#3|H
H-C-C-H; H|#2|H; H|#3|H

Здесь мы видим две ссылки: #2 и #3. Использовать для ссылки символ углерода тут уже нельзя, т.к. это два разных атома углерода. Поэтому используются номера узлов.

Here we see two links: #2 and #3. It is no longer possible to use the carbon symbol for the link here, since these are two different carbon atoms. Therefore, node numbers are used.

Узлы нумеруются в порядке их определения в формуле. Вот тут обозначены номера всех узлов для данной формулы:

The nodes are numbered in the order they are defined in the formula. Here are the numbers of all the nodes for this formula:

H1-C2-C3-H4; H5|#2|H6; H7|#3|H8
$L(1.2)H@:n(n,y:-.45,x:0.35)<$itemColor1(blue)_(x&x,y&y,N0)"&n">@(1)--C@n(2)--C:c2@n(3)--H@n(4); H@n(5)|#C|H@n(6); H@n(7)|#c2|H@n(8)

Относительные номера узлов Relative Node Numbers

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

In large formulas it can be quite difficult to count nodes from the beginning. Also, the numbers can change if some changes are made to the formula.

Тогда можно использовать относительную нумерацию.

Then you can use relative numbering.

H-O-C-H; H|#-3|H
H-O-C-H; H|#-3|H
H-O-C-3-H-2; H-1|#-3|H
$L(1.2)H@:n(n,y:-.45,x:0.35)<$itemColor1(blue)_(x&x,y&y,N0)"&n">@;--O--C@n(-3)--H@n(-2); H@n(-1)|#C|H

Для относительной нумерации используются отрицательные числа. Они отсчитываются в обратную сторону от ссылки.

Negative numbers are used for relative numbering. They are counted backwards from the reference.

Конечно, использование относительной нумерации может быть ещё сложнее, чем абсолютной. Кроме того, чем дальше нужный узел от ссылки, тем меньше пользы от такого способа.

Of course, using relative numbering can be even more difficult than using absolute numbering. Also, the further the node you want is from the reference, the less useful this method is.

Метки узлов Node labels

Наиболее надёжным способом является использование метки.

The most reliable way is to use a label.

H-C:a-C:b-H; H|#a|H; H|#b|H
H-C:a-C:b-H; H|#a|H; H|#b|H

Здесь нужные узлы снабжены метками a и b. Метка ставится после узла (без пробела). Она состоит из символа двоеточия и имени.

Here the required nodes are provided with labels a and b. The label is placed after the node (without a space). It consists of a colon symbol and a name.

Правила для имён меток:

Rules for label names:

Правильные имена: Correct names: a, a1, A11, first, First.

Неправильные имена: Incorrect names: He (химический элементchemical element) 1a (должно начинаться с буквыmust start with a letter), a1_1 (должно состоять только из букв и цифрmust consist of letters and numbers only).

PS. На самом деле имя может совпадать с символом химического элемента. Строго говоря, ошибкой это не является. Но делать так не рекомендуется во избежание неопределённости.

P.S. In fact, the name may coincide with the symbol of the chemical element. Strictly speaking, this is not an error. But it is not recommended to do so in order to avoid uncertainty.

Использование ссылок для циклов Using links for cycles

Ссылки можно использовать не только для того чтобы соединять разные цепочки. Но с их помощью можно делать циклы для одной цепи.

Links can be used not only to connect different chains, but also to make cycles for one chain.

Вот достаточно распространённая структура в виде пятиугольного цикла

Here is a fairly common structure in the form of a pentagonal cycle

|\/`|`-
|\/`|`-

Как видно, здесь цикл не замкнут. Но достаточно добавить ссылку на первый узел, и получится цикл.

As you can see, the cycle is not closed here. But it is enough to add a link to the first node, and you will get a cycle.

|\/`|`-#1
|\/`|`-#1

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

Moreover, in this case the last bond will connect the last node with the first node, regardless of how the bond is described. Because the coordinates of the nodes are already fixed before the description of the last bond begins. And it only connects them.

Разрыв Break

Символ # и пробел (а так же перенос строки или табуляция) является отдельной конструкцией, которая позволяет разбить длинное описание с целью улучшения читабельности.

The # symbol and a space (as well as a line break or tab) are a separate construct that allows you to break up a long description to improve readability.

\/# \/# \/
\/# \/# \/
\/ \/ \/
\/ \/ \/

Как видно, при наличии разрывов получено описание одного реагента. А если просто вставить пробелы, то это будет три разных реагента.

As you can see, with the breaks, a description of one reagent is obtained. But if you simply insert spaces, then these will be three different reagents.

Функции для химических связей Functions for chemical bonds

Ранее мы уже рассматривали функции, которые применяются для узлов. Кроме того, полный список функций есть в справочнике.

We have already looked at the functions that apply to nodes. In addition, a full list of functions is available in the reference.

Для лучшего понимания давайте более подробно изучим химическую связь, которая получается из описания \.

For a better understanding, let's take a closer look at the chemical bond that results from the description \.

_(y-.5,N0)$color(#999)_(y3,>); #1_(x-.5,N0)_(x5.5,>); #1_(y2,N0,x-.5)_(x5.5,H); #1_(x2,y-.5,N0)_(y3,H)_(x2,N0)_(y-3,H); #1_(x3,N0):a; #1_(A30,L3,N0)_m(x.3)_m(y-1,x.3)_(>)#a; #1$color(#007)@:n(v)<_(A-45,L0.5,N0)"&v">@(0)_(x2,N0)@n(0.5)_(x2,N0)@n(1)_(x1,N0)@n(x)_(x-1.3,y.8,N0)"30^o"; #1_(y2,N0)@n(0.5)_(y0.7,N0)@n(y); #1$color()_(A30,L4,w2)

В системе координат, которая используется для формул, у этой связи будут следующие свойства:

In the coordinate system used for the formulas, this bond will have the following properties:

Такие свойства хорошо подходят для конструирования шестиугольников.

These properties are well suited for constructing hexagons.

Угол наклона Tilt angle

Но давайте изобразим структурную формулу сульфата кальция But let's draw the structural formula of calcium sulfate CaSO4.

Здесь намного лучше подходит угол наклона не 30°, а 45°. Для этого используем функцию Here, a tilt angle of 45° rather than 30° is much more suitable. For this, we use function $slope()

$slope(45)Ca/O\S<//O><\\O>`/O`\
$slope(45)Ca/O\S<//O><\\O>`/O`\

Действие функции $slope распространяется до конца формулы, либо до следующей такой функции.

The scope of the $slope function extends to the end of the formula, or to the next such function.

Вот немного искусственный пример, где демонстрируется применение нескольких функций для изменения угла.

Here's a slightly contrived example that demonstrates the use of multiple functions to change the angle.

/\$slope(40)/\$slope(50)/\$slope(60)/\$slope()/\
/\$slope(40)/\$slope(50)/\$slope(60)/\$slope()/\

Обратите внимание, что функция без параметра (с пустыми скобками) возвращает исходное значение наклона.

Note that the function without a parameter (with empty parentheses) returns the original slope value.

Кроме того, использование slope с явно указанным углом запрещает автоматическое распознавание горизонтальных шестиугольников (см. следующий раздел). Поэтому $slope(30) и $slope() - не одно и то же.

Also, using slope with an explicit angle disables automatic recognition of horizontal hexagons (see next section). Therefore, $slope(30) and $slope() are not the same.

Длина связи Bond length

Длину связей можно менять при помощи функции $L()

The length of chemical bonds can be changed using the $L() function.

Для формулы сульфата кальция желательно удлиннить связи, т.к. стандартная длина ориентирована на узлы с одной буквой (C, H или S). А для Ca выглядит слишком короткой.

For the calcium sulfate formula, it is desirable to lengthen the bonds, since the standard length is oriented towards nodes with one letter (C, H or S). And for Ca it looks too short.

$L(1.3)$slope(45)Ca/O\S<//O><\\O>`/O`\
$L(1.3)$slope(45)Ca/O\S<//O><\\O>`/O`\

Действие функции распространяется до конца формулы, либо до следующей функции. Пустые параметры означают возврат к значению по-умолчанию, которое равно 1.

The function scope extends to the end of the formula or to the next function.
Empty parameters mean returning to the default value, which is 1.

$L(2)|$L(3)-$L(2)`|$L()`-|`-`|`-
$L(2)|$L(3)-$L(2)`|$L()`-|`-`|`-

Вот ещё пример, где используется тот факт, что расстояние между верхней и нижней точкой шестиугольника равно 2.

Here's another example that uses the fact that the distance between the top and bottom points of a hexagon is 2.

\|`/`\`|/$L(2)|
\|`/`\`|/$L(2)|

Выравнивание двойных связей Alignment of double bonds

По-умолчанию при выводе двойных связей выполняется автоматическое выравнивание. Вот три примера, где цепь начинается от атома хлора.

By default, automatic alignment is performed when deriving double bonds. Here are three examples where the chain starts from the chlorine atom.

Cl\||`/ Cl\||\ Cl`/||\
Cl\||`/ Cl\||\ Cl`/||\

В первом случае произошло выравнивание вправо, во втором - по центру, в третьем - влево. Здесь лево и право определяются относительно направления связи в цепи.

In the first case, alignment occurred to the right, in the second - to the center, in the third - to the left. Here, left and right are defined relative to the direction of the bond in the chain.

Однако, есть способ явно указать, в какую сторону надо выравнивать двойные связи при помощи функции $dblAlign().

However, there is a way to explicitly specify which direction double bonds should be aligned using the $dblAlign() function.

Cl$dblAlign(R)\||`/ Cl$dblAlign(M)\||`/ Cl$dblAlign(L)\||`/
Cl$dblAlign(R)\||`/ Cl$dblAlign(M)\||`/ Cl$dblAlign(L)\||`/

Здесь R означает "право", M - "середина", L - "лево". Можно использовать строчные буквы - r, m и l.

Here R means "right", M means "middle", L means "left". Lowercase letters can be used - r, m and l.

Функция так же, как и предыдущие, действует до конца формулы, либо до следующей функции. А пустые параметры означают восстановление поведения по-умолчанию.

The function, like the previous ones, has a scope until the end of the formula or until the next function. And empty parameters mean restoring the default behavior.

Цвет связей Color of bonds

Единственным способом указать цвет связей является функция $color()

The only way to specify the color of bonds is the $color() function.

\$color(red)||`/$color(green)`\\`|$color()//
\$color(red)||`/$color(green)`\\`|$color()//

Вертикальные и горизонтальные шестиугольники Vertical and horizontal hexagons

Есть два вида шестиугольников:

There are two types of hexagons:

\|`/`\`|/ = /-\`/`-`\
\|`/`\`|/ = /-\`/`-`\

Левый называется вертикальным, а правый — горизонтальным.

The left one is called vertical and the right one is called horizontal.

Разница в том, что наклонная связь, которая описывается символом \ (обратный слэш), в вертикальном шестиугольнике образует с осью X угол в 30°, а во втором — 60°.

The difference is that the inclined bond, which is described by the symbol \ (backslash), forms an angle of 30° with the X-axis in the vertical hexagon, and 60° in the second.

Основным способом является вертикальный. Но CharChem может определить по сочетанию определённых символов, что нужно использовать горизонтальный вариант. Например, здесь таким сочетанием является /-.

The main way is vertical. But CharChem can determine by a combination of certain characters that the horizontal variant should be used. For example, here such a combination is /-.

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

However, in some cases the system may make mistakes. This most often happens when there are different types of hexagons in one formula.

/`\`-`/\-\$slope(30)`/|\/`|`\
/`\`-`/\-\$slope(30)`/|\/`|`\

Здесь пришлось явно указать угол в 30° при помощи функции slope. Потому что сочетание \`/ по-умолчанию относится к горизонтальному режиму.

Here I had to explicitly specify the angle of 30° using the slope function. Because the combination \`/ by default refers to the horizontal mode.

\`/
\`/

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

In addition to the slope function, other methods of describing chemical bonds, discussed in the following sections, can be used to solve such problems. For example, universal descriptions. Because switching to horizontal mode only works for short descriptions.

Другая распространённая ситуация - продолжение цепочек. Например:

Another common situation is the continuation of chains. For example:

`-`\/-\`/\C\\\N
`-`\/-\`/\C\\\N

Здесь используется горизонтальный режим. Но нитрильная группа к нему уже не отностися. Потому что сочетание \ и \\\ не отностится к тем, которые образуют горизонтальный режим.

Here the horizontal mode is used. But the nitrile group does not belong to it. Because the combination \ and \\\ does not belong to those that form the horizontal mode.

Для исправления ситуации можно указать $slope(60), либо заменить описание тройной связи:

To correct the situation, you can specify $slope(60), or replace the description of the triple bond:

`-`\/-\`/\C_(a0,N3)N
`-`\/-\`/\C_(a0,N3)N

Конструкция _(a0,N3) означает что химическая связь отклоняется от предыдущей на 0° и имеет кратность 3.

The construction _(a0,N3) means that the chemical bond deviates from the previous one by 0° and has a multiplicity of 3.

Суффиксы Suffixes

Суффиксы служат для придания связям дополнительных свойств. Полный список суффиксов есть в справочнике.

Suffixes serve to impart additional properties to chemical bonds. The full list of suffixes is in the reference book.

Суффикс записывается сразу после описания связи. Он включает только строчные буквы, т.к. прописные используются для химических элементов.

The suffix is ​​written immediately after the description of the bond. It includes only lowercase letters, since uppercase letters are used for chemical elements.

Прозрачные связи Transparent bonds

Бывают формулы солей, где есть ионные связи, которые явно не отображаются. Например, There are salt formulas that contain ionic bonds that are not clearly displayed. For example, Сульфит калия Potassium Sulfite

K^+/0O^-\S<||O>/O^-\0K^+
K^+/0O^-\S<||O>/O^-\0K^+

Связи между калием и кислородом есть, но они не видны. Для этого к ним добавлена цифра 0. То есть, можно считать что кратность связи равна нулю.

There are bonds between potassium and oxygen, but they are not visible. For this reason, the number 0 is added to them. That is, we can assume that the bond multiplicity is zero.

Кроме того, прозрачные связи могут быть использованы, чтобы "поднять карандаш" и переместить в другую точку.

Additionally, transparent bonds can be used to "lift the pencil" and move it to another point.

Вот например, так можно описать формулу формальдегида без использования ветвлений:

For example, this is how the formula of formaldehyde can be described without using branches:

H/C`|O|\H
H/C`|O|\H

Но тут двойная связь образовалась потому что мы сначала провели связь от углерода к кислороду, а потом вторую - обратно.

But here a double bond was formed because we first made a bond from carbon to oxygen, and then a second one back.

Тот же принцип можно использовать для формулы аммиака:

The same principle can be used for the formula for ammonia:

H/N`|H|0\H
H/N`|H|0\H

Но чтобы избежать появления двойной связи, здесь вторая связь - прозрачная.

But to avoid the appearance of a double bond, the second bond here is transparent.

Хиральность Chirality

Иногда бывает необходимо отобразить особенности пространственного строения молекул. Для этого вводятся такие понятия как центр хиральности, ось хиральности, плоскость хиральности и т.п. А химические связи имеют клиновидную форму. Закрашенные, если направлены из центра к наблюдателю. И пунктирные, если от наблюдателя.

Sometimes it is necessary to display the features of the spatial structure of molecules. For this purpose, such concepts as the chirality center, chirality axis, chirality plane, etc. are introduced. And chemical bonds have a wedge shape. Painted if directed from the center to the observer. And dotted if from the observer.

Для закрашенных используется суффикс w, а для пунктирных - d. Это если остриё клина в исходной точке связи. А если нужно чтобы остриё было в конечной точке, то ww и dd соответственно.

For filled bonds, the suffix w is used, and for dotted figures, d. Provided that the wedge tip is at the initial point of the bond. And if you want the tip to be at the end point, then ww and dd, respectively.

\w \ww \d \dd
\w \ww \d \dd

Вот пример, где они применяются все вместе:

Here's an example where they are all used together:

\w-/ww`\d`-`/dd
\w-/ww`\d`-`/dd

Рацемические соединения Racemic mixtures

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

Wavy lines are used when it is necessary to depict the formula of a racemic mixture of optical isomers. For this purpose, the suffix ~ (tilde) is used.

HO/~\O/`|`\`/|
HO/~\O/`|`\`/|

А для смеси цис- и транс-изомеров используется перекрещенная двойная связь. Для этого используется суффикс x.

And for a mixture of cis- and trans-isomers, a crossed double bond is used. For this, the suffix x is used.

Cl\=x/Cl
Cl\=x/Cl

Водородная связь Hydrogen bond

Для водородных связей используется суффикс h.

For hydrogen bonds, the suffix h is used.

H/O\H/hN<`|H></H>\H
H/O\H/hN<`|H></H>\H

Иногда это может быть полезно для отображения ионных связей. Например, для такой формулы хлорида кальция:

Sometimes this can be useful for showing ionic bonds. For example, for this formula of calcium chloride.

$L(2)Cl^-\hCa^++/hCl^-
$L(2)Cl^-\hCa^++/hCl^-

Стрелки Arrows

Суффиксы Suffixes v, vv иand vvv

\v \vv \vvv
\v \vv \vvv

Выравнивание двойных связей Alignment of double bonds

Функция $dblAlign() полезна для тех случаев, когда нужно указать правила для нескольких связей. А если нужно указать выравнивание только для одной связи, то лучше использовать суффиксы r (вправо), m (по центру) и l (влево).

The $dblAlign() function is useful when you need to specify rules for several bonds. And if you need to specify alignment for only one bond, it is better to use the suffixes r (right), m (center), and l (left).

\||r`/ \||m`/ \||l`/
\||r`/ \||m`/ \||l`/

Центры узлов Node centers

До сих пор мы рассматривали формулы, где использовались довольно простые узлы

So far we have looked at formulas that used fairly simple nodes

\O$color(#AAA)<_(y-1,N0)_(y2,H)><_(x-1,N0)_(x2,H)>$color()/

Здесь центром узла является середина буквы O.

Here the center of the node is the middle of the letter O.

Давайте посмотрим, как выглядит вертикальная связь, которая выходит из сложных узлов

Let's take a look at what a vertical bond looks like when it comes out of complex nodes.

Обратите внимание, что описание связи всегда стоит после узла. Но центр меняется, в зависимости от содержимого.

Note that the bond description always comes after the node. But the center changes depending on the content.

Это происходит потому что в CharChem есть правила, по которым определяется приоритет центра узла.

This happens because CharChem has rules that determine the priority of the node center.

  1. КомментарийComment
  2. Абстрактный элементAbstract item
  3. ВодородHydrogen
  4. Радикалы и все атомы, кроме H и C Radicals and all atoms except H and C
  5. УглеродCarbon
  6. Элемент, явно указанный при помощи обраного апострофа An element explicitly indicated by a backtick symbol

Центром становится первый элемент узла с наивысшим приоритетом.

The first node item with the highest priority becomes the center.

Например, у кислорода приоритет выше, чем у водорода. Поэтому в узле HO связь выходит из кислорода. А углерод имеет приоритеты выше, чем остальные элементы. Поэтому в узле HOOC центром является последний атом.

For example, oxygen has a higher priority than hydrogen. Therefore, in the HO node, the bond comes out of oxygen. And carbon has higher priorities than other elements. Therefore, in the HOOC node, the center is the last atom.

Отдельного пояснения требует 6 пункт. Он нужен для тех случаев, когда остальные правила не помогают. Примеры таких случаев показаны в следующей таблице:

Point 6 requires a separate explanation. It is needed for those cases when the other rules do not help. Examples of such cases are shown in the following table:

Мягкие связи Soft bonds

Не зря химики любят говорить, что химия не является точной наукой. Это относится и к формулам. Посмотрите на следующий пример:

It is not for nothing that chemists like to say that chemistry is not an exact science. This also applies to formulas. Look at the following example:

CH3-C<||O>-CH2-CH3
CH3-C<||O>-CH2-CH3

Здесь можно видеть, что горизонтальные связи соединяют не центры узлов, а края. Потому что если бы соединялись центры, то единичной длины связи было бы слишком мало.

Here you can see that horizontal bonds connect not the centers of the nodes, but the edges. Because if the centers were connected, then the unit length of the bond would be too small.

Такие связи называются мягкие.

Such bonds are called soft.

Они создаются автоматически для описаний -, = и %, Если с обоих концов находятся не автоматические узлы.

They are created automatically for -, = and % descriptions if there are non-automatic nodes at both ends.

|- |-Br |O- |O-Br
|-
|-Br
|O-
|O$color(var(--select-color))-$color()Br
обычнаяordinary обычнаяordinary обычнаяordinary мягкаяsoft

С одной стороны, они очень полезные. Но они могут создать и некоторые проблемы.

On the one hand, they are very useful. But they can also create some problems.

Дело в том, что обычные связи образуют набор в одной системе координат. А мягкие связи делят цепь на подцепи, в каждой из которой своя система координат.

The point is that ordinary bonds form a set in one coordinate system. And soft bonds divide the chain into subchains, each of which has its own coordinate system.

Здесь подцепи выделены разными цветами:

Here the subchains are highlighted with different flowers:

$color(blue)`/`-`\/-\-CH2$color()-$color(green)C<`|H3C><|O|CH2$color()-$color(red)COOH>$color()-$color(magenta)N^+<\\O>/O^-

Возможность автоматически соединить несколько связей в один цикл существует только внутри подцепи. Если захотие соединить узлы из разных подцепей, то придётся пользоваться ссылками. Например, тут:

The ability to automatically connect several bonds into one cycle exists only within a subchain. If you want to connect nodes from different subchains, you will have to use links. For example, here:

HC=CH\CH`//CH`-HC`\\HC/#1
HC=CH\CH`//CH`-HC`\\HC/#1

Причём, здесь нам вообще-то не нужны мягкие связи. Они не помогают, а мешают.

Moreover, we don't really need soft connections here. They don't help, they hinder.

Есть способ отказаться от использования мягких связей - это использовать удвоенные символы --, == и %%:

There is a way to avoid using soft links - this is to use doubled symbols --, == and %%:

HC==CH\CH`//CH`--HC`\\HC/
HC==CH\CH`//CH`--HC`\\HC/

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

The reason for all these difficulties is that from one description one can obtain different formulas by using different fonts. The binding of soft bonds occurs at the moment of drawing, when all styles are known. While other bonds fix the coordinates of nodes regardless of graphic parameters. Therefore, cycles can be built from them.

H2C-{Radical}-NH|CH2`-O_#1
H2C-{Radical}-NH|CH2`-O_#1
H2C-{Radical}-NH|CH2`-O_#1

В справочнике веществ CharChem мягкие связи составляют 3.2%

In the CharChem Substances reference, soft bonds account for 3.2%

Полигональные связи Polygonal bonds

-_p3_p3
-_q4_q4_q4
-_p_p_p_p
-_p6_p6_p6_p6_p6
-_p7_p7_p7_p7_p7_p7
-_p8_p8_p8_p8_p8_p8_p8
-_p9_p9_p9_p9_p9_p9_p9_p9

Это правильные многоугольники (полигоны). А ещё это формулы циклических углеводородов.

These are regular polygons. And these are also formulas of cyclic hydrocarbons.

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

Using short bonds we can construct a hexagon or a square, but this won't work with a pentagon.

Для этих целей в CharChem есть специальная конструкция - полигональная связь.

For these purposes, CharChem has a special construction - a polygonal bond.

Полигональные связи всегда должны быть пристыкованы к какой-то предыдущей связи, чтобы отклониться от неё на определённый угол и образовать новую сторону полигона.

Polygonal bonds must always be attached to some previous bond in order to deviate from it by a certain angle and form a new side of the polygon.

Вот несколько примеров:

Here are some examples:

-_p3_p3
-_p3_p3
|_q3_q3
|_q3_q3
-_p_p_p_p
-_p_p_p_p
|_qq_qNH_q_qq
|_qq_qNH_q_qq

Правила такие:

The rules are as follows:

Полигональные связи начинаются с _p или _q. Для поворота по часовой (p) или против часовой (q) стрелки. Polygonal connections start with _p or _q. For clockwise (p) or counterclockwise (q) rotation. -_p -_q
-_p -_q
Двойные связи делаются при помощи повтора буквы.
С тройными так не получится. Если нужна тройная, то используйте универсальную связь.
Double bonds are made by repeating a letter.
This won't work with triple bonds. If you need a triple bond, use a universal bond.
-_pp -_qq
-_pp -_qq
Число означает, сколько углов (сторон) должно быть у полигона. Например, для треугольника — 3.
А если число не указано, то по-умолчанию считается 5.
The number indicates how many angles (sides) the polygon should have. For example, for a triangle — 3.
And if the number is not specified, then 5 is considered by default.
-_p3 -_p4 -_p5 -_p -_p6 -_p7
-_p3 -_p4 -_p5 -_p -_p6 -_p7
Ветки не влияют на работу полигональных связей. Branches do not affect the operation of polygonal bonds. |_q_q<=O>_q_q
|_q_q<=O>_q_q
Важно! Длина полигональной связи соответствует длине той связи, к которой она пристыкована.
Иначе не получится замкнуть цикл. Поэтому на них не действует функция $L()
Important! The length of a polygonal bond corresponds to the length of the bond to which it is attached.
Otherwise, it will not be possible to close the cycle. Therefore, the $L() function does not work on them.
$L(1.5)/$L()<`||O>_p6
$L(1.5)/$L()<`||O>_p6
Для полигональных связей работают суффиксы, как и для кратких связей For polygonal bonds, suffixes work in the same way as for short bonds. -_p_pwO_pww_p
-_p_pwO_pww_p

Стоит отметить, что полигональные связи используют относительные коррдинаты. В то время как краткие используют абсолютные координаты. Это значит, что одинаковое описание полигона может выглядеть по-разному, в зависимости от первой связи.

It is worth noting that polygonal bonds use relative coordinates. While short ones use absolute coordinates. This means that the same description of a polygon may look different, depending on the first bond.

|_p_p_p_p -_p_p_p_p `|_p_p_p_p `-_p_p_p_p
|_p_p_p_p -_p_p_p_p `|_p_p_p_p `-_p_p_p_p

Существует два основных способа для соединения нескольких циклов. Первый способ - использование веток.

There are two main ways to connect multiple loops. The first way is to use branches.

|<_q_q_q_q>_p7_p7_p7_p7_p7_p7
|$color(var(--select-color))<_q_q_q_q$color()>_p7_p7_p7_p7_p7_p7

Здесь пятиугольник и семиугольник используют первую вертикальную связь. Но пятиугольник находится в ветке.

Here the pentagon and heptagon use the first vertical link. But the pentagon is in a branch.

Второй способ - повторный проход по уже существующей связи.

The second method is to re-pass through an existing bond.

|_q_q_q_q|0_p7_p7_p7_p7_p7_p7
$color(var(--select-color))|$color()_q_q_q_q|0_p7_p7_p7_p7_p7_p7

Суффикс 0 здесь использован, чтобы не появилась двойная связь при повторном проходе.

The suffix 0 is used here to avoid a double bond when re-passing.

Иногда полигональные связи могут быть полезны даже в тех случаях, когда полигоны не нужны. Например, вот 3,3-диэтилпентан:

Sometimes polygonal bonds can be useful even in cases where polygons are not needed. For example, here is 3,3-diethylpentane:

\/<_p4_p6><_q4_p6>/\
\/<_p4_p6><_q4_p6>/\

В справочнике веществ CharChem полигональные связи составляют 12.6%

In the CharChem Substances reference, polygonal bonds account for 12.6%

Универсальные связи Universal bonds

Краткие и полигональные связи предназначены для решения узкоспециальных задач. А универсальные связи (как следует из их названия) служат для решения всех возможных задач по описанию связей между двумя узлами. Обратной стороной такой мощности является более сложное описание.

Short and polygonal chemical bonds are intended to solve highly specialized problems. And universal bonds (as their name suggests) serve to solve all possible problems of describing bonds between two nodes. The downside of such power is a more complex description.

Доля универсальных связей в справочнике веществ CharChem составляет менее 10%. Потому что они используются там, где не получается использовать краткие или полигональные связи.

The share of universal bonds in the CharChem substances reference directory is less than 10%. Because they are used where it is not possible to use short or polygonal bonds.

Универсальные связи в общем виде выглядят так: _(параметры). Параметры перечисляются через запятую, без пробелов. Каждый параметр начинается с определённой буквы. Например:

Generally, universal links look like this: _(parameters). Parameters are listed separated by commas, without spaces. Each parameter begins with a specific letter. For example:

_(x2,y1,H,>)
_(x2,y1,H,>)

Полный список параметров есть в справочнике. Как видно, они больше напоминают команды какого-то графического формата.

The full list of parameters is in the reference. As you can see, they are more like commands of some graphic format.

Если нет ни одного параметра, то можно обойтись без скобок. То есть, в самом простом случае универсальная связь состоит из одного знака подчёркивания. Но такие связи могут быть использованы только для соединения по ссылке двух узлов, у которых уже зафиксированы координаты.

If there are no parameters, then the brackets are not required. That is, in the simplest case, a universal bond consists of a single underscore. But such bonds can only be used to connect two nodes by reference that already have fixed coordinates.

|\/`|_#1
|\/`|$color(var(--select-color))_#1

Здесь связь _ служит для соединения последнего узла с первым. Однако, чтобы получить больше пользы от универсальных связей, нужно использовать параметры.

Here the chemical bond _ serves to connect the last node to the first. However, to get more benefit from universal bonds, you need to use parameters.

Параметры всегда начинаются с определённой буквы, которая определяет назначение параметра. А далее без пробела следует значение параметра. Регистр имеет значение: A и a - разные параметры.

Parameters always start with a specific letter that defines the purpose of the parameter. Then, without a space, comes the value of the parameter. The register matters: A and a are different parameters.

Например, _(x1.5) или _(x-1) означает, что координата x конца связи перемещается на 1.5 или на -1 относительно начала.

For example, _(x1.5) or _(x-1) means that the x-coordinate of the end of the link is moved by 1.5 or -1 relative to the beginning.

Часть параметров нужны для того чтобы указывать координаты следующего узла относительно предыдущего. Но есть параметры, которые определяют другие свойства связи.

Some parameters are needed to indicate the coordinates of the next node relative to the previous one. But there are parameters that determine other properties of the bond.

Параметры x и y Parameters x and y

При помощи параметров x и y можно указать координаты следующего узла относительно предыдущего.

Using the x and y parameters, you can specify the coordinates of the next node relative to the previous one.

В следующем примере мы видим связь _(x1,y1). Координаты первого узла всегда (0, 0). Поэтому координаты второго будут (1, 1). А третьего - (2, 0), т.к. связь _(x1,y-1) увеличивает x и уменьшает y.

In the following example we see the chemical bond _(x1,y1). The coordinates of the first node are always (0, 0). Therefore, the coordinates of the second will be (1, 1). And the third - (2, 0), since the bond _(x1,y-1) increases x and decreases y.

Последняя связь _(x-2) возвращается в первый узел. То есть, x уменьшается на 2, а y остаётся без изменений равным 0. Получаем координаты (0, 0).

Последняя связь _(x-2) возвращается в первый узел. То есть, x уменьшается на 2, а y остаётся без изменений равным 0. Получаем координаты (0, 0).

_(x1,y1)_(x1,y-1)_(x-2)
_(x1,y1)_(x1,y-1)_(x-2)
{}<_(x1,y1,W2)_(x1,y-1)_(x-2)><$color(silver)_(y-.5,x1,N0,W1)_(y2,H)_(y-2,x1,N0)_(y2,H)_(x.5,y-.5,N0)_(x-3,H)><$color(brown)_(y-.5,N0)_(y2,>)@:t(t,y:-0.4)<_(x.25,y&y,N0)"&t">@(y,0.1)_(y-.5,N0)@t(1,-.1)><_(x-.5,N0)_(x3.3,>)><@t(0)_(x1,N0)@t(1)_(x1,N0)@t(2)_(x0.9,N0)@t(x)>

Вот как меняются координаты условного пера при отрисовке узлов в данной формуле:

Here's how the virtual pen coordinates change when drawing nodes in this formula:

Номер узлаNode number Координаты пераPen coordinates ИзменениеChange
10, 01, 1
21, 11, -1
32, 0-2, 0
10, 0

Координаты являются числовыми параметрами. Вместо чисел иногда удобно использовать переменные.

Coordinates are numeric parameters. It is sometimes convenient to use variables instead of numbers.

_(x%d:1.5,y%d)_(x%d,y-%d)
_(x%d:1.5,y%d)_(x%d,y-%d)
{}_(x%d:1.5,y%d,W2)_(x%d,y-%d); #1$color(silver)_(y-.5,x1,N0,W1)_(y3,H)_(y-3,x1,N0)_(y3,H)_(x1,y-3,N0)_(y3,H); #1_(x-.5,y1,N0)_(x4,H)_(y1,N0)_(x-4,H); #1$color(brown)_(y-.5,N0)_(y3,>); #1@:t(t,y:-0.33)<_(x.25,y&y,N0)"&t">@(0)_(y1,N0)@t(1)_(y1,N0)@t(2)_(y0.8,N0)@t(y); #1_(x-.5,N0)_(x4.3,>); #1_(x1,N0)@t(1)_(x1,N0)@t(2)_(x1,N0)@t(3)_(x0.9,N0)@t(x)

Здесь %d:1.5 означает, что создаётся переменная d, которая равна 1.5. А далее эта переменная используется при помощи %d.

Here %d:1.5 means that a variable d is created, which is equal to 1.5. And then this variable is used using %d.

Переменные могут быть удобны, если часто применяются одни и те же числовые значения.

Variables can be convenient if you use the same numeric values ​​frequently.

Специальный случай Special case y=0.5

Бывает, что нужно изобразить атом водорода впритык к атому азота:

Sometimes it is necessary to depict a hydrogen atom above or below a nitrogen atom:

\N<_(y.5)H>/N<_(y-.5)H>\
\N<_(y.5)H>/N<_(y-.5)H>\

Для этого нужно использовать ветку, в которой вертикальная связь длиной 0.5

To do this, you need to use a branch in which the vertical bond is 0.5 long.

Это работает потому что высота шрифта тоже равна 0.5

This works because the font height is also 0.5

Кратность Multiplicity

Параметр N позволяет указывать кратность связи. Обычно это число от 0 до 3.

The N parameter allows you to specify the multiplicity of the bond. Usually this is a number from 0 to 3.

Na^+_(x1,y1,N0)Cl^- N_(x1,y1,N3)N
Na^+_(x1,y1,N0)Cl^- N_(x1,y1,N3)N

Для двойных связей можно использовать суффиксы x l r m (или равнозначно X L R M). Здесь x - перекрещенная связь, а остальные - режим выравнивания.

For double bonds, the suffixes x l r m (or equivalently X L R M) can be used. Here x is the crossed bond and the rest are the alignment mode.

|_(x1,N2x)`| |_(x1,N2r)`| |_(x1,N2m)`| |_(x1,N2L)`|
|_(x1,N2x)`| |_(x1,N2r)`| |_(x1,N2m)`| |_(x1,N2L)`|

Абсолютные углы Absolute angles

Параметр A позволяет указать угол относительно оси X. Например:

The A parameter allows you to specify an angle relative to the X axis. For example:

_(A45)_(A135)_(A-135)_(A-45)
_(A45)_(A135)_(A-135)_(A-45)

Вот более детальная расшифровка

Here is a more detailed explanation

_(A45)
_(A45)
_(y-.5,N0)$color(brown)_(y2.5,>); #1_(x-.5,N0)_(x3,>); #1_(A45,N0,L1.5)_m(x.5)_m(x.2,y-.5)_(x-.1,y-.5,>); #3_(x.4,y-.3,N0)"y"; #5_(y.1,x.3,N0)"x"_(x-.6,y.8,N0)"45^o"; #1$color()_(A45,L2,w2)

По-сути, является аналогом кратких связей, но с указанным углом

In essence, this construction is an analogue of short bonds, but with the specified angle.

Чтобы указать длину связи, можно использовать параметр L:

To specify the length of the link, you can use the L parameter:

_(A30,L2)_(A-90)
_(A30,L2)_(A-90)

Если параметр L не указан в сочетании с A или a, то используется значение функции $L()

If the L parameter is not specified in combination with A or a, then the value of the $L() function is used.

_(A45)$L(2)_(A-45)_(A45)$L()_(A-45)
_(A45)$L(2)_(A-45)_(A45)$L()_(A-45)

Часто используемые значения углов Frequently used angle values

{}@:a(a,d:.5)<_(A&a,L2.5,>)_(a0,L&d,N0)"&a^o">@(0)@a(30,0.7)@a(60)@a(90,0.4)@a(120)@a(150,0.7)@a(180,0.8)@a(-30,0.7)@a(-60)@a(-90,0.4)@a(-120)@a(-150,0.7)

Полигональные связи Polygonal bonds

Параметр P является аналогом полигональных связей, которые описываются через _p и _q.

The parameter P is an analogue of polygonal bonds, which are described through _p and _q.

-_(P3)_(P3) = `-_(P-3)_(P-3)
-_(P3)_(P3) = -_(P-3)_(P-3)
-_(P)_(P)_(P)_(P) = -_(P-5)_(P-5)_(P-5)_(P-5)
-_(P)_(P)_(P)_(P) = -_(P-5)_(P-5)_(P-5)_(P-5)
-_(P,N3)
-_(P,N3)

Однако, в отличие от _p и _q, здесь можно описать и тройные связи.

However, unlike _p and _q, triple bonds can also be described here.

Число в параметре P означает сколько углов должно быть у полигона. Если не указано, то 5. А если число отрицательное, то поворот против часовой стрелки.

The number in the P parameter means how many corners the polygon should have. If not specified, then 5. And if the number is negative, then it means counterclockwise rotation.

Относительные углы Relative angles

Параметр a позволяет указать отклонение от направления предыдущей связи.

The a parameter allows you to specify a deviation from the direction of the previous bond.

Такой способ чем-то похож на полигональные связи. Здесь тоже требуется предыдущая связь. Но числовым параметром является угол в градусах. И длина связи не зависит от предыдущей, а указывается либо параметром L, либо функцией $L, либо 1.

This method is somewhat similar to polygonal bonds. Here, too, a previous bond is required. But the numerical parameter is the angle in degrees. And the length of the bond does not depend on the previous one, but is specified either by the L parameter, or the $L function, or 1.

-_(a60) -_(a-90) -_(a120)
-_(a60) -_(a-90) -_(a120)

Отрицательные значения означают поворот против часовой стрелки.

Negative values ​​indicate counter-clockwise rotation.

Вот более подробная иллюстрация

Here is a more detailed illustration

_(A30)_(a-60)
_(A30)_(a-60)
$color(brown)_(A30,L3)<_(a0,L.6,>)>_m(y-.45,x.4)_(y-.45,x-.4,>); #1_(x-1,N0)_(x6,>); #1_(y-1,N0)_(y3,>); #1_(A30,L1,N0)_m(x.3,y.1)_(x.1,y-.3)_(y-.2,>); #1_(y1.8,x.4,N0)"y"_(x5,y-2,N0)"x"_(x-1.8,y1.2,N0)"-60^o"_(x-1.7,y-.65,N0)"30^o"; #1$color()$L(2)_(A30,w2)_(a-60,w2)

Для первой связи указан абсолютный угол 30°. А для второй - относительный -60°. Это означает что из 30 вычитается 60 и в результате для второй связи вычисляется абсолютный угол -30°.

For the first chemical bond, the absolute angle is 30°. And for the second, the relative angle is -60°. This means that 60 is subtracted from 30 and as a result, the absolute angle calculated for the second bond is -30°.

Использование относительных углов для нормалей Using relative angles for normals

Допустим, есть вот такое циклическое соединение:

For example, there is a cyclic compound like this:

-_q_q_q_q
-_q_q_q_q

Но из него нужно сделать спирт. То есть нужно из какого-то угла вывести линию с гидроксильной группой на конце. Самый простой способ для этого - использовать относительные углы.

But you need to make alcohol out of it. That is, you need to draw a line with a hydroxyl group at the end from some angle. The easiest way to do this is to use relative angles.

Подробнее см. раздел справочника Нормали. А в этой таблице уже вычислены наиболее часто используемые значения:

For more details, see the Normals section of the reference book. And this table already calculates the most frequently used values:

Число угловNumber of angles Относительный уголRelative angle
330°
445°
554°
660°
764.3°
867.5°

Если полигон образуется поворотом по часовой стрелке (конструкция _p), то надо использовать отрицательный угол.

If the polygon is formed by a clockwise rotation (_p construction), then a negative angle must be used.

Примеры:

Examples:

-<_(a54)OH>_q<_(a54)OH>_q<_(a54)OH>_q_q
-<_(a54)OH>_q<_(a54)OH>_q<_(a54)OH>_q_q
-<_(a-54)OH>_p<_(a-54)OH>_p<_(a-54)OH>_p_p
-<_(a-54)OH>_p<_(a-54)OH>_p<_(a-54)OH>_p_p

Как видно, можно вставить конструкцию с относительным углом в любой узел полигона и получить правильную нормаль.

As you can see, you can insert a construction with a relative angle into any node of the polygon and get the correct normal.

А если нужно вывести не одну, а две дополнительных связи, то для одной нужно к соответствующему относительному углу прибавить 30 для одной связи и отнять для второй. Например, для 54 это будет 84 и 24:

And if you need to draw not one, but two additional chemical bonds, then for one you need to add 30 to the corresponding relative angle for one bond and subtract it for the second. For example, for 54 it will be 84 and 24:

-_q<_(a24)Cl><_(a84)Cl>_q_q_q
-_q<_(a24)Cl><_(a84)Cl>_q_q_q

Относительный угол 0 Relative angle 0

Ещё довольно часто используется угол 0, чтобы нарисовать две связи в одном направлении. Это обычно используется для тройных связей

Another common use of angle 0 is to draw two bonds in the same direction. This is usually used for triple bonds.

-\C_(a0,N3)N
-\C_(a0,N3)N

Использование ссылок Using links

Иногда бывает удобно указать координаты относительно других ранее созданных узлов. Для этого используются ссылки.

Sometimes it is convenient to specify coordinates relative to other previously created nodes. For this purpose, links are used.

Допустим, мы хотим провести связь не прямо к узлу 1, а использовать его только X-координату.

For example, we want to draw a chemical bond not directly to node 1, but use only its X-coordinate.

/\/\|_(x#1)
/\/\|_(x#1)

То есть, мы можем использовать ссылки в параметрах x и y.

That is, we can use links in the x and y parameters.

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

But in addition, you can use a link to several nodes. To do this, you can list several links separated by a semicolon, without spaces. In this case, the average value will be calculated.

/\/\|_(x#1;-1)
/\/\|_(x#1;-1)
$bg(round,brown,p:%a:0.15)/\$bg(round,brown,p:0.2)/\$bg(round,brown,p:%a)|_(x#1;-1); $color(brown)#1_#5; #3_(H)#7; #1_(x-.4,N0)"1"; #5_(x.6,N0)"-1"

Здесь выражение #1;-1 означает середину линии из узла 1, до предыдущего, который указан как -1

Here the expression #1;-1 means the middle of the line from node 1 to the previous one, which is specified as -1

Кроме того, есть параметр p, который указывает узел или список узлов. Причём, без знака #.

In addition, there is a parameter p, which specifies a node or a list of nodes. Moreover, without the # sign.

Вот две конструкции, которые фактически выполняют одно и то же:

Here are two constructs that essentially do the same thing:

-|_#1 = -|_(p1)
-|_#1 = -|_(p1)

Однако, у конструкции _(p) есть дополнительные возможности. Например, вот так можно провести связь к центру квадрата:

However, the _(p) construction has additional possibilities. For example, here is how you can draw a chemical bond to the center of the square:

|-`|_(p1;3)
|-`|_(p1;3)
@:b(r:0.1)$bg(round,brown,p:&r)@()|-@b()`|_(p1;3)@b(0.15); $color(brown)"1"_(x.3,N0)#1_(H)#3_(x.3,N0)"3"

А вот так можно сочетать параметры p и x,y:

And this is how you can combine the parameters p and x,y:

/\|_(p1,y1)
/\|_(p1,y1)
/\|_(p1,y1); #4$color(brown)\hv#1\hv#5; #1_(x-.3,N0)"1"

Но параметр p нельзя использовать, если между текущим узлом и указанными существуют мягкие связи. Потому что эти узлы находятся в разных подцепях. Единственный способ, чтобы зациклить такие конструкции - использовать связь с указанным узлом:

But the p parameter cannot be used if there are soft bonds between the current node and the specified ones. Because these nodes are in different subchains. The only way to loop such constructions is to use a bond with the specified node:

O-CH2-CH2|CH2_#1
O-CH2-CH2|CH2_#1

Хиральность. Локальный и глобальный режим Chirality. Local and global mode

Параметры w и d могут использоваться для вывода клиновидных связей. Для этого нужно использовать + или -, что соответствует расширению из исходного узла в конечный или наоборот.

The parameters w and d can be used to infer wedge-shaped connections by using + or -, which corresponds to an extension from the source node to the destination node or vice versa.

_(A45,w+) _(A45,w-) _(A45,d+) _(A45,d-)
_(A45,w+) _(A45,w-) _(A45,d+) _(A45,d-)

Кроме того, можно использовать w2 и d2, чтобы вывести толстую линию.

Additionally, you can use w2 and d2 to draw a thick line.

_(A45,w2) _(A45,d2)
_(A45,w2) _(A45,d2)

Вот комплексный пример

Here is a complex example

_(A60,w+)_(x1,w2)_(A-60,w-)_(A-120,d+)_(x-1,d2)_(A120,d-)
_(A60,w+)_(x1,w2)_(A-60,w-)_(A-120,d+)_(x-1,d2)_(A120,d-)

Глобальный режим Global mode

Для тех же целей можно использовать параметры W и D.

For the same purposes, you can use the W and D parameters.

Разница в том, что W+, W2, D+ и D2 включают глобальный режим толстой линии, который действует на все следующие универсальные связи в пределах реагента.

The difference is that W+, W2, D+, and D2 enable a global thick line mode that affects all subsequent universal bonds within the reagent.

Но этот режим может быть выключен параметрами W-, D-, W1 или D1.

But this mode can be disabled by the parameters W-, D-, W1 or D1.

Вот несколько примеров:

Here are some examples:

_(A0)_(A60,W+)_(A0)O_(A0)_(A-60,W-)_(A0)
_(A0)_(A60,W+)_(A0)O_(A0)_(A-60,W-)_(A0)
_(A0)_(A60,D+)_(A0)O_(A0)_(A-60,D-)_(A0)
_(A0)_(A60,D+)_(A0)O_(A0)_(A-60,D-)_(A0)
_(A0)_(A60,W2)_(A0)O_(A0)_(A-60,W1)_(A0)
_(A0)_(A60,W2)_(A0)O_(A0)_(A-60,W1)_(A0)
_(A0)_(A60,D2)_(A0)O_(A0)_(A-60,D1)_(A0)
_(A0)_(A60,D2)_(A0)O_(A0)_(A-60,D1)_(A0)

После включения глобального режима для вывода узкой линии можно использовать связи с параметрами w и d. Они действуют только на свою связь, а для остальных режим продолжает действовать.

After enabling the global mode, chemical bonds with the parameters w and d can be used to output a thin line. They only affect their own bond, and the mode continues to operate for the others.

_(A45,W2)_(A-45)_(A45,w1)_(A-45)
_(A45,W2)_(A-45)_(A45,w1)_(A-45)

Кроме того, глобальный режим действует только на универсальные связи.

In addition, the global mode only affects universal bonds.

_(y1,W2)-_(y-1)_p4_(y1)
_(y1,W2)-_(y-1)_p4_(y1)

Подобная техника часто используется для описания формул углеводов.

A similar technique is often used to describe carbohydrate formulas.

Вот два варианта описания одного вещества - β-D-глюкопираноза:

Here are two options for describing one substance - β-D-glucopyranose:

CH2OH|_(x-1,y1)<|OH>_(x1,y1,W+)<`|OH>_(x1.4)<|OH>_(x1,y-1,W-)<`|OH>_(x-1,y-1)O_#2
CH2OH|_(x-1,y1)<|OH>_(x1,y1,W+)<`|OH>_(x1.4)<|OH>_(x1,y-1,W-)<`|OH>_(x-1,y-1)O_#2
HO_(A-15)_(x%a:1.2,y%d:.4)<`\/OH>_(x%b:1.4,y-%d)O_(x%c:.6,y%h:1.2)<_(A-15)OH>_(x-%a,y-%d,W+)<_(A60,w1)OH>_(x-%b,y%d)<_(A-165,w1)HO>_(x-%c,y-%h,W-)
HO_(A-15)_(x%a:1.2,y%d:.4)<`\/OH>_(x%b:1.4,y-%d)O_(x%c:.6,y%h:1.2)<_(A-15)OH>_(x-%a,y-%d,W+)<_(A60,w1)OH>_(x-%b,y%d)<_(A-165,w1)HO>_(x-%c,y-%h,W-)

Декоративные параметры Decorative parameters

Целый ряд параметров предназначен для изменения внешнего вида связей. Аналогичные возможности для других видов связей реализуются через суффиксы.

A whole series of parameters are intended for changing the external appearance of bonds. Similar possibilities for other types of bonds are realized through suffixes.

Водородная связь Hydrogen bond

Параметр H служит для описания водородной связи (или просто штриховой линии).

The H parameter is used to describe the hydrogen bond (or simply the dashed line).

_(x2,y1,H)
_(x2,y1,H)

Волнистая линия Wavy line

Для волнистой линии используется параметр ~ (тильда).

For a wavy line, the ~ (tilde) parameter is used.

_(x2,y1,~)
_(x2,y1,~)

Стрелки Arrows

Для стрелок используются параметры C, < и >

For arrows, the parameters C, < and > are used.

Прямая стрелка: C или >

Forward arrow: C or >

_(x2,y1,C) _(x2,y1,>)
_(x2,y1,C) _(x2,y1,>)

Обратная стрелка: C- или <

Backward arrow: C- or <

_(x2,y1,C-) _(x2,y1,<)
_(x2,y1,C-) _(x2,y1,<)

Стрелка в обе стороны: C+

Arrow in both directions: C+

_(x2,y1,C+)
_(x2,y1,C+)

СтилиStyles

Допустим, нужно изобразить вот такую формулу из Википедии: For example, you need to depict this formula from Wikipedia:

Здесь интерес представляют связи, состоящие из двух линий, одна из которых - штриховая.

Of interest here are bonds consisting of two lines, one of which is dashed.

Параметр S позволяет указать стили связи.

The S parameter allows you to specify bond styles.

Стили указываются следующими символами: Styles are indicated by the following symbols: ~ : | I

СимволSymbols ОписаниеDescription ПримерExample
~ Волнистая линияWavy line
_(A45,S~)
_(A45,S~)
: Штриховая линияDashed line
_(A45,S:)
_(A45,S:)
| Тонкая линияThin line
_(A45,S|)
_(A45,S|)
I Толстая линияThick line
_(A45,SI)
_(A45,SI)

Волнистая линия может быть только одинарной. Остальные можно комбинировать друг с другом вплоть до тройной.

The wavy line can only be single. The others can be combined with each other up to a triple.

Для этого перечисляются символы в том порядке, как если бы линия была проведена вертикально сверху вниз.

To do this, the symbols are listed in the order as if the line were drawn vertically from top to bottom.

O_(y1,S:|) O_(y1,S|:) O_(y1,S:|:) O_(y1,SI|) O_(y1,S:|I)
O_(y1,S:|)
O_(y1,S|:)
O_(y1,S:|:)
O_(y1,SI|)
O_(y1,S:|I)

Не важно, в каком направлении рисуется связь. Описание стилей всегда соответствует этому правилу.

It does not matter in which direction the bond is drawn. The description of styles always corresponds to this rule.

$L(1.5){A}<_(A90,S|:)><_(A30,S|:)><_(A-30,S|:)><_(A-90,S|:)><_(A-150,S|:)><_(A150,S|:)>
$L(1.5){A}<_(A90,S|:)><_(A30,S|:)><_(A-30,S|:)><_(A-90,S|:)><_(A-150,S|:)><_(A150,S|:)>

Таким образом, упомянутая выше формула диэтилдитиокарбамата натрия может быть описана с использованием стилей:

Thus, the above mentioned formula of sodium diethyldithiocarbamate can be described using the styles:

$L(1.4)C_(A-45,S|:)S_(A-135,N0)Na^+_(A135,N0)S_(A45,S|:)<_(p2;4,N0){}^->$L()|N<\Et>`/Et
$L(1.4)C_(A-45,S|:)S_(A-135,N0)Na^+_(A135,N0)S_(A45,S|:)<_(p2;4,N0){}^->$L()|N<\Et>`/Et

Выравнивание двойных связей Alignment of double bonds

Если используются двойные связи, то для них действуют такие же суффиксы, как для параметра N:

If double bonds are used, the same suffixes apply to them as to the N parameter:

_(A30,S|:)_(A90,S|:)_(A30,S|:)
_(A30,S|:)_(A90,S|:)_(A30,S|:)
_(A30,S|:L)_(A90,S|:L)_(A30,S|:L)
_(A30,S|:L)_(A90,S|:L)_(A30,S|:L)
_(A30,S|:m)_(A90,S|:m)_(A30,S|:m)
_(A30,S|:m)_(A90,S|:m)_(A30,S|:m)
_(A30,S|:R)_(A90,S|:R)_(A30,S|:R)
_(A30,S|:R)_(A90,S|:R)_(A30,S|:R)

То есть, L или l - влево, R или r - вправо, M или m - посередине.

That is, L or l - to the left, R or r - to the right, M or m - in the middle.

Мягкие связи Soft bonds

В большинстве случаев мягкие связи создаются при помощи кратких описаний: In most cases, soft bonds are created using short descriptions: - = %.

Но изредка бывает необходимо использовать универсальные связи. Для этого служит параметр h

But sometimes it is necessary to use universal bonds. The parameter h is used for this.

Один из таких случаев - если по какой-то причине мягкая связь не является горизонтальной.

One such case is if for some reason the soft bond is not horizontal.

H3C_(A10,h)CH2_(A-10,h)CH3
H3C_(A10,h)CH2_(A-10,h)CH3

Тут важно, что сам по себе параметр h не определяет смещение второго узла относительно первого. Для этого нужно использовать x, y, A или a.

It is important here that the h parameter itself does not determine the offset of the second node relative to the first. To do this, you need to use x, y, A or a.

Однако, бывают случаи когда нужно разделить один длинный узел на несколько более простых, но так чтобы не было видно разделяющих связей.

However, there are cases when it is necessary to divide one long node into several simpler ones, but so that the dividing bonds are not visible.

CH3_(h)CH2_(h)OH
CH3_(h)CH2_(h)OH

Зачем же это нужно? Причина тут может быть в том, что один узел может иметь только один центр. И если вдруг по какой-то причине нужно изобразить длинную цепочку без горизонтальных связей, но с какими-то вертикальными ответвлениями, то без деления тут не обойтись.

Why is this necessary? The reason may be that one node can have only one center. And if for some reason it is necessary to depict a long chain without horizontal bonds, but with some vertical branches, then division is indispensable.

CH3_(h)CH<|Cl>_(h)CH2_(h)CH<|Cl>_(h)CH3
CH3_(h)CH<|Cl>_(h)CH2_(h)CH<|Cl>_(h)CH3

Здесь _(h) соединяет соседние узлы так, чтобы они шли слева направо.

Here _(h) connects adjacent nodes so that they go from left to right.

Для того чтобы выводить справа налево используется _(h-)

To output from right to left, use _(h-)

-\`/O_(h-)C<||O>_(h-)H3C
-\`/O_(h-)C<||O>_(h-)H3C

Распределённые связи Delocalized bonds

Казалось бы, что универсальные связи могут решать любые задачи по описанию химических связей. Но они помогают только в тех ситуациях, когда связь соединяет два узла. А ещё есть случаи, когда нужно описать связь, которая охватывает три и более узлов.

It would seem that universal bonds can solve any problems in describing chemical bonds. But they only help in situations where the bond connects two nodes. And there are also cases when you need to describe a bond that covers three or more nodes.

Кольцевая связь Ring bond

Достаточно часто используется формула бензола с кольцом. Так же известная как формула Полинга

The formula for benzene with a ring is used quite often. It is also known as the Pauling formula or the Armstrong's inner cycle.

/\|`/`\`|_o
/\|`/`\`|_o

То есть, используется конструкция _o в том месте, где последний узел цикла соединяется с первым.

That is, the _o construct is used in the place where the last node of the loop is connected to the first.

Не обязательно должно быть 6 узлов в цикле. Но узлы должны следовать друг за другом. А ветки игнорируются.

There doesn't have to be 6 nodes in a cycle. But the nodes must follow each other. And branches are ignored.

/\</OH>|<\OH>`/`\`|_o
/\</OH>|<\OH>`/`\`|_o
-_p_p<|CH3>_p_p_o
-_p_p<|CH3>_p_p_o

Можно совмещать несколько циклов, но надо выполнять условие последовательного соединения узлов.

It is possible to combine several cycles, but the condition of sequential connection of nodes must be met.

/\|<\/`|`\`/_o>`/`\`|_o
/\|<\/`|`\`/_o>`/`\`|_o
/\|<\/`|`\`/_o>`/`\`|_o
@:n(t,a)<_(A&a,N0,L0.4)$itemColor1(blue)"&t">@(1,-150)/@n(2,-90)\@n(3,-90)$color(var(--select-color))|@n(4,90)<\@n(5,90)/@n(6,30)`|@n(7,-30)`\@n(8,-90)`/_o$color()>`/@n(9,90)`\@n(10,120)`|_o

Здесь первое кольцо образовано узлами 1-2-3-4-9-10. Узлы с 5 по 8 игнорируются, т.к. находятся в ветке.

Here the first ring is formed by nodes 1-2-3-4-9-10. Nodes 5 through 8 are ignored because they are in a branch.

Второе кольцо подсвечено. Оно образовано узлами 3-4-5-6-7-8. Хотя конструкция _o находится внутри ветки, то это "своя" ветка. Она не игнорируется. Игнорируются "чужие", которым не принадлежит конструкция _o.

The second ring is highlighted. It is formed by nodes 3-4-5-6-7-8. Although the _o structure is inside the branch, it is "its" branch. It is not ignored. The "foreign" ones, to which the _o structure does not belong, are ignored.

Если это кажется слишком сложно, то можно использовать невидимые связи (то есть, кратность которых указана как 0).

If this seems too complicated, you can use invisible bonds (that is, those whose multiplicity is indicated as 0).

/\|`/`\`|_o/0\0|0\/`|`\`/_o
/\|`/`\`|_o/0\0|0\/`|`\`/_o
/\|`/`\`|_o/0\0|0\/`|`\`/_o
@:n(t,a)<_(A&a,N0,L0.4)$itemColor1(blue)"&t">@(1,-150)/@n(2,-90)\@n(3,-90)|@n(4,90)`/@n(5,90)`\@n(6,150)`|_o/0\0$color(var(--select-color))|0\@n(7,90)/@n(8,30)`|@n(9,-30)`\@n(10,-90)`/_o

То есть, просто замыкается цикл, ставится _o. Затем невидимыми линиями перемещаемся к началу нового цикла (узел 3). А так же невидимые лини подходят для замыкания цикла. Например, здесь невидимая линия использована для первой стороны второго шестиугольника (из 3 в 4). Иначе там появилась бы ненужная двойная связь.

That is, the cycle is simply closed, _o is put. Then we move to the beginning of the new cycle with invisible lines (node ​​3). And invisible lines are also suitable for closing a cycle. For example, here the invisible line is used for the first side of the second hexagon (from 3 to 4). Otherwise, an unnecessary double bond would appear there.

Обратите внимание, что второй цикл образован узлами 3-4-7-8-9-10. Хотя они и не все идут друг за другом, но важно что они последовательно соединены.

Note that the second cycle is formed by nodes 3-4-7-8-9-10. Although they are not all in sequence, it is important that they are connected in series.

Сплайновая связь Spline bond

Конструкция _o была реализована в самых ранних версиях CharChem (0.7). Но она всегда рисует ровный круг. Поэтому вскоре стало понятно, что этого недостаточно чтобы нарисовать например такую формулу из википедии: The _o construct was implemented in the earliest versions of CharChem (0.7). But it always draws a perfect circle. So it soon became clear that it was not enough to draw, for example, this formula from Wikipedia:

Потому что там не круг, а эллипс.

Because it's not a circle, but an ellipse.

В результате в версии 1.0 появилась конструкция _s().

As a result, the _s() construct appeared in version 1.0.

Она позволяет изобразить распределённую связь не только в виде круга. Кроме того, возможно использовать прерывистую линию при помощи параметра S:

It allows to depict distributed chemical bond not only in the form of a circle. In addition, it is possible to use a dashed line using the parameter S:

_(x2)\<->`/_(x-2)`\/_s()
_(x2)\<->`/_(x-2)`\/_s()
/\</>|`/`\`|_s(S:)
/\</>|`/`\`|_s(S:)
-\<->`/`-_s(S:)
-\<->`/`-_s(S:)
$slope(45)-\|`/`-`\`|/_s(#1;2;5;6;1)
$slope(45)-\|`/`-`\`|/_s(#1;2;5;6;1)

Кроме параметра S, есть параметр #, который позволяет явно указать те узлы, которые будут использованы для распределённой связи при помощи ссылок.

In addition to the S parameter, there is a # parameter that allows you to explicitly specify the nodes that will be used for distributed bond using links.

А так же есть параметр o, который означает, что связь будет зациклена независимо от того, зациклена ли цепочка.

There is also a parameter o, which means that the bond will be looped regardless of whether the chain is looped.

-|`-_s()
-|`-_s()
-|`-_s(o)
-|`-_s(o)

Ну и вот как можно описать упомянутую выше формулу Ферроцена

Well, here's how you can describe the above-mentioned formula of Ferrocene

Fe_(y1.2,H){}_(x-.5,y-.6,N0)_(x1)_(x.4,y.8)_(x-.9,y.5,w+)_(x-.9,y-.5,w-)_(x.4,y-.8)_s();
#1_(y-1.2,H){}_(x-.5,y.6,N0)_(x1,w2)_(x.4,y-.8,w-)_(x-.9,y-.5)_(x-.9,y.5)_(x.4,y.8,w+)_s()
Fe_(y1.2,H){}_(x-.5,y-.6,N0)_(x1)_(x.4,y.8)_(x-.9,y.5,w+)_(x-.9,y-.5,w-)_(x.4,y-.8)_s(); #1_(y-1.2,H){}_(x-.5,y.6,N0)_(x1,w2)_(x.4,y-.8,w-)_(x-.9,y-.5)_(x-.9,y.5)_(x.4,y.8,w+)_s()

Изогнутые линии Curved lines

Пусть и крайне редко, но всё-таки бывает необходимость использовать не прямые, а изогнутые линии.

Although it is extremely rare, there is still a need to use curved rather than straight lines.

H2C`|H2C`|H2C_m(x2)_m(y2)_(x-2)
H2C`|H2C`|H2C_m(x2)_m(y2)_(x-2)

Это делается при помощи кривых Безье. Конструкцей _m задаются промежуточные контрольные точки. При помощи одной промежуточной точки задаётся квадратичная кривая, при помощи двух - кубическая.

This is done using Bezier curves. The _m construct specifies intermediate control points. A quadratic curve is specified using one intermediate point, and a cubic curve is specified using two.

Конструкция _m() похожа на универсальную связь. Но в ней используются только те параметры, которые отвечают за координаты: The _m() construct is similar to the universal bond. However, it uses only those parameters that are responsible for the coordinates: x y A a L P p.

Конструкции _m не образуют новых узлов. Узел появится только после описания связи. Но все координаты вычисляются относительно предыдущей конструкции.

The _m constructions do not form new nodes. The node will appear only after the bond is described. But all coordinates are calculated relative to the previous point.

Здесь показаны промежуточные точки для предыдущего примера:

Here are the intermediate points for the previous example:

H2C`|H2C`|H2C_m(x2)_m(y2)_(x-2); $color(brown)#3_(x2,H,>)"a"_(y2,H,>)"b"_(x-2,H,>)
{A}_m(x1,y-2)_(x1,y2,>){B}-h#1
{A}_m(x1,y-2)_(x1,y2,>){B}-h#1
Квадратичеая кривая образована одной промежуточной точкой.
Всегда имеет форму дуги.
A quadratic curve is formed by one intermediate point.
Always has the shape of an arc.
{A}_m(y-2)_m(x2)_(y2,>){B}-h#1
{A}_m(y-2)_m(x2)_(y2,>){B}-h#1
Кубическая кривая образована двумя промежуточными точками.
Имеет форму дуги, если обе точки находятся с одной стороны от отрезка AB.
A cubic curve is formed by two intermediate points. It has the shape of an arc if both points are on the same side of the segment AB.
{A}_m(x1,y-2)_m(x1,y4)_(x1,y-2,>){B}-h#1
{A}_m(x1,y-2)_m(x1,y4)_(x1,y-2,>){B}-h#1
Кубическая кривая имеет S-образную форму,
если точки находятся по разные стороны от отрезка AB.
A cubic curve has an S-shape
if the points are on opposite sides of the segment AB.

Это конечно всё достаточно сложно. Но такие возможности требуются довольно редко.

This is all quite complicated, of course. But such capabilities are required quite rarely.

Вот ещё пара примеров формул, где требуется изогнутая связь:

Here are a couple more examples of formulas that require a curved connection:

HO\C</H>|<-H><`-HO>|<-H><`-HO>|<`-H><|CH2OH>_m(x1.8)_m(x.2,y-.2)_(y-1.3)O_m(y-1.3)_m(y-.2,x-.2)_#2
HO\C</H>|<-H><`-HO>|<-H><`-HO>|<`-H><|CH2OH>_m(x1.8)_m(x.2,y-.2)_(y-1.3)O_m(y-1.3)_m(y-.2,x-.2)_#2
HOCH2-C<-OH>|<-H><`-HO>|<-OH><`-H>|<-OH><`-H>|CH2_(x1,h){}:e;
#2_m(y-0.8)_m(y-0.2,x.2)_(x%d:1){}_m(x%d)_m(x.2,y.2)_(y.8){}_(y2)O_(y1)_m(y.8)_m(x-.2,y.2)_(x-%d)_#e
HOCH2-C<-OH>|<-H><`-HO>|<-OH><`-H>|<-OH><`-H>|CH2_(x1,h){}:e; #2_m(y-0.8)_m(y-0.2,x.2)_(x%d:1){}_m(x%d)_m(x.2,y.2)_(y.8){}_(y2)O_(y1)_m(y.8)_m(x-.2,y.2)_(x-%d)_#e

Обратите внимание, что во втором примере форма линии слишком сложная для одной кривой Безье. Поэтому она составлена из трёх отдельных связей, между которыми находятся пустые узлы {}.

Note that in the second example, the line shape is too complex for a single Bézier curve. So it is made up of three separate bonds, with empty nodes {} between them.

Дополнительные приёмы Additional techniques

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

We have finished looking at descriptions of chemical bonds. There are still a few additional techniques that may be useful in some less common cases.

Пустые узлы Empty nodes

Иногда нужно изобразить не всю формулу вещества, а часть. Например, Карбоксильная группа:

Sometimes it is necessary to depict not the entire formula of a substance, but a part. For example, the Carboxyl group:

{}--C<//O>\OH
{}--C<//O>\OH

Конструкция {} означает пустой узел. Если его не указывать, то на этом месте будет создан автоузел. На внешний вид формулы это не повлияет. Но если для такой формулы посчитать атомную массу или состав элементов, то с автоузлом это будет уксусная кислота.

The {} construction means an empty node. If it is not specified, an autonode will be created in this place. This will not affect the appearance of the formula. But if you calculate the atomic mass or composition of elements for such a formula, then with an autonode it will be acetic acid.

Здесь пустые узлы находятся в центре каждого шестиугольника. Они нужны, чтобы к ним можно было провести штриховую линию:

Here the empty nodes are in the center of each hexagon. They are needed so that a dashed line can be drawn to them:

/\|`/`\`|_o\0{}_(x2,H)Fe_(x2,H){}/0|`/`\`|/\_o
/\|`/`\`|_o\0{}_(x2,H)Fe_(x2,H){}/0|`/`\`|/\_o

Ещё пустые узлы могут быть полезны для вывода декоративных линий из нескольких составных сегментов.

Empty nodes can also be useful for drawing decorative lines from several component segments.

Fe$color(brown)`|hvv{}_(x2,H){}|h{}-h"`Fe`"
Fe$color(brown)`|hvv{}_(x2,H){}|h{}-h"`Fe`"

Кроме того, пустой узел может иметь заряд:

In addition, an empty node can have a charge:

$L(1.3){R}--C_(A-45,S:|)S_p4oNa^+_p4oS_(A-135,S:|)_(x0.8,N0){}^-
$L(1.3){R}--C_(A-45,S:|)S_p4oNa^+_p4oS_(A-135,S:|)_(x0.8,N0){}^-

Явное создание автоузла Explicit creation of an autonode

Обычно автоузлы создаются автоматически. Но давайте рассмотрим несколько вариантов скелетной формулы 1-бутина:

Usually autonodes are created automatically. But let's look at several variants of the skeletal formula of 1-Butyne:

\-%
\-%
Здесь каждая связь указана отдельным символом, которые всегда воспринимаются однозначно. Here, each bond is indicated by a separate symbol, which is always perceived unambiguously.
|`/`///
|`/`///
Здесь тоже понятно, где заканчивается одинарная связь и начинается тройная из-за наличия обратного апострофа. Here, too, it is clear where the single bond ends and the triple bond begins due to the presence of the backtick.
|\c\\\
|\c\\\
А тут пришлось явно указать, где должен располагаться автоузел при помощи специальной конструкции c. And here it was necessary to clearly indicate where the auto unit should be located using a special construction c.
\\\\/
\\\\/
Если указать четыре обратных слэша подряд, то в первую очередь создаётся связь с максимальной кратностью - тройная.
Но делать так не рекомендуется. Желательно всё-таки ставить символ c, чтобы отделить одну связь от другой.
If you specify four backslashes in a row, then first of all a chemical bond with the maximum multiplicity is created - a triple one.
But it is not recommended to do this. It is still advisable to put the c symbol to separate one bond from another.

Несмотря на сходство конструкции c с химическим элеменом C, он не всегда означает углерод. К примеру, вот формула перхлората калия:

Despite the similarity of the structure c to the chemical element C, it does not always mean carbon. For example, here is the formula for potassium perchlorate:

O=Cl`|O|c|O`|-O-K
O=Cl`|O|c|O`|-O-K

Здесь c используется для того чтобы отделить описание одной связи от другой.

Here c is used to separate the description of one bond from another.

А вот ещё один интересный случай - конструкция c используется чтобы отделить связь от описания заряда:

Here's another interesting case - the c construction is used to separate the bond from the charge description:

K^+-0O`^-c-Cl|O`|`|O|=O
K^+-0O`^-c-Cl|O`|`|O|=O

Сочетание +- выглядит довольно странно, но работает правильно. Потому что не бывает описания заряда из этих символов. Поэтому система понимает, что заряд - это плюс, а дальше уже связь.

The combination +- looks a bit strange, but works correctly. Because there is no description of the charge from these symbols. Therefore, the system understands that the charge is a plus, and then there is a sbond.

Но далее идёт сочетание -c-. Здесь пришлось вставить c, т.к. два минуса - это допустимое описания заряда.

But then comes the combination -c-. Here I had to insert c, because two minuses are an acceptable description of the charge.

Использование разрыва Using the break

В разделе, где обсуждались ссылки, есть описание разрыва - # с пробелом. Разрывы можно использовать вместо c. Они работают практически одинаково.

In the section where links were discussed, there is a description of a break - # with a space. Breaks can be used instead of c. They work almost the same.

O=Cl`|O|# |O`|-O-K
O=Cl`|O|# |O`|-O-K
K^+-0O`^-# -Cl|O`|`|O|=O
K^+-0O`^-# -Cl|O`|`|O|=O

Скобки Brackets

В самых ранних версиях CharChem можно было использовать скобки только для узлов:

In the earliest versions of CharChem, you could only use brackets on nodes:

Ca(OH)2
K3[Fe(CN)6]

Но начиная с версии 1.0 внутри скобок могут быть описания химических связей.

But starting with version 1.0, there can be descriptions of chemical bonds inside the brackets.

Виды скобок Types of brackets

Всего доступно три вида скобок: круглые, квадратные и фигурные:

There are three types of brackets available: round, square and curly:

(H) [H] {{H}} (H) [H] {{H}} ({R}) [{R}] {{{R}}} ({R}) [{R}] {{{R}}}

Фигурные добавились в версии 2.0 и для их описания нужно использовать конструкции {{ и }}. Потому что одинарные фигурные скобки используются для описания радикалов и абстрактных элементов.

Curly brackets were added in version 2.0 and to describe them you need to use the {{ and }} constructions. Because single curly brackets are used to describe radicals and abstract elements.

Принципиальной разницы между видами скобок нет. Но для открытия и закрытия нужно использовать скобки одного типа.

There is no fundamental difference between the types of brackets. But you need to use the same type of brackets for opening and closing.

Заряд скобок Charge of brackets

Используются такие же правила, как для заряда узла:

The same rules are used as for node charging:

[Ca]^2+ = [Ca]`^+2 [Ca]^2+ = [Ca]`^+2

Количественный коэффициент Quantitative coefficient

Можно использовать числовые и абстрактные коэффициенты, как для элементов узлов:

You can use numeric and abstract coefficients, as for node items:

(CN)6
(CN)6
H-(CH2)'n'-H
H-(CH2)'n'-H
H-(CH2)'300-400'-H
H-(CH2)'300-400'-H

Размеры Sizes

Если внутри скобок появляются несколько узлов, то размер скобок меняется автоматически.

If multiple nodes appear inside the brackets, the size of the brackets changes automatically.

(H|N<`/H><_(A20,d+)H><_(A75,w+)H>)^+
(H|N<`/H><_(A20,d+)H><_(A75,w+)H>)^+

Если хочется увеличить отступ внутри скобок, то можно поставить перед открывающейся скобкой функцию $padding().

If you want to increase the indentation inside the brackets, you can put the $padding() function before the opening bracket.

$padding(0.25)(H|N<`/H><_(A20,d+)H><_(A75,w+)H>)^+
$padding(0.25)(H|N<`/H><_(A20,d+)H><_(A75,w+)H>)^+

Соединение узлов со скобками Connecting nodes with brackets

Узлы и скобки могут соседствовать друг с другом.

Nodes and brackets can be adjacent to each other.

Ca(OH)2
Ca(OH)2
K[Cu<`|Br><|Br>]
K[Cu<`|Br><|Br>]
[H--N^+<`|H><|H>--H]2^+($slope(45)O`^-/S\O`\`\O\/O^-)
[H--N^+<`|H><|H>--H]2^+($slope(45)O`^-/S\O`\`\O\/O^-)

При этом происходит центрирование относительно горизонтальной оси.

In this case, centering occurs relative to the horizontal axis.

Входящие и исходящие связи Incoming and outgoing bonds

Если связь должна пересекать границу скобок, то она всегда ставится снаружи от скобок.

If a bond must cross the boundary of the brackets, it is always placed outside the brackets.

А точнее, схема всегда такая: исходящая связь, открывающася скобка, содержимое, закрывающаяся скобка, коэффициент (если есть), заряд (если есть) и исходящая связь.

More precisely, the scheme is always like this: outgoing bond, opening parenthesis, contents, closing parenthesis, coefficient (if any), charge (if any), and outgoing bond.

H--$padding(0.1)(C<`|H><|H>)22--H
H--$padding(0.1)(C<`|H><|H>)22--H

То есть, связь ставится непосредственно рядом со скобкой. Но без учёта функций, коэффициентов и зарядов.

That is, the bond is placed directly next to the bracket. But without taking into account functions, coefficients and charges.

При этом связь соединяет ближайшие к ней узлы, без учёта веток.

In this case, the ыbond connects the nodes closest to it, without taking into account the branches.

Соседство скобок с мягкими связями Adjacency of brackets with soft bonds

Мягкие связи ведут себя иначе. Они присоединяются ко всей скобке и не пересекают её.

Soft bonds behave differently. They attach to the entire bracket and do not cross it.

$slope(45)H`^+-[O`^-/S\O`\`\O\/O^-]-H^+
$slope(45)H`^+-[O`^-/S\O`\`\O\/O^-]-H^+
$slope(45)H`^+-[S<`/O`^-><`\\O><\\O></O^->]-H^+
$slope(45)H`^+-[S<`/O`^-><`\\O><\\O></O^->]-H^+

Но положение связи определяется с учетом соединяемых узлов. В предыдущем примере в первой формуле атомы водорода соединяются с атомами кислорода. А во втором - с атомом серы.

But the position of the bond is determined taking into account the nodes being connected. In the previous example, in the first formula, hydrogen atoms are connected to oxygen atoms. And in the second - to a sulfur atom.

Требования к длине входящих и исходящих связей Requirements for the length of incoming and outgoing bonds

Как уже было сказано ранее, границы скобок определяются автоматически. Допустим, есть вот такая часть формулы, где представлена внутренняя часть скобок и нужно добавить внешнюю.

As mentioned earlier, the bracket boundaries are determined automatically. For example, there is a part of the formula where the inner part of the brackets is presented and the outer part needs to be added.

[N<`|CH<`-H3C>-CH3>]'n'
[N<`|CH<`-H3C>-CH3>]'n'

Пусть левая внешняя часть будет называться R1, а правая - R2. И обе они должны присоединиться к атому азота. Но вот что произойдёт, если не позаботиться о длине связей.

Let's call the left outer part R1 and the right one R2. And both of them should attach to the nitrogen atom. But here's what happens if you don't take care of the bond lengths.

{R1}--[N<`|CH<`-H3C>-CH3>]'n'--{R2}
$color(#C0C){R1}--$color()[N<`|CH<`-H3C>-CH3>]'n'$color(#C0C)--{R2}

Хотя R1 и R2 объявлены снаружи скобок, но выглядят они так как будто находятся внутри.

Although R1 and R2 are declared outside the brackets, they look like they are inside.

Чтобы этого не происходило, необходимо явно указать такую длину связей, чтобы они визуально вышли за границы скобок:

To prevent this from happening, you need to explicitly specify the length of the links so that they visually extend beyond the boundaries of the brackets:

{R1}_(x3)[N<`|CH<`-H3C>-CH3>]'n'_(x3.5){R2}
$color(#C0C){R1}_(x3)$color()[N<`|CH<`-H3C>-CH3>]'n'$color(#C0C)_(x3.5){R2}

Использование ссылок Using links

У скобки может быть одна входящая связь и одна исходящая. Но что делать, если нужно больше? Например, чтобы вывести структурную формулу такого вещества: A bracket can have one incoming bond and one outgoing bond. But what if you need more? For example, to derive the structural formula of such a substance: H3[SbCl6].

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

Using links, you can add any number of incoming or outgoing links. But it is important that the contents of the brackets are described first, and then other chains are attached by link.

[Sb</Cl><\Cl><|Cl><`/Cl><`\Cl><`|Cl>]^3-;
Na^+_(x%d:2.8,N0)#1;
Na^+_(x%d,y1,N0)#1_(x-%d,y1,N0)Na^+
[Sb</Cl><\Cl><|Cl><`/Cl><`\Cl><`|Cl>]^3-; Na^+_(x%d:2.8,N0)#1; Na^+_(x%d,y1,N0)#1_(x-%d,y1,N0)Na^+

Тем не менее, при помощи такого подхода не нужно пытаться изменить содержимое скобок. Все узлы, которые входят в скобки, должны быть объявлены в скобках. А все узлы из других цепей, которые присоединяются по ссылке, остаются внешними.

However, with this approach, you should not try to change the contents of the parentheses. All nodes that go into the parentheses must be declared in parentheses. And all nodes from other chains that are attached by reference remain external.

Вывод справа налево Output from right to left

Допустим, у нас есть вот такая формула:

Let's say we have a formula like this:

H3C-(CH=CCl)2-COOH
H3C-(CH=CCl)2-COOH

И по какой-то причине нужно вывести её в обратном направлении - справа налево. До версии 2.0 так делать было невозможно. Но и сейчас так стоит делать только в крайних случаях, когда иначе обойтись нельзя.

And for some reason it needs to be output in the opposite direction - from right to left. Before version 2.0 it was impossible to do this. But even now it should be done only in extreme cases, when there is no other way.

Начинаем с узла COOH. Затем связь в обратную сторону `-. А дальше важно — нужно обозначить открывающуюся скобку. Хотя визуально на этом месте должна быть закрывающаяся скобка с коэфиициентом. Но при описании формулы всегда сначала идёт открывающаяся скобка.

We start with the COOH node. Then the chemical bond in the opposite direction `-. And then it is important — you need to designate the opening bracket. Although visually there should be a closing bracket with a coefficient in this place. But when describing a formula, the opening bracket always comes first.

Затем перечисляем содержимое скобки справа налево. То есть, сначала узел CCl, затем связь `=, затем узел CH.

Then we list the contents of the bracket from right to left. That is, first the CCl node, then the `= bond, then the CH node.

И вот теперь нужно поставить закрывающуюся скобку с коэффициентом.

And now you need to put a closing bracket with the coefficient.

Далее исходящая связь `- и последний узел H3C:

Next is the outgoing bond `- and the last node H3C:

COOH`-(CCl`=CH)2`-H3C
COOH`-(CCl`=CH)2`-H3C

То есть, узлы и связи действительно следуют в обратном порядке. А скобки всегда сначала открываются, а затем закрываются. Но при выводе формулы они рисуются в нужном порядке.

That is, the nodes and bonds really follow in reverse order. And the brackets always open first and then close. But when the formula is drawn, they are displayed in the correct order.

Вот пример, где это действительно нужно:

Here's an example where this is really needed:

$slope(30)/\|<\(O-CH2)3-H>`/`\<`|>`/(O`-CH2)3`-H
$slope(30)/\|<\(O-CH2)3-H>`/`\<`|>`/$color(var(--select-color))(O`-CH2)3`-H

Макрокоманды Macro commands

Макрокоманды (или макросы) позволяют автоматизировать описание однотипных компонент. Хотя они не вносят никаких специфичных способов описания химических структур, зато позволяют повысить эффективность применения всего инструмента в целом.

Macrocommands (or macros) are powerful tool to automate the description of similar components. Although they did not make any specific ways to describe chemical structures, but it can improve the efficiency of the entire instrument as a whole.

В следующей таблице в кратком виде представлены все синтаксические конструкции.

The following table briefly presents all syntactic constructions.

ДействиеAction Пример синтаксисаExample syntax Выход пост-обработкиPost processing output
Простейшее объявлениеThe simplest declaration @:MyMacro()...some text...@;
ПрименениеCall the macros @MyMacro()...some text...
Одновременно объявление и применение Simultaneous declaration and use macros @MyMacro()...some text...@() ...some text...
Использование позиционных параметров Using positional parameters @:MyMacro(a,b)...&a...&b...@(First,Second) ...First...Second...
Использование именованных параметров Using named parameters @:MyMacro(a,b)...&a...&b...@(b:Second,a:First) ...First...Second...
Значения по-умолчанию Default values @:MyMacro(a:First,b:Second)...&a...&b...@()
@MyMacro(,Last)
...First...Second...
...First...Last...
Вложенные вызовы Nested calls @:MyMacro(a,b)[&a...&b]@(@MyMacro(A,B),@MyMacro(C,D)) [[A...B]...[C...D]]

Создание простейшего макроса и его использование Creating a simple macro and using it

Допустим, нужно описать взаимодействие кислоты с щёлочью:

Let's say we need to describe the interaction of an acid with an alkali:

H3C-CH2-C<//O>\O-H + NaOH -> H3C-CH2-C<//O>\O-Na + H2O <=> H3C-CH2-C<//O>\O^- + Na^+ + H2O
H3C-CH2-C<//O>\O-H + NaOH -> H3C-CH2-C<//O>\O-Na + H2O <=> H3C-CH2-C<//O>\O^- + Na^+ + H2O

Несложно заметить, что здесь три раза повторяется изрядный кусок молекулы пропионовой кислоты. Давайте вынесем его описание в виде макроса. Детали описания макрокоманды выделены цветом.

It is easy to see that a good portion of the propionic acid molecule is repeated three times here. Let's put its description in the form of a macro. The details of the macro description are highlighted in color.

@:Pr()H3C-CH2-C<//O>\O@;
@Pr()-H + NaOH -> @Pr()-Na + H2O <=> @Pr()^- + Na^+ + H2O
@:Pr()H3C-CH2-C<//O>\O@; @:Pr1()$color(var(--select-color))@Pr()$color()@; @Pr1()-H + NaOH -> @Pr1()-Na + H2O <=> @Pr1()^- + Na^+ + H2O

Здесь мы видим, что макрокоманда описывается при помощи конструкции @:Pr() . . . @;
А используется при помощи @Pr(). В качестве имени может выступать слово, начинающееся с латинской буквы.
При использовании нужно учитывать регистр букв. То есть, ABC и Abc - разные имена.
Объявленный макрос можно использовать далее в тексте. Он является глобальным определением. Например, мы можем использовать его в другой формуле:

Here we see that the macro command is described using the @:Pr() . . . @;
And it is used by @Pr(). The name must be a word starting with a Latin letter.
When using, the case of the letters must be taken into account. That is, ABC and Abc are different names.
The declared macro can be used further in the text. It is a global definition. For example, we can use it in another formula:

@Pr()-CH3
@Pr()-CH3

Одновременное объявление и использование макроса Declaring and using a macro at the same time

Существует способ одновременно описать и использовать макроопределение. Для этого нужно в конце определения вместо @; использовать @().
Наш предыдущий пример может быть переписан так:

There is a way to simultaneously declare and use a macro definition. To do this, at the end of the declaration, instead of @;, use @().
Our previous example can be rewritten as follows:

@:Pr()H3C-CH2-C<//O>\O@()-H + NaOH -> @Pr()-Na + H2O <=> @Pr()^- + Na^+ + H2O
@:Pr()H3C-CH2-C<//O>\O@()-H + NaOH -> @Pr()-Na + H2O <=> @Pr()^- + Na^+ + H2O

Использование параметров Using parameters

Следующим естественным шагом использования макросов является применение параметров. Пример с пропионовой кислотой может быть переписан так:

The next natural step in using macros is to use parameters. The propionic acid example can be rewritten as:

@:Pr(x)H3C-CH2-C<//O>\O&x@(-H) + NaOH -> @Pr(-Na) + H2O <=> @Pr(^-) + Na^+ + H2O
@:Pr(x)H3C-CH2-C<//O>\O&x@(-H) + NaOH -> @Pr(-Na) + H2O <=> @Pr(^-) + Na^+ + H2O

Здесь мы видим параметр x. Он объявлен в скобках, а используется с помощью &x. Названием параметра может быть имя, начинающееся с латинской буквы, далее могут следовать другие буквы или цифры.
Впрочем, в этом примере мы мало что выиграли от использования параметра. Зато здесь иллюстрируется переопределение макроса. Мы создали новый макрос с тем же именем. Он заменил собой старый макрос. Те обращения, которые использовали вариант без параметра, не могут применяться после объявления нового макроса.

Here we see the parameter x. It is declared in brackets and used with &x. The parameter name can be a name starting with a Latin letter, followed by other letters or numbers.
However, in this example we have gained little from using the parameter. But here we illustrate macro redefinition. We have created a new macro with the same name. It has replaced the old macro. Those calls that used the variant without the parameter cannot be used after the declaration of the new macro.

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

{}_(x.8,H)$color(red)Na$color()_(x1.4,H)$color(blue)Cl$color()_(x.8,H){};
{}_(x.8,H)$color(blue)Cl$color()_(x1.4,H)$color(red)Na$color()_(x.8,H){};
{}|h#-8|h#-4|h{};{}|h#-9|h#-5|h{}
{}_(x.8,H)$color(red)Na$color()_(x1.4,H)$color(blue)Cl$color()_(x.8,H){}; {}_(x.8,H)$color(blue)Cl$color()_(x1.4,H)$color(red)Na$color()_(x.8,H){}; {}|h#-8|h#-4|h{};{}|h#-9|h#-5|h{}

Описание вышло довольно громоздким. Но тем больше причин для того, чтобы его автоматизировать для дальнейшего использования. Превратим прототип в макрос, заменив Na и Cl на параметры. Назовём их a и b. А сам макрос пусть называется Cross.

The description turned out to be rather cumbersome. But all the more reason to automate it for further use. Let's turn the prototype into a macro, replacing Na and Cl with parameters. Let's call them a and b. And let's call the macro Cross.

@:Cross(a,b){}_(x.8,H)$color(red)&a$color()_(x1.4,H)$color(blue)&b$color()_(x.8,H){};
{}_(x.8,H)$color(blue)&b$color()_(x1.4,H)$color(red)&a$color()_(x.8,H){};
{}|h#-8|h#-4|h{};{}|h#-9|h#-5|h{}@;
"Cross demo:"_(x2,h,N0){}@Cross(Na,Cl)
@:Cross(a,b){}_(x.8,H)$color(red)&a$color()_(x1.4,H)$color(blue)&b$color()_(x.8,H){}; {}_(x.8,H)$color(blue)&b$color()_(x1.4,H)$color(red)&a$color()_(x.8,H){}; {}|h#-8|h#-4|h{};{}|h#-9|h#-5|h{}@; "Cross demo:"_(x2,h,N0){}@Cross(Na,Cl)

Зато теперь мы получили довольно мощную конструкцию:

But now we have a rather powerful design:

@Cross(K,Br) @Cross(Li,F) @Cross(Ga,As)
@Cross(K,Br) @Cross(Li,F) @Cross(Ga,As)

Позиционные и именованные параметры Positional and named parameters

Допустим мы хотим создать макрос, определяющий производные бензола. Для этого в узлах расставим параметры с номерами, соответствующими номенклатуре IUPAC.

For example, we want to create a macro that defines benzene derivatives. To do this, we will place parameters with numbers corresponding to the IUPAC nomenclature in the nodes.

@:Ph(n1,n2,n3,n4,n5,n6)&n1\\&n2|&n3`//&n4`\&n5`||&n6/@()
@:Ph(n1,n2,n3,n4,n5,n6)&n1\\&n2|&n3`//&n4`\&n5`||&n6/@()

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

Although we declared as many as 6 parameters, we didn't use any of them for the first demonstration. The result was just benzene. But now we can make toluene from this construction by specifying a methyl group in the first position.

@Ph(CH3|)
@Ph(CH3|)

Но это лишь малая часть того, как можно использовать полученный макрос. Изобразим орто-, мета- и пара-крезол, подключив гидроксильную группу в позиции 2, 3 и 4 соответственно:

But this is only a small part of how the resulting macro can be used. Let's depict ortho-, meta- and para-cresol by connecting the hydroxyl group in positions 2, 3 and 4, respectively:

@Ph(CH3|,</OH>) @Ph(CH3|,,<\OH>) @Ph(CH3|,,,<|OH>)
@Ph(CH3|,</OH>) @Ph(CH3|,,<\OH>) @Ph(CH3|,,,<|OH>)

Здесь мы использовали позиционную подстановку, пропуская те узлы, которые не нужно заполнять. Но можно сразу указать название того параметра, который нужен:

Here we used positional substitution, skipping those nodes that do not need to be filled. But you can immediately specify the name of the parameter that is needed:

@Ph(CH3|,n6:<`\HO>) @Ph(CH3|,n5:<`/HO>) @Ph(CH3|,n4:<|HO>) @Ph(n6:<`\H3C>,n2:</CH3>,n4:<|CH3>)
@Ph(CH3|,n6:<`\HO>) @Ph(CH3|,n5:<`/HO>) @Ph(CH3|,n4:<|HO>) @Ph(n6:<`\H3C>,n2:</CH3>,n4:<|CH3>)

Для первых трех молекул первый параметр задан позиционно. Потому что он и так первый, зачем писать лишнее? А второй параметр указан по названию.
В последней молекуле все параметры указаны по имени. Как видно, в ней 6-й параметр указан раньше 2-го. Потому что не имеет значения, в каком порядке перечислены именованные параметры.

For the first three molecules, the first parameter is specified positionally. Because it is the first anyway, why write extra? And the second parameter is specified by name.
In the last molecule, all parameters are specified by name. As you can see, the 6th parameter is specified before the 2nd. Because it does not matter in what order the named parameters are listed.

Следует уточнить, что при описании макроса мы получили некоторую особенность, связанную с использованием параметров. Первый параметр является началом цепочки, а остальные должны образовывать ответвления. Поэтому конструкции < > используются для всех параметров, кроме первого. Впрочем, ничто не мешает использовать ветку и для первого параметра.
А ещё мы можем описать пиридин, указав азот в 4-м параметре. В этом случае ветка не нужна:

It should be clarified that when describing the macro we got a certain feature related to the use of parameters. The first parameter is the beginning of the chain, and the rest should form branches. Therefore, the < > constructions are used for all parameters except the first. However, nothing prevents us from using a branch for the first parameter as well.
We can also describe pyridine by specifying nitrogen in the 4th parameter. In this case, a branch is not needed:

@Ph(n4:N)
@Ph(n4:N)

Использование значений по-умолчанию Using default values

Дальнейшим улучшением описания макроса служит использование параметров с заранее заданными значениями (значениями по-умолчанию). Это позволяет описать достаточно сложные структуры с удобным способом внесения небольших изменений. В качестве примера выполним усовершенствование описанного выше макроса Cross. Дадим пользователю возможность влиять на цвет элементов и длину связей. Для этого добавим параметры colorA и colorB, которым через знак : заданы желаемые значения red и blue. Длину центральной связи зададим параметром len1:1.4, а боковой связи - len2:0.8.

A further improvement of the macro description is the use of parameters with predefined values (default values). This allows describing fairly complex structures with a convenient way to make small changes. As an example, we will improve the Cross macro described above. We will give the user the ability to influence the color of the elements and the length of the links. To do this, we will add the parameters colorA and colorB, which are given the desired values red and blue via the : sign. We will set the length of the central link with the parameter len1:1.4, and the lateral link with len2:0.8.

@:Cross(a,b,colorA:red,colorB:blue,len1:1.4,len2:0.8)#
{}_(x&len2,H)$itemColor(&colorA)&a$itemColor()_(x&len1,H)$itemColor(&colorB)&b$itemColor()_(x&len2,H){};
{}_(x&len2,H)$itemColor(&colorB)&b$itemColor()_(x&len1,H)$itemColor(&colorA)&a$itemColor()_(x&len2,H){};
{}_(y&len2,H)#-8_(y&len1,H)#-4_(y&len2,H){};
{}_(y&len2,H)#-9_(H)#-5_(y&len2,H){}@;
@Cross(Na,Cl)
@:Cross(a,b,colorA:red,colorB:blue,len1:1.4,len2:0.8)# {}_(x&len2,H)$itemColor(&colorA)&a$itemColor()_(x&len1,H)$itemColor(&colorB)&b$itemColor()_(x&len2,H){}; {}_(x&len2,H)$itemColor(&colorB)&b$itemColor()_(x&len1,H)$itemColor(&colorA)&a$itemColor()_(x&len2,H){}; {}_(y&len2,H)#-8_(y&len1,H)#-4_(y&len2,H){}; {}_(y&len2,H)#-9_(H)#-5_(y&len2,H){}@; @Cross(Na,Cl)

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

Please note that after the improvement, it is still possible to use the macro in the same way as before. This ensures that all previously done work, which contains a reference to the macro, will not require reworking. But you can use the new features where necessary:

@Cross(K,Br,colorB:darkmagenta,len1:2,len2:1.5)
$color(blue)@Cross(Fe,Cl,len2:1,colorA:black,colorB:darkgreen)$color()
$color(#888)@Cross({[+]},{[-]},len2:0.1,colorA:,colorB:)$color()
@Cross(K,Br,colorB:darkmagenta,len1:2,len2:1.5) $color(blue)@Cross(Fe,Cl,len2:1,colorA:black,colorB:darkgreen)$color() $color(#888)@Cross({[+]},{[-]},len2:0.1,colorA:,colorB:)$color()

Первая структура демонстрирует расширенные возможности использования макроса при помощи дополнительных параметров.
Вторая структура использует внешнее описание цвета линий.
Третья структура демонстрирует возможность отменить те значения по-умолчанию, которые установлены при описании макроса. То есть, вместо $itemColor(red) будет использоваться $itemColor(), что не повлияет на цвет, заданный ранее.

The first structure demonstrates the advanced capabilities of using the macro with additional parameters.
The second structure uses an external description of the line color.
The third structure demonstrates the ability to cancel the default values ​​that are set when describing the macro. That is, $itemColor() will be used instead of $itemColor(red), which will not affect the color specified earlier.

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

Let's look at a simpler, but quite practical example. Let's say we are working on an article about amino acids. It needs to demonstrate various reactions, including the formation of a peptide bond. It is desirable to provide a certain general style for displaying amino acids so that the reader immediately pays attention to important features, without wasting time on small details. To do this, we will develop a macro where it will be possible to determine the radical and, if necessary, modify the amino group depicted on the left and the carboxyl group depicted on the right.

@:AminoAcid(r:{R},a:H-,c:OH,rcol:blue)&a$C()N<`|H&>-C<`|H><|$color(&rcol)&r$color()>-C<`||O>-&c@()
@:AminoAcid(r:{R},a:H-,c:OH,rcol:blue)&a$C()N<`|H&>-C<`|H><|$color(&rcol)&r$color()>-C<`||O>-&c@()

Мы получили мощный инструмент, которым можно легко оперировать. (Хотя конечно под эту схему не подходит пролин).

We have received a powerful tool that can be easily operated. (Although of course proline does not fit this scheme).

Конечно, это не соответствует правилам хиральности аминокислот. Но допустим, что это сделано чтобы избежать лишней сложности Of course, this does not comply with the rules of amino acid chirality. But let's assume that this is done to avoid unnecessary complexity :)

Нарисуем несколько аминокислот - аланин, метионин и глутамин:

Let's draw some amino acids - alanine, methionine and glutamine:

@AminoAcid(CH3) @AminoAcid(CH2|CH2|S|CH3) @AminoAcid(CH2|CH2|C`/O/\NH2)
@AminoAcid(CH3) @AminoAcid(CH2|CH2|S|CH3) @AminoAcid(CH2|CH2|C`/O/\NH2)

Теперь изобразим для этих молекул реакцию с образованием пептидной связи.

Now let us depict for these molecules the reaction with the formation of a peptide bond.

@AminoAcid(CH3) + @AminoAcid(CH2|CH2|S|CH3) + @AminoAcid(CH2|CH2|C`/O/\NH2) ->
@AminoAcid(CH3,c:)@AminoAcid(CH2|CH2|S|CH3,a:,c:)@AminoAcid(CH2|CH2|C`/O/\NH2,a:) + 2H2O
@AminoAcid(CH3) + @AminoAcid(CH2|CH2|S|CH3) + @AminoAcid(CH2|CH2|C`/O/\NH2) -> @AminoAcid(CH3,c:)@AminoAcid(CH2|CH2|S|CH3,a:,c:)@AminoAcid(CH2|CH2|C`/O/\NH2,a:) + 2H2O

Вложенное использование макросов Nested use of macros

Из последнего примера видно, что неплохо бы ввести отдельное описание для аминокислот, чтобы не перечислять каждый раз их радикалы в параметрах. Опишем макросы для трёх упоминавшихся выше аминокислот.

From the last example it is clear that it would be a good idea to introduce a separate description for amino acids, so as not to list their radicals in the parameters each time. Let's describe the macros for the three amino acids mentioned above.

@:Ala(a,c)@AminoAcid(CH3,&a,&c)@;
@:Met(a,c)@AminoAcid(CH2|CH2|S|CH3,&a,&c)@;
@:Gln(a,c)@AminoAcid(CH2|CH2|C`/O/\NH2,&a,&c)@;
@:Ala(a,c)@AminoAcid(CH3,&a,&c)@; @:Met(a,c)@AminoAcid(CH2|CH2|S|CH3,&a,&c)@; @:Gln(a,c)@AminoAcid(CH2|CH2|C`/O/\NH2,&a,&c)@;

И перепишем уравнение с образованием пептидной связи

And we will rewrite the equation with the formation of a peptide bond

@Ala() + @Met() + @Gln() -> @Ala(c:# )@Met(# ,# )@Gln(a:# )
@Ala() + @Met() + @Gln() -> @Ala(c:# )@Met(# ,# )@Gln(a:# )

Некоторое неудобство состоит в том, что тут пришлось явно указать, что в местах стыковки аминогруппа и карбоксильная группа задана пустым местом. Для этого используется разрыв: #пробел. Это компромиссное решение, связанное с конкретным способом объявления макроса.
Но мы можем улучшить описание @Ala, чтобы оно стало аналогичным по поведению @AminoAcid:

Some inconvenience is that here it was necessary to explicitly indicate that in the places of joining the amino group and carboxyl group the empty space is specified. For this, break is used: #space. This is a compromise solution related to the specific way of declaring the macro.
But we can improve the description of @Ala so that it becomes similar in behavior to @AminoAcid:

@:Ala(a:H-,c:OH)@AminoAcid(CH3,a:&a,c:&c)@;
@Ala() -> {R1}-@Ala(a:,c:){R2}
@:Ala(a:H-,c:OH)@AminoAcid(CH3,a:&a,c:&c)@; @Ala() -> {R1}-@Ala(a:,c:){R2}

Здесь всё в руках автора макроса. Он может выбирать, где какой способ применить.

Here everything is in the hands of the macro author. He can choose where to apply which method.

Попробуем совместить разработанные макросы @AminoAcid и @Ph для описания ароматических аминокислот: фенилаланин и тирозин. У обеих метильная группа стыкуется к узлу 1, а у тирозина гидроксильная группа - к узлу 4.

Let's try to combine the developed macros @AminoAcid and @Ph to describe aromatic amino acids: phenylalanine and tyrosine. In both, the methyl group is attached to node 1, and in tyrosine, the hydroxyl group is attached to node 4.

@:Phe(a,c)@AminoAcid(@Ph(CH2|),&a,&c)@()
+ @:Tyr(a,c)@AminoAcid(@Ph(CH2|,n4:<|OH>),&a,&c)@() =
@Phe(c:# )@Tyr(a:# ) + H2O
@:Phe(a,c)@AminoAcid(@Ph(CH2|),&a,&c)@() + @:Tyr(a,c)@AminoAcid(@Ph(CH2|,n4:<|OH>),&a,&c)@() = @Phe(c:# )@Tyr(a:# ) + H2O

Ну и ещё один пример, где используем вложенный вызов @Cross для создания увеличенной структуры.

Well, here's another example where we use a nested @Cross call to create an enlarged structure.

@:Cross1(a,b,colorA:red,colorB:blue)@Cross(&a,&b,colorA:&colorA,colorB:&colorB,len1:2,len2:1)@;
@:Cross2(a,b,colorA:red,colorB:blue)@Cross1(&a,&b,colorA:&colorA,colorB:&colorB)_(x1,y-3,N0)# @Cross1(&a,&b,colorA:&colorA,colorB:&colorB)@;
@:Cross4(a,b,colorA:red,colorB:blue)@Cross2(&a,&b,colorA:&colorA,colorB:&colorB)_(x-7,y1,N0)# @Cross2(&a,&b,colorA:&colorA,colorB:&colorB)@;
@Cross1(Na,Cl) -> @Cross2($C()Na,Cl,colorB:green) -> @Cross4($C()Na,Cl)
@:Cross1(a,b,colorA:red,colorB:blue)@Cross(&a,&b,colorA:&colorA,colorB:&colorB,len1:2,len2:1)@; @:Cross2(a,b,colorA:red,colorB:blue)@Cross1(&a,&b,colorA:&colorA,colorB:&colorB)_(x1,y-3,N0)# @Cross1(&a,&b,colorA:&colorA,colorB:&colorB)@; @:Cross4(a,b,colorA:red,colorB:blue)@Cross2(&a,&b,colorA:&colorA,colorB:&colorB)_(x-7,y1,N0)# @Cross2(&a,&b,colorA:&colorA,colorB:&colorB)@; @Cross1(Na,Cl) -> @Cross2($C()Na,Cl,colorB:green) -> @Cross4($C()Na,Cl)

Функция $C() использована для выравнивания реагентов по вертикали.

The $C() function is used to align the reagents vertically.

Пример. Нумерация узлов Example. Node numbering

В номенклатуре химических соединений часто возникает необходимость показать нумерацию узлов (локанты). Это удобно делать при помощи макроса:

In the nomenclature of chemical compounds, it is often necessary to show the numbering of nodes (locants). This is conveniently done using a macro:

@:n(n,a,L:0.4)<_(A&a,L&L,N0)$itemColor1(blue)"&n">@;
-S@n(3,30,.5)_q@n(2,-10)_qqS<_(y-.5)H>@n(1,90,.6)_q_qq
=_q7SH@n(3,180,.5)_qq7@n(2,-20)_q7S<_(y-.5)H2>@n(1,90,.6)_q7_qq7_q7
=_q7@n(3,0)_qq7@n(2,-20)_q7S<_(y-.5)H2>@n(1,90,.6)_q7_qq7_q7
@:n(n,a,L:0.4)<_(A&a,L&L,N0)$itemColor1(blue)"&n">@; -S@n(3,30,.5)_q@n(2,-10)_qqS<_(y-.5)H>@n(1,90,.6)_q_qq =_q7SH@n(3,180,.5)_qq7@n(2,-20)_q7S<_(y-.5)H2>@n(1,90,.6)_q7_qq7_q7 =_q7@n(3,0)_qq7@n(2,-20)_q7S<_(y-.5)H2>@n(1,90,.6)_q7_qq7_q7

Здесь макрос называется n и имеет три параметра:

Here the macro is called n and has three parameters:

Макрос ставится сразу после объявления узла. А если автоузел, то вместо объявления узла.

The macro is placed immediately after the node declaration. And if autonode, then instead of the node declaration.

Заключение Conclusion

Подведём итоги. Применение макроопределений позволяет:

Let's sum it up. Using macro definitions allows you:

Обратной стороной медали является дополнительное время, связанное с изучением данного раздела. Кроме того, описание макроса потребует несколько больше усилий и времени, чем описание формулы. Чем более универсальный функционал, тем больше потребуется время на его тестирование и отладку.

The downside is the extra time associated with studying this section. In addition, describing a macro will require a little more effort and time than describing a formula. The more universal the functionality, the more time it will take to test and debug it.

Фигуры Figures

Здесь представлены фигуры, которые втречаются не часто, но всё-таки иногда бывают нужны.

Here are presented figures that are not encountered often, but are still sometimes needed.

Пятиугольник, который стыкуется с двумя шестиугольниками A pentagon that is joined to two hexagons

Пятиугольник, у которого две соседние стороны стыкуются полициклической структурой из шестиугольников. При этом, все его стороны имеют одинаковую длину.
А так же подходит для стыковки в одной точке трёх пятиугольников.

A pentagon in which two adjacent sides are joined by a polycyclic structure of hexagons. Moreover, all its sides have the same length.
It is also suitable for joining three pentagons at one point.

`\`|/\/\|`/`\<`|>`/_(a-%pa:81.4707)_(a-%pb:68.5292)_(a-%pb)
`\`|/\/\|`/`\<`|>`/_(a-%pa:81.4707)_(a-%pb:68.5292)_(a-%pb)
`/|<_(a-%pa:81.4707)_(a-%pb:68.5292)_(a-%pb)>_(a%pa)_(a%pb)_(a%pb)\/0_(a-%pa)_(a-%pb)_(a-%pb)
`/|<_(a-%pa:81.4707)_(a-%pb:68.5292)_(a-%pb)>_(a%pa)_(a%pb)_(a%pb)\/0_(a-%pa)_(a-%pb)_(a-%pb)

Такая фигура образуется при помощи трёх относительных углов:

This figure is formed using three relative angles:

$L(2)/:c\:a_(a%pa:81.4707):b_(a%pb:68.5292)_(a%pb); #c@:A(t,a)<_(A&a,L0.5,N0)$itemColor(blue)"&t">@(c,90); #a@A(a,170); #b@A(b,-120); #5@A(b,-60); #1@A(a,10)

Угол c = 120°, обычно образуется краткими связями, либо при помощи конструкций _p6,_q6 или _(a60)

Angle c = 120°, usually formed by short bonds, or using the constructions _p6,_q6 or _(a60)

Для углов a и b используются следующие конструкции:

For angles a and b the following constructions are used:

a:
_(a81.4707)
b:
_(a68.5292)

В примерах выше использованы переменные %pa и %pb, чтобы не повторять длинные числа.

The examples above use variables %pa and %pb, to avoid repeating long numbers.

Spiro compounds Спиросоединения

Здесь предполагается, что к правильному многоугольнику A в одной вершине присоединяется правильный многоугольник B.

Here it is assumed that a regular polygon A is joined at one vertex by a regular polygon B.

@:n(n,a:180,L:0.4)(*_(A&a,L&L,N0)$itemColor1(gray)"&n"*)@; $itemColor(blue)|_q_qv(*_q_q*)(*_(x-.85,N0)"A"*)\@n(1)-/`\`-@n(2)`/-0"B"

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

In general, it is recommended to solve this problem by using relative angles, which are calculated using the following formula:

угол angle  1 = 180 · ( 1
n + m n·m
) , угол angle  2 = 180 ·
n − m n·m

Здесь n — количество углов полигона A, а m — полигона B. Если обход полигона A идёт по часовой стрелке, то полученные углы нужно использовать с обратным знаком.

Here n is the number of corners of polygon A, and m is the number of corners of polygon B. If the polygon A is traversed clockwise, then the obtained corners must be used with the opposite sign.

Достаточно использовать только первый угол, чтобы сохранить направление обхода.

It is enough to use only the first corner to preserve the direction of the traversal.

Калькулятор Calculator

Подсказки Hints

В этом разделе для удобства собраны примеры использования разных конструкций CharChem.

For convenience, this section contains examples of using different CharChem designs.

C'n'H'2n+2'
K(+1)Mn(+7)O4(-2)
$M(235)U
$nM(232)Th + $nM(1,0){n}
H-$dots(TB)O-H
$color(blue)H2$color()S$color(red)O4
PO4^3-
O`^-/N$pos(90)^+`|O|\O^-
S"|v" + H2"|^, 0^oC"
{[gamma]} "[Delta]"->
{R^A} {R_{AB}}
-"AB{\color{red}CD}EF"
Na"`(s)`" + Cl2"`(g)`"
CuSO4*5H2O
\<|>/
$slope(45)Ca/O\S<//O><\\O>`/O`\
$L(2)|$L(3)-$L(2)`|$L()`-|`-`|`-
$dblAlign(R)\</>||<\>`/ $dblAlign(L)\</>||<\>`/
\$color(#F0F)//$color()\
/\|`/`\`|
-\`/`-`\/
Na|0Cl_q4oNa_(y-1,N0)Cl
\w-/ww`\d`-`/dd
\=x/
_(x2,y1,~)
/h_(x2,y1,H)
\v \vv \vvv
/`OCH3
HC|H2C--NH`|CH`==
-_p3_p3 |_q3_qq3
-_p_p_p_p |_qq_qNH_q_qq
-_p7_pp7_p7O_p7_pp7_p7
\N<_(y.5)H>/N<_(y-.5)H>\
|\/`|_(x-$3)
_(x%a:.6,y%h:1.2)_(x%b:1.1,y-%d:.4)_(x%c:1.4,y%d)_(x-%a,y-%h)_(x-%b,y%d)_(x-%c,y-%d)
-v_(a54)_q<_(a54)>_q<_(a54)>_q_q
-\C_(a0,N3)N
_(y1,S|:)_(A30,S|:)_(A-30,S|:)_(y-1,S|:)
H3C_(h)C<||O>CH2_(h)C<||O>CH3
/\|`/`\`|_o
_(x2)\`/_(x-2)`\/_s(S:)
H2C`|H2C`|H2C_m(x2)_m(y2)_(x-2)
|\c\\\
{{H}} {{{R}}}
Na[B$slope(45)</F><\F><`/F><`\F>]
H-(O|O)-H
K_(x2,H)[B$slope(45)<\F><`/F><`\F></F>]
$padding(0.7)[N]
@:n(n,a,L:.4)<_(A&a,L&L,N0)$itemColor1(#999)"&n">@;
OH|@n(1,-30)\@n(2,-30)||@n(3,30)`/`\`|/
$bg(orange,ellipse)OH|\|`/`\`|/
H2O + H\$C()C|O`|/H
`/|<_(a-%pa:81.4707)_(a-%pb:68.5292)_(a-%pb)>_(a%pa)_(a%pb)_(a%pb)\/0_(a-%pa)_(a-%pb)_(a-%pb)
|_q3_(a84)_q_q_q_q_(a84)

Абстрактный коэффициент Abstract coefficient

Если значение коэффициента не является целым числом, то оно указывается при помощи апострофов.

If the value of the coefficient is not an integer, it is indicated using apostrophes.

См: Возможности элементов узлов

See: Features of node items

Степень окисления Oxidation state

Степень окисления элемента указывается как описание заряда в скобках сразу после описания атома.

The oxidation state of an element is given as a charge description in parentheses immediately following the atom description.

См: Возможности элементов узлов

See: Features of node items

Атомная масса изотопа Atomic mass of isotope

Используется функция $M()

The function $M() is used

См: Возможности элементов узлов

See: Features of node items

Атомный номер и масса изотопа Atomic number and mass of the isotope

Используется функция $nM()

The function $nM() is used.

См: Возможности элементов узлов

See: Features of node items

Структуры Льюиса Lewis structures

Используется функция $dots()

The function $dots() is used

См: Возможности элементов узлов

See: Features of node items

Цветовые функции Color functions

Для изменения цвета разных частей формулы используется несколько функций. Чаще всего $color()

Several functions are used to change the color of different parts of a formula. The most common is $color()

См: Цветовые функции

See: Color functions

Заряд узла Node charge

После описания узла ставится знак ^ и описание заряда

After the description of the node, the ^ sign and charge description are placed.

См: Заряд узла

See: Node charge

Положение заряда узла Node charge position

Если нужно расположить заряд слева сверху от узла, то используется конструкция `^.

If you need to place a charge to the left above the node, then the `^ construction is used.

А если нужно расположить как-то иначе, то используется функция $pos().

And if you need to arrange it in some other way, then the function $pos() is used.

См: Заряд узла

See: Node charge

Специальные символы Special characters

Внутри текстовых элементов можно использовать магические комбинации: You can use "magic" combinations inside text items: ^o |^ |v

См: Текстовые возможности

See: Text features

Греческие буквы Greek letters

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

Within text and abstract items, you can use Greek letters by their names in square brackets.

См: Текстовые возможности

See: Text features

Надстрочные и подстрочные символы Superscript and subscript characters

Внутри текстовых и абстрактных элементов можно использовать для надстрочных символов: ^ (для одного) или ^{} (для нескольких). А для подстрочных соответственно - _ (для одного) или _{} (для нескольких).

Inside text and abstract items, you can use for superscript characters: ^ (for one) or ^{} (for several). And for subscript characters, respectively - _ (for one) or _{} (for several).

См: Текстовые возможности

See: Text features

Цвет внутри текста Color inside text

Внутри текстовых и абстрактных элементов можно менять цвет при помощи \color{код-цвета} или {\color{код-цвета}текст}.

Within text and abstract items, you can change the color using \color{color-code} or {\color{color-code}text}.

См: Текстовые возможности

See: Text features

Локализованные фразы Localized phrases

Внутри текстовых элементов при помощи обратных апострофов можно использовать фразы из словаря, которые должны переводиться на разные языки.

Within text items, using backticks, you can use phrases from the dictionary that should be translated into different languages.

См: Текстовые возможности

See: Text features

Гидраты, сольваты Hydrates, solvates

Используется символ * (без пробелов).

The symbol * is used (no spaces).

См: Гидраты, сольваты и аддукты

See: Hydrates, solvates and adducts

Ветвления Branching

Для простейших случаев ветвления используются угловые скобки < > или (* *).

For the simplest cases of branching, angle brackets < > or (* *) are used.

См: Ветвления.

See: Branching.

Для более сложных случаев можно использовать соединение цепочек.

For more complex cases, chain connection can be used.

Угол наклона связей Angle of bonds

Для кратких связей можно менять угол наклона при помощи $slope().

For short bonds, you can change the slope using $slope().

См: Функции для химических связей.

See: Functions for chemical bonds.

Длина связи Bond length

Длину кратких связей можно регулировать функцией $L().

The length of short bonds can be adjusted using the $L() function.

См: Функции для химических связей.

See: Functions for chemical bonds.

Выравнивание двойных связей Alignment of double bonds

По-умолчанию при выводе двойных связей выполняется автоматическое выравнивание. В том случае, если нужно явно указать выравнивание для любых типов связей, может быть использована функция $dblAlign().

By default, automatic alignment is performed when outputting double bonds. In case it is necessary to explicitly specify the alignment for any type of bonds, the function $dblAlign() can be used.

См: Функции для химических связей.

See: Functions for chemical bonds.

Цвет связей Color of bonds

Единственным способом указать цвет связей является функция $color().

The only way to specify the color of bonds is the function $color().

См: Функции для химических связей.

See: Functions for chemical bonds.

Вертикальный шестиугольник Vertical hexagon

Стандартный угол наклона кратких связей составляет 30°, что позволяет формировать вертикальные шестиугольники.

The standard short bond angle is 30°, which allows the formation of vertical hexagons.

См: Вертикальные и горизонтальные шестиугольники

See: Vertical and horizontal hexagons

Горизонтальный шестиугольник Horizontal hexagon

Горизонтальный шестиугольник использует угол наклона кратких связей 60°. Это нестандартное значение. Оно автоматически включается при наличии определённых сочетаний соседних связей.

The horizontal hexagon uses a short bond angle of 60°. This is a non-standard value. It is automatically applied in the presence of certain combinations of adjacent bonds.

См: Вертикальные и горизонтальные шестиугольники

See: Vertical and horizontal hexagons

Невидимые связи Transparent bonds

Для кратких и полигональных связей используются суффиксы 0 или o. А для универсальных связей - параметр N0.

For short and polygonal bonds, the suffixes 0 or o are used. And for universal bonds, the parameter N0.

См: Суффиксы, Кратность универсальной связи

See: Suffixes, Multiplicity

Хиральность Chirality

Для кратких и полигональных связей используются суффиксы w ww d dd. А для универсальных связей - параметры w W d D.

For short and polygonal connections, the suffixes w ww d dd are used. And for universal bonds, the parameters w W d D.

См: Суффиксы, Хиральность универсальной связи

See: Suffixes, Chirality of the universal bond

Перекрещенная двойная связь Crossed double bond

Для кратких и полигональных связей используются суффикс x. А для универсальных связей - параметр N2x.

For short and polygonal bonds, the suffix x is used. And for universal bonds, the parameter N2x is used.

См: Суффиксы, Кратность универсальной связи

See: Suffixes, Multiplicity of universal bond

Волнистая связь Wavy bond

Для кратких и полигональных связей используются суффикс ~. А для универсальных связей - параметр ~.

For short and polygonal bonds the suffix ~ is used. And for universal bonds the parameter ~ is used.

См: Суффиксы, Декоративные параметры универсальной связи

See: Suffixes, Decorative parameters of universal bonds

Водородная связь Hydrogen bond

Для кратких и полигональных связей используются суффикс h. А для универсальных связей - параметр H.

For short and polygonal bonds, the suffix h is used. And for universal bonds, the parameter H is used.

См: Суффиксы, Декоративные параметры универсальной связи

See: Suffixes, Decorative parameters of universal bonds

Стрелки Arrows

Для кратких и полигональных связей используются суффиксы v vv vvv. А для универсальных связей - параметры С < >.

For short and polygonal bonds, the suffixes v vv vvv are used. And for universal bonds, the parameters С < > are used.

См: Суффиксы, Декоративные параметры универсальной связи

See: Suffixes, Decorative parameters of universal bonds

Центр узла Center of a node

Чтобы явно указать центр узла, используется обратный апостроф перед элементом узла.

To explicitly indicate the center of a node, a backtick is used before the node item.

См: Центры узлов

See: Node centers

Жесткие связи Hard bonds

Если нужно избежать использования мягких связей, используются специальные краткие связи: If it is necessary to avoid the use of soft bonds, special short bonds are used: -- == %%.

Обычно это нужно для циклических формул.

This is usually needed for cyclic formulas.

См: Мягкие связи

See: Soft bonds

Циклопропан Cyclopropane

Правильный треугольник обычно строится при помощи конструкций _p3 или _q3.

A regular triangle is usually constructed using the _p3 or _q3 constructions.

См: Полигональные связи

See: Polygonal bonds

Циклопентан Cyclopentane

Правильный пятиугольник обычно строится при помощи конструкций _p или _q.

A regular pentagon is usually constructed using the _p or _q constructions.

См: Полигональные связи

See: Polygonal bonds

Циклогептан Cycloheptane

Правильный семиугольник обычно строится при помощи конструкций _p7 или _q7.

A regular heptagon is usually constructed using the _p7 or _q7 constructions.

См: Полигональные связи

See: Polygonal bonds

Половинная высота Half height

Чтобы изобразить один атом впритык к другому сверху или снизу, нужно использовать ветку, в которой вертикальная связь длиной 0.5

To depict one atom close to another from above or below, you need to use a branch in which the vertical bond is 0.5 long.

См: Универсальные связи. Параметры x и y

See: Universal bonds. Parameters x and y

Хорда в шестиугольнике Chord in a hexagon

Для соединения сторон шестиугольника используется линия длиной √3 (при условии, что длина обычной линии равна 1). Такое число можно указать при помощи специальной константы $3.

To connect the sides of a hexagon, a line of length √3 is used (assuming that the length of a normal line is 1). This number can be specified using the special constant $3.

См: Универсальные связи. Параметры x и y и Числовые параметры.

See: Universal bonds. Parameters x and y and Numeric parameters

Использование переменных Using variables

В параметрах универсальных связей можно использовать переменные.

Variables can be used in the parameters of universal bonds.

Например, x%c:1.4 создаёт переменную c=1.4. А x%c - это её применение.

For example, x%c:1.4 creates the variable c=1.4. And x%c is its application.

См: Универсальные связи. Параметры x и y и Числовые параметры.

See: Universal bonds. Parameters x and y and Numeric parameters

Нормали Normals

Боковые ответвления от полигонов рекомендуется делать при помощи относительных углов.

It is recommended to make lateral branches from polygons using relative angles.

См: Нормали.

See: Normals.

Относительный угол 0 Relative angle 0

Чтобы нарисовать последовательно две связи в одном направлении рекомендуется использовать _(a0). Это обычно используется для тройных связей.

To draw two bonds in a row in one direction, it is recommended to use _(a0). This is usually used for triple bonds.

См: Относительные углы.

See: Relative angles.

Стиль связи Bond style

Чтобы комбинировать различные типы линий, используются универсальные связи с параметром S.

To combine different types of lines, universal bonds with parameter S are used.

См: Стили.

See: Styles.

Неявные узлы Implicit nodes

Если нужно делать ветки от одного большого узла, то его нужно разделить на меньшие узлы, соединённые конструкцией _(h).

If you need to make branches from one large node, then it needs to be divided into smaller nodes, connected by the _(h) construction.

См: Мягкие универсальные связи.

See: Soft universal bonds.

Кольцевая связь Ring bond

Кольцевая связь создаётся конструкцией _o.

A ring bond is created by the _o construct.

См: Распределённые связи.

See: Delocalized bonds.

Сплайновая связь Spline bond

Конструкция _s() позволяет создать сомкнутую или разомкнутую связь для нескольких узлов.

The _s() construct allows you to create a closed or open bond for several nodes.

См: Распределённые связи.

See: Delocalized bonds.

Изогнутые линии Curved lines

Изогнутые линии формируются при помощи кривых Безье. Конструкцей _m задаются промежуточные контрольные точки. При помощи одной промежуточной точки задаётся квадратичная кривая, при помощи двух - кубическая.

Curved lines are formed using Bezier curves. The _m construct specifies intermediate control points. A quadratic curve is specified using one intermediate point, and a cubic curve is specified using two.

См: Изогнутые линии.

See: Curved lines.

Явное создание автоузла Explicit creation of an autonode

Чтобы отделить одну связь от другой без создания видимого узла используется символ c.

To separate one bond from another without creating a visible node, the c symbol is used.

См: Дополнительные приёмы.

See: Additional techniques.

Фигурные скобки Braces

Для описания фигурных скобок нужно использовать конструкции {{ и }}

To describe curly braces, you need to use the {{ and }} constructs.

См: Скобки.

See: Brackets.

Узел + скобка Node + bracket

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

If a node is connected to a bracket, it is centered relative to the horizontal axis.

См: Скобки.

See: Brackets.

Мягкая связь + скобка Soft bond + bracket

Если скобка соединяется с мягкой связью, то связь не пересекает скобку. А оба узла связи остаются на одном уровне.

If a bracket is connected to a soft bond, the bond does not cross the bracket. And both bond nodes remain at the same level.

Соединительные связи всегда снаружи от скобок.

The connecting bonds are always outside the brackets.

См: Скобки.

See: Brackets.

Cвязь + скобка Bond + bracket

Если скобка соединяется с любой связью, кроме мягкой, то связь пересекает скобку.

If a bracket is connected to any bond except a soft bond, the bond crosses the bracket.

Соединительные связи всегда снаружи от скобок.

The connecting bonds are always outside the brackets.

См: Скобки.

See: Brackets.

Отступы внутри скобок Indentation inside brackets

Отступы указываются функцией $padding().

The padding is specified by the $padding() function.

См: Скобки.

See: Brackets.

Макрос для нумерации узлов Macro for node numbering

Если нужно показать локанты, то рекомендуется использовать макрокоманду.

If you need to show locants, it is recommended to use a macro.

См: Макрокоманды.

See: Macro commands.

Центрирование реагентов Centering of reagents

Можно управлять вертикальным центрированием реагентов при помощи функции $C()

You can control the vertical centering of reagents using the $C() function.

См: Центр формулы.

See: Center of the formula.

Фоновая фигура Background figure

Можно выделить какую-то часть формулы при помощи фона функцией $background() или $bg().

You can highlight some part of the formula using the background by function $background() or $bg().

См: Фоновая фигура.

See: Background figure

Пятиугольник, который присоединяется двумя сторонами к сотовой структуре A pentagon that is attached by two sides to a honeycomb structure

Подробности в разделе Фигуры

Details in the Figures section

Спиросоединения Spiro compounds

Для присоединения одного полигона к другому рекомендуется использовать относительные углы. Подробнее см. раздел Спиросоединения

It is recommended to use relative angles to join one polygon to another. For more information, see the section Spiro compounds

Примеры перечислены в том порядке, в котором они следуют в разделе Описание химических формул

Examples are listed in the order they appear in the Description of chemical formulas section.

Справочник Reference

Где можно или необходимо вставлять пробелы Where can or should spaces be inserted?

Во всех случаях, где можно вставить один пробел, там на самом деле можно вставлять любое количество пробелов, символов табуляции и конца строки.

In all cases where you can insert one space, you can actually insert any number of spaces, tabs, and line breaks.

Способы указания цвета Methods of specifying color

Иногда внутри формулы может потребоваться какой-то специальный цвет. Для обозначения цветов используются те же способы, что в HTML, CSS и SVG

Sometimes a special color may be needed within a formula. The same methods as in HTML, CSS, and SVG are used to indicate colors.

См. Цветовые функции или Фоновая фигура

See. Color functions or Background figure

По шестнадцатеричному значению (коду) By hexadecimal value (code)

Описание начинается с # (решетка) и состоит из 6 или 3 шеснадцатеричных цифр. Если указано 3, то они превращаются в 6 путем удвоения каждого символа. Цвета идут в порядке красный-зелёный-синий. Регистр не имеет значения.

The description starts with # (pound) and consists of 6 or 3 hexadecimal digits. If 3 is specified, they are converted to 6 by doubling each character. The colors are in the order red-green-blue. Case is not important.

НапримерFor example: #FA8 = #FFAA88 = #ffaa88 =

Поддержка описания цветов в таком формате есть во многих графических редакторах. Например в PhotoShop или GIMP.

Many graphic editors support color descriptions in this format. For example, PhotoShop or GIMP.

RGB

Начинается с ключевого слова rgb, а затем в скобках, через запятую указываются компоненты цвета. Диапазон от 0 до 255.

It starts with the keyword rgb, and then in brackets, separated by commas, the color components are indicated. The range of values ​​is from 0 to 255.

НапримерFor example: rgb(255, 128, 128).

RGBA

Формат RGBA похож по синтаксису на RGB, но включает в себя альфа-канал, задающий прозрачность элемента. Значение 0 соответствует полной прозрачности, 1 — непрозрачности, а промежуточное значение вроде 0.5 — полупрозрачности.

The RGBA format is similar in syntax to RGB, but includes an alpha channel that specifies the transparency of the element. A value of 0 corresponds to full transparency, 1 to opacity, and an intermediate value like 0.5 to semi-transparency.

НапримерFor example: rgba(255, 255, 255, 0.5)

Важно! Альфа-канал поддерживается не всеми форматами графических файлов. К таким относится EPS и другие варианты PostScript. Поэтому не рекомендуется использовать цвета с прозрачностью для тех формул, которые предназначены для широкого распространения. Например, в справочнике веществ CharChem такие цвета не используются.

Important! There are graphic file formats that do not support the alpha channel. These include EPS and other PostScript variants. Therefore, it is not recommended to use colors with transparency for formulas that are intended for wide distribution. For example, such colors are not used in the CharChem substance reference.

По названию By name

В следующей таблице представлены основные цвета с названиями и кодировкой. The following table shows the main colors with their names and coding.

ЦветColor НазваниеName КодCode RGB

Подробнее можно ознакомиться в For more details, please refer to the официальной документации CSS official CSS documentation .

Обратите внимание, что в CSS существуют и другие способы описания цветов. Но их использовать не рекомендуется. Они будут работать, если формула рисуется браузером в составе документа. Но нет гарантий поддержки, если формула будет отрисована каким-то иным программным обеспечением.

Please note that there are other ways to describe colors in CSS. But it is not recommended to use them. They will work if the formula is drawn by the browser as part of the document. But there is no guarantee of support if the formula is drawn by some other software.

Например, для создания этой документации в CSS-файле есть такая конструкция:

For example, to create this documentation, the CSS file contains the following construct:

      :root {
        --select-color: #B0B;
      }

Поэтому для единообразного выделения частей формул в разных местах документа используется такое описание цвета:

Therefore, to consistently highlight parts of formulas in different places in a document, the following color description is used:

\<`/>-$color(var(--select-color))OH
\<`/>-$color(var(--select-color))OH

Здесь var(--select-color) — это способ обращения к переменной в CSS3.

Here var(--select-color) is the CSS3 way of referring to a variable.

Но если попробовать использовать такое описание за пределами документа, то оно работать не будет.

But if you try to use such a description outside the document, it will not work.

Числовые параметры Numeric parameters

Числовые параметры могут потребоваться в параметрах функций и универсальных связей.

Numeric parameters may be required in the parameters of functions and universal bonds.

ЧислаNumbers

Числа описываются как в языках программирования. То есть:

Numbers are described as in programming languages. That is:

ПеременныеVariables

Иногда удобно запомнить один раз число под каким-то именем. А далее использовать имя.

Sometimes it is convenient to remember a number once under some name. And then use the name.

Для этого в числовых значениях CharChem можно использовать конструкцию %x:9, а далее можно пользоваться этим именем так: %x. Здесь x - это любое имя, состоящее из латинских букв (регистр важен). А вместо 9 может быть любое число.

To do this, you can use the %x:9 construction in CharChem numeric values, and then you can use this name like this: %x. Here x is any name consisting of Latin letters (case is important). And 9 can be any number.

Например:

For example:

$slope(%a:70)\$slope(%b:20)/\$slope(%a)`\$slope(%b)`\`/
$slope(%a:70)\$slope(%b:20)/\$slope(%a)`\$slope(%b)`\`/

Здесь переменная a означает наклон в 70° и b — 20°

Here the variable a means a slope of 70° and b means 20°

А вот пример посложнее

Here is a more complicated example

_(x%a:.6,y%h:1.2)_(x%b:1.1,y-%d:.4)_(x%c:1.4,y%d)_(x-%a,y-%h)_(x-%b,y%d)_(x-%c,y-%d)
_(x%a:.6,y%h:1.2)_(x%b:1.1,y-%d:.4)_(x%c:1.4,y%d)_(x-%a,y-%h)_(x-%b,y%d)_(x-%c,y-%d)

Здесь кооодината x меняется так: a, b, c, -a, -b, -c, что гарантирует возврат в исходную точку. Для y ещё интереснее: h, -d, d, -h, d, -d, что тоже даёт возврат в исходную точку. А в результате получаем фигуру, которая часто используется для изображения молекул сахаров или иных производных циклогексана.

Here the coordinate x changes as follows: a, b, c, -a, -b, -c, which guarantees a return to the starting point. For y it is even more interesting: h, -d, d, -h, d, -d, which also gives a return to the starting point. And as a result we get a figure that is often used to depict sugar molecules or other cyclohexane derivatives.

КонстантыConstants

Есть несколько иррациональных значений, представленных константами, которые начинаются со знака $.

There are several irrational values ​​represented by constants that begin with the $ sign.

$3=3  $2=2
$32=3/2  $22=2/2
$3x2=3×2  $2x2=2×2

Корень из 2 — это длина диагонали квадрата, а корень из 3 — расстояние между противоположными сторонами в шестиугольнике. (При условии что длина стороны = 1)

The square root of 2 is the length of the diagonal of a square, and the square root of 3 is the distance between opposite sides of a hexagon. (Assuming that the side length = 1)

Например:

For example:

_(A45,L$2)`-`|
_(A45,L$2)`-`|
|\/`|_(x-$3)
|\/`|_(x-$3)

Способы описания зарядов Methods of describing charges

Заряды могут быть указаны для узлов, скобок а так же как степень окисления для элементов узлов.

Charges can be specified for nodes, brackets, and also as oxidation states for node items.

Существует несколько способов для описания зарядов.

There are several ways to describe charges.

СпособWay ПояснениеExplanation ПримерыExamples
МинусыMinuses - илиor -- илиor ---
Cl^-
Cl^-
S^--
S^--
N^---
N^---
Плюсы Pluses + илиor ++ илиor +++
Li^+
Li^+
Mg^++
Mg^++
Al^+++
Al^+++
Целое число и знак Integer and sign 2- 1+ 6+... Типично для ионов с зарядом более чем 1 (положительным или отрицательным) Typical for ions with a charge greater than 1 (positive or negative)
Sn^4+
Sn^4+
PO4^3-
PO4^3-
Знак и целое число Sign and integer -2 +1 +6... Обычно используется для степени окисления, либо для случая, когда заряд слева от узла. Usually used for oxidation state, or when the charge is to the left of the node.
Cl(-1)
Cl(-1)
Mg`^+2
Mg`^+2
Целое число без знака Unsigned integer 0 1 2... Полезно, если нужно указать нулевой заряд. Useful if you need to specify a zero charge.
Сa(0)
Ca(0)
Плюс или минус в круге Plus or minus in a circle Знак + или - и маленькая буква o: The + or - sign and a small letter o: +o -o
{R}\<|wNH3`^+o>/`|O|\O^-o
{R}\<|wNH3`^+o>/`|O|\O^-o
Римские цифры Roman numerals Касается чисел от 1 до 8. Применяется для степеней окисления.
Римские цифры записываются маленькими буквами. Потому что большие используются для химических элементов:
This applies to numbers from 1 to 8. It is used for oxidation states.
Roman numerals are written in small letters. Because large ones are used for chemical elements:

i ii iii iv v vi vii viii
KFe(iii)[Fe(ii)(CN)6]
KFe(iii)[Fe(ii)(CN)6]
KMn(vii)O4
KMn(vii)O4

Список радикалов List of Radicals

Поддержка радикалов появилась в версии CharChem 1.0. Подробнее см. Элементы узла

Radicals support was introduced in CharChem 1.0. For more information, see Node items

CharChem ОписаниеDescription Структурная формулаStructural formula
Me Метил Methyl
{}_(x1)CH3
Et Этил Ethyl
{}_(x1)CH2-CH3
Pr = n-Pr = Pr-n Пропил Propyl
{}_(x1)CH2-CH2-CH3
iPr = i-Pr = Pr-i Изопропил Isopropyl
{}-<\CH3>/CH3
Bu = nBu = n-Bu = Bu-n н-Бутил n-Butyl
{}_(x1)CH2-CH2-CH2-CH3
i-Bu = Bu-i = iBu Изобутил или 2-метилпропил isobutyl or 2-methylpropyl
{}_(x1)CH2-CH<\CH3>/CH3
s-Bu = Bu-s = sBu втор-бутил или 1-метилпропил sec-butyl or butan-2-yl
{}-CH</CH3>\CH2-CH3
t-Bu = Bu-t = tBu Третичный бутил, трет-бутил или 1,1-диметилэтил tert-butyl
{}_(x1)C<`|CH2><|CH3>-CH3
Ph Фенил Phenyl
{}-//-\\`/`=`\
Ac Ацетил Acetyl
{}_(x1)C`|O|-CH3
Tf Triflyl or trifluoromethanesulfonyl
{}--S|O`|`|O|--C<`|F><|F>-F
CoA Кофермент A Coenzyme A
$L(.9)$color(red)SH$color()`/`\`/N<_(y.5)H>`\`/O/`|/`|NH`\`/O/`|<`\dHO>/<_q4H3C><_(a-30)CH3>\/O_(A0)P`|O|<|OH>-O-P`|O|<|OH>-O:o; `-<_(a-54,d+)O|P<-OH>|O`|`-HO>_p<_(a-54,w+)`/#o>_pO_p<_p_(a-54,d+)OH>_(a-54,w+)N_(a54)_q_p6<_q6NH2>_pp6N_p6_pp6N_p6_p6_qN_qq_q = {CoA}$color(red)SH

Список функций List of functions

Функция всегда ставится перед тем объектом, к которому она должна применяться.

The function is always placed before the object to which it should be applied.

См. такжеSee also: Функции CharChemCharChem functions, Цветовые функцииColor functions, Функции для химических связейFunctions for chemical bonds.

НазваниеName
Краткое описаниеBrief description
ПримерExample
Код примераExample code
atomColor
Цвет атомовColor of atoms
$atomColor(brown)2H2SO4 <=> 2H^+ + SO4^2- $atomColor(brown)2H2SO4 <=> 2H^+ + SO4^2- atomColor1
Цвет следующего атомаColor of the next atom
H2$atomColor1(brown)SO4 H2$atomColor1(brown)SO4 background илиor bg
Фоновая фигураBackground figure
/`|$bg(orange,round)S|\ /`|$bg(orange,round)S|\ C
Центр формулыCenter of the formula
2/`|$C()S|\ -> /`|$C()S|\/`|S|\ 2/`|$C()S|\ -> /`|$C()S|\/`|S|\ color
Цвет для всех частей формулы Color for all parts of the formula
3$color(blue)(NH4)2$color(red)SO4 3$color(blue)(NH4)2$color(red)SO4 dblAlign
Выравнивание двойных связей Alignment of double bonds
\$dblAlign(r)||\ <-> \$dblAlign(L)||\ \$dblAlign(r)||\ <-> \$dblAlign(L)||\ dots
Lewis structures Структуры Льюиса
H/$dots(LtURt)O\H H/$dots(LtURt)O\H itemColor
Цвет элементов узла Color of node items
$itemColor(blue)(NH4)2$itemColor(brown)SO4 $itemColor(blue)(NH4)2$itemColor(brown)SO4 itemColor1
Цвет следующего элемента узла Color of next node items
$itemColor1(blue)Fe2(S$itemColor1(red)O4)3 $itemColor1(blue)Fe2(S$itemColor1(red)O4)3 L
Длина химических связей Length of chemical bonds
\|`/$L(2)`| \|`/$L(2)`| M
Атомная масса изотопа Atomic mass of isotope
$M(235)U $M(235)U nM
Атомный номер и масса изотопа Atomic number and mass of the isotope
$nM(26)Al + $nM(1,0){n} -> $nM(27)Al"*" $nM(26)Al + $nM(1,0){n} -> $nM(27)Al"*" padding
Отступы внутри скобок Indentation inside brackets
H\$padding(0.4,0.1)[O/`|O|]'150-300'\O/H H\$padding(0.4,0.1)[O/`|O|]'150-300'\O/H pos
Положение заряда узла Node charge position
$pos(LT)O^-\$pos(LB)N^+|O`|/CH3 $pos(LT)O^-\$pos(LB)N^+|O`|/CH3 slope
Угол наклона для кратких химических связей Slope angle for short chemical bonds
$slope(45)/\`/`\ $slope(45)/\`/`\ ver
Версия CharChem CharChem version
$ver(1)-_qwO_qww_qdO_qdd $ver(1)-_qwO_qww_qdO_qdd

Цвет атомовColor of atoms

Позволяет указать цвет только для атомов. То есть, не действует на коэффициенты, заряды, радикалы, комментарии, скобки, связи и т.п.

Allows you to specify a color for atoms only. That is, it does not affect coefficients, charges, radicals, comments, brackets, bonds, etc.

СинтаксисSyntax: $atomColor(color)

color - описание цветаcolor description. Если не указан, то будет восстановлен цвет по-умолчанию. If not specified, the default color will be restored.

Область действия: до конца формулы. Для прекращения действия можно использовать $atomColor()

Scope: Until the end of the formula. To stop the action, you can use $atomColor()

$atomColor(red){R}-CO2H
$atomColor(red){R}-CO2H
$atomColor(blue)H2N$atomColor()-CH<|{R}>-$atomColor(red)COOH
$atomColor(blue)H2N$atomColor()-CH<|{R}>-$atomColor(red)COOH
$atomColor(#C0C)I|\\|<\I>`//`\<`/I>`||/
$atomColor(#C0C)I|\\|<\I>`//`\<`/I>`||/

Смотри также: See also: $atomColor1(), цветовые функцииcolor functions.

Цвет следующего атома Color of the next atom

Аналог функции atomColor, но действует только на следующий атом

Similar to the atomColor function, but only affects the next atom.

СинтаксисSyntax: $atomColor1(color)

color - описание цвета color description .

Область действия: следующий за функцией атом.

Scope: the atom following the function.

{R}-$atomColor1(red)CO2H
{R}-$atomColor1(red)CO2H
\\|$atomColor1(red)O`/`\$atomColor1(blue)N`||/
\\|$atomColor1(red)O`/`\$atomColor1(blue)N`||/

Смотри такжеSee also: $atomColor(), цветовые функцииcolor functions.

Фоновая фигура Background figure

Позволяет выделить какую-то часть формулы при помощи фона

Allows you to highlight some part of the formula using a background

СинтаксисSyntax:: $background(параметрыparams) или корочеor shorter $bg(параметрыparams)

Минимальная версия CharChem: 2.0

Minimum CharChem version: 2.0

Параметры могут следовать в любом порядке и не являются обязательными. Но чтобы увидеть результат, нужно указать либо цвет заливки (fill), либо цвет линии по периметру фигуры (stroke).

The parameters can be in any order and are not mandatory. But to see the result, you need to specify either the fill color (fill) or the color of the line around the shape's perimeter (stroke).

ПараметрParameter ОписаниеDescription
цветcolor
| fill:цветcolor | f:цветcolor
Цвет фигуры. Например, orange или #F00.
То есть, обычно указывается просто цвет. Но для большей информативности можно указать что это цвет заливки при помощи префиксов fill: или f:.
Если параметр не указан, то заливки не будет. Предполагается что в этом случае будет указан периметр.
The color of the figure. For example, orange or #F00. That is, usually just the color is specified. But for more information, you can specify that this is the fill color using the fill: or f: prefixes. If the parameter is not specified, there will be no fill. It is assumed that in this case the perimeter will be specified.
rect | round | ellipse
Форма фигуры. Если не указана, то rect
The shape of the figure. If not specified, then rect
*
Звёздочка означает, что фигура будет применяться ко всему реагенту.
The Asterisk (Star) symbol means that the shape will be applied to the entire reagent.
to:n илиor :n
Если не указан, то фигура применяется к тому узлу, перед которым находится функция.
В качестве n указывается номер узла. Если значение положительное, то это порядковый номер узла от начала реагента. Если отрицательный - то относительно того узла, для которого указана функция. Но нельзя указывать те узлы, которые находятся после функции (т.к. они еще не существуют на момент обработки функции)
Можно указать несколько узлов через точку с запятой. Фигура будет сформирована так, чтобы захватить все указанные узлы. Во втором примере жёлтый прямоугольник соединяет первый и четверый узел, но третий тоже указан, т.к. он не находится с ними на одной линии.
Если функция стоит в конце реагента и за ней нет узлов, то нужно указать минимум два узла.
If not specified, the figure is applied to the node before which the function is located.
The node number is specified as n. If the value is positive, it is the ordinal number of the node from the beginning of the reagent. If negative, it is relative to the node for which the function is specified. However, you cannot specify nodes that are after the function (since they do not yet exist at the time the function is processed).
You can specify several nodes separated by a semicolon. The figure will be formed in such a way as to capture all the specified nodes. In the second example, the yellow rectangle connects the first and fourth nodes, but the third is also specified, since it is not on the same line with them. If the function is at the end of the reagent and there are no nodes after it, then at least two nodes must be specified.
stroke:цветcolor | s:цветcolor Цвет линии по периметру фигуры. Если не указан, то не выводится. Color of the line around the perimeter of the figure. If not specified, it is not displayed.
width:числоnumber | w:числоnumber Толщина линии по периметру фигуры. Имеет смысл только совместно с параметром stroke.
Если не указан, то будет использоваться внешняя настройка, которая обычно соответствует 1 пикселю.
Если указан, то 1 соответствует ширине одинарной химической связи.
The thickness of the line around the perimeter of the figure. Only makes sense in combination with the stroke parameter.
If not specified, the external setting will be used, which usually corresponds to 1 pixel.
If specified, 1 corresponds to the width of a single chemical bond.
padding:от 1 до 4 чисел1..4 numbers | p:от 1 до 4 чисел1..4 numbers
Внутренний отступ от границы фигуры до содержимого. Концептуально соответсвует свойству padding в CSS.
Единицы измерения такие же, как для всех параметров, связанных с координатами. То есть, 1 соответствует длине химической связи.
Если указывается несколько значений, то они разделяются ; (точкой с запятой) без пробелов.
[all], [vert, horiz], [top, horiz, bottom], [top, l, bot, r] Указанные числа в зависимости от их количества означают отступы:
  1. Со всех сторон
  2. Вертикальные и горизонтальные
  3. Сверху, горизонтальные и снизу
  4. Сверху, справа, снизу и слева
В последнем примере можно увидеть, как это работает.
А в предпоследнем примере можно видеть применение отрицательного отсупа. Это может быть полезно для круга и эллипса, т.к. там не всегда оптимально определяются границы фигуры, которая захватывает все необходимые узлы.
Inner padding from the border of the figure to the content. Conceptually corresponds to the padding property in CSS.
The units of measurement are the same as for all coordinate-related parameters. That is, 1 corresponds to the length of the chemical bond.
If several values ​​are specified, they are separated by ; (semicolon) without spaces.
[all], [vert, horiz], [top, horiz, bottom], [top, l, bot, r] The specified numbers, depending on their quantity, mean padding:
  1. On all sides
  2. Vertical and horizontal
  3. Top, horizontal and bottom
  4. Top, right, bottom and left
In the last example you can see how it works.
And in the penultimate example you can see the use of a negative offset. This can be useful for a circle and an ellipse, because there the boundaries of the figure that captures all the necessary nodes are not always optimally determined.
r:числоnumber
Радиус закругления углов. Для прямоугольной фигуры. Единицы измерения такие же как у padding. Если не указан, то закругление не используется.
Corner rounding radius. For a rectangular shape. Units are the same as padding. If not specified, rounding is not used.

Примеры Examples

$background(cyan)H2N\/`|$bg(orange,round)O|\</$bg(#FFA,ellipse,stroke:#888)COOH>|`/`\`|
$background(cyan)H2N\/`|$bg(orange,round)O|\</$bg(#FFA,ellipse,stroke:#888)COOH>|`/`\`|
H2N-C<`|H><-$bg(yellow,to:1;3,padding:.2)COOH>|S|C<|$bg(to:3,rgba(0,255,255,0.4),p:.4;.2;.1)H><-NH2>`-HOOC
H2N-C<`|H><-$bg(yellow,to:1;3,padding:.2)COOH>|S|C<|$bg(to:3,rgba(0,255,255,0.4),p:.4;.2;.1)H><-NH2>`-HOOC
`-<_(a54)HO>_q<_(a54)H3C>_q<||O>_q<_(a54)NH2>_q_(a54)$itemColor1(#C00){R}$background(#FFA,*,ellipse,p:-.5)
`-<_(a54)HO>_q<_(a54)H3C>_q<||O>_q<_(a54)NH2>_q_(a54)$itemColor1(#C00){R}$background(#CFC,*,ellipse,p:-.5)
|$bg(#FCF,*,p:1) = |$bg(#FCF,*,p:0.2;1) = |$bg(#FCF,*,p:0.2;1;1.5) = |$bg(#FCF,*,p:0.1;1;1.5;2)
|$bg(#FCF,*,p:1) = |$bg(#FCF,*,p:0.2;1) = |$bg(#FCF,*,p:0.2;1;1.5) = |$bg(#FCF,*,p:0.1;1;1.5;2)

Центр формулы Center of the formula

СинтаксисSyntax: $C()

Область действия: следующий за функцией узел.

Scope: The next node following the function.

Минимальная версия CharChem: 1.0

Minimum version of CharChem: 1.0

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

Sometimes you need to use structural formulas in your equations. In this case, it is desirable that the reagents are properly aligned in height. Quite often, the built-in algorithm can do this automatically. For example, everything looks good here.

2H\N<`/H>_(A0)H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4
2H\N<`/H>_(A0)H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4

Но так происходит не всегда. Например, если немного повернуть первый реагент, то внешний вид станет хуже.

But this is not always the case. For example, if you turn the first reagent a little, the appearance will become worse.

2H/N<`|H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4
2H/N<`|H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4

Так происходит от того, что при автоматическом поиске центральной оси учитывается количество узлов на одинаковой высоте. Здесь два нижних атома водорода оказались на одной линии. Поэтому выравнивание произошло по нижнему краю формулы. Это выглядит некрасиво. Поэтому при помощи конструкции $C() можно явно указать узел, по которому будет выполняться центрирование.

This is because the automatic search for the central axis takes into account the number of nodes at the same height. Here, the two lower hydrogen atoms were on the same line. Therefore, the alignment occurred along the lower edge of the formula. This does not look nice. Therefore, using the $C() construction, you can explicitly specify the node by which the centering will be performed.

2H/$C()$itemColor1(var(--select-color))N<`|H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4
2H/$C()N<`|H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4

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

Here the $C() construction before the nitrogen atom helped to improve the appearance considerably. But it is possible to use several such constructions in one formula. In this case, the average value is calculated for them. For example, the lower and upper nodes of the formula can be designated as centers.

2$C()$itemColor1(var(--select-color))H/N<`|$C()$itemColor1(var(--select-color))H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4
2$C()H/N<`|$C()H>\H + $slope(45)H-O\S/O`/\O`\`/O`-H -> (NH4)2SO4

На следующей иллюстрации более подробно демонстрируется, как из двух центров вычисляется финальный результат.

The following illustration shows in more detail how the final result is calculated from two centers.

2$itemColor1(var(--select-color))$C()H/N<`|$itemColor1(var(--select-color))$C()H>\H; $color(brown)#1_(x-.7,N0):a_(x%h:3,H)_(y#3,N0)_(x-%h,H)_(x.3,N0)_(y#1,C+)_(y#1;3,N0)$bg(round,brown,p:.13)_(x#a,N0)_(x%h,H)$color() +

Цвет конструкций формулы Color of formula parts

СинтаксисSyntax: $color(colorDef)

colorDef - описание цветаcolor description.

Область действия: до конца формулы. Для прекращения действия можно использовать $color()

Scope: Until the end of the formula. To stop the action, you can use $color()

CH3-CH2$color(blue)-COOH
CH3-CH2$color(blue)-COOH
$color(blue)H3N-$color()CH<|CH3>$color(red)-COOH
$color(blue)H3N-$color()CH<|CH3>$color(red)-COOH

Цвет по-умолчанию Default color

Использование $color() (с пустыми параметрами) восстанавливает цвет по-умолчанию. Этот цвет устанавливается "снаружи".

Using $color() (with empty parameters) restores the default color. This color is set "outside".

Следующий пример показывает, как одно описание правильно отрисовывается в светлой и тёмной теме.

The following example shows how a single description renders correctly in both light and dark themes.

NH2`|ww$color(red)<`\`/HS>$color()/`|O|\OH
NH2`|ww$color(red)<`\`/HS>$color()/`|O|\OH
NH2`|ww$color(red)<`\`/HS>$color()/`|O|\OH

Смотри также: Цветовые функции

See also: Color functions

Выравнивание двойных связей Alignment of double bonds

СинтаксисSyntax: $dblAlign(mode)

mode - Режим выравнивания, который задаётся буквами The alignment mode, which is specified by the letters r, R, m, M, l илиor L.

Область действия: до конца формулы. Для прекращения действия можно использовать $dblAlign()

Scope: Until the end of the formula. To stop the action, you can use $dblAlign()

По-умолчанию, двойные связи выравниваются автоматически. Вот примеры того, как это происходит:

By default, double bonds are automatically aligned. Here are examples of how this happens:

\=/
\=/
Выравнивание влево Align left
/=\
/=\
Выравнивание вправо Align right
\=\
\=\
Выравнивание по центру Center alignment

Лево и право определяются относительно направления связи.

Left and right are defined relative to the direction of the bond.

ПараметрParameter РежимMode Пример описанияExample description РезультатResult
r илиor R Выравнивание вправоAlign right $dblAlign(r)/=\ \=\ \=/
$dblAlign(r)/=\ \=\ \=/
l илиor L Выравнивание влевоAlign left $dblAlign(L)/=\ \=\ \=/
$dblAlign(L)/=\ \=\ \=/
m илиor M Выравнивание по центруCenter alignment $dblAlign(m)/=\ \=\ \=/
$dblAlign(m)/=\ \=\ \=/

Функция dblAlign действует на любые виды связей — краткие, полигональные и универсальные. Но режим выравнивания, указанный через суффикс или параметр, имеет больший приоритет чем функция.

The dblAlign function works on any type of bonds — short, polygonal and universal. But the alignment mode specified via a suffix or parameter has a higher priority than the function.

Структуры Льюиса (точки) Lewis structures (dots)

СинтаксисSyntax: $dots(params)

Область действия: следующий элемент узла.

Scope: next node item.

Возможные параметры Possible parameters

Используются первые буквы от следующих слов: The first letters of the following words are used: Left, Right, Top, Up, Bottom, Down.
ГдеWhere Top = Up, Bottom = Down.

Важно соблюдать регистр.

It is important to respect the case of the characters.

ПараметрParameter ОписаниеDescription Пример описанияExample description РезультатResult
L Две точки слеваTwo dots on the left $dots(L)H
$dots(L)H
R Две точки справаTwo dots on the right $dots(R)H
$dots(R)H
U или T Две точки сверхуTwo dots on the top $dots(U)N-$dots(T)N
$dots(U)N-$dots(T)N
B илиor D Две точки снизуTwo dots on the bottom $dots(B)N-$dots(D)N
$dots(B)N-$dots(D)N
Lt илиor Lu Точка слева сверхуDot on the left top $dots(Lt)H $dots(Lu)H
$dots(Lt)H $dots(Lu)H
Lb илиor Ld Точка слева снизуDot on the left bottom $dots(Lb)H $dots(Ld)H
$dots(Lb)H $dots(Ld)H
Rt илиor Ru Точка справа сверхуDot on the right top $dots(Rt)H $dots(Ru)H
$dots(Rt)H $dots(Ru)H
Rb илиor Rd Точка справа снизуDot on the right bottom $dots(Rb)H $dots(Rd)H
$dots(Rb)H $dots(Rd)H
Tl илиor Ul Точка сверху слеваDot on the top left $dots(Tl)H $dots(Ul)H
$dots(Tl)H $dots(Tl)H
Tr илиor Ur Точка сверху справаDot on the top right $dots(Tr)H $dots(Ur)H
$dots(Tr)H $dots(Ur)H
Bl илиor Dl Точка снизу слеваDot on the bottom left $dots(Bl)H $dots(Dl)H
$dots(Bl)H $dots(Dl)H
Br илиor Dr Точка снизу справаDot on the bottom right $dots(Br)H $dots(Dr)H
$dots(Br)H $dots(Dr)H
! Меняет значения буквенных параметров на обратные.
Если параметров нет, то 8 точек.
Changes the values ​​of letter parameters to the opposite.
If there are no parameters, then 8 dots.
$dots(!L)O $dots(!)He
$dots(!L)O $dots(!)He
color: илиor c: Цвет следующих точек Color of the following points $dots(color:red,U,c:blue,D)O
$dots(color:red,U,c:blue,D)O
margin: илиor m: Числовое значение отступа.
Действует на следующие за ним параметры. 1 соответствует стандартной длине связи.
Numeric value of the indent.
Affects the parameters that follow it. 1 corresponds to the standard bond length.
$dots(m:0.1,!)Ar
$dots(m:0.1,!)Ar
числоnumber Угол в градусах относительно оси X по часовой стрелке. Angle in degrees relative to the X-axis clockwise. $dots(0,90,-90,180)C
$dots(0,90,-90,180)C

Буквенные обозначения можно совмещать даже без запятых

Letter designations can be combined even without commas.

$dots(UD)O
$dots(UD)O
$dots(LbDl)O
$dots(LbDl)O

Цвет элементов узла Color of node items

Относится к цветовым функциям.

It refers to color functions.

СинтаксисSyntax: $itemColor(colorDef)

colorDef - описание цветаcolor description.

Область действия: до конца формулы, либо до следующего $itemColor.

Scope: until the end of the formula, or until the next $itemColor.

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

Affects only node items: atoms, radicals, abstract elements and comments. Including their coefficients, oxidation states, points, atomic mass, atomic number.

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

Does not affect the charge of the node, brackets, chemical bonds, operations.

Имеет больший приоритет, чем функция $color().

Has higher priority than the $color() function.

$color(red)$itemColor(blue)3$nM(2)H2 + O(+2) O^2- $dots(!)O {R}-"test" (Ca,Mg)3[PO4]2
$color(red)$itemColor(blue)3$nM(2)H2 + O(+2) O^2- $dots(!)O {R}-"test" (Ca,Mg)3[PO4]2

Цвет следующего элемента узла The color of the next node item

Относится к цветовым функциям.

It refers to color functions.

Аналог функции itemColor, но действует только на следующий элемент узла.

Analogous to the itemColor function, but only affects the next node item.

СинтаксисSyntax: $itemColor1(color)

color - описание цветаcolor description.

Область действия: следующий за функцией элемент узла.

Scope: The node item following the function.

Имеет больший приоритет, чем $itemColor().

Has higher priority than $itemColor().

CH3-$itemColor(blue)C$itemColor1(red)O2H
CH3-$itemColor(blue)C$itemColor1(red)O2H
$itemColor1(brown)Fe(+3)2(S$itemColor1(red)O4)3
$itemColor1(brown)Fe(+3)2(S$itemColor1(red)O4)3

Длина связей Length of chemical bonds

СинтаксисSyntax: $L(длинаlength)

длина - числовое значение длины связи. Либо пустой параметр, чтобы восстановить дефолтное значение.

length - numeric value of the bond length. Or an empty parameter to restore the default value.

По-умолчанию длина связи равна 1.

By default, the bond length is 1.

Область действия: до конца формулы, либо до следующего $L.

Scope: until the end of the formula, or until the next $L.

Действует на краткие связи и на универсальные связи с параметрами A или a, но без L.

Affects short bonds and universal bonds with parameters A or a, but without L.

Не действует на полигональные связи, т.к. их длина копируется из предыдущей связи.

Does not affect polygonal bonds, since their length is copied from the previous bond.

Примеры

Examples

\$L(2)/_(A30)$L()/
\$L(2)/_(A30)$L()/
$L(2)|$L(4)-$L(2)`|$L()`-|$L(2)`-$L()`|`-
$L(2)|$L(4)-$L(2)`|$L()`-|$L(2)`-$L()`|`-

Атомная масса изотопа Atomic mass of isotope

Синтаксис: $M(масса)

Syntax: $M(mass)

масса - Целое число, соответствующее атомной массе изотопа

mass - An integer corresponding to the atomic mass of an isotope

Область действия: следующий атом.

Scope: next atom.

$M(235)U
$M(235)U
O=$M(99)Tc<`||O><||O>-O^-
O=$M(99)Tc<`||O><||O>-O^-

Атомный номер и масса изотопа Atomic number and mass of the isotope

Масса выводится слева сверху, а номер - слева снизу. Такое представление известно как AZE-нотация

The mass is displayed at the top left and the number at the bottom left. This representation is known as AZE notation.

Минимальная версия CharChem: 1.0

Minimum version of CharChem: 1.0

Синтаксис: $nM(масса[,номер])

Syntax: $nM(mass[,number])

масса - Целое число, соответствующее атомной массе изотопа

mass - An integer corresponding to the atomic mass of an isotope

номер - для атомов этот параметр использовать не рекомендуется, т.к. он определяется автоматически. Но если используются абстрактные элементы, то для них номер нужен.

number - it is not recommended to use this parameter for atoms, since it is determined automatically. But if abstract items are used, then a number is needed for them.

Область действия: следующий элемент узла.

Scope: next node item.

$nM(26)Al + $nM(1,0){n} -> $nM(27)Al"*"
$nM(26)Al + $nM(1,0){n} -> $nM(27)Al"*"

Отступы внутри скобок Indentation inside brackets

Синтаксис: $padding(параметры)

Syntax: $padding(parameters)

Область действия: следующая открывающаяся скобка.

Scope: next opening parenthesis.

Функция влияет только на внешний вид формулы в графическом представлении. Не влияет на функциональность описания и на текстовое представление.

The function only affects the appearance of the formula in the graphical representation. Does not affect the functionality of the description and the text representation.

Наличие данной функции делает формулу не текстовой.

The presence of this function makes the formula non-textual.

Принцип работы заимствован из The principle of operation is borrowed from CSS padding.

параметры - от одного до четырёх числовых значений, означающих расстояние в системе координат. То есть, 1 соответствует стандартной длине связи.
Параметры перечисляются через запятую, без пробелов.

parameters - from one to four numeric values, meaning the distance in the coordinate system. That is, 1 corresponds to the standard length of a chemical bond.
Parameters are listed separated by commas, without spaces.

КоличествоQuantity ОписаниеDescription ПримерExample РезультатResult
Одно числоOne number Отступ со всех сторонIndentation on all sides $padding(1)[C] $padding(0.1)[N]
$padding(1)[C] $padding(0.1)[N]
Два числаTwo numbers
  1. Вертикальный отступ (сверху и снизу). Vertical indentation (top and bottom).
  2. Горизонтальный отступ (слева и справа). Horizontal indentation (left and right).
$padding(0.1,1)[C] $padding(1,0.1)[N]
$padding(0.1,1)[C] $padding(1,0.1)[N]
Три числаThree numbers
  1. Отступ сверху.Indentation from top.
  2. Горизонтальный отступ (слева и справа). Horizontal indentation (left and right).
  3. Отступ снизу. Indentation from bottom.
$padding(0.1,0.5,1)[C]
$padding(0.1,0.5,1)[C]
Четыре числаFour numbers
  1. Отступ сверху.Indentation from top.
  2. Отступ справа.Indentation from right.
  3. Отступ снизу.Indentation from bottom.
  4. Отступ слева.Indentation from left
$padding(0.1,0.5,1,1.5)[C]
$padding(0.1,0.5,1,1.5)[C]

Положение заряда узла Node charge position

СинтаксисSyntax: $pos(положениеposition)

Область действия: следующий заряд узла.

Scope: Next node charge.

положение — указывается одним из следующих способов:

position is indicated in one of the following ways:

ПараметрParameter ОписаниеDescription ПримерExample РезультатResult
LT Слева сверхуLeft top `|$pos(LT)H^+
`|$pos(LT)H^+
RT Справа сверхуRight top `|$pos(RT)H^+
`|$pos(RT)H^+
LB Слева снизуLeft bottom |$pos(LB)H^+
|$pos(LB)H^+
RB Справа снизу |$pos(RB)H^+
|$pos(RB)H^+
CU Сверху в центреTop center `|$pos(CU)H^+
`|$pos(CU)H^+
CD Снизу в центреBottom center |$pos(CD)H^+
|$pos(CD)H^+
числоnumber Числовое значение угла Numerical value of the angle _(x1)$pos(0)H^+
_(x1)$pos(0)H^+

Угол наклона для кратких химических связей Slope angle for short chemical bonds

Синтаксис: $slope(угол)

Syntax: $slope(angle)

Область действия: до конца формулы или до следующего $slope.

Scope: until the end of the formula or until the next $slope.

Значение угла указывается в диапазоне от 0 до 90.

The angle value is specified in the range from 0 to 90.

Указанный угол соответствует наклонным связям, которые определяются символом \

The angle indicated corresponds to inclined bonds, which are defined by the symbol \

Для остальных наклонных связей углы вычисляются автоматически.

For other inclined bonds, the angles are calculated automatically.

Чаще всего используются значения: 30, 45 и 60

The most commonly used values ​​are: 30, 45 and 60

$slope(30)\/`\`/
$slope(30)\/`\`/
$slope(45)\/`\`/
$slope(45)\/`\`/
$slope(60)\/`\`/
$slope(60)\/`\`/

По-умолчанию для вертикальных шестиугольников используется угол наклона 30°, а для горизонтальных — 60°. Если использовать $slope с каким-либо числовым параметром, то автоматическое определение шестиугольников отключается.

By default, vertical hexagons use a slope angle of 30°, and horizontal hexagons use a slope angle of 60°. Using $slope with any numeric parameter disables automatic hexagon detection.

А чтобы восстановить поведение по-умолчанию, нужно использовать функцию без параметров: $slope().

And to restore the default behavior, you need to use a function without parameters: $slope().

/\$slope(15)/\$slope(40)/\$slope(70)/\$slope()/\
/\$slope(15)/\$slope(40)/\$slope(70)/\$slope()/\

Следующий пример демонстрирует разницу между определением наклона по-умолчанию и с использованием $slope:

The following example demonstrates the difference between specifying the default slope and using $slope:

\|`/ = /-\
\|`/ = /-\
$slope(30)\|`/ = /-\
$slope(30)\|`/ = /-\
$slope(60)\|`/ = /-\
$slope(60)\|`/ = /-\

Версия CharChem CharChem version

Данная функция нужна для контроля совместимости формул с испольуемой программной библиотекой.

This function is needed to control the compatibility of formulas with the software library used.

У этой функции нет области действия. Но рекомендуется помещать её в самое начало формулы.

This function has no scope. However, it is recommended to place it at the very beginning of the formula.

Синтаксис: $ver(версия)

Syntax: $ver(version)

версия = major.minor или major,minor или только major

version = major.minor or major,minor or only major

В данном документе используется библиотека CharChem версии This document uses CharChem library version _. Это значит что This means that major = , а and minor = . Третье число называется patch и оно не проверяется. The third number is called patch and it is not checked.

Некоторые возможности формул CharChem появились не сразу, а начиная с каких-то версий. В функции $ver нужно указывать самое большое значение. И если эту формулу попытаться вывести в системе, где используется более ранняя версия библиотеки, то формула показываться не будет. Но это лучше, чем если они бы возникли ошибки при обработке тех синтаксических конструкций, которые не поддерживаются библиотекой.

Some features of CharChem formulas appeared not immediately, but starting with some versions. In the function $ver you need to specify the largest value. And if you try to display this formula in a system that uses an earlier version of the library, the formula will not be shown. But this is better than if errors occurred when processing those syntactic structures that are not supported by the library.

$ver(1.0)H2O
$ver(1.0)H2O
$ver(1,0)H2O
$ver(1,0)H2O
$ver(1)H2O
$ver(1)H2O
$ver(1000)H2O
$ver(1000)H2O

Если Вы уверены, что Ваши формулы будут использованы только в таких обстоятелствах, когда для их обработки будет использована соответствующая версия библиотеки, тогда использование функции $ver не требуется.

If you are confident that your formulas will only be used in circumstances where the appropriate version of the library will be used to process them, then using the $ver function is not required.

Химические операции Chemical operations

Также см. описание химических операций.

See also the description of chemical operations.

КодCode ТекстText SVG

Суффиксы химических связей Chemical bond suffixes

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

Suffixes can be used to modify short and polygonal bonds. The suffix is placed immediately after the description of the bond.

Также см. описание суффиксов.

See also description of suffixes.

СуффиксSuffix ОписаниеDescription Пример для краткихExample for short Пример для полигональныхExample for polygonal
0
нольzero
Прозрачная связь. Но только для кратких связей. Transparent bond. But only for short bonds. \-0/
\-0/
нетnone
o
(маленькая буква оsmall letter o)
Тоже прозрачная связь, но для обоих типов. Also transparent bond, but for both types. \-o/
\-0/
-_po_p
-_po_p
h Водородная связьHydrogen bond -\h
-\h
-_ph
-_ph
w Исходящая клиновидная (из плоскости к наблюдателю) Outgoing wedge-shaped bond (from the plane to the observer) -\w
-\w
-_pw
-_pw
ww Входящая клиновидная (от наблюдателя в плоскость) Incoming wedge-shaped bond (from the observer to the plane) -\ww
-\ww
-_pww
-_pww
d Исходящая пунктирная клиновидная (из плоскости от наблюдателя) Outgoing dashed wedge-shaped bond (from the plane away from the observer) -\d
-\d
-_pd
-_pd
dd Входящая пунктирная клиновидная (в плоскось с дальней стороны от наблюдателя) Incoming dashed wedge-shaped bond (into the plane on the far side from the observer) -\dd
-\dd
-_pdd
-_pdd
x Перекрещенная связь (только для двойных) Crossed bond (for doubles only) -\\x
-\\x
-_ppx
-_ppx
~
(тильдаtilde)
Волнистая связь (для рацемической смеси оптических изомеров) Wavy bond (for a racemic mixture of optical isomers) -\~
-\~
-_p~
-_p~
r Выравнивание вправо (только для двойных) Right alignment (double only) /=r\
/=r\
-_ppr_p
-_ppr_p
l
(маленькаяsmall L)
Выравнивание влево (только для двойных) Left alignment (double only) /=l\
/=l\
-_ppl_p
-_ppl_p
m Выравнивание по центру (только для двойных) Middle alignment (double only) /=m\
/=m\
-_ppm_p
-_ppm_p
v Стрелка в направлении связи Arrow in the direction of bond -\v
-\v
-_pv
-_pv
vv Стрелка против направления связи Arrow against the direction of the bond -\vv
-\vv
-_pvv
-_pvv
vvv Стрелка в оба направления Arrow in both directions -\vvv
-\vvv
-_pvvv
-_pvvv

Параметры универсальных связей Parameters of universal bonds

См. также описание универсальных связей.

See also: description of universal bonds.

Несовместимыми являются параметры: p, P, a, A. (В порядке убывания приоритета.) Но они сочетаются с x и y.

The following parameters are incompatible: p, P, a, A. (In descending order of priority.) But they are compatible with x and y.

ПараметрParameter ОписаниеDescription ПримерыExamples
A
Абсолютное значение угла (т.е. относительно оси X). Числовое значение в градусах. Примеры:
The absolute value of the angle (i.e. relative to the X-axis). Numerical value in degrees. Examples:
{}@:d(a,b:0,d:.4)<_(A&a,L1.5,>){}_(a&b,N0,L&d)"&a">@(0)@d(45,10)@d(90,-10)@d(135,0,0.5)@d(180,0,0.7)@d(-45,-10)@d(-90)
Если длина связи не указана параметром L, то используется глобальное значение, устанавливаемое функцией $L().
If the bond length is not specified by the L parameter, then the global value set by the $L() function is used.
_(A0)_(A45)_(A-90)
_(A0)_(A45)_(A-90)
a

Относительное значение угла. Числовое значение в градусах.
Предполагается, что перед этой связью есть предыдущая, относительно которой указывается угол. Иначе угол относительно оси X.

Relative value of the angle. Numerical value in degrees.
It is assumed that there is a previous chemical bond before this one, relative to which the angle is specified. Otherwise, the angle is relative to the X axis.

Если длина связи не указана параметром L, то используется глобальное значение, устанавливаемое функцией $L()

If the bond length is not specified by the L parameter, then the global value set by the $L() function is used.

\v_(a30)_(a-120)_(a-120)
\v_(a30)_(a-120)_(a-120)
C Координационная связь. Ну или просто связь со стрелкой.
Есть три варианта:
Coordination bond. Or simply a bond with an arrow.
There are three options:
C, C-, C+.
_(A30,C) _(A30,C-) _(A30,C+)
_(A30,C) _(A30,C-) _(A30,C+)
D Клиновидные пунктирные связи. Глобальный режим.
Есть два варианта: D+ (включает режим) и D- (выключает).
Wedge-shaped dashed bonds. Global mode.
There are two options: D+ (turns the mode on) and D- (turns it off).
_(A60,D+)_(A0)_(A-60,D-)_(A-120)
_(A60,D+)_(A0)_(A-60,D-)_(A-120)
d
Клиновидные пунктирные связи. Локально (т.е. только для текущей связи).
Варианты: d+ (прямая), d- (обратная) и d2 (равномерная).
Wedge-shaped dashed bonds. Locally (i.e. only for the current bond).
Options: d+ (direct), d- (reverse) and d2 (uniform).
_(A60,d+)_(A0)_(A-60,d-)_(A-120)
_(A60,d+)_(A0)_(A-60,d-)_(A-120)
H Водородная связь. Действует только для связей с кратностью 1. Hydrogen bond. Only valid for bonds with multiplicity 1. H`^+_(x2,H)OH^-
H`^+_(x2,H)OH^-
h
Мягкая связь. Не обязательно строго горизонтальная (в отличие от кратких связей).
Существуют специальные случаи h+ и h-. В этом случае узлы выводятся вплотную друг к другу, как будто никакой связи между ними нет. Слева направо для h+ и справа налево для h-.
Если у связи указан параметр h, но отсутствует смещение по оси x, то это равнозначно варианту h+.
Soft bond. Not necessarily strictly horizontal (unlike short bonds).
There are special cases h+ and h-. In this case, the nodes are displayed close to each other, as if there is no connection between them. Left to right for h+ and right to left for h-.
If the bond has an h parameter, but no offset along the x axis, then this is equivalent to the h+ variant.
CH3_(h,A0)OCOH
CH3_(h,A-15)OCOH
CH3_(h+)CH<|F>O_(h)CH<|F>CH3
CH3_(h,A0)OCOH
CH3_(h,A-15)OCOH
CH3_(h+)CH<|F>O_(h)CH<|F>CH3
L
Длина связи. Числовое значение
Используется совместно с параметрами A или a. Имеет больший приоритет, чем функция $L().
Стандартная единичная длина подобрана так, чтобы хорошо выглядели связи между атомами из одной буквы (C, H, S, F...). Если используются атомы из двух букв, то рекомендуется использовать длину от 1.2 до 1.4.
Bond length. Numeric value
Used with A or a parameters. Higher priority than the $L() function.
The default unit length is chosen so that bonds between single-letter atoms (C, H, S, F...) look good. If two-letter atoms are used, it is recommended to use a length of 1.2 to 1.4.
Ca_(A30,L1.2)O
Ca_(A30,L1.2)O
N
Кратность связи. Целое число от 0 до 3.
Для двойных связей возможны варианты: 2x, 2r, 2m и 2l. Они соответствуют суффиксам. Допускается использование верхнего регистра (2L), т.к. буква l слишком похожа на 1.
The multiplicity of the bond. An integer from 0 to 3.
For double bonds, the following options are possible: 2x, 2r, 2m, and 2l. They correspond to suffixes. Using uppercase (2L) is allowed, since the letter l is too similar to 1.
I_(A9,N0)I I_(A9,N1)I O_(A9,N2)O N_(A9,N3)N
\_(y1,N2x) \_(y1,N2L) \_(y1,N2m) \_(y1,N2r)
I_(A9,N0)I I_(A9,N1)I O_(A9,N2)O N_(A9,N3)N

\_(y1,N2x) \_(y1,N2L) \_(y1,N2m) \_(y1,N2r)
P
Полигональная связь. Положительное или отрицательное число от 3, соответствующее числу углов полигона. Положительное число — по часовой стрелке, отрицательное — против часовой. Если не указано, то 5.
В большинстве случаев предпочтительнее использовать _p и _q. Но может быть полезно, если нужно использовать глобальные режимы (W, D) или стили S.
Polygonal bond. A positive or negative number from 3, corresponding to the number of corners of the polygon. A positive number is clockwise, a negative number is counterclockwise. If not specified, then 5.
In most cases, it is preferable to use _p and _q. But it can be useful if you need to use global modes (W, D) or S styles.
-_(P3) -_(P-3) -_(P) -_(P-5)
-_(P3) -_(P-3) -_(P) -_(P-5)
p
Указание координат по ссылке. Одна или несколько ссылок, разделённых символом ; (точка с запятой) без пробелов и без знака #.
Можно комбинировать с параметрами x и y.
Например, конструкция _(p1) то же самое что _#1. Но вот для _(p1,x1) или _(p1;2) аналогов нет.
Specifying coordinates by link. One or more links separated by the ; symbol (semicolon) without spaces and without the # sign.
Can be combined with the x and y parameters.
For example, the _(p1) construction is the same as _#1. But there are no analogues for _(p1,x1) or _(p1;2).
_(x2)_q3_q3_(p1;2;3)
_(x2.5)_(y1.5)_(p1,y0.8)_#1
_(x2)_q3_q3_(p1;2;3)
_(x2.5)_(y1.5)_(p1,y0.8)_#1
S
Стиль. Определяется символами: ~ : | I
~ – волнистая, : – штриховая, | – тонкая, I – толстая.
Для двойных и тройных связей эти символы можно комбинировать (кроме тильды). Перечислять нужно в том порядке, как будто для вертикальной линии (сверху вниз).
Стиль влияет только на внешний вид формулы и не учитывается при вычислении химических свойств. Параметр S не исключает использование N. При этом N влияет на вычисления, но не на внешний вид.
Если нужно явно указать выравнивание двойных связей, то для этого есть три суффикса: r, m и l (можно и верхнем регистре).
Style. Defined by symbols: ~ : | I
~ – wavy, : – dashed, | – thin, I – thick.
For double and triple bonds, these symbols can be combined (except for the tilde). They must be listed in the same order as for a vertical line (top to bottom).
The style only affects the appearance of the formula and is not taken into account when calculating chemical properties. The S parameter does not exclude the use of N. However, N affects the calculations, but not the appearance.
If you need to explicitly specify the alignment of double bonds, there are three suffixes for this: r, m and l (uppercase is also possible).
C_(y1,S~) C_(y1,S:) C_(y1,S|) C_(y1,SI) C_(y1,S:|) C_(y1,S|:) C_(y1,S:|:)

_(A90,S|:)_(A30,S|:)_(A-30,S|:)_(A-90,S|:)

\_(y1,S:|r) \_(y1,S:|m) \_(y1,S:|L)
C_(y1,S~) C_(y1,S:) C_(y1,S|) C_(y1,SI) C_(y1,S:|) C_(y1,S|:) C_(y1,S:|:)
_(A90,S|:)_(A30,S|:)_(A-30,S|:)_(A-90,S|:)
\_(y1,S:|r) \_(y1,S:|m) \_(y1,S:|L)
T
Текстовое описание связи. Не используется при выводе графической формулы, но может быть полезно для разработчиков.
Text description of the bond. Not used when deriving the graphical formula, but may be useful for developers.
H_(A-30,T/)O_(A30,T\)H
H_(A-30,T/)O_(A30,T\)H
W
Клиновидные связи. Глобальный режим.
Есть варианты: W+ (включает режим) и W- (выключает).
Так же есть вариант W2, когда текущая связь и следующие выводятся толстыми. Выключается параметром W0 или W1.
Wedge-shaped bonds. Global mode.
There are options: W+ (turns the mode on) and W- (turns it off).
There is also an option W2, when the current bond and the following ones are displayed in thick. It is turned off by the parameter W0 or W1.
_(A60,W+)_(A0)_(A-60,W-)_(A-120)
_(A60,W+)_(A0)_(A-60,W-)_(A-120)
w
Клиновидные связи. Локально (т.е. только для текущей связи).
Возможны варианты: w+ (прямая), w- (обратная), w2 (равномерно толстая).
Wedge-shaped bonds. Locally (i.e. only for the current bond).
Possible options: w+ (direct), w- (reverse), w2 (uniformly thick).
_(A60,w+)_(A0)_(A-60,w-)_(A-120)
_(A60,w+)_(A0)_(A-60,w-)_(A-120)
x
Смещение по оси X. Числовое значение или ссылка на x-координаты других узлов.
X-axis offset. Numeric value or reference to x-coordinates of other nodes.
_(x2)|_(x-0.75)
\|_(x#1)
_(x2)|_(x-0.75)
\|_(x#1)
y
Смещение по оси Y. Числовое значение или ссылка на y-координаты других узлов.
Y-axis offset. Numeric value or reference to y-coordinates of other nodes.
_(y2)_(x1,y-.3)_(y#1;2)
_(y2)_(x1,y-.3)_(y#1;2)
>
Прямая стрелка. То же самое, что C.
Forward arrow. Same as C.
_(A30,>)
_(A30,>)
<
Обратная стрелка. То же самое, что C-.
Backward arrow. Same as C-.
_(A30,<)
_(A30,<)
~
Волнистая линия. Обычно используется для рацемической смеси оптических изомеров.
Wavy line. Usually used for a racemic mixture of optical isomers.
_(x2,y1,~)OH
_(x2,y1,~)OH

Греческие буквы Greek letters

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

Greek letters can be used in comments and abstract items. To do this, enter the name of the letter in square brackets.

В CharChem версии 2.2+ можно использовать греческие буквы как в TeX-системах — через обратный слэш и название буквы. Н.р.: \Alpha

In CharChem version 2.2+, you can use Greek letters as in TeX systems — via a backslash and the letter name. For example, \Alpha

[Alpha] [alpha]Α α
[Beta] [beta]Β β
[Gamma] [gamma]Γ γ
[Delta] [delta]Δ δ
[Epsilon] [epsilon]Ε ε
[Zeta] [zeta]Ζ ζ
[Eta] [eta]Η η
[Theta] [theta]Θ θ
[Iota] [iota]Ι ι
[Kappa] [kappa]Κ κ
[Lambda] [lambda]Λ λ
[Mu] [mu]Μ μ
[Nu] [nu]Ν ν
[Xi] [xi]Ξ ξ
[Omicron] [omicron]Ο ο
[Pi] [pi]Π π
[Rho] [rho]Ρ ρ
[Sigma] [sigma]Σ σ
[Tau] [tau]Τ τ
[Upsilon] [upsilon]Υ υ
[Phi] [phi]Φ φ
[Chi] [chi]Χ χ
[Psi] [psi]Ψ ψ
[Omega] [omega]Ω ω

Примеры

Examples

$nM(27)Al + {[gamma]} -> $nM(27)Al"*"
$nM(27)Al + $itemColor1(var(--select-color)){[gamma]} -> $nM(27)Al"*"
C + O2 -> CO2"; \Delta_RH=-393,51 kJ/mol"
C + O2 -> CO2"; {\color{var(--select-color)}\Delta}_RH=-393,51 kJ/mol"

Символ обратного апострофа Backtick symbol

Обратный апостроф ` располагается на клавиатуре в верхнем левом углу под Esc.

` Backtick. It is also known as backquote, grave, or grave accent. It is located on the keyboard in the upper left corner under the Esc key.

В CharChem он используется для разных целей. Обычно он служит для изменения поведения следующей за ним конструкции.

In CharChem it is used for different purposes. Usually it serves to change the behavior of the construct following it.

Ниже представлены все случаи использования:

Below are all the use cases:

МестоLocation НазначениеPurpose ПримерыExamples
Перед краткой связью Before a short bond Изменение направления на противоположное Reversal of direction
-v `-v |v `|v \v `\v
-v `-v |v `|v \v `\v
Перед зарядом узла Before a node charge Заряд выводится не справа, а слева The charge is discharged not from the right, but from the left
Mg^2+ Mg`^+2
Mg^2+ Mg`^+2
Перед элементом узла Before a node item Для указания центрального элемента узла To indicate the central node item
|SCH3 |`SCH3
|SCH3 |`SCH3
Внутри комментария Inside the comment Если нужно вставить фразу из словаря, которая должна переводиться на разные языки, то она заключается в обратные апострофы. If you need to insert a phrase from a dictionary that needs to be translated into different languages, it is enclosed in backticks.
H-Br|h"`Br`"
H-Br|h"`Br`"
2Na"`(s)`" + Cl2"`(g)`"
2Na"`(s)`" + Cl2"`(g)`"

НормалиNormals

Обычно нормали используются для боковых ответвлений от правильных полигонов при помощи относительных углов.

Normals are typically used to branch off from regular polygons using relative angles.

Общая формула относительного угла нормали: 90 - 180/n, где n — это количество углов полигона.

The general formula for the relative normal angle is 90 - 180/n, where n is the number of angles of the polygon.

Калькулятор. Число углов полигона (от 3): Calculator. Number of polygon angles (from 3): Относительный угол: Relative angle:

Чаще нужны исходящие нормали, которые исходят из углов полигона. А если нужно к концу связи присоединить полигон, то это входящая нормаль. Но угол у них одинаковый.

More often, outgoing normals are needed, which come from the corners of the polygon. And if you need to attach a polygon to the end of a bond, then this is an incoming normal. But their angle is the same.

Число
углов
Number
of angles
Относительный
угол
Relative
angle
Исходящая нормаль Входящая нормаль
Код примераExample code РезультатResult Код примераExample code РезультатResult
3 30° -<_(a30,C)>_q3<_(a30,C)>_q3_(a30,C)
-<_(a30,C)>_q3<_(a30,C)>_q3_(a30,C)
-v_(a30)_q3_q3
-v_(a30)_q3_q3
4 45° |<_(a45,C)>-<_(a45,C)>`|
|<_(a45,C)>-<_(a45,C)>`|
-v_(a45)_q4_q4_q4
-v_(a45)_q4_q4_q4
5 54° -<_(a54,C)>_q<_(a54,C)>_q_q_q
-<_(a54,C)>_q<_(a54,C)>_q_q_q
-v_(a54)_q_q_q_q
-v_(a54)_q_q_q_q
6 60° |<_(a60,C)>\<_(a60,C)>/<_(a60,C)>`|
|<_(a60,C)>\<_(a60,C)>/<_(a60,C)>`|
_(A-20,C)_(a60)_q6_q6_q6_q6_q6
_(A-20,C)_(a60)_q6_q6_q6_q6_q6
7 64.3° -<_(a64.3,C)>_q7<_(a64.3,C)>_q7_q7_q7_q7_q7
-<_(a64.3,C)>_q7<_(a64.3,C)>_q7_q7_q7_q7_q7
-v_(a64.3)_q7_q7_q7_q7_q7_q7
-v_(a64.3)_q7_q7_q7_q7_q7_q7
8 67.5° |_q8<_(a67.5,C)>-<_(a67.5,C)>_q8`|
|_q8<_(a67.5,C)>-<_(a67.5,C)>_q8`|
-v_(a67.5)_q8_q8_q8_q8_q8_q8_q8
-v_(a67.5)_q8_q8_q8_q8_q8_q8_q8

Словарь терминов Glossary of Terms

Абстрактная формула Abstract formula

Содержит в себе либо абстрактные элементы (R-OH), либо абстрактные коэффициенты ((C2H4)'n'), либо формулы минералов с непостоянным составом ((Ca,Na2,K2)3Al6Si10O32*12H2O).

Contains either abstract items (R-OH), or abstract coefficients ((C2H4)'n'), or formulas of minerals with variable composition ((Ca,Na2,K2)3Al6Si10O32*12H2O).

Функциональность абстрактной формулы снижается. Например, для неё нельзя вычислить атомную массу.

The functionality of an abstract formula is reduced. For example, it is impossible to calculate the atomic mass for it.

Абстрактный элемент узла Abstract node item

используется для тех случаев, когда нужно обозначить не какой-то определённый элемент, а обобщающую конструкцию. Например, щелочной металл или галоген. Или спирт: {R}-OH

is used for those cases when it is necessary to designate not some specific element, but a general construction. For example, an alkali metal or a halogen. Or alcohol: {R}-OH

Абстрактный коэффициент Abstract coefficient

Бывают вещества, где точно не известно количество атомов. Например, полиэтилен: (C2H4)'n'. Или Fe2O3*'n'H2O

There are substances where the exact number of atoms is not known. For example, polyethylene: (C2H4)'n'. Or Fe2O3*'n'H2O

Автоузел Autonode

Узлы скелетных формул. Хотя они и не видны, но в системе они автоматически преобразуются. То есть, добавляется один атом углерода и нужное количество атомов водорода.

Skeletal formula nodes. Although they are not visible, they are automatically converted in the system. That is, one carbon atom and the required number of hydrogen atoms are added.

Исходная формула с автоузлами Original formula with autonodes
Аналог во внутреннем представлении Analogue in internal representation
/\<|>/`|c|\
H3C/C<_(y-.5)H2>\C<_(y-.5)H><|CH3>/C`|CH2|\CH3
Краткая химическая связь Short chemical bond

Способ описания химических связей при помощи символов / \ | - = %
Основная статья.

A method of describing chemical bonds using symbols / \ | - = %
Main atricle

Мягкие связи Soft bonds

Используются для соединения краёв узлов, а не центров (как у остальных связей).
Например: H2N-CH2-COOH.
Основная статья

are used to connect the edges of nodes, rather than the centers (like other bonds).
For example: H2N-CH2-COOH.
Main article

Операция Operation

Часть формулы CharChem. Служит для соединения реагентов.
Основная статья, Список операций

Part of the CharChem formula. Serves to connect reagents.
Maint article, List of operations

Полигональная связь Polygonal bond

Способ описания химических связей для образования правильных многоугольников (полигонов) при помощи конструкций _p и _q.
Например: -_q3_q3 или -_q_q_q_q
Основная статья.

A method for describing chemical bonds to form regular polygons using the _p and _q constructions.
For example: -_q3_q3 or -_q_q_q_q
Main article

Реагент Reagent

Часть формулы CharChem. Представляет отдельное вещество, ион, радикал (и т.п.)

Part of the CharChem formula. Represents a single substance, ion, radical (etc.)

"2"H2:n1_(x1.1,N0)"+"_(x.7,N0)O2:n2_(x1.1,N0)"="_(x1.2,N0)"2"`H2O:n3_(y2,x#n2,N0)"`Reagent`"$color(#888)@:ar(n)(*_(C,p&n,y.55)$bg(to:&n,s:#DDD,p:.2;.2;0)*)@(n1)@ar(n2)@ar(n3)
Скелетная формула Skeletal formula

Это общепринятая разновидность химических формул. Отличается тем, что углы и пустые концы соответствуют атомам углерода, а количество атомов водорода вычисляется автоматически.
Статья в википедии

This is a common type of chemical formula. It differs in that the angles and empty ends correspond to carbon atoms, and the number of hydrogen atoms is calculated automatically.
Wikipedia article

Универсальная связь Universal bond

Способ описания химической связи при помощи конструкции _(параметры). Является наиболее мощным способом, но и самым сложным.
Основная статья

A method of describing a chemical bond using the _(parameters) construction. It is the most powerful method, but also the most complex.
Main article

Узел Node

Узлы входят в состав реагентов

Nodes are part of reagents

COOH|CH2|NH2$color(#BBB)_(x-2,y#2,C-){}(*_(C)#2*)(*_(C)#1*)_(h-)$color()"`Node`"

Химическая связь

Chemical bond

Химические связи входят в состав реагентов и служат для связи узлов.

Chemical bonds are part of reagents and serve to connect nodes.

Виды химических связей в CharChem: краткие, полигональные, универсальные и распределённые.

Types of chemical bonds in CharChem: short, polygonal, universal and delocalized.

Элемент узла Node item

Не путать с химическим элементом! Составная часть узла. Обычно это атом, который может иметь подстрочный коэффициент. Например, здесь узел состоит из 4 элементов: NH4OH. Но элементами узла так же могут быть радикалы и комментарии.
Основная статья

A component of a node. Usually it is an atom, which can have a subscript coefficient. For example, here the node consists of 4 items: NH4OH. But the items of a node can also be radicals and comments.
Main article