]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCommandParams.cpp
Merge branch 'features/indexmacros'
[lyx.git] / src / insets / InsetCommandParams.cpp
1 /**
2  * \file InsetCommandParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  * \author Georg Baum
8  * \author Richard Kimberly Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "InsetCommandParams.h"
16
17 #include "InsetBibitem.h"
18 #include "InsetBibtex.h"
19 #include "InsetCitation.h"
20 #include "InsetCounter.h"
21 #include "InsetFloatList.h"
22 #include "InsetHyperlink.h"
23 #include "InsetInclude.h"
24 #include "InsetIndex.h"
25 #include "InsetLabel.h"
26 #include "InsetLine.h"
27 #include "InsetNomencl.h"
28 #include "InsetRef.h"
29 #include "InsetTOC.h"
30
31 #include "Buffer.h"
32 #include "Encoding.h"
33 #include "Lexer.h"
34
35 #include "frontends/alert.h"
36
37 #include "support/debug.h"
38 #include "support/docstream.h"
39 #include "support/ExceptionMessage.h"
40 #include "support/gettext.h"
41 #include "support/lstrings.h"
42
43 #include "support/lassert.h"
44
45 #include <algorithm>
46 #include <functional>
47
48 using namespace std;
49 using namespace lyx::support;
50
51
52 namespace lyx {
53
54 /// Get information for \p code and command \p cmdName.
55 /// Don't call this without first making sure the command name is
56 /// acceptable to the inset.
57 static ParamInfo const & findInfo(InsetCode code, string const & cmdName)
58 {
59         switch (code) {
60         case BIBITEM_CODE:
61                 return InsetBibitem::findInfo(cmdName);
62         case BIBTEX_CODE:
63                 return InsetBibtex::findInfo(cmdName);
64         case CITE_CODE:
65                 return InsetCitation::findInfo(cmdName);
66         case COUNTER_CODE:
67                 return InsetCounter::findInfo(cmdName);
68         case FLOAT_LIST_CODE:
69                 return InsetFloatList::findInfo(cmdName);
70         case HYPERLINK_CODE:
71                 return InsetHyperlink::findInfo(cmdName);
72         case INCLUDE_CODE:
73                 return InsetInclude::findInfo(cmdName);
74         case INDEX_PRINT_CODE:
75                 return InsetPrintIndex::findInfo(cmdName);
76         case LABEL_CODE:
77                 return InsetLabel::findInfo(cmdName);
78         case LINE_CODE:
79                 return InsetLine::findInfo(cmdName);
80         case NOMENCL_CODE:
81                 return InsetNomencl::findInfo(cmdName);
82         case NOMENCL_PRINT_CODE:
83                 return InsetPrintNomencl::findInfo(cmdName);
84         case REF_CODE:
85                 return InsetRef::findInfo(cmdName);
86         case TOC_CODE:
87                 return InsetTOC::findInfo(cmdName);
88         default:
89                 LATTEST(false);
90                 // fall through in release mode
91         }
92         static const ParamInfo pi;
93         return pi;
94 }
95
96
97 /////////////////////////////////////////////////////////////////////
98 //
99 // ParamInfo::ParamData
100 //
101 /////////////////////////////////////////////////////////////////////
102
103 ParamInfo::ParamData::ParamData(std::string const & s, ParamType t,
104                                 ParamHandling h, bool ignore,
105                                 docstring default_value)
106         : name_(s), type_(t), handling_(h), ignore_(ignore),
107           default_value_(default_value)
108 {}
109
110
111 bool ParamInfo::ParamData::isOptional() const
112 {
113         return type_ == ParamInfo::LATEX_OPTIONAL;
114 }
115
116
117 bool ParamInfo::ParamData::operator==(ParamInfo::ParamData const & rhs) const
118 {
119         return name() == rhs.name() && type() == rhs.type()
120                 && handling() == rhs.handling();
121 }
122
123
124 bool ParamInfo::hasParam(std::string const & name) const
125 {
126         const_iterator it = begin();
127         const_iterator last = end();
128         for (; it != last; ++it) {
129                 if (it->name() == name)
130                         return true;
131         }
132         return false;
133 }
134
135
136 void ParamInfo::add(std::string const & name, ParamType type,
137                     ParamHandling handling, bool ignoreval,
138                     docstring default_value)
139 {
140         info_.push_back(ParamData(name, type, handling, ignoreval, default_value));
141 }
142
143
144 bool ParamInfo::operator==(ParamInfo const & rhs) const
145 {
146         if (size() != rhs.size())
147                 return false;
148         return equal(begin(), end(), rhs.begin());
149 }
150
151
152 ParamInfo::ParamData const &
153         ParamInfo::operator[](std::string const & name) const
154 {
155         const_iterator it = begin();
156         const_iterator last = end();
157         for (; it != last; ++it) {
158                 if (it->name() == name)
159                         return *it;
160         }
161         LATTEST(false);
162         // we will try to continue in release mode
163         static const ParamData pd("asdfghjkl", LYX_INTERNAL);
164         return pd;
165 }
166
167
168 /////////////////////////////////////////////////////////////////////
169 //
170 // InsetCommandParams
171 //
172 /////////////////////////////////////////////////////////////////////
173
174
175 InsetCommandParams::InsetCommandParams(InsetCode code)
176         : insetCode_(code), preview_(false)
177 {
178         cmdName_ = getDefaultCmd(code);
179         info_ = findInfo(code, cmdName_);
180 }
181
182
183 InsetCommandParams::InsetCommandParams(InsetCode code,
184         string const & cmdName)
185         : insetCode_(code), cmdName_(cmdName), preview_(false)
186 {
187         info_ = findInfo(code, cmdName);
188 }
189
190
191 std::string InsetCommandParams::insetType() const
192 {
193         return insetName(insetCode_);
194 }
195
196
197 string InsetCommandParams::getDefaultCmd(InsetCode code)
198 {
199         switch (code) {
200                 case BIBITEM_CODE:
201                         return InsetBibitem::defaultCommand();
202                 case BIBTEX_CODE:
203                         return InsetBibtex::defaultCommand();
204                 case CITE_CODE:
205                         return InsetCitation::defaultCommand();
206                 case COUNTER_CODE:
207                         return InsetCounter::defaultCommand();
208                 case FLOAT_LIST_CODE:
209                         return InsetFloatList::defaultCommand();
210                 case HYPERLINK_CODE:
211                         return InsetHyperlink::defaultCommand();
212                 case INCLUDE_CODE:
213                         return InsetInclude::defaultCommand();
214                 case INDEX_PRINT_CODE:
215                         return InsetPrintIndex::defaultCommand();
216                 case LABEL_CODE:
217                         return InsetLabel::defaultCommand();
218                 case LINE_CODE:
219                         return InsetLine::defaultCommand();
220                 case NOMENCL_CODE:
221                         return InsetNomencl::defaultCommand();
222                 case NOMENCL_PRINT_CODE:
223                         return InsetPrintNomencl::defaultCommand();
224                 case REF_CODE:
225                         return InsetRef::defaultCommand();
226                 case TOC_CODE:
227                         return InsetTOC::defaultCommand();
228                 default:
229                         LATTEST(false);
230                         // fall through in release mode
231         }
232         return string();
233 }
234
235
236 bool InsetCommandParams::isCompatibleCommand(InsetCode code, string const & s)
237 {
238         switch (code) {
239                 case BIBITEM_CODE:
240                         return InsetBibitem::isCompatibleCommand(s);
241                 case BIBTEX_CODE:
242                         return InsetBibtex::isCompatibleCommand(s);
243                 case CITE_CODE:
244                         return InsetCitation::isCompatibleCommand(s);
245                 case COUNTER_CODE:
246                         return InsetCounter::isCompatibleCommand(s);
247                 case FLOAT_LIST_CODE:
248                         return InsetFloatList::isCompatibleCommand(s);
249                 case HYPERLINK_CODE:
250                         return InsetHyperlink::isCompatibleCommand(s);
251                 case INCLUDE_CODE:
252                         return InsetInclude::isCompatibleCommand(s);
253                 case INDEX_PRINT_CODE:
254                         return InsetPrintIndex::isCompatibleCommand(s);
255                 case LABEL_CODE:
256                         return InsetLabel::isCompatibleCommand(s);
257                 case LINE_CODE:
258                         return InsetLine::isCompatibleCommand(s);
259                 case NOMENCL_CODE:
260                         return InsetNomencl::isCompatibleCommand(s);
261                 case NOMENCL_PRINT_CODE:
262                         return InsetPrintNomencl::isCompatibleCommand(s);
263                 case REF_CODE:
264                         return InsetRef::isCompatibleCommand(s);
265                 case TOC_CODE:
266                         return InsetTOC::isCompatibleCommand(s);
267         default:
268                 LATTEST(false);
269                 // fall through in release mode
270         }
271         return false;
272 }
273
274
275 void InsetCommandParams::setCmdName(string const & name)
276 {
277         if (!isCompatibleCommand(insetCode_, name)) {
278                 LYXERR0("InsetCommand: Incompatible command name " <<
279                                 name << ".");
280                 throw ExceptionMessage(WarningException, _("InsetCommand Error: "),
281                                        _("Incompatible command name."));
282         }
283
284         cmdName_ = name;
285         info_ = findInfo(insetCode_, cmdName_);
286 }
287
288
289 void InsetCommandParams::read(Lexer & lex)
290 {
291         Read(lex, nullptr);
292 }
293
294
295 void InsetCommandParams::Read(Lexer & lex, Buffer const * buffer)
296 {
297         lex.setContext("InsetCommandParams::read");
298         lex >> insetName(insetCode_).c_str();
299         lex >> "LatexCommand";
300         lex >> cmdName_;
301         if (!isCompatibleCommand(insetCode_, cmdName_)) {
302                 lex.printError("Incompatible command name " + cmdName_ + ".");
303                 throw ExceptionMessage(WarningException, _("InsetCommandParams Error: "),
304                                        _("Incompatible command name."));
305         }
306
307         info_ = findInfo(insetCode_, cmdName_);
308
309         for (ParamInfo::ParamData const & param : info_)
310                 if (param.ignore()) {
311                         params_[param.name()] = param.defaultValue();
312                 }
313
314         string token;
315         while (lex.isOK()) {
316                 lex.next();
317                 token = lex.getString();
318                 if (token == "\\end_inset")
319                         break;
320                 if (token == "preview") {
321                         lex.next();
322                         preview_ = lex.getBool();
323                         continue;
324                 }
325                 if (hasParam(token)) {
326                         lex.next(true);
327                         docstring data = lex.getDocString();
328                         if (buffer && token == "filename") {
329                                 data = from_utf8(buffer->includedFilePath(to_utf8(data)));
330                         } else if (buffer && token == "bibfiles") {
331                                 int i = 0;
332                                 docstring newdata;
333                                 docstring bib = support::token(data, ',', i);
334                                 while (!bib.empty()) {
335                                         bib = from_utf8(buffer->includedFilePath(to_utf8(bib), "bib"));
336                                         if (!newdata.empty())
337                                                 newdata.append(1, ',');
338                                         newdata.append(bib);
339                                         bib = support::token(data, ',', ++i);
340                                 }
341                                 data = newdata;
342                         } else if (buffer && token == "options") {
343                                 data = from_utf8(buffer->includedFilePath(to_utf8(data), "bst"));
344                         }
345                         params_[token] = data;
346                 } else {
347                         lex.printError("Unknown parameter name `$$Token' for command " + cmdName_);
348                         throw ExceptionMessage(WarningException,
349                                 _("InsetCommandParams: ") + from_ascii(cmdName_),
350                                 _("Unknown parameter name: ") + from_utf8(token));
351                 }
352         }
353         if (token != "\\end_inset") {
354                 lex.printError("Missing \\end_inset at this point. "
355                                "Read: `$$Token'");
356                 throw ExceptionMessage(WarningException,
357                         _("InsetCommandParams Error: "),
358                         _("Missing \\end_inset at this point: ") + from_utf8(token));
359         }
360 }
361
362
363 void InsetCommandParams::write(ostream & os) const
364 {
365         Write(os, nullptr);
366 }
367
368
369 void InsetCommandParams::Write(ostream & os, Buffer const * buffer) const
370 {
371         os << "CommandInset " << insetType() << '\n';
372         os << "LatexCommand " << cmdName_ << '\n';
373         if (preview_)
374                 os << "preview true\n";
375         ParamInfo::const_iterator it  = info_.begin();
376         ParamInfo::const_iterator end = info_.end();
377         for (; it != end; ++it) {
378                 if (it->ignore())
379                         continue;
380                 string const & name = it->name();
381                 string data = to_utf8((*this)[name]);
382                 if (!data.empty()) {
383                         // Adjust path of files if document was moved
384                         if (buffer && name == "filename") {
385                                 data = buffer->includedFilePath(data);
386                         } else if (buffer && name == "bibfiles") {
387                                 int i = 0;
388                                 string newdata;
389                                 string bib = token(data, ',', i);
390                                 while (!bib.empty()) {
391                                         bib = buffer->includedFilePath(bib, "bib");
392                                         if (!newdata.empty())
393                                                 newdata.append(1, ',');
394                                         newdata.append(bib);
395                                         bib = token(data, ',', ++i);
396                                 }
397                                 data = newdata;
398                         } else if (buffer && name == "options") {
399                                 data = buffer->includedFilePath(data, "bst");
400                         }
401                         os << name << ' '
402                            << Lexer::quoteString(data)
403                            << '\n';
404                 }
405         }
406 }
407
408
409 bool InsetCommandParams::writeEmptyOptional(ParamInfo::const_iterator ci) const
410 {
411         LASSERT(ci->isOptional(), return false);
412
413         ++ci; // we want to start with the next one
414         ParamInfo::const_iterator end = info_.end();
415         for (; ci != end; ++ci) {
416                 switch (ci->type()) {
417                 case ParamInfo::LYX_INTERNAL:
418                         break;
419
420                 case ParamInfo::LATEX_REQUIRED:
421                         return false;
422
423                 case ParamInfo::LATEX_OPTIONAL: {
424                         std::string const & name = ci->name();
425                         docstring const & data = (*this)[name];
426                         if (!data.empty())
427                                 return true;
428                         break;
429                 }
430
431                 } //end switch
432         }
433         return false;
434 }
435
436
437 docstring InsetCommandParams::prepareCommand(OutputParams const & runparams,
438                                              docstring const & command,
439                                              ParamInfo::ParamHandling handling) const
440 {
441         docstring result;
442         bool ltrimmed = false;
443         // Trimming can be done on top of any of the other handlings
444         // We check this here since handling might be changed below.
445         if (handling & ParamInfo::HANDLING_LTRIM) {
446                 // this is used if no other handling is done
447                 result = command;
448                 ltrimmed = true;
449         }
450         if (handling & ParamInfo::HANDLING_LATEXIFY
451             || handling & ParamInfo::HANDLING_INDEX_ESCAPE)
452                 if ((*this)["literal"] == "true")
453                         handling = ParamInfo::HANDLING_NONE;
454
455         // LATEXIFY, ESCAPE and NONE are mutually exclusive
456         if (handling & ParamInfo::HANDLING_LATEXIFY) {
457                 // First handle backslash
458                 result = subst(command, from_ascii("\\"), from_ascii("\\textbackslash{}"));
459                 // Then get LaTeX macros
460                 pair<docstring, docstring> command_latexed =
461                         runparams.encoding->latexString(result, runparams.dryrun);
462                 result = command_latexed.first;
463                 if (!command_latexed.second.empty()) {
464                         // Issue a warning about omitted characters
465                         // FIXME: should be passed to the error dialog
466                         frontend::Alert::warning(_("Uncodable characters"),
467                                 bformat(_("The following characters that are used in the inset %1$s are not\n"
468                                           "representable in the current encoding and therefore have been omitted:\n%2$s."),
469                                         from_utf8(insetType()), command_latexed.second));
470                 }
471                 // Now escape special commands
472                 static docstring const backslash = from_ascii("\\");
473                 int const nchars_escape = 8;
474                 static char_type const chars_escape[nchars_escape] = {
475                         '&', '_', '$', '%', '#', '^', '{', '}'};
476
477                 if (!result.empty()) {
478                         int previous;
479                         // The characters in chars_name[] need to be changed to a command when
480                         // they are LaTeXified.
481                         for (int k = 0; k < nchars_escape; k++)
482                                 for (size_t i = 0, pos;
483                                         (pos = result.find(chars_escape[k], i)) != string::npos;
484                                         i = pos + 2) {
485                                                 //(Only) \\^ needs to be terminated
486                                                 docstring const term = (k == 5) ? from_ascii("{}") : docstring();
487                                                 if (pos == 0)
488                                                         previous = 0;
489                                                 else
490                                                         previous = pos - 1;
491                                                 // only if not already escaped
492                                                 if (result[previous] != '\\')
493                                                         result.replace(pos, 1, backslash + chars_escape[k] + term);
494                                 }
495                 }
496         }
497         else if (handling & ParamInfo::HANDLING_ESCAPE)
498                 result = escape(command);
499         else if (handling & ParamInfo::HANDLING_NONE) {
500                 // we can only output characters covered by the current
501                 // encoding!
502                 docstring uncodable;
503                 for (char_type c : command) {
504                         try {
505                                 if (runparams.encoding->encodable(c))
506                                         result += c;
507                                 else if (runparams.dryrun) {
508                                         result += "<" + _("LyX Warning: ")
509                                            + _("uncodable character") + " '";
510                                         result += docstring(1, c);
511                                         result += "'>";
512                                 } else
513                                         uncodable += c;
514                         } catch (EncodingException & /* e */) {
515                                 if (runparams.dryrun) {
516                                         result += "<" + _("LyX Warning: ")
517                                            + _("uncodable character") + " '";
518                                         result += docstring(1, c);
519                                         result += "'>";
520                                 } else
521                                         uncodable += c;
522                         }
523                 }
524                 if (!uncodable.empty() && !runparams.silent) {
525                         // issue a warning about omitted characters
526                         // FIXME: should be passed to the error dialog
527                         frontend::Alert::warning(_("Uncodable characters in inset"),
528                                 bformat(_("The following characters in one of the insets are\n"
529                                           "not representable in the current encoding and have been omitted: %1$s.\n"
530                                           "Unchecking 'Literal' in the respective inset dialog might help."),
531                                 uncodable));
532                 }
533         }
534         // INDEX_ESCAPE is independent of the others
535         if (handling & ParamInfo::HANDLING_INDEX_ESCAPE) {
536                 // Now escape special commands
537                 static docstring const quote = from_ascii("\"");
538                 int const nchars_escape = 4;
539                 static char_type const chars_escape[nchars_escape] = { '"', '@', '|', '!' };
540
541                 if (!result.empty()) {
542                         // The characters in chars_name[] need to be changed to a command when
543                         // they are LaTeXified.
544                         for (int k = 0; k < nchars_escape; k++)
545                                 for (size_t i = 0, pos;
546                                         (pos = result.find(chars_escape[k], i)) != string::npos;
547                                         i = pos + 2)
548                                                 result.replace(pos, 1, quote + chars_escape[k]);
549                 }
550         }
551
552         return ltrimmed ? ltrim(result) : result;
553 }
554
555
556 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
557 {
558         docstring s = '\\' + from_ascii(cmdName_);
559         bool noparam = true;
560         ParamInfo::const_iterator it  = info_.begin();
561         ParamInfo::const_iterator end = info_.end();
562         for (; it != end; ++it) {
563                 std::string const & name = it->name();
564                 switch (it->type()) {
565                 case ParamInfo::LYX_INTERNAL:
566                         break;
567
568                 case ParamInfo::LATEX_REQUIRED: {
569                         docstring const data =
570                                 prepareCommand(runparams, (*this)[name], it->handling());
571                         s += '{' + data + '}';
572                         noparam = false;
573                         break;
574                 }
575                 case ParamInfo::LATEX_OPTIONAL: {
576                         docstring data =
577                                 prepareCommand(runparams, (*this)[name], it->handling());
578                         if (!data.empty()) {
579                                 s += '[' + protectArgument(data) + ']';
580                                 noparam = false;
581                         } else if (writeEmptyOptional(it)) {
582                                         s += "[]";
583                                         noparam = false;
584                         }
585                         break;
586                 }
587                 } //end switch
588         }
589         if (noparam)
590                 // Make sure that following stuff does not change the
591                 // command name.
592                 s += "{}";
593         return s;
594 }
595
596
597 docstring InsetCommandParams::getFirstNonOptParam() const
598 {
599         ParamInfo::const_iterator it =
600                 find_if(info_.begin(), info_.end(),
601                         [](ParamInfo::ParamData const & d) { return !d.isOptional(); });
602         LASSERT(it != info_.end(), return docstring());
603         return (*this)[it->name()];
604 }
605
606
607 bool InsetCommandParams::hasParam(std::string const & name) const
608 {
609         return info_.hasParam(name);
610 }
611
612
613 docstring const & InsetCommandParams::getParamOr(std::string const & name, docstring const & defaultValue) const
614 {
615         if (hasParam(name))
616                 return (*this)[name];
617         return defaultValue;
618 }
619
620
621 docstring const & InsetCommandParams::operator[](string const & name) const
622 {
623         static const docstring dummy;
624         LASSERT(hasParam(name), return dummy);
625         ParamMap::const_iterator data = params_.find(name);
626         if (data == params_.end() || data->second.empty())
627                 return dummy;
628         ParamInfo::ParamData const & param = info_[name];
629         if (param.ignore())
630                 return param.defaultValue();
631         return data->second;
632 }
633
634
635 docstring & InsetCommandParams::operator[](string const & name)
636 {
637         LATTEST(hasParam(name));
638         // this will add the name in release mode
639         ParamInfo::ParamData const & param = info_[name];
640         if (param.ignore())
641                 params_[name] = param.defaultValue();
642         return params_[name];
643 }
644
645
646 void InsetCommandParams::clear()
647 {
648         params_.clear();
649         preview(false);
650 }
651
652
653 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
654 {
655         return o1.insetCode_ == o2.insetCode_
656                 && o1.cmdName_ == o2.cmdName_
657                 && o1.info_ == o2.info_
658                 && o1.params_ == o2.params_
659                 && o1.preview_ == o2.preview_;
660 }
661
662
663 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)
664 {
665         return !(o1 == o2);
666 }
667
668
669 } // namespace lyx