]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListingsParams.cpp
Make logic clearer, with help from Lars.
[lyx.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 "InsetListingsParams.h"
14
15 #include "gettext.h"
16 #include "Length.h"
17 #include "Lexer.h"
18
19 #include "support/lstrings.h"
20 #include "support/textutils.h"
21 #include "support/convert.h"
22
23 #include <boost/assert.hpp>
24
25 #include <sstream>
26
27 using std::map;
28 using std::vector;
29 using std::ostream;
30 using std::string;
31 using std::exception;
32
33 namespace lyx
34 {
35
36 using support::bformat;
37 using support::trim;
38 using support::subst;
39 using support::isStrInt;
40 using support::prefixIs;
41 using support::suffixIs;
42 using support::getVectorFromString;
43
44 namespace {
45
46 enum param_type {
47         ALL,  // accept all
48         TRUEFALSE, // accept 'true' or 'false'
49         INTEGER, // accept an integer
50         LENGTH,  // accept a latex length
51         ONEOF,  // accept one of a few values
52         SUBSETOF, // accept a string composed of given characters
53 };
54
55
56 /** Information about each parameter
57  */
58 struct listings_param_info {
59         /// name of the parameter
60         string name;
61         /// default value
62         string value;
63         // for option with value "true", "false",
64         // if onoff is true,
65         //   "true":  option
66         //   "false": 
67         //   "other": option="other"
68         // onoff is false,
69         //   "true":  option=true
70         //   "false": option=false
71         bool onoff;
72         /// validator type
73         // ALL:
74         // TRUEFALSE:
75         // INTEGER:
76         // LENGTH:
77         //     info is ignored.
78         // ONEOF
79         //     info is a \n separated string with allowed values
80         // SUBSETOF
81         //     info is a string from which par is composed of
82         //     (e.g. floatplacement can be one or more of *tbph)
83         param_type type;
84         /// parameter info, meaning depending on parameter type
85         string info;
86         /// a help message that is displayed in the gui
87         docstring hint;
88 };
89
90
91 /// languages and language/dialect combinations
92 char const * allowed_languages = 
93         "no language\nABAP\n[R/2 4.3]ABAP\n[R/2 5.0]ABAP\n[R/3 3.1]ABAP\n"
94         "[R/3 4.6C]ABAP\n[R/3 6.10]ABAP\nACSL\nAda\n[2005]Ada\n[83]Ada\n"
95         "[95]Ada\nALGOL\n[60]ALGOL\n[68]ALGOL\nAssembler\n"
96         "[Motorola68k]Assembler\n[x86masm]Assembler\nAwk\n[gnu]Awk\n[POSIX]Awk\n"
97         "bash\nBasic\n[Visual]Basic\nC\n[ANSI]C\n[Handel]C\n[Objective]C\n"
98         "[Sharp]C\nC++\n[ANSI]C++\n[GNU]C++\n[ISO]C++\n[Visual]C++\nCaml\n"
99         "[light]Caml\n[Objective]Caml\nClean\nCobol\n[1974]Cobol\n[1985]Cobol\n"
100         "[ibm]Cobol\nComal 80\ncommand.com\n[WinXP]command.com\nComsol\ncsh\n"
101         "Delphi\nEiffel\nElan\nEuphoria\nFortran\n[77]Fortran\n[90]Fortran\n"
102         "[95]Fortran\nGCL\nGnuplot\nHaskell\nHTML\nIDL\n[CORBA]IDL\ninform\n"
103         "Java\n[AspectJ]Java\nJVMIS\nksh\nLingo\nLisp\n[Auto]Lisp\nLogo\n"
104         "make\n[gnu]make\nMathematica\n[1.0]Mathematica\n[3.0]Mathematica\n"
105         "[5.2]Mathematica\nMatlab\nMercury\nMetaPost\nMiranda\nMizar\nML\n"
106         "Modula-2\nMuPAD\nNASTRAN\nOberon-2\nOCL\n[decorative]OCL\n[OMG]OCL\n"
107         "Octave\nOz\nPascal\n[Borland6]Pascal\n[Standard]Pascal\n[XSC]Pascal\n"
108         "Perl\nPHP\nPL/I\nPlasm\nPostScript\nPOV\nProlog\nPromela\nPSTricks\n"
109         "Python\nR\nReduce\nRexx\nRSL\nRuby\nS\n[PLUS]S\nSAS\nScilab\nsh\n"
110         "SHELXL\nSimula\n[67]Simula\n[CII]Simula\n[DEC]Simula\n[IBM]Simula\n"
111         "SPARQL\nSQL\ntcl\n[tk]tcl\nTeX\n[AlLaTeX]TeX\n[common]TeX\n[LaTeX]TeX\n"
112         "[plain]TeX\n[primitive]TeX\nVBScript\nVerilog\nVHDL\n[AMS]VHDL\nVRML\n"
113         "[97]VRML\nXML\nXSLT";
114
115 docstring const empty_hint;
116 docstring const style_hint = _("Use \\footnotesize, \\small, \\itshape, "
117                          "\\ttfamily or something like that");
118
119 docstring const frame_hint = _("none, leftline, topline, bottomline, lines, "
120                          "single, shadowbox or subset of trblTRBL");
121
122 docstring const frameround_hint = _("Enter four letters (either t = round "
123                               "or f = square) for top right, bottom "
124                               "right, bottom left and top left corner.");
125
126 docstring const color_hint = _("Enter something like \\color{white}");
127
128
129 /// options copied from page 26 of listings manual
130 // FIXME: add default parameters ... (which is not used now)
131 listings_param_info const listings_param_table[] = {
132         { "float", "false", true,  SUBSETOF, "*tbph", empty_hint},
133         { "floatplacement", "tbp", false, SUBSETOF, "tbp", empty_hint},
134         { "aboveskip", "\\medskipamount", false, LENGTH, "", empty_hint},
135         { "belowskip", "\\medskipamount", false, LENGTH, "", empty_hint},
136         { "lineskip", "", false, LENGTH, "", empty_hint},
137         { "boxpos", "", false, SUBSETOF, "bct", empty_hint},
138         { "print", "", false, TRUEFALSE, "", empty_hint},
139         { "firstline", "", false, INTEGER, "", empty_hint},
140         { "lastline", "", false, INTEGER, "", empty_hint},
141         { "showlines", "", false, TRUEFALSE, "", empty_hint},
142         { "emptylines", "", false, ALL, "", _("Expect a number with an optional * before it")},
143         { "gobble", "", false, INTEGER, "", empty_hint},
144         { "style", "", false, ALL, "", empty_hint},
145         { "language", "", false, ONEOF, allowed_languages, empty_hint},
146         { "alsolanguage", "", false, ONEOF, allowed_languages, empty_hint},
147         { "defaultdialect", "", false, ONEOF, allowed_languages, empty_hint},
148         { "printpod", "", false, TRUEFALSE, "", empty_hint},
149         { "usekeywordsintag", "", false, TRUEFALSE, "", empty_hint},
150         { "tagstyle", "", false, ALL, "", style_hint },
151         { "markfirstintag", "", false, ALL, "", style_hint },
152         { "makemacrouse", "", false, TRUEFALSE, "", empty_hint},
153         { "basicstyle", "", false, ALL, "", style_hint },
154         { "identifierstyle", "", false, ALL, "", style_hint },
155         { "commentstyle", "", false, ALL, "", style_hint },
156         { "stringstyle", "", false, ALL, "", style_hint },
157         { "keywordstyle", "", false, ALL, "", style_hint },
158         { "ndkeywordstyle", "", false, ALL, "", style_hint },
159         { "classoffset", "", false, INTEGER, "", empty_hint},
160         { "texcsstyle", "", false, ALL, "", style_hint },
161         { "directivestyle", "", false, ALL, "", style_hint },
162         { "emph", "", false, ALL, "", empty_hint},
163         { "moreemph", "", false, ALL, "", empty_hint},
164         { "deleteemph", "", false, ALL, "", empty_hint},
165         { "emphstyle", "", false, ALL, "", empty_hint},
166         { "delim", "", false, ALL, "", empty_hint},
167         { "moredelim", "", false, ALL, "", empty_hint},
168         { "deletedelim", "", false, ALL, "", empty_hint},
169         { "extendedchars", "", false, TRUEFALSE, "", empty_hint},
170         { "inputencoding", "", false, ALL, "", empty_hint},
171         { "upquote", "", false, TRUEFALSE, "", empty_hint},
172         { "tabsize", "", false, INTEGER, "", empty_hint},
173         { "showtabs", "", false, ALL, "", empty_hint},
174         { "tab", "", false, ALL, "", empty_hint},
175         { "showspaces", "", false, TRUEFALSE, "", empty_hint},
176         { "showstringspaces", "", false, TRUEFALSE, "", empty_hint},
177         { "formfeed", "", false, ALL, "", empty_hint},
178         { "numbers", "", false, ONEOF, "none\nleft\nright", empty_hint},
179         { "stepnumber", "", false, INTEGER, "", empty_hint},
180         { "numberfirstline", "", false, TRUEFALSE, "", empty_hint},
181         { "numberstyle", "", false, ALL, "", style_hint },
182         { "numbersep", "", false, LENGTH, "", empty_hint},
183         { "numberblanklines", "", false, ALL, "", empty_hint},
184         { "firstnumber", "", false, ALL, "", _("auto, last or a number") },
185         { "name", "", false, ALL, "", empty_hint},
186         { "thelstnumber", "", false, ALL, "", empty_hint},
187         { "title", "", false, ALL, "", empty_hint},
188         // this option is not handled in the parameter box
189         { "caption", "", false, ALL, "", _("This parameter should not be entered here. "
190                 "Please use caption editbox (Include dialog) or insert->caption (listings inset)") },
191         // this option is not handled in the parameter box
192         { "label", "", false, ALL, "", _("This parameter should not be entered here. "
193                 "Please use label editbox (Include dialog) or insert->caption (listings inset)") },
194         { "nolol", "", false, TRUEFALSE, "", empty_hint},
195         { "captionpos", "", false, SUBSETOF, "tb", empty_hint},
196         { "abovecaptionskip", "", false, LENGTH, "", empty_hint},
197         { "belowcaptionskip", "", false, LENGTH, "", empty_hint},
198         { "linewidth", "", false, LENGTH, "", empty_hint},
199         { "xleftmargin", "", false, LENGTH, "", empty_hint},
200         { "xrightmargin", "", false, LENGTH, "", empty_hint},
201         { "resetmargins", "", false, TRUEFALSE, "", empty_hint},
202         { "breaklines", "", false, TRUEFALSE, "", empty_hint},
203         { "prebreak", "", false, ALL, "", empty_hint},
204         { "postbreak", "", false, ALL, "", empty_hint},
205         { "breakindent", "", false, LENGTH, "", empty_hint},
206         { "breakautoindent", "", false, TRUEFALSE, "", empty_hint},
207         { "frame", "", false, ALL, "", frame_hint },
208         { "frameround", "", false, SUBSETOF, "tf", frameround_hint },
209         { "framesep", "", false, LENGTH, "", empty_hint},
210         { "rulesep", "", false, LENGTH, "", empty_hint},
211         { "framerule", "", false, LENGTH, "", empty_hint},
212         { "framexleftmargin", "", false, LENGTH, "", empty_hint},
213         { "framexrightmargin", "", false, LENGTH, "", empty_hint},
214         { "framextopmargin", "", false, LENGTH, "", empty_hint},
215         { "framexbottommargin", "", false, LENGTH, "", empty_hint},
216         { "backgroundcolor", "", false, ALL, "", color_hint },
217         { "rulecolor", "", false, ALL, "", color_hint },
218         { "fillcolor", "", false, ALL, "", color_hint },
219         { "rulesepcolor", "", false, ALL, "", color_hint },
220         { "frameshape", "", false, ALL, "", empty_hint},
221         { "index", "", false, ALL, "", empty_hint},
222         { "moreindex", "", false, ALL, "", empty_hint},
223         { "deleteindex", "", false, ALL, "", empty_hint},
224         { "indexstyle", "", false, ALL, "", empty_hint},
225         { "columns", "", false, ALL, "", empty_hint},
226         { "flexiblecolumns", "", false, ALL, "", empty_hint},
227         { "keepspaces", "", false, TRUEFALSE, "", empty_hint},
228         { "basewidth", "", false, LENGTH, "", empty_hint},
229         { "fontadjust", "", true, TRUEFALSE, "", empty_hint},
230         { "texcl", "", false, TRUEFALSE, "", empty_hint},
231         { "mathescape", "", false, TRUEFALSE, "", empty_hint},
232         { "escapechar", "", false, ALL, "", empty_hint},
233         { "escapeinside", "", false, ALL, "", empty_hint},
234         { "escepeinside", "", false, ALL, "", empty_hint},
235         { "escepebegin", "", false, ALL, "", empty_hint},
236         { "escepeend", "", false, ALL, "", empty_hint},
237         { "fancyvrb", "", false, TRUEFALSE, "", empty_hint},
238         { "fvcmdparams", "", false, ALL, "", empty_hint},
239         { "morefvcmdparams", "", false, ALL, "", empty_hint},
240         { "keywordsprefix", "", false, ALL, "", empty_hint},
241         { "keywords", "", false, ALL, "", empty_hint},
242         { "morekeywords", "", false, ALL, "", empty_hint},
243         { "deletekeywords", "", false, ALL, "", empty_hint},
244         { "ndkeywords", "", false, ALL, "", empty_hint},
245         { "morendkeywords", "", false, ALL, "", empty_hint},
246         { "deletendkeywords", "", false, ALL, "", empty_hint},
247         { "texcs", "", false, ALL, "", empty_hint},
248         { "moretexcs", "", false, ALL, "", empty_hint},
249         { "deletetexcs", "", false, ALL, "", empty_hint},
250         { "directives", "", false, ALL, "", empty_hint},
251         { "moredirectives", "", false, ALL, "", empty_hint},
252         { "deletedirectives", "", false, ALL, "", empty_hint},
253         { "sensitive", "", false, ALL, "", empty_hint},
254         { "alsoletter", "", false, ALL, "", empty_hint},
255         { "alsodigit", "", false, ALL, "", empty_hint},
256         { "alsoother", "", false, ALL, "", empty_hint},
257         { "otherkeywords", "", false, ALL, "", empty_hint},
258         { "tag", "", false, ALL, "", empty_hint},
259         { "string", "", false, ALL, "", empty_hint},
260         { "morestring", "", false, ALL, "", empty_hint},
261         { "deletestring", "", false, ALL, "", empty_hint},
262         { "comment", "", false, ALL, "", empty_hint},
263         { "morecomment", "", false, ALL, "", empty_hint},
264         { "deletecomment", "", false, ALL, "", empty_hint},
265         { "keywordcomment", "", false, ALL, "", empty_hint},
266         { "morekeywordcomment", "", false, ALL, "", empty_hint},
267         { "deletekeywordcomment", "", false, ALL, "", empty_hint},
268         { "keywordcommentsemicolon", "", false, ALL, "", empty_hint},
269         { "podcomment", "", false, ALL, "", empty_hint},
270         { "", "", false, ALL, "", empty_hint}
271 };
272
273
274 class parValidator
275 {
276 public:
277         parValidator(string const & name);
278
279         /// validate given parameter
280         /// invalidParam will be thrown if invalid 
281         /// parameter is found.
282         void validate(std::string const & par) const;
283
284 private:
285         /// parameter name
286         string const & name;
287         ///
288         listings_param_info const * info;
289 };
290
291
292 parValidator::parValidator(string const & n)
293         : name(n), info(0)
294 {
295         if (name.empty())
296                 throw invalidParam(_("Invalid (empty) listings param name."));
297         else if (name == "?") {
298                 string pars;
299                 size_t idx = 0;
300                 while (listings_param_table[idx].name != string()) {
301                         if (!pars.empty())
302                                 pars += ", ";
303                         pars += listings_param_table[idx].name;
304                         ++idx;
305                 }
306                 throw invalidParam(bformat(
307                         _("Available listings parameters are %1$s"), from_utf8(pars)));
308         }
309         // locate name in parameter table
310         size_t idx = 0;
311         while (listings_param_table[idx].name != name && listings_param_table[idx].name != string())
312                 ++idx;
313         // found the name
314         if (!listings_param_table[idx].name.empty()) {
315                 info = &listings_param_table[idx];
316                 return;
317         }
318         // otherwise, produce a meaningful error message.
319         string matching_names;
320         for (size_t i = 0; i < idx; ++i) {
321                 string n(listings_param_table[i].name);
322                 if (prefixIs(n, name)) {
323                         if (matching_names.empty())
324                                 matching_names += n;
325                         else
326                                 matching_names += ", " + n;
327                 }
328         }
329         if (matching_names.empty())
330                 throw invalidParam(bformat(_("Unknown listings param name: %1$s"),
331                                                     from_utf8(name)));
332         else
333                 throw invalidParam(bformat(_("Parameters starting with '%1$s': %2$s"),
334                                                     from_utf8(name), from_utf8(matching_names)));
335 }
336
337
338 void parValidator::validate(std::string const & par) const
339 {
340         bool unclosed = false;
341         string par2 = par;
342         // braces are allowed
343         if (prefixIs(par, "{") && suffixIs(par, "}"))
344                 par2 = par.substr(1, par.size() - 2);
345         else if (prefixIs(par, "{")) {
346                 par2 = par.substr(1);
347                 unclosed = true;
348         }
349         
350                 
351         switch (info->type) {
352         case ALL:
353                 if (par2.empty() && !info->onoff) {
354                         if (!info->hint.empty())
355                                 throw invalidParam(info->hint);
356                         else
357                                 throw invalidParam(_("A value is expected"));
358                 }
359                 if (unclosed)
360                                 throw invalidParam(_("Unbalanced braces!"));
361                 return;
362         case TRUEFALSE: {
363                 if (par2.empty() && !info->onoff) {
364                         if (!info->hint.empty())
365                                 throw invalidParam(info->hint);
366                         else
367                                 throw invalidParam(_("Please specify true or false"));
368                 }
369                 if (par2 != "true" && par2 != "false")
370                         throw invalidParam(bformat(_("Only true or false is allowed for parameter %1$s"),
371                                                    from_utf8(name)));
372                 if (unclosed)
373                                 throw invalidParam(_("Unbalanced braces!"));
374                 return;
375         }
376         case INTEGER: {
377                 if (!isStrInt(par2)) {
378                         if (!info->hint.empty())
379                                 throw invalidParam(info->hint);
380                         else
381                                 throw invalidParam(_("Please specify an integer value"));
382                 }
383                 if (convert<int>(par2) == 0 && par2[0] != '0')
384                         throw invalidParam(bformat(_("An integer is expected for parameter %1$s"),
385                                                    from_utf8(name)));
386                 if (unclosed)
387                                 throw invalidParam(_("Unbalanced braces!"));
388                 return;
389         }
390         case LENGTH: {
391                 if (par2.empty() && !info->onoff) {
392                         if (!info->hint.empty())
393                                 throw invalidParam(info->hint);
394                         else
395                                 throw invalidParam(_("Please specify a latex length expression"));
396                 }
397                 if (!isValidLength(par2))
398                         throw invalidParam(bformat(_("Invalid latex length expression for parameter %1$s"),
399                                                    from_utf8(name)));
400                 if (unclosed)
401                                 throw invalidParam(_("Unbalanced braces!"));
402                 return;
403         }
404         case ONEOF: {
405                 if (par2.empty() && !info->onoff) {
406                         if (!info->hint.empty())
407                                 throw invalidParam(info->hint);
408                         else
409                                 throw invalidParam(bformat(_("Please specify one of %1$s"),
410                                                            from_utf8(string(info->info))));
411                 }
412                 // break value to allowed strings
413                 vector<string> lists;
414                 string v;
415                 for (size_t i = 0; info->info[i] != '\0'; ++i) {
416                         if (info->info[i] == '\n') {
417                                 lists.push_back(v);
418                                 v = string();
419                         } else
420                                 v += info->info[i];
421                 }
422                 if (!v.empty())
423                         lists.push_back(v);
424
425                 // good, find the string
426                 if (std::find(lists.begin(), lists.end(), par2) != lists.end()) {
427                         if (unclosed)
428                                 throw invalidParam(_("Unbalanced braces!"));
429                         return;
430                 }
431                 // otherwise, produce a meaningful error message.
432                 string matching_names;
433                 for (vector<string>::iterator it = lists.begin(); 
434                         it != lists.end(); ++it) {
435                         if (it->size() >= par2.size() && it->substr(0, par2.size()) == par2) {
436                                 if (matching_names.empty())
437                                         matching_names += *it;
438                                 else
439                                         matching_names += ", " + *it;
440                         }
441                 }
442                 if (matching_names.empty())
443                         throw invalidParam(bformat(_("Try one of %1$s"),
444                                                    from_utf8(string(info->info))));
445                 else
446                         throw invalidParam(bformat(_("I guess you mean %1$s"),
447                                                    from_utf8(matching_names)));
448                 return;
449         }
450         case SUBSETOF: {
451                 if (par2.empty() && !info->onoff) {
452                         if (!info->hint.empty())
453                                 throw invalidParam(info->hint);
454                         else
455                                 throw invalidParam(bformat(_("Please specify one or more of '%1$s'"),
456                                                            from_utf8(string(info->info))));
457                 }
458                 for (size_t i = 0; i < par2.size(); ++i)
459                         if (string(info->info).find(par2[i], 0) == string::npos)
460                                 throw invalidParam(
461                                         bformat(_("Parameter %1$s should be composed of one or more of %2$s"),
462                                                 from_utf8(name), from_utf8(info->info)));
463                 if (unclosed)
464                                 throw invalidParam(_("Unbalanced braces!"));
465                 return;
466         }
467         }
468 }
469
470 } // namespace anon.
471
472 InsetListingsParams::InsetListingsParams() :
473         inline_(false), params_(), status_(InsetCollapsable::Open)
474 {
475 }
476
477
478 InsetListingsParams::InsetListingsParams(string const & par, bool in, InsetCollapsable::CollapseStatus s)
479         : inline_(in), params_(), status_(s)
480 {
481         // this will activate parameter validation.
482         fromEncodedString(par);
483 }
484
485
486 void InsetListingsParams::write(ostream & os) const
487 {
488         if (inline_)
489                 os << "true ";
490         else
491                 os << "false ";
492         os << status_ << " \""  << encodedString() << "\"";
493 }
494
495
496 void InsetListingsParams::read(Lexer & lex)
497 {
498         lex >> inline_;
499         int s;
500         lex >> s;
501         if (lex)
502                 status_ = static_cast<InsetCollapsable::CollapseStatus>(s);
503         string par;
504         lex >> par;
505         fromEncodedString(par);
506 }
507
508
509 string InsetListingsParams::params(string const & sep) const
510 {
511         string par;
512         for (map<string, string>::const_iterator it = params_.begin();
513                 it != params_.end(); ++it) {
514                 if (!par.empty())
515                         par += sep;
516                 if (it->second.empty())
517                         par += it->first;
518                 else
519                         par += it->first + '=' + it->second;
520         }
521         return par;
522 }
523
524
525 void InsetListingsParams::addParam(string const & key, string const & value)
526 {       
527         if (key.empty())
528                 return;
529         // exception may be thown.
530         parValidator(key).validate(value);
531         // duplicate parameters!
532         if (params_.find(key) != params_.end())
533                 throw invalidParam(bformat(_("Parameter %1$s has already been defined"),
534                                           from_utf8(key)));
535         // check onoff flag
536         size_t idx = 0;
537         while (listings_param_table[idx].name != key)
538                 ++idx;
539         BOOST_ASSERT(listings_param_table[idx].name == key);
540         // onoff parameter with value false
541         if (listings_param_table[idx].onoff && (value == "false" || value == "{false}"))
542                 params_[key] = string();
543         // if the parameter is surrounded with {}, good
544         else if (prefixIs(value, "{") && suffixIs(value, "}"))
545                 params_[key] = value;
546         // otherwise, check if {} is needed. Add {} to all values with 
547         // non-ascii/number characters, just to be safe
548         else {
549                 bool has_special_char = false;
550                 for (size_t i = 0; i < value.size(); ++i)
551                         if (!isAlphaASCII(value[i]) && !isDigit(value[i])) {
552                                 has_special_char = true;
553                                 break;
554                         }
555                 if (has_special_char)
556                         params_[key] = "{" + value + "}";
557                 else
558                         params_[key] = value;
559         }
560 }
561
562
563 void InsetListingsParams::addParams(string const & par)
564 {
565         string key;
566         string value;
567         bool isValue = false;
568         int braces = 0;
569         for (size_t i = 0; i < par.size(); ++i) {
570                 // end of par
571                 if (par[i] == '\n') {
572                         addParam(trim(key), trim(value));
573                         key = string();
574                         value = string();
575                         isValue = false;
576                         continue;
577                 } else if (par[i] == ',' && braces == 0) {
578                         addParam(trim(key), trim(value));
579                         key = string();
580                         value = string();
581                         isValue = false;
582                         continue;
583                 } else if (par[i] == '=' && braces == 0) {
584                         isValue = true;
585                         continue;
586                 } else if (par[i] == '{' && par[i - 1] == '=')
587                         braces ++;
588                 else if (par[i] == '}' && (i == par.size() - 1 || par[i + 1] == ',' || par[i + 1] == '\n'))
589                         braces --;
590                 
591                 if (isValue)
592                         value += par[i];
593                 else
594                         key += par[i];
595         }
596         if (!trim(key).empty())
597                 addParam(trim(key), trim(value));
598 }
599
600
601 void InsetListingsParams::setParams(string const & par)
602 {
603         params_.clear();
604         addParams(par);
605 }
606
607
608 string InsetListingsParams::encodedString() const
609 {
610         // Encode string!
611         // '"' is handled differently because it will 
612         // terminate a lyx token.
613         string par = params();
614         // '"' is now &quot;  ==> '"' is now &amp;quot;
615         par = subst(par, "&", "&amp;");
616         // '"' is now &amp;quot; ==> '&quot;' is now &amp;quot;
617         par = subst(par, "\"", "&quot;");
618         return par;     
619 }
620
621
622 string InsetListingsParams::separatedParams(bool keepComma) const
623 {
624         if (keepComma)
625                 return params(",\n");
626         else
627                 return params("\n");
628 }
629
630
631 void InsetListingsParams::fromEncodedString(string const & in)
632 {
633         // Decode string! Reversal of encodedString
634         string par = in;
635         // '&quot;' is now &amp;quot; ==> '"' is now &amp;quot;
636         par = subst(par, "&quot;", "\"");
637         //  '"' is now &amp;quot; ==> '"' is now &quot;
638         par = subst(par, "&amp;", "&");
639         setParams(par);
640 }
641
642
643 bool InsetListingsParams::isFloat() const
644 {
645         return params_.find("float") != params_.end();
646 }
647
648
649 string InsetListingsParams::getParamValue(string const & param) const
650 {
651         // is this parameter defined?
652         map<string, string>::const_iterator it = params_.find(param);
653         return (it == params_.end()) ? string() : it->second;
654 }
655
656
657 } // namespace lyx