]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCommandParams.cpp
Run codespell on tex2lyx/, client/, convert/ and graphics/
[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 Heck
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14 #include <algorithm>
15 #include <functional>
16
17
18 #include "InsetCommandParams.h"
19
20 #include "InsetBibitem.h"
21 #include "InsetBibtex.h"
22 #include "InsetCitation.h"
23 #include "InsetCounter.h"
24 #include "InsetFloatList.h"
25 #include "InsetHyperlink.h"
26 #include "InsetInclude.h"
27 #include "InsetIndex.h"
28 #include "InsetLabel.h"
29 #include "InsetLine.h"
30 #include "InsetNomencl.h"
31 #include "InsetRef.h"
32 #include "InsetTOC.h"
33
34 #include "Buffer.h"
35 #include "Encoding.h"
36 #include "Lexer.h"
37 #include "OutputParams.h"
38
39 #include "frontends/alert.h"
40
41 #include "support/debug.h"
42 #include "support/docstream.h"
43 #include "support/ExceptionMessage.h"
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46
47 #include "support/lassert.h"
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 (size_type i = 0 ; i < command.size() ; ++i) {
505                         char_type c = command[i];
506                         try {
507                                 if (runparams.encoding->encodable(c))
508                                         result += c;
509                                 else if (runparams.dryrun) {
510                                         result += "<" + _("LyX Warning: ")
511                                            + _("uncodable character") + " '";
512                                         result += docstring(1, c);
513                                         result += "'>";
514                                 } else
515                                         uncodable += c;
516                         } catch (EncodingException & /* e */) {
517                                 if (runparams.dryrun) {
518                                         result += "<" + _("LyX Warning: ")
519                                            + _("uncodable character") + " '";
520                                         result += docstring(1, c);
521                                         result += "'>";
522                                 } else
523                                         uncodable += c;
524                         }
525                 }
526                 if (!uncodable.empty() && !runparams.silent) {
527                         // issue a warning about omitted characters
528                         // FIXME: should be passed to the error dialog
529                         frontend::Alert::warning(_("Uncodable characters in inset"),
530                                 bformat(_("The following characters in one of the insets are\n"
531                                           "not representable in the current encoding and have been omitted: %1$s.\n"
532                                           "Unchecking 'Literal' in the respective inset dialog might help."),
533                                 uncodable));
534                 }
535         }
536         // INDEX_ESCAPE is independent of the others
537         if (handling & ParamInfo::HANDLING_INDEX_ESCAPE) {
538                 // Now escape special commands
539                 static docstring const quote = from_ascii("\"");
540                 int const nchars_escape = 4;
541                 static char_type const chars_escape[nchars_escape] = { '"', '@', '|', '!' };
542
543                 if (!result.empty()) {
544                         // The characters in chars_name[] need to be changed to a command when
545                         // they are LaTeXified.
546                         for (int k = 0; k < nchars_escape; k++)
547                                 for (size_t i = 0, pos;
548                                         (pos = result.find(chars_escape[k], i)) != string::npos;
549                                         i = pos + 2)
550                                                 result.replace(pos, 1, quote + chars_escape[k]);
551                 }
552         }
553
554         return ltrimmed ? ltrim(result) : result;
555 }
556
557
558 docstring InsetCommandParams::getCommand(OutputParams const & runparams) const
559 {
560         docstring s = '\\' + from_ascii(cmdName_);
561         bool noparam = true;
562         ParamInfo::const_iterator it  = info_.begin();
563         ParamInfo::const_iterator end = info_.end();
564         for (; it != end; ++it) {
565                 std::string const & name = it->name();
566                 switch (it->type()) {
567                 case ParamInfo::LYX_INTERNAL:
568                         break;
569
570                 case ParamInfo::LATEX_REQUIRED: {
571                         docstring const data =
572                                 prepareCommand(runparams, (*this)[name], it->handling());
573                         s += '{' + data + '}';
574                         noparam = false;
575                         break;
576                 }
577                 case ParamInfo::LATEX_OPTIONAL: {
578                         docstring data =
579                                 prepareCommand(runparams, (*this)[name], it->handling());
580                         if (!data.empty()) {
581                                 s += '[' + protectArgument(data) + ']';
582                                 noparam = false;
583                         } else if (writeEmptyOptional(it)) {
584                                         s += "[]";
585                                         noparam = false;
586                         }
587                         break;
588                 }
589                 } //end switch
590         }
591         if (noparam)
592                 // Make sure that following stuff does not change the
593                 // command name.
594                 s += "{}";
595         return s;
596 }
597
598
599 docstring InsetCommandParams::getFirstNonOptParam() const
600 {
601         ParamInfo::const_iterator it =
602                 find_if(info_.begin(), info_.end(),
603                         [](ParamInfo::ParamData const & d) { return !d.isOptional(); });
604         LASSERT(it != info_.end(), return docstring());
605         return (*this)[it->name()];
606 }
607
608
609 docstring const & InsetCommandParams::operator[](string const & name) const
610 {
611         static const docstring dummy;
612         LASSERT(info_.hasParam(name), return dummy);
613         ParamMap::const_iterator data = params_.find(name);
614         if (data == params_.end() || data->second.empty())
615                 return dummy;
616         ParamInfo::ParamData const & param = info_[name];
617         if (param.ignore())
618                 return param.defaultValue();
619         return data->second;
620 }
621
622
623 docstring & InsetCommandParams::operator[](string const & name)
624 {
625         LATTEST(info_.hasParam(name));
626         // this will add the name in release mode
627         ParamInfo::ParamData const & param = info_[name];
628         if (param.ignore())
629                 params_[name] = param.defaultValue();
630         return params_[name];
631 }
632
633
634 void InsetCommandParams::clear()
635 {
636         params_.clear();
637         preview(false);
638 }
639
640
641 bool operator==(InsetCommandParams const & o1, InsetCommandParams const & o2)
642 {
643         return o1.insetCode_ == o2.insetCode_
644                 && o1.cmdName_ == o2.cmdName_
645                 && o1.info_ == o2.info_
646                 && o1.params_ == o2.params_
647                 && o1.preview_ == o2.preview_;
648 }
649
650
651 bool operator!=(InsetCommandParams const & o1, InsetCommandParams const & o2)
652 {
653         return !(o1 == o2);
654 }
655
656
657 } // namespace lyx