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