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