]> git.lyx.org Git - features.git/blob - src/insets/InsetListingsParams.cpp
InsetListingsParams.h/cpp: Allow , in parameter string which is common in caption
[features.git] / src / insets / InsetListingsParams.cpp
1 /**
2  * \file InsetListingsParams.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Bo Peng
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Lexer.h"
14 #include "InsetListingsParams.h"
15
16 #include "gettext.h"
17 #include "Length.h"
18
19 #include <sstream>
20 #include <boost/assert.hpp>
21
22 #include "support/lstrings.h"
23 #include "support/convert.h"
24
25 using std::vector;
26 using std::ostream;
27 using std::string;
28 using std::exception;
29 using lyx::support::trim;
30 using lyx::support::isStrInt;
31
32 namespace lyx
33 {
34
35 enum param_type {
36         ALL,
37         TRUEFALSE,
38         INTEGER,
39         LENGTH,
40         ONEOF,
41         SUBSETOF,
42 };
43
44
45 /** Information about each parameter
46  */
47 struct listings_param_info {
48         /// name of the parameter
49         char const * name;
50         /// default value
51         char const * value;
52         // for option with value "true", "false", 
53         // if onoff is true,
54         //   "true":  option
55         //   "false": 
56         //   "other": option="other"
57         // onoff is false,
58         //   "true":  option=true
59         //   "false": option=false
60         bool onoff;
61         /// validator type
62         param_type type;
63         // ALL:
64         // TRUEFALSE:
65         // INTEGER:
66         // LENGTH:
67         //     info is ignored.
68         // ONEOF
69         //     info is a \n separated string with allowed values
70         // SUBSETOF
71         //     info is a string from which par is composed of
72         //     (e.g. floatplacement can be one or more of tbph)
73         char const * info;
74         //
75         char const * hint;
76 };
77
78
79 char const * allowed_languages = 
80         "no language\nBAP\nACSL\nAda\nALGOL\nC\nC++\nCaml\nClean\nCobol\n"
81         "Comal 80\ncsh\nDelphi\nEiffel\nElan\nEuphoria\nFortran\nHaskell\n"
82         "HTML\nIDL\nJava\nLisp\nLogo\nmake\nMathematica\nMatlab\nMercury\n"
83         "Miranda\nML\nModula-2\nOberon-2\nOCL\nPascal\nPerl\nPHP\nPL/I\nPOV\n"
84         "Python\nProlog\nR\nS\nSAS\nSHELXL\nSimula\ntcl\nSQL\nTeX\nVBScript\n"
85         "VHDL\nXML";
86
87 char const * style_hint = "Use \\footnotessize, \\small, \\itshape, \\ttfamily or something like that";
88 char const * frame_hint = "none, leftline, topline, bottomline, lines, single, shadowbox or subset of trblTRBL";
89 char const * frameround_hint = "The foru letters (t or f) attached to top right, bottom right, bottom left and top left corner.";
90 char const * color_hint = "Enter something like \\color{white}";
91
92 /// options copied from page 26 of listings manual
93 // FIXME: add default parameters ... (which is not used now)
94 listings_param_info const listings_param_table[] = {
95         { "float", "false", true,  SUBSETOF, "tbph", "" },
96         { "floatplacement", "tbp", false, SUBSETOF, "tbph", "" },
97         { "aboveskip", "\\medskipamount", false, LENGTH, "", "" },
98         { "belowskip", "\\medskipamount", false, LENGTH, "", "" },
99         { "lineskip", "", false, LENGTH, "", "" },
100         { "boxpos", "", false, SUBSETOF, "bct", "" },
101         { "print", "", false, TRUEFALSE, "", "" },
102         { "firstline", "", false, INTEGER, "", "" },
103         { "lastline", "", false, INTEGER, "", "" },
104         { "showlines", "", false, TRUEFALSE, "", "" },
105         { "emptylines", "", false, ALL, "", "Expect a number with an optional * before it" },
106         { "gobble", "", false, INTEGER, "", "" },
107         { "style", "", false, ALL, "", "" },
108         { "language", "", false, ONEOF, allowed_languages, "" },
109         { "alsolanguage", "", false, ONEOF, allowed_languages, "" },
110         { "defaultdialect", "", false, ONEOF, allowed_languages, "" },
111         { "printpod", "", false, TRUEFALSE, "", "" },
112         { "usekeywordsintag", "", false, TRUEFALSE, "", "" },
113         { "tagstyle", "", false, ALL, "", style_hint },
114         { "markfirstintag", "", false, ALL, "", style_hint },
115         { "makemacrouse", "", false, TRUEFALSE, "", "" },
116         { "basicstyle", "", false, ALL, "", style_hint },
117         { "identifierstyle", "", false, ALL, "", style_hint },
118         { "commentstyle", "", false, ALL, "", style_hint },
119         { "stringstyle", "", false, ALL, "", style_hint },
120         { "keywordstyle", "", false, ALL, "", style_hint },
121         { "ndkeywordstyle", "", false, ALL, "", style_hint },
122         { "classoffset", "", false, INTEGER, "", "" },
123         { "texcsstyle", "", false, ALL, "", style_hint },
124         { "directivestyle", "", false, ALL, "", style_hint },
125         { "emph", "", false, ALL, "", "" },
126         { "moreemph", "", false, ALL, "", "" },
127         { "deleteemph", "", false, ALL, "", "" },
128         { "emphstyle", "", false, ALL, "", "" },
129         { "delim", "", false, ALL, "", "" },
130         { "moredelim", "", false, ALL, "", "" },
131         { "deletedelim", "", false, ALL, "", "" },
132         { "extendedchars", "", false, TRUEFALSE, "", "" },
133         { "inputencoding", "", false, ALL, "", "" },
134         { "upquote", "", false, TRUEFALSE, "", "" },
135         { "tabsize", "", false, INTEGER, "", "" },
136         { "showtabs", "", false, ALL, "", "" },
137         { "tab", "", false, ALL, "", "" },
138         { "showspaces", "", false, TRUEFALSE, "", "" },
139         { "showstringspaces", "", false, TRUEFALSE, "", "" },
140         { "formfeed", "", false, ALL, "", "" },
141         { "numbers", "", false, ONEOF, "none\nleft\nright", "" },
142         { "stepnumber", "", false, INTEGER, "", "" },
143         { "numberfirstline", "", false, TRUEFALSE, "", "" },
144         { "numberstyle", "", false, ALL, "", style_hint },
145         { "numbersep", "", false, LENGTH, "", "" },
146         { "numberblanklines", "", false, ALL, "", "" },
147         { "firstnumber", "", false, ALL, "", "auto, last or a number" },
148         { "name", "", false, ALL, "", "" },
149         { "thelstnumber", "", false, ALL, "", "" },
150         { "title", "", false, ALL, "", "" },
151         { "caption", "", false, ALL, "", "" },
152         { "label", "", false, ALL, "", "" },
153         { "nolol", "", false, TRUEFALSE, "", "" },
154         { "captionpos", "", false, SUBSETOF, "tb", "" },
155         { "abovecaptionskip", "", false, LENGTH, "", "" },
156         { "belowcaptionskip", "", false, LENGTH, "", "" },
157         { "linewidth", "", false, LENGTH, "", "" },
158         { "xleftmargin", "", false, LENGTH, "", "" },
159         { "xrightmargin", "", false, LENGTH, "", "" },
160         { "resetmargins", "", false, TRUEFALSE, "", "" },
161         { "breaklines", "", false, TRUEFALSE, "", "" },
162         { "prebreak", "", false, ALL, "", "" },
163         { "postbreak", "", false, ALL, "", "" },
164         { "breakindent", "", false, LENGTH, "", "" },
165         { "breakautoindent", "", false, TRUEFALSE, "", "" },
166         { "frame", "", false, ALL, "", frame_hint },
167         { "frameround", "", false, SUBSETOF, "tf", frameround_hint },
168         { "framesep", "", false, LENGTH, "", "" },
169         { "rulesep", "", false, LENGTH, "", "" },
170         { "framerule", "", false, LENGTH, "", "" },
171         { "framexleftmargin", "", false, LENGTH, "", "" },
172         { "framexrightmargin", "", false, LENGTH, "", "" },
173         { "framextopmargin", "", false, LENGTH, "", "" },
174         { "framexbottommargin", "", false, LENGTH, "", "" },
175         { "backgroundcolor", "", false, ALL, "", color_hint },
176         { "rulecolor", "", false, ALL, "", color_hint },
177         { "fillcolor", "", false, ALL, "", color_hint },
178         { "rulesepcolor", "", false, ALL, "", color_hint },
179         { "frameshape", "", false, ALL, "", "" },
180         { "index", "", false, ALL, "", "" },
181         { "moreindex", "", false, ALL, "", "" },
182         { "deleteindex", "", false, ALL, "", "" },
183         { "indexstyle", "", false, ALL, "", "" },
184         { "columns", "", false, ALL, "", "" },
185         { "flexiblecolumns", "", false, ALL, "", "" },
186         { "keepspaces", "", false, TRUEFALSE, "", "" },
187         { "basewidth", "", false, LENGTH, "", "" },
188         { "fontadjust", "", true, TRUEFALSE, "", "" },
189         { "texcl", "", false, TRUEFALSE, "", "" },
190         { "mathescape", "", false, TRUEFALSE, "", "" },
191         { "escapechar", "", false, ALL, "", "" },
192         { "escapeinside", "", false, ALL, "", "" },
193         { "escepeinside", "", false, ALL, "", "" },
194         { "escepebegin", "", false, ALL, "", "" },
195         { "escepeend", "", false, ALL, "", "" },
196         { "fancyvrb", "", false, TRUEFALSE, "", "" },
197         { "fvcmdparams", "", false, ALL, "", "" },
198         { "morefvcmdparams", "", false, ALL, "", "" },
199         { "keywordsprefix", "", false, ALL, "", "" },
200         { "keywords", "", false, ALL, "", "" },
201         { "morekeywords", "", false, ALL, "", "" },
202         { "deletekeywords", "", false, ALL, "", "" },
203         { "ndkeywords", "", false, ALL, "", "" },
204         { "morendkeywords", "", false, ALL, "", "" },
205         { "deletendkeywords", "", false, ALL, "", "" },
206         { "texcs", "", false, ALL, "", "" },
207         { "moretexcs", "", false, ALL, "", "" },
208         { "deletetexcs", "", false, ALL, "", "" },
209         { "directives", "", false, ALL, "", "" },
210         { "moredirectives", "", false, ALL, "", "" },
211         { "deletedirectives", "", false, ALL, "", "" },
212         { "sensitive", "", false, ALL, "", "" },
213         { "alsoletter", "", false, ALL, "", "" },
214         { "alsodigit", "", false, ALL, "", "" },
215         { "alsoother", "", false, ALL, "", "" },
216         { "otherkeywords", "", false, ALL, "", "" },
217         { "tag", "", false, ALL, "", "" },
218         { "string", "", false, ALL, "", "" },
219         { "morestring", "", false, ALL, "", "" },
220         { "deletestring", "", false, ALL, "", "" },
221         { "comment", "", false, ALL, "", "" },
222         { "morecomment", "", false, ALL, "", "" },
223         { "deletecomment", "", false, ALL, "", "" },
224         { "keywordcomment", "", false, ALL, "", "" },
225         { "morekeywordcomment", "", false, ALL, "", "" },
226         { "deletekeywordcomment", "", false, ALL, "", "" },
227         { "keywordcommentsemicolon", "", false, ALL, "", "" },
228         { "podcomment", "", false, ALL, "", "" },
229         { "", "", false, ALL, "", ""}
230 };
231
232
233 class parValidator
234 {
235 public:
236         parValidator(string const & name);
237
238         /// validate given parameter
239         /// invalidParam will be thrown if invalid 
240         /// parameter is found.
241         void validate(std::string const & par) const;
242
243 private:
244         /// parameter name
245         string const & name;
246         ///
247         listings_param_info const * info;
248 };
249
250
251 parValidator::parValidator(string const & n)
252         : name(n), info(0)
253 {
254         if (name.empty())
255                 throw invalidParam("Invalid (empty) listings param name.");
256         else if (name == "?") {
257                 string pars;
258                 size_t idx = 0;
259                 while (listings_param_table[idx].name != string()) {
260                         if (!pars.empty())
261                                 pars += ", ";
262                         pars += listings_param_table[idx].name;
263                         ++idx;
264                 }
265                 throw invalidParam("Available listings parameters are " + pars);
266         }
267         // locate name in parameter table
268         size_t idx = 0;
269         while (listings_param_table[idx].name != name && listings_param_table[idx].name != string())
270                 ++idx;
271         // found the name
272         if (listings_param_table[idx].name != "") {
273                 info = &listings_param_table[idx];
274                 return;
275         }
276         // otherwise, produce a meaningful error message.
277         string matching_names;
278         for (size_t i = 0; i < idx; ++i) {
279                 string n(listings_param_table[i].name);
280                 if (n.size() >= name.size() && n.substr(0, name.size()) == name) {
281                         if (matching_names.empty())
282                                 matching_names += n;
283                         else
284                                 matching_names += ", " + n;
285                 }
286         }
287         if (matching_names.empty())
288                 throw invalidParam("Unknown listings param name: " + name);
289         else
290                 throw invalidParam("Parameters starting with '" + name + 
291                         "': " + matching_names);
292 }
293
294
295 void parValidator::validate(std::string const & par) const
296 {
297         switch (info->type) {
298         case ALL:
299                 if (par.empty() && !info->onoff) {
300                         if (info->hint != "")
301                                 throw invalidParam(info->hint);
302                         else
303                                 throw invalidParam("An value is expected");
304                 }
305                 return;
306         case TRUEFALSE: {
307                 if (par.empty() && !info->onoff) {
308                         if (info->hint != "")
309                                 throw invalidParam(info->hint);
310                         else
311                                 throw invalidParam("Please specify true or false");
312                 }
313                 if (par != "true" && par != "false")
314                         throw invalidParam("Only true or false is allowed for parameter" + name);
315                 return;
316         }
317         case INTEGER: {
318                 if (!isStrInt(par)) {
319                         if (info->hint != "")
320                                 throw invalidParam(info->hint);
321                         else
322                                 throw invalidParam("Please specify an integer value");
323                 }
324                 if (convert<int>(par) == 0 && par[0] != '0')
325                         throw invalidParam("An integer is expected for parameter " + name);
326                 return;
327         }
328         case LENGTH: {
329                 if (par.empty() && !info->onoff) {
330                         if (info->hint != "")
331                                 throw invalidParam(info->hint);
332                         else
333                                 throw invalidParam("Please specify a latex length expression");
334                 }
335                 if (!isValidLength(par))
336                         throw invalidParam("Invalid latex length expression for parameter " + name);
337                 return;
338         }
339         case ONEOF: {
340                 if (par.empty() && !info->onoff) {
341                         if (info->hint != "")
342                                 throw invalidParam(info->hint);
343                         else
344                                 throw invalidParam("Please specify one of " + string(info->info));
345                 }
346                 // break value to allowed strings
347                 vector<string> lists;
348                 string v;
349                 for (size_t i = 0; info->info[i] != '\0'; ++i) {
350                         if (info->info[i] == '\n') {
351                                 lists.push_back(v);
352                                 v = string();
353                         } else
354                                 v += info->info[i];
355                 }
356                 if (!v.empty())
357                         lists.push_back(v);
358
359                 // good, find the string
360                 if (std::find(lists.begin(), lists.end(), par) != lists.end())
361                         return;
362                 // otherwise, produce a meaningful error message.
363                 string matching_names;
364                 for (vector<string>::iterator it = lists.begin(); 
365                         it != lists.end(); ++it) {
366                         if (it->size() >= par.size() && it->substr(0, par.size()) == par) {
367                                 if (matching_names.empty())
368                                         matching_names += *it;
369                                 else
370                                         matching_names += ", " + *it;
371                         }
372                 }
373                 if (matching_names.empty())
374                         throw invalidParam("Try one of " + string(info->info));
375                 else
376                         throw invalidParam("I guess you mean " + matching_names);
377                 return;
378         }
379         case SUBSETOF: {
380                 if (par.empty() && !info->onoff) {
381                         if (info->hint != "")
382                                 throw invalidParam(info->hint);
383                         else
384                                 throw invalidParam("Please specify one or more of " + string(info->info));
385                 }
386                 for (size_t i = 0; i < par.size(); ++i)
387                         if (string(info->info).find(par[i], 0) == string::npos)
388                                 throw invalidParam("Parameter " + name + 
389                                         " should be composed of one or more of " + info->info);
390                 return;
391         }
392         }
393 }
394
395
396 InsetListingsParams::InsetListingsParams() :
397         inline_(false), status_(InsetCollapsable::Open), params_()
398 {
399 }
400
401
402 InsetListingsParams::InsetListingsParams(string const & par, bool in, InsetCollapsable::CollapseStatus s)
403         : inline_(in), status_(s)
404 {
405         // this will activate parameter validation.
406         fromEncodedString(par);
407 }
408
409
410 void InsetListingsParams::write(ostream & os) const
411 {
412         if (inline_)
413                 os << "true ";
414         else
415                 os << "false ";
416         os << status_ << " \""  << encodedString() << "\"";
417 }
418
419
420 void InsetListingsParams::read(Lexer & lex)
421 {
422         lex >> inline_;
423         int s;
424         lex >> s;
425         if (lex)
426                 status_ = static_cast<InsetCollapsable::CollapseStatus>(s);
427         string par;
428         lex >> par;
429         fromEncodedString(par);
430 }
431
432
433 void InsetListingsParams::addParam(string const & key, string const & value)
434 {       
435         if (key.empty())
436                 return;
437         // exception may be thown.
438         parValidator(key.c_str()).validate(value);
439         // duplicate parameters!
440         if (find(keys_.begin(), keys_.end(), key) != keys_.end())
441                 throw invalidParam("Parameter " + key + " has already been defined");   
442         else
443                 keys_.push_back(key);
444         if (!params_.empty())
445                 params_ += ',';
446         if (value.empty())
447                 params_ += key;
448         else {
449                 // check onoff flag
450                 size_t idx = 0;
451                 while (listings_param_table[idx].name != key)
452                         ++idx;
453                 BOOST_ASSERT(listings_param_table[idx].name == key);
454                 if (listings_param_table[idx].onoff && value == "false")
455                         params_ += key;
456                 else
457                         params_ += key + '=' + value;
458         }
459 }
460
461
462 void InsetListingsParams::addParams(string const & par)
463 {
464         string key;
465         string value;
466         bool isValue = false;
467         int braces = 0;
468         for (size_t i = 0; i < par.size(); ++i) {
469                 // end of par
470                 if (par[i] == '\n') {
471                         addParam(trim(key), trim(value));
472                         key = string();
473                         value = string();
474                         isValue = false;
475                         continue;
476                 } else if (par[i] == ',' && braces == 0) {
477                         addParam(trim(key), trim(value));
478                         key = string();
479                         value = string();
480                         isValue = false;
481                         continue;
482                 } else if (par[i] == '=' && braces == 0) {
483                         isValue = true;
484                         continue;
485                 } else if (par[i] == '{' && par[i - 1] == '=')
486                         braces ++;
487                 else if (par[i] == '}' && (i == par.size() - 1 || par[i + 1] == ','))
488                         braces --;
489                 
490                 if (isValue)
491                         value += par[i];
492                 else
493                         key += par[i];
494         }
495         if (!trim(key).empty())
496                 addParam(trim(key), trim(value));
497 }
498
499
500 void InsetListingsParams::setParams(string const & par)
501 {
502         params_.clear();
503         keys_.clear();
504         addParams(par);
505 }
506
507
508 string InsetListingsParams::encodedString() const
509 {
510         // Encode string!
511         // FIXME:
512         // '"' should be handled differently because it will 
513         // terminate a lyx token. Right now, it is silently ignored. 
514         string par;
515         for (size_t i = 0; i < params_.size(); ++i) {
516                 BOOST_ASSERT(params_[i] != '\n');
517                 if (params_[i] != '"')
518                         par += params_[i];
519         }
520         return par;
521 }
522
523
524 string InsetListingsParams::separatedParams(bool keepComma) const
525 {
526         // , might be used as regular parameter option so 
527         // the prcess might be more complicated than what I am doing here
528         string opt;
529         int braces = 0;
530         for (size_t i = 0; i < params_.size(); ++i)
531                 if (params_[i] == ',' && braces == 0) {
532                         if (keepComma)
533                                 opt += ",\n";
534                         else
535                                 opt += "\n";
536                 } else if (params_[i] == '{' && params_[i - 1] == '=') {
537                         braces ++;
538                         opt += params_[i];
539                 } else if (params_[i] == '}' && (i == params_.size() -1 || params_[i + 1] == ',')) {
540                         braces --;
541                         opt += params_[i];
542                 } else
543                         opt += params_[i];
544         return opt;
545 }
546
547
548 void InsetListingsParams::fromEncodedString(string const & in)
549 {
550         // Decode string! 
551         // Do nothing because " was silently ignored.
552         setParams(in);
553 }
554
555
556
557 } // namespace lyx