Fix typos.
[alexxy/gromacs.git] / src / gromacs / selection / selhelp.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements functions in selhelp.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 #include "gmxpre.h"
43
44 #include "selhelp.h"
45
46 #include <memory>
47 #include <set>
48 #include <string>
49 #include <utility>
50 #include <vector>
51
52 #include "gromacs/onlinehelp/helptopic.h"
53 #include "gromacs/onlinehelp/helpwritercontext.h"
54 #include "gromacs/utility/exceptions.h"
55 #include "gromacs/utility/gmxassert.h"
56 #include "gromacs/utility/stringutil.h"
57 #include "gromacs/utility/textwriter.h"
58
59 #include "selmethod.h"
60 #include "symrec.h"
61
62 namespace
63 {
64
65 struct CommonHelpText
66 {
67     static const char        name[];
68     static const char        title[];
69     static const char *const text[];
70 };
71
72 const char        CommonHelpText::name[]  = "selections";
73 const char        CommonHelpText::title[] =
74     "Selection syntax and usage";
75 const char *const CommonHelpText::text[] = {
76     "Selections are used to select atoms/molecules/residues for analysis.",
77     "In contrast to traditional index files, selections can be dynamic, i.e.,",
78     "select different atoms for different trajectory frames. The GROMACS",
79     "manual contains a short introductory section to selections in the",
80     "Analysis chapter, including suggestions on how to get familiar with",
81     "selections if you are new to the concept. The subtopics listed below",
82     "provide more details on the technical and syntactic aspects of",
83     "selections.[PAR]",
84
85     "Each analysis tool requires a different number of selections and the",
86     "selections are interpreted differently. The general idea is still the",
87     "same: each selection evaluates to a set of positions, where a position",
88     "can be an atom position or center-of-mass or center-of-geometry of",
89     "a set of atoms. The tool then uses these positions for its analysis to",
90     "allow very flexible processing. Some analysis tools may have limitations",
91     "on the types of selections allowed."
92 };
93
94 struct ArithmeticHelpText
95 {
96     static const char        name[];
97     static const char        title[];
98     static const char *const text[];
99 };
100
101 const char        ArithmeticHelpText::name[]  = "arithmetic";
102 const char        ArithmeticHelpText::title[] =
103     "Arithmetic expressions in selections";
104 const char *const ArithmeticHelpText::text[] = {
105     "Basic arithmetic evaluation is supported for numeric expressions.",
106     "Supported operations are addition, subtraction, negation, multiplication,",
107     "division, and exponentiation (using ^).",
108     "Result of a division by zero or other illegal operations is undefined.",
109 };
110
111 struct CmdLineHelpText
112 {
113     static const char        name[];
114     static const char        title[];
115     static const char *const text[];
116 };
117
118 const char        CmdLineHelpText::name[]  = "cmdline";
119 const char        CmdLineHelpText::title[] =
120     "Specifying selections from command line";
121 const char *const CmdLineHelpText::text[] = {
122     "If no selections are provided on the command line, you are prompted to",
123     "type the selections interactively (a pipe can also be used to provide",
124     "the selections in this case for most tools). While this works well for",
125     "testing, it is easier to provide the selections from the command line",
126     "if they are complex or for scripting.[PAR]",
127
128     "Each tool has different command-line arguments for specifying selections",
129     "(see the help for the individual tools).",
130     "You can either pass a single string containing all selections (separated",
131     "by semicolons), or multiple strings, each containing one selection.",
132     "Note that you need to quote the selections to protect them from the",
133     "shell.[PAR]",
134
135     "If you set a selection command-line argument, but do not provide any",
136     "selections, you are prompted to type the selections for that argument",
137     "interactively. This is useful if that selection argument is optional,",
138     "in which case it is not normally prompted for.[PAR]",
139
140     "To provide selections from a file, use [TT]-sf file.dat[tt] in the place",
141     "of the selection for a selection argument (e.g.,",
142     "[TT]-select -sf file.dat[tt]). In general, the [TT]-sf[tt] argument reads",
143     "selections from the provided file and assigns them to selection arguments",
144     "that have been specified up to that point, but for which no selections",
145     "have been provided.",
146     "As a special case, [TT]-sf[tt] provided on its own, without preceding",
147     "selection arguments, assigns the selections to all (yet unset) required",
148     "selections (i.e., those that would be promted interactively if no",
149     "selections are provided on the command line).[PAR]",
150
151     "To use groups from a traditional index file, use argument [TT]-n[tt]",
152     "to provide a file. See the \"syntax\" subtopic for how to use them.",
153     "If this option is not provided, default groups are generated.",
154     "The default groups are generated with the same logic as for",
155     "non-selection tools.",
156     "",
157     "Depending on the tool, two additional command-line arguments may be",
158     "available to control the behavior:",
159     "",
160     "* [TT]-seltype[tt] can be used to specify the default type of",
161     "  positions to calculate for each selection.",
162     "* [TT]-selrpos[tt] can be used to specify the default type of",
163     "  positions used in selecting atoms by coordinates.",
164     "",
165     "See the \"positions\" subtopic for more information on these options.",
166     "",
167     "Tools that take selections apply them to a structure/topology and/or",
168     "a trajectory file. If the tool takes both (typically as [TT]-s[tt]",
169     "for structure/topology and [TT]-f[tt] for trajectory), then the",
170     "trajectory file is only used for coordinate information, and all other",
171     "information, such as atom names and residue information, is read from",
172     "the structure/topology file. If the tool only takes a structure file,",
173     "or if only that input parameter is provided, then also the coordinates",
174     "are taken from that file.",
175     "For example, to select atoms from a [TT].pdb[tt]/[TT].gro[tt] file in",
176     "a tool that provides both options, pass it as [TT]-s[tt] (only).",
177     "There is no warning if the trajectory file specifies, e.g., different",
178     "atom names than the structure file. Only the number of atoms is checked.",
179     "Many selection-enabled tools also provide an [TT]-fgroup[tt] option",
180     "to specify the atom indices that are present in the trajectory for cases",
181     "where the trajectory only has a subset of atoms from the",
182     "topology/structure file."
183 };
184
185 struct EvaluationHelpText
186 {
187     static const char        name[];
188     static const char        title[];
189     static const char *const text[];
190 };
191
192 const char        EvaluationHelpText::name[]  = "evaluation";
193 const char        EvaluationHelpText::title[] =
194     "Selection evaluation and optimization";
195 const char *const EvaluationHelpText::text[] = {
196     "Boolean evaluation proceeds from left to right and is short-circuiting",
197     "i.e., as soon as it is known whether an atom will be selected, the",
198     "remaining expressions are not evaluated at all.",
199     "This can be used to optimize the selections: you should write the",
200     "most restrictive and/or the most inexpensive expressions first in",
201     "boolean expressions.",
202     "The relative ordering between dynamic and static expressions does not",
203     "matter: all static expressions are evaluated only once, before the first",
204     "frame, and the result becomes the leftmost expression.[PAR]",
205
206     "Another point for optimization is in common subexpressions: they are not",
207     "automatically recognized, but can be manually optimized by the use of",
208     "variables. This can have a big impact on the performance of complex",
209     "selections, in particular if you define several index groups like this::",
210     "",
211     "  rdist = distance from com of resnr 1 to 5;",
212     "  resname RES and rdist < 2;",
213     "  resname RES and rdist < 4;",
214     "  resname RES and rdist < 6;",
215     "",
216     "Without the variable assignment, the distances would be evaluated three",
217     "times, although they are exactly the same within each selection.",
218     "Anything assigned into a variable becomes a common subexpression that",
219     "is evaluated only once during a frame.",
220     "Currently, in some cases the use of variables can actually lead to a small",
221     "performance loss because of the checks necessary to determine for which",
222     "atoms the expression has already been evaluated, but this should not be",
223     "a major problem.",
224 };
225
226 struct ExamplesHelpText
227 {
228     static const char        name[];
229     static const char        title[];
230     static const char *const text[];
231 };
232
233 const char        ExamplesHelpText::name[]  = "examples";
234 const char        ExamplesHelpText::title[] =
235     "Selection examples";
236 const char *const ExamplesHelpText::text[] = {
237     "Below, examples of different types of selections are given.",
238     "",
239     "* Selection of all water oxygens::",
240     "",
241     "    resname SOL and name OW",
242     "",
243     "* Centers of mass of residues 1 to 5 and 10::",
244     "",
245     "    res_com of resnr 1 to 5 10",
246     "",
247     "* All atoms farther than 1 nm of a fixed position::",
248     "",
249     "    not within 1 of [1.2, 3.1, 2.4]",
250     "",
251     "* All atoms of a residue LIG within 0.5 nm of a protein (with a custom name)::",
252     "",
253     "    \"Close to protein\" resname LIG and within 0.5 of group \"Protein\"",
254     "",
255     "* All protein residues that have at least one atom within 0.5 nm of a residue LIG::",
256     "",
257     "    group \"Protein\" and same residue as within 0.5 of resname LIG",
258     "",
259     "* All RES residues whose COM is between 2 and 4 nm from the COM of all of them::",
260     "",
261     "    rdist = res_com distance from com of resname RES",
262     "    resname RES and rdist >= 2 and rdist <= 4",
263     "",
264     // TODO: Make it possible to use links below.
265     "* Selection like with duplicate atoms like C1 C2 C2 C3 C3 C4 ... C8 C9::",
266     "",
267     "    name \"C[1-8]\" merge name \"C[2-9]\"",
268     "",
269     "  This can be used with [TT]gmx distance[tt] to compute C1-C2, C2-C3 etc.",
270     "  distances.",
271     "",
272     "* Selection with atoms in order C2 C1::",
273     "",
274     "    name C1 C2 permute 2 1",
275     "",
276     "  This can be used with [TT]gmx gangle[tt] to get C2->C1 vectors instead of",
277     "  C1->C2.",
278     "",
279     "* Selection with COMs of two index groups::",
280     "",
281     "    com of group 1 plus com of group 2",
282     "",
283     "  This can be used with [TT]gmx distance[tt] to compute the distance between",
284     "  these two COMs.",
285     "",
286     "* Fixed vector along x (can be used as a reference with [TT]gmx gangle[tt])::",
287     "",
288     "    [0, 0, 0] plus [1, 0, 0]",
289     "",
290     "* The following examples explain the difference between the various",
291     "  position types.  This selection selects a position for each residue",
292     "  where any of the three atoms C[123] has [TT]x < 2[tt].  The positions",
293     "  are computed as the COM of all three atoms.",
294     "  This is the default behavior if you just write [TT]res_com of[tt]. ::",
295     "",
296     "    part_res_com of name C1 C2 C3 and x < 2",
297     "",
298     "  This selection does the same, but the positions are computed as COM",
299     "  positions of whole residues::",
300     "",
301     "    whole_res_com of name C1 C2 C3 and x < 2",
302     "",
303     "  Finally, this selection selects the same residues, but the positions",
304     "  are computed as COM of exactly those atoms atoms that match the",
305     "  [TT]x < 2[tt] criterion::",
306     "",
307     "    dyn_res_com of name C1 C2 C3 and x < 2",
308     "",
309     "* Without the [TT]of[tt] keyword, the default behavior is different from",
310     "  above, but otherwise the rules are the same::",
311     "",
312     "    name C1 C2 C3 and res_com x < 2",
313     "",
314     "  works as if [TT]whole_res_com[tt] was specified, and selects the three",
315     "  atoms from residues whose COM satisfiex [TT]x < 2[tt].",
316     "  Using ::",
317     "",
318     "    name C1 C2 C3 and part_res_com x < 2",
319     "",
320     "  instead selects residues based on the COM computed from the C[123] atoms.",
321 };
322
323 struct KeywordsHelpText
324 {
325     static const char        name[];
326     static const char        title[];
327     static const char *const text[];
328 };
329
330 const char        KeywordsHelpText::name[]  = "keywords";
331 const char        KeywordsHelpText::title[] =
332     "Selection keywords";
333 const char *const KeywordsHelpText::text[] = {
334     "The following selection keywords are currently available.",
335     "For keywords marked with a plus, additional help is available through",
336     "a subtopic KEYWORD, where KEYWORD is the name of the keyword.",
337 };
338
339 struct LimitationsHelpText
340 {
341     static const char        name[];
342     static const char        title[];
343     static const char *const text[];
344 };
345
346 const char        LimitationsHelpText::name[]  = "limitations";
347 const char        LimitationsHelpText::title[] =
348     "Selection limitations";
349 const char *const LimitationsHelpText::text[] = {
350     "* Some analysis programs may require a special structure for the input",
351     "  selections (e.g., some options of [TT]gmx gangle[tt] require the index",
352     "  group to be made of groups of three or four atoms).",
353     "  For such programs, it is up to the user to provide a proper selection",
354     "  expression that always returns such positions.",
355     "",
356     "* All selection keywords select atoms in increasing order, i.e., you can",
357     "  consider them as set operations that in the end return the atoms in",
358     "  sorted numerical order.  For example, the following selections select",
359     "  the same atoms in the same order::",
360     "",
361     "    resname RA RB RC",
362     "    resname RB RC RA",
363     "",
364     "  ::",
365     "",
366     "    atomnr 10 11 12 13",
367     "    atomnr 12 13 10 11",
368     "    atomnr 10 to 13",
369     "    atomnr 13 to 10",
370     "",
371     "  If you need atoms/positions in a different order, you can:",
372     "",
373     "  * use external index groups (for some static selections),",
374     "  * use the [TT]permute[tt] keyword to change the final order, or",
375     "  * use the [TT]merge[tt] or [TT]plus[tt] keywords to compose the",
376     "    final selection from multiple distinct selections.",
377     "",
378     "* Due to technical reasons, having a negative value as the first value in",
379     "  expressions like ::",
380     "",
381     "    charge -1 to -0.7",
382     "",
383     "  result in a syntax error. A workaround is to write ::",
384     "",
385     "    charge {-1 to -0.7}",
386     "",
387     "  instead.",
388     "",
389     "* When [TT]name[tt] selection keyword is used together with PDB input",
390     "  files, the behavior may be unintuitive. When GROMACS reads in a PDB",
391     "  file, 4 character atom names that start with a digit are transformed",
392     "  such that, e.g., 1HG2 becomes HG21, and the latter is what is matched",
393     "  by the [TT]name[tt] keyword. Use [TT]pdbname[tt] to match the atom name",
394     "  as it appears in the input PDB file.",
395 };
396
397 struct PositionsHelpText
398 {
399     static const char        name[];
400     static const char        title[];
401     static const char *const text[];
402 };
403
404 const char        PositionsHelpText::name[]  = "positions";
405 const char        PositionsHelpText::title[] =
406     "Specifying positions in selections";
407 const char *const PositionsHelpText::text[] = {
408     "Possible ways of specifying positions in selections are:",
409     "",
410     "1. A constant position can be defined as [TT][XX, YY, ZZ][tt], where",
411     "   [TT]XX[tt], [TT]YY[tt] and [TT]ZZ[tt] are real numbers.[PAR]",
412     "",
413     "2. [TT]com of ATOM_EXPR [pbc][tt] or [TT]cog of ATOM_EXPR [pbc][tt]",
414     "   calculate the center of mass/geometry of [TT]ATOM_EXPR[tt]. If",
415     "   [TT]pbc[tt] is specified, the center is calculated iteratively to try",
416     "   to deal with cases where [TT]ATOM_EXPR[tt] wraps around periodic",
417     "   boundary conditions.",
418     "",
419     "3. [TT]POSTYPE of ATOM_EXPR[tt] calculates the specified positions for",
420     "   the atoms in [TT]ATOM_EXPR[tt].",
421     "   [TT]POSTYPE[tt] can be [TT]atom[tt], [TT]res_com[tt], [TT]res_cog[tt],",
422     "   [TT]mol_com[tt] or [TT]mol_cog[tt], with an optional prefix [TT]whole_[tt]",
423     "   [TT]part_[tt] or [TT]dyn_[tt].",
424     "   [TT]whole_[tt] calculates the centers for the whole residue/molecule,",
425     "   even if only part of it is selected.",
426     "   [TT]part_[tt] prefix calculates the centers for the selected atoms, but",
427     "   uses always the same atoms for the same residue/molecule. The used atoms",
428     "   are determined from the largest group allowed by the selection.",
429     "   [TT]dyn_[tt] calculates the centers strictly only for the selected atoms.",
430     "   If no prefix is specified, whole selections default to [TT]part_[tt] and",
431     "   other places default to [TT]whole_[tt].",
432     "   The latter is often desirable to select the same molecules in different",
433     "   tools, while the first is a compromise between speed ([TT]dyn_[tt]",
434     "   positions can be slower to evaluate than [TT]part_[tt]) and intuitive",
435     "   behavior.",
436     "",
437     "4. [TT]ATOM_EXPR[tt], when given for whole selections, is handled as 3.",
438     "   above, using the position type from the command-line argument",
439     "   [TT]-seltype[tt].",
440     "",
441     "Selection keywords that select atoms based on their positions, such as",
442     "[TT]dist from[tt], use by default the positions defined by the",
443     "[TT]-selrpos[tt] command-line option.",
444     "This can be overridden by prepending a [TT]POSTYPE[tt] specifier to the",
445     "keyword. For example, [TT]res_com dist from POS[tt] evaluates the",
446     "residue center of mass distances. In the example, all atoms of a residue",
447     "are either selected or not, based on the single distance calculated.",
448 };
449
450 struct SyntaxHelpText
451 {
452     static const char        name[];
453     static const char        title[];
454     static const char *const text[];
455 };
456
457 const char        SyntaxHelpText::name[]  = "syntax";
458 const char        SyntaxHelpText::title[] =
459     "Selection syntax";
460 const char *const SyntaxHelpText::text[] = {
461     "A set of selections consists of one or more selections, separated by",
462     "semicolons. Each selection defines a set of positions for the analysis.",
463     "Each selection can also be preceded by a string that gives a name for",
464     "the selection for use in, e.g., graph legends.",
465     "If no name is provided, the string used for the selection is used",
466     "automatically as the name.[PAR]",
467
468     "For interactive input, the syntax is slightly altered: line breaks can",
469     "also be used to separate selections. \\ followed by a line break can",
470     "be used to continue a line if necessary.",
471     "Notice that the above only applies to real interactive input,",
472     "not if you provide the selections, e.g., from a pipe.[PAR]",
473
474     "It is possible to use variables to store selection expressions.",
475     "A variable is defined with the following syntax::",
476     "",
477     "  VARNAME = EXPR ;",
478     "",
479     "where [TT]EXPR[tt] is any valid selection expression.",
480     "After this, [TT]VARNAME[tt] can be used anywhere where [TT]EXPR[tt]",
481     "would be valid.[PAR]",
482
483     "Selections are composed of three main types of expressions, those that",
484     "define atoms ([TT]ATOM_EXPR[tt]), those that define positions",
485     "([TT]POS_EXPR[tt]), and those that evaluate to numeric values",
486     "([TT]NUM_EXPR[tt]). Each selection should be a [TT]POS_EXPR[tt]",
487     "or a [TT]ATOM_EXPR[tt] (the latter is automatically converted to",
488     "positions). The basic rules are as follows:",
489     "",
490     "* An expression like [TT]NUM_EXPR1 < NUM_EXPR2[tt] evaluates to an",
491     "  [TT]ATOM_EXPR[tt] that selects all the atoms for which the comparison",
492     "  is true.",
493     "* Atom expressions can be combined with boolean operations such as",
494     "  [TT]not ATOM_EXPR[tt], [TT]ATOM_EXPR and ATOM_EXPR[tt], or",
495     "  [TT]ATOM_EXPR or ATOM_EXPR[tt]. Parentheses can be used to alter the",
496     "  evaluation order.",
497     "* [TT]ATOM_EXPR[tt] expressions can be converted into [TT]POS_EXPR[tt]",
498     "  expressions in various ways, see the \"positions\" subtopic for more",
499     "  details.",
500     "* [TT]POS_EXPR[tt] can be converted into [TT]NUM_EXPR[tt] using syntax",
501     "  like \"[TT]x of POS_EXPR[tt]\". Currently, this is only supported for single",
502     "  positions like in expression \"[TT]x of cog of ATOM_EXPR[tt]\".",
503     "",
504
505     "Some keywords select atoms based on string values such as the atom name.",
506     "For these keywords, it is possible to use wildcards ([TT]name \"C*\"[tt])",
507     "or regular expressions (e.g., [TT]resname \"R[AB]\"[tt]).",
508     "The match type is automatically guessed from the string: if it contains",
509     "other characters than letters, numbers, '*', or '?', it is interpreted",
510     "as a regular expression.",
511     "To force the matching to use literal string matching, use",
512     "[TT]name = \"C*\"[tt] to match a literal C*.",
513     "To force other type of matching, use '?' or '~' in place of '=' to force",
514     "wildcard or regular expression matching, respectively.[PAR]",
515
516     "Strings that contain non-alphanumeric characters should be enclosed in",
517     "double quotes as in the examples. For other strings, the quotes are",
518     "optional, but if the value conflicts with a reserved keyword, a syntax",
519     "error will occur. If your strings contain uppercase letters, this should",
520     "not happen.[PAR]",
521
522     "Index groups provided with the [TT]-n[tt] command-line option or",
523     "generated by default can be accessed with [TT]group NR[tt] or",
524     "[TT]group NAME[tt], where [TT]NR[tt] is a zero-based index of the group",
525     "and [TT]NAME[tt] is part of the name of the desired group.",
526     "The keyword [TT]group[tt] is optional if the whole selection is",
527     "provided from an index group.",
528     "To see a list of available groups in the interactive mode, press enter",
529     "in the beginning of a line.",
530 };
531
532 } // namespace
533
534 namespace gmx
535 {
536
537 namespace
538 {
539
540 /*! \internal \brief
541  * Help topic implementation for an individual selection method.
542  *
543  * \ingroup module_selection
544  */
545 class KeywordDetailsHelpTopic : public AbstractSimpleHelpTopic
546 {
547     public:
548         //! Initialize help topic for the given selection method.
549         KeywordDetailsHelpTopic(const std::string         &name,
550                                 const gmx_ana_selmethod_t &method)
551             : name_(name), method_(method)
552         {
553         }
554
555         const char *name() const override
556         {
557             return name_.c_str();
558         }
559         const char *title() const override
560         {
561             return method_.help.helpTitle;
562         }
563
564     protected:
565         std::string helpText() const override
566         {
567             return joinStrings(method_.help.help,
568                                method_.help.help + method_.help.nlhelp, "\n");
569         }
570
571     private:
572         std::string                name_;
573         const gmx_ana_selmethod_t &method_;
574
575         GMX_DISALLOW_COPY_AND_ASSIGN(KeywordDetailsHelpTopic);
576 };
577
578 /*! \internal \brief
579  * Custom help topic for printing a list of selection keywords.
580  *
581  * \ingroup module_selection
582  */
583 class KeywordsHelpTopic : public CompositeHelpTopic<KeywordsHelpText>
584 {
585     public:
586         KeywordsHelpTopic();
587
588         void writeHelp(const HelpWriterContext &context) const override;
589
590     private:
591         /*! \brief
592          * Container for known selection methods.
593          *
594          * The first item in the pair is the name of the selection method, and
595          * the second points to the static data structure that describes the
596          * method.
597          * The name in the first item may differ from the name of the static
598          * data structure if an alias is defined for that method.
599          */
600         typedef std::vector<std::pair<std::string,
601                                       const gmx_ana_selmethod_t *> >
602             MethodList;
603
604         /*! \brief
605          * Prints markup for starting a list of keywords.
606          */
607         void writeKeywordListStart(const HelpWriterContext &context,
608                                    const char              *heading) const;
609         /*! \brief
610          * Prints markup for ending a list of keywords.
611          */
612         void writeKeywordListEnd(const HelpWriterContext &context,
613                                  const char              *extraInfo) const;
614
615         /*! \brief
616          * Prints a brief list of keywords (selection methods) available.
617          *
618          * \param[in] context  Context for printing the help.
619          * \param[in] type     Only methods that return this type are printed.
620          * \param[in] bModifiers  If false, \ref SMETH_MODIFIER methods are
621          *      excluded, otherwise only them are printed.
622          */
623         void printKeywordList(const HelpWriterContext &context,
624                               e_selvalue_t type, bool bModifiers) const;
625
626         /*! \brief
627          * Prints the detailed help for keywords for rst export.
628          */
629         void writeKeywordSubTopics(const HelpWriterContext &context) const;
630
631         MethodList              methods_;
632 };
633
634 KeywordsHelpTopic::KeywordsHelpTopic()
635 {
636     // TODO: This is not a very elegant way of getting the list of selection
637     // methods, but this needs to be rewritten in any case if/when #652 is
638     // implemented.
639     const std::unique_ptr<SelectionParserSymbolTable> symtab(
640             new SelectionParserSymbolTable);
641     gmx_ana_selmethod_register_defaults(symtab.get());
642
643     SelectionParserSymbolIterator symbol
644         = symtab->beginIterator(SelectionParserSymbol::MethodSymbol);
645     while (symbol != symtab->endIterator())
646     {
647         const std::string         &symname = symbol->name();
648         const gmx_ana_selmethod_t *method  = symbol->methodValue();
649         methods_.push_back(std::make_pair(std::string(symname), method));
650         if (method->help.nlhelp > 0 && method->help.help != nullptr)
651         {
652             addSubTopic(HelpTopicPointer(
653                                 new KeywordDetailsHelpTopic(symname, *method)));
654         }
655         ++symbol;
656     }
657 }
658
659 void KeywordsHelpTopic::writeHelp(const HelpWriterContext &context) const
660 {
661     context.writeTextBlock(helpText());
662
663     // Print the list of keywords
664     writeKeywordListStart(context, "Keywords that select atoms by an integer property:");
665     printKeywordList(context, INT_VALUE, false);
666     writeKeywordListEnd(context, "(use in expressions or like \"atomnr 1 to 5 7 9\")");
667
668     writeKeywordListStart(context, "Keywords that select atoms by a numeric property:");
669     printKeywordList(context, REAL_VALUE, false);
670     writeKeywordListEnd(context, "(use in expressions or like \"occupancy 0.5 to 1\")");
671
672     writeKeywordListStart(context, "Keywords that select atoms by a string property:");
673     printKeywordList(context, STR_VALUE, false);
674     writeKeywordListEnd(context, "(use like \"name PATTERN [PATTERN] ...\")");
675
676     writeKeywordListStart(context, "Additional keywords that directly select atoms:");
677     printKeywordList(context, GROUP_VALUE, false);
678     writeKeywordListEnd(context, nullptr);
679
680     writeKeywordListStart(context, "Keywords that directly evaluate to positions:");
681     printKeywordList(context, POS_VALUE, false);
682     writeKeywordListEnd(context, "(see also \"positions\" subtopic)");
683
684     writeKeywordListStart(context, "Additional keywords:");
685     printKeywordList(context, POS_VALUE, true);
686     printKeywordList(context, NO_VALUE, true);
687     writeKeywordListEnd(context, nullptr);
688
689     writeKeywordSubTopics(context);
690 }
691
692 void KeywordsHelpTopic::writeKeywordListStart(const HelpWriterContext &context,
693                                               const char              *heading) const
694 {
695     context.paragraphBreak();
696     std::string fullHeading("* ");
697     fullHeading.append(heading);
698     context.writeTextBlock(fullHeading);
699     if (context.outputFormat() == eHelpOutputFormat_Rst)
700     {
701         context.paragraphBreak();
702         context.writeTextBlock("  ::");
703         context.paragraphBreak();
704     }
705 }
706
707 void KeywordsHelpTopic::writeKeywordListEnd(const HelpWriterContext &context,
708                                             const char              *extraInfo) const
709 {
710     if (context.outputFormat() == eHelpOutputFormat_Rst)
711     {
712         context.paragraphBreak();
713     }
714     if (!isNullOrEmpty(extraInfo))
715     {
716         std::string fullInfo("  ");
717         fullInfo.append(extraInfo);
718         context.writeTextBlock(fullInfo);
719     }
720 }
721
722 void KeywordsHelpTopic::printKeywordList(const HelpWriterContext &context,
723                                          e_selvalue_t             type,
724                                          bool                     bModifiers) const
725 {
726     TextWriter                &file = context.outputFile();
727     MethodList::const_iterator iter;
728     for (iter = methods_.begin(); iter != methods_.end(); ++iter)
729     {
730         const gmx_ana_selmethod_t &method = *iter->second;
731         const bool                 bIsModifier
732             = (method.flags & SMETH_MODIFIER) != 0;
733         if (method.type == type && bModifiers == bIsModifier)
734         {
735             const bool bHasHelp = (method.help.nlhelp > 0 && method.help.help != nullptr);
736             const bool bPrintHelpMark
737                 = bHasHelp && context.outputFormat() == eHelpOutputFormat_Console;
738             file.writeString(formatString("   %c ", bPrintHelpMark ? '+' : ' '));
739             if (method.help.syntax != nullptr)
740             {
741                 file.writeLine(method.help.syntax);
742             }
743             else
744             {
745                 std::string symname = iter->first;
746                 if (symname != method.name)
747                 {
748                     symname.append(formatString(" (synonym for %s)", method.name));
749                 }
750                 file.writeLine(symname);
751             }
752         }
753     }
754 }
755
756 void KeywordsHelpTopic::writeKeywordSubTopics(const HelpWriterContext &context) const
757 {
758     if (context.outputFormat() != eHelpOutputFormat_Rst)
759     {
760         return;
761     }
762     std::set<std::string>      usedSymbols;
763     MethodList::const_iterator iter;
764     for (iter = methods_.begin(); iter != methods_.end(); ++iter)
765     {
766         const gmx_ana_selmethod_t &method = *iter->second;
767         const bool                 bHasHelp
768             = (method.help.nlhelp > 0 && method.help.help != nullptr);
769         if (!bHasHelp || usedSymbols.count(iter->first) > 0)
770         {
771             continue;
772         }
773
774         std::string                title;
775         if (method.help.helpTitle != nullptr)
776         {
777             title = method.help.helpTitle;
778             title.append(" - ");
779         }
780         title.append(iter->first);
781         MethodList::const_iterator mergeIter = iter;
782         for (++mergeIter; mergeIter != methods_.end(); ++mergeIter)
783         {
784             if (mergeIter->second->help.help == method.help.help)
785             {
786                 title.append(", ");
787                 title.append(mergeIter->first);
788                 usedSymbols.insert(mergeIter->first);
789             }
790         }
791
792         const IHelpTopic         *subTopic = findSubTopic(iter->first.c_str());
793         GMX_RELEASE_ASSERT(subTopic != nullptr, "Keyword subtopic no longer exists");
794         HelpWriterContext         subContext(context);
795         subContext.enterSubSection(title);
796         subTopic->writeHelp(subContext);
797     }
798 }
799
800 }   // namespace
801
802 //! \cond libapi */
803 HelpTopicPointer createSelectionHelpTopic()
804 {
805     CompositeHelpTopicPointer root(new CompositeHelpTopic<CommonHelpText>);
806     root->registerSubTopic<SimpleHelpTopic<CmdLineHelpText> >();
807     root->registerSubTopic<SimpleHelpTopic<SyntaxHelpText> >();
808     root->registerSubTopic<SimpleHelpTopic<PositionsHelpText> >();
809     root->registerSubTopic<SimpleHelpTopic<ArithmeticHelpText> >();
810     root->registerSubTopic<KeywordsHelpTopic>();
811     root->registerSubTopic<SimpleHelpTopic<EvaluationHelpText> >();
812     root->registerSubTopic<SimpleHelpTopic<LimitationsHelpText> >();
813     root->registerSubTopic<SimpleHelpTopic<ExamplesHelpText> >();
814     return HelpTopicPointer(root.release());
815 }
816 //! \endcond
817
818 } // namespace gmx