]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Rename LATEX debug level to OUTFILE and use it for DocBook, HTML, and XML messages.
[lyx.git] / src / insets / InsetListings.cpp
1 /**
2  * \file InsetListings.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  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "InsetListings.h"
15
16 #include "Buffer.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
19 #include "Cursor.h"
20 #include "Encoding.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "InsetCaption.h"
24 #include "InsetLabel.h"
25 #include "InsetLayout.h"
26 #include "Language.h"
27 #include "LaTeXFeatures.h"
28 #include "Lexer.h"
29 #include "output_latex.h"
30 #include "output_docbook.h"
31 #include "output_xhtml.h"
32 #include "TexRow.h"
33 #include "texstream.h"
34
35 #include "support/debug.h"
36 #include "support/docstream.h"
37 #include "support/gettext.h"
38 #include "support/lstrings.h"
39 #include "support/lassert.h"
40
41 #include "frontends/alert.h"
42 #include "frontends/Application.h"
43
44 #include <cstring>
45 #include <regex>
46 #include <sstream>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53
54 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
55         : InsetCaptionable(buf,"listing")
56 {
57         params_.setMinted(buffer().params().use_minted);
58         status_ = par.status();
59 }
60
61
62 InsetListings::~InsetListings()
63 {
64         hideDialogs("listings", this);
65 }
66
67
68 int InsetListings::rowFlags() const
69 {
70         return params().isInline() || params().isFloat() ? Inline : Display | AlignLeft;
71 }
72
73
74 docstring InsetListings::layoutName() const
75 {
76         if (buffer().params().use_minted)
77                 return from_ascii("MintedListings");
78         else
79                 return from_ascii("Listings");
80 }
81
82
83 void InsetListings::write(ostream & os) const
84 {
85         os << "listings" << "\n";
86         InsetListingsParams const & par = params();
87         // parameter string is encoded to be a valid lyx token.
88         string opt = par.encodedString();
89         if (!opt.empty())
90                 os << "lstparams \"" << opt << "\"\n";
91         if (par.isInline())
92                 os << "inline true\n";
93         else
94                 os << "inline false\n";
95         InsetCaptionable::write(os);
96 }
97
98
99 void InsetListings::read(Lexer & lex)
100 {
101         while (lex.isOK()) {
102                 lex.next();
103                 string token = lex.getString();
104                 if (token == "lstparams") {
105                         lex.next();
106                         string const value = lex.getString();
107                         params().fromEncodedString(value);
108                 } else if (token == "inline") {
109                         lex.next();
110                         params().setInline(lex.getBool());
111                 } else {
112                         // no special option, push back 'status' etc
113                         lex.pushToken(token);
114                         break;
115                 }
116         }
117         InsetCaptionable::read(lex);
118 }
119
120
121 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
122                                                Encoding const * outer_enc) const
123 {
124         // The listings package cannot deal with multi-byte-encoded
125         // glyphs, except for Xe/LuaTeX (with non-TeX fonts) or pLaTeX.
126         // Minted can deal with all encodings.
127         if (buffer().params().use_minted
128                 || inner_enc->name() == "utf8-plain"
129                 || inner_enc->package() == Encoding::japanese
130                 || inner_enc->hasFixedWidth())
131                 return 0;
132
133         // We try if there's a singlebyte encoding for the outer
134         // language; if not, fall back to latin1.
135         // Power-users can set inputenc to utf8-plain to bypass this workaround
136         // and provide alternatives in the user-preamble.
137         return (outer_enc->hasFixedWidth()) ?
138                         outer_enc : encodings.fromLyXName("iso8859-1");
139 }
140
141
142 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
143 {
144         string param_string = params().params();
145         // NOTE: I use {} to quote text, which is an experimental feature
146         // of the listings package (see page 25 of the manual)
147         bool const isInline = params().isInline();
148         bool const use_minted = buffer().params().use_minted;
149         static regex const reg1("(.*)(basicstyle=\\{)([^\\}]*)(\\\\ttfamily)([^\\}]*)(\\})(.*)");
150         static regex const reg2("(.*)(basicstyle=\\{)([^\\}]*)(\\\\rmfamily)([^\\}]*)(\\})(.*)");
151         static regex const reg3("(.*)(basicstyle=\\{)([^\\}]*)(\\\\sffamily)([^\\}]*)(\\})(.*)");
152         static regex const reg4("(.*)(basicstyle=\\{)([^\\}]*)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))([^\\}]*)(\\})(.*)");
153         static regex const reg5("(.*)(fontfamily=)(tt|sf|rm)(.*)");
154         static regex const reg6("(.*)(fontsize=\\{)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))(\\})(.*)");
155         if (use_minted) {
156                 // If params have been entered with "listings", and then the user switched to "minted",
157                 // we have params that need to be translated.
158                 // FIXME: We should use a backend-abstract syntax in listings params instead!
159                 // Substitute fontstyle option
160                 smatch sub;
161                 if (regex_match(param_string, sub, reg1))
162                         param_string = sub.str(1) + "fontfamily=tt," + sub.str(2) + sub.str(3)
163                                         + sub.str(5) + sub.str(6) + sub.str(7);
164                 if (regex_match(param_string, sub, reg2))
165                         param_string = sub.str(1) + "fontfamily=rm," + sub.str(2) + sub.str(3)
166                                         + sub.str(5) + sub.str(6) + sub.str(7);
167                 if (regex_match(param_string, sub, reg3))
168                         param_string = sub.str(1) + "fontfamily=sf," + sub.str(2) + sub.str(3)
169                                         + sub.str(5) + sub.str(6) + sub.str(7);
170                 // as well as fontsize option
171                 if (regex_match(param_string, sub, reg4))
172                         param_string = sub.str(1) + "fontsize={" + sub.str(4) + sub.str(3) + sub.str(7) + sub.str(8);
173         } else {
174                 // And the same vice versa
175                 // Substitute fontstyle option
176                 smatch sub;
177                 string basicstyle;
178                 if (regex_match(param_string, sub, reg5)) {
179                         basicstyle = "\\" + sub.str(3) + "family";
180                         param_string = sub.str(1) + sub.str(4);
181                 }
182                 // as well as fontsize option
183                 if (regex_match(param_string, sub, reg6)) {
184                         basicstyle += sub.str(3);
185                         param_string = sub.str(1) + sub.str(6);
186                 }
187                 if (!basicstyle.empty())
188                         param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
189         }
190         if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
191                 // We need to use the *latin switches (#11554)
192                 smatch sub;
193                 if (regex_match(param_string, sub, reg1))
194                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
195                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
196                 if (regex_match(param_string, sub, reg2))
197                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
198                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
199                 if (regex_match(param_string, sub, reg3))
200                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
201                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
202         }
203         string minted_language;
204         string float_placement;
205         bool const isfloat = params().isFloat();
206         if (use_minted && (isfloat || contains(param_string, "language="))) {
207                 // Get float placement and/or language of the code,
208                 // then remove the relative options.
209                 vector<string> opts =
210                         getVectorFromString(param_string, ",", false);
211                 for (size_t i = 0; i < opts.size(); ++i) {
212                         if (prefixIs(opts[i], "float")) {
213                                 if (prefixIs(opts[i], "float="))
214                                         float_placement = opts[i].substr(6);
215                                 opts.erase(opts.begin() + int(i--));
216                         }
217                         else if (prefixIs(opts[i], "language=")) {
218                                 minted_language = opts[i].substr(9);
219                                 opts.erase(opts.begin() + int(i--));
220                         }
221                 }
222                 param_string = getStringFromVector(opts, ",");
223         }
224         // Minted needs a language specification
225         if (minted_language.empty()) {
226                 // If a language has been set globally, use that,
227                 // otherwise use TeX by default
228                 string const & blp = buffer().params().listings_params;
229                 size_t start = blp.find("language=");
230                 if (start != string::npos) {
231                         start += strlen("language=");
232                         size_t len = blp.find(",", start);
233                         if (len != string::npos)
234                                 len -= start;
235                         minted_language = blp.substr(start, len);
236                 } else
237                         minted_language = "TeX";
238         }
239
240         // get the paragraphs. We can not output them directly to given odocstream
241         // because we can not yet determine the delimiter character of \lstinline
242         docstring code;
243         docstring uncodable;
244         ParagraphList::const_iterator par = paragraphs().begin();
245         ParagraphList::const_iterator end = paragraphs().end();
246
247         bool encoding_switched = false;
248         Encoding const * const save_enc = runparams.encoding;
249
250         Encoding const * const outer_encoding =
251                 (runparams.local_font != 0) ?
252                         runparams.local_font->language()->encoding()
253                         : buffer().params().language->encoding();
254         Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
255         if (fixedlstenc) {
256                 // We need to switch to a singlebyte encoding, due to
257                 // the restrictions of the listings package (see above).
258                 // This needs to be consistent with
259                 // LaTeXFeatures::getTClassI18nPreamble().
260                 // We need to put this into a group in order to prevent encoding leaks
261                 // (happens with cprotect).
262                 os << "\\bgroup";
263                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
264                 runparams.encoding = fixedlstenc;
265                 encoding_switched = true;
266         }
267
268         bool const captionfirst = !isfloat && par->isInset(0)
269                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
270
271         while (par != end) {
272                 pos_type const siz = par->size();
273                 bool captionline = false;
274                 for (pos_type i = 0; i < siz; ++i) {
275                         if (i == 0 && par->isInset(i) && i + 1 == siz)
276                                 captionline = true;
277                         // ignore all struck out text and (caption) insets
278                         if (par->isDeleted(i)
279                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
280                                 continue;
281                         if (par->isInset(i)) {
282                                 // Currently, this can only be a quote inset
283                                 // that is output as plain quote here, but
284                                 // we use more generic code anyway.
285                                 otexstringstream ots;
286                                 OutputParams rp = runparams;
287                                 rp.pass_thru = true;
288                                 par->getInset(i)->latex(ots, rp);
289                                 code += ots.str();
290                                 continue;
291                         }
292                         char_type c = par->getChar(i);
293                         // we can only output characters covered by the current
294                         // encoding!
295                         try {
296                                 if (runparams.encoding->encodable(c))
297                                         code += c;
298                                 else if (runparams.dryrun) {
299                                         code += "<" + _("LyX Warning: ")
300                                            + _("uncodable character") + " '";
301                                         code += docstring(1, c);
302                                         code += "'>";
303                                 } else
304                                         uncodable += c;
305                         } catch (EncodingException & /* e */) {
306                                 if (runparams.dryrun) {
307                                         code += "<" + _("LyX Warning: ")
308                                            + _("uncodable character") + " '";
309                                         code += docstring(1, c);
310                                         code += "'>";
311                                 } else
312                                         uncodable += c;
313                         }
314                 }
315                 ++par;
316                 // Add new line between paragraphs in displayed listings.
317                 // Exception: merged paragraphs in change tracking mode.
318                 // Also, for the inline case, if there are multiple paragraphs
319                 // they are simply joined. Otherwise, expect latex errors.
320                 if (par != end && !isInline && !captionline && !par->parEndChange().deleted())
321                         code += "\n";
322         }
323         if (isInline) {
324                 static const docstring delimiters =
325                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
326
327                 size_t pos = delimiters.find_first_not_of(code);
328
329                 // This code piece contains all possible special character? !!!
330                 // Replace ! with a warning message and use ! as delimiter.
331                 if (pos == string::npos) {
332                         docstring delim_error = "<" + _("LyX Warning: ")
333                                 + _("no more lstline delimiters available") + ">";
334                         code = subst(code, from_ascii("!"), delim_error);
335                         pos = 0;
336                         if (!runparams.dryrun && !runparams.silent) {
337                                 // FIXME: warning should be passed to the error dialog
338                                 frontend::Alert::warning(_("Running out of delimiters"),
339                                 _("For inline program listings, one character must be reserved\n"
340                                   "as a delimiter. One of the listings, however, uses all available\n"
341                                   "characters, so none is left for delimiting purposes.\n"
342                                   "For the time being, I have replaced '!' by a warning, but you\n"
343                                   "must investigate!"));
344                         }
345                 }
346                 docstring const delim(1, delimiters[pos]);
347                 if (use_minted) {
348                         os << "\\mintinline";
349                         if (!param_string.empty())
350                                 os << "[" << from_utf8(param_string) << "]";
351                         os << "{" << ascii_lowercase(minted_language) << "}";
352                 } else {
353                         os << "\\lstinline";
354                         if (!param_string.empty())
355                                 os << "[" << from_utf8(param_string) << "]";
356                         else if (pos >= delimiters.find('Q'))
357                                 // We need to terminate the command before
358                                 // the delimiter
359                                 os << " ";
360                 }
361                 os << delim << code << delim;
362         } else if (use_minted) {
363                 OutputParams rp = runparams;
364                 rp.moving_arg = true;
365                 TexString caption = getCaption(rp);
366                 if (isfloat) {
367                         os << breakln << "\\begin{listing}";
368                         if (!float_placement.empty())
369                                 os << '[' << float_placement << "]";
370                 } else if (captionfirst && !caption.str.empty()) {
371                         os << breakln << "\\lyxmintcaption[t]{"
372                            << move(caption) << "}\n";
373                 }
374                 os << breakln << "\\begin{minted}";
375                 if (!param_string.empty())
376                         os << "[" << param_string << "]";
377                 os << "{" << ascii_lowercase(minted_language) << "}\n"
378                    << code << breakln << "\\end{minted}\n";
379                 if (isfloat) {
380                         if (!caption.str.empty())
381                                 os << "\\caption{" << move(caption) << "}\n";
382                         os << "\\end{listing}\n";
383                 } else if (!captionfirst && !caption.str.empty()) {
384                         os << breakln << "\\lyxmintcaption[b]{"
385                            << move(caption) << "}";
386                 }
387         } else {
388                 OutputParams rp = runparams;
389                 rp.moving_arg = true;
390                 TexString caption = getCaption(rp);
391                 os << breakln << "\\begin{lstlisting}";
392                 if (param_string.empty() && caption.str.empty())
393                         os << "\n";
394                 else {
395                         if (!runparams.nice)
396                                 os << safebreakln;
397                         os << "[";
398                         if (!caption.str.empty()) {
399                                 os << "caption={" << move(caption) << '}';
400                                 if (!param_string.empty())
401                                         os << ',';
402                         }
403                         os << from_utf8(param_string) << "]\n";
404                 }
405                 os << code << breakln << "\\end{lstlisting}\n";
406         }
407
408         if (encoding_switched){
409                 // Switch back
410                 switchEncoding(os.os(), buffer().params(),
411                                runparams, *save_enc, true, true);
412                 os << "\\egroup" << breakln;
413                 runparams.encoding = save_enc;
414         }
415
416         if (!uncodable.empty() && !runparams.silent) {
417                 // issue a warning about omitted characters
418                 // FIXME: should be passed to the error dialog
419                 if (fixedlstenc)
420                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
421                                 bformat(_("The following characters in one of the program listings are\n"
422                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
423                                           "This is due to a restriction of the listings package, which does\n"
424                                           "not support your encoding '%2$s'.\n"
425                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
426                                           "might help."),
427                                 uncodable, _(runparams.encoding->guiName())));
428                 else
429                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
430                                 bformat(_("The following characters in one of the program listings are\n"
431                                           "not representable in the current encoding and have been omitted:\n%1$s."),
432                                 uncodable));
433         }
434 }
435
436
437 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
438 {
439         odocstringstream ods;
440         XMLStream out(ods);
441
442         bool const isInline = params().isInline();
443         if (isInline)
444                 out << xml::CompTag("br");
445         else {
446                 out << xml::StartTag("div", "class='float-listings'");
447                 docstring caption = getCaptionHTML(rp);
448                 if (!caption.empty())
449                         out << xml::StartTag("div", "class='listings-caption'")
450                             << XMLStream::ESCAPE_NONE
451                             << caption << xml::EndTag("div");
452         }
453
454         InsetLayout const & il = getLayout();
455         string const & tag = il.htmltag();
456         string attr = "class ='listings";
457         string const lang = params().getParamValue("language");
458         if (!lang.empty())
459                 attr += " " + lang;
460         attr += "'";
461         out << xml::StartTag(tag, attr);
462         OutputParams newrp = rp;
463         newrp.html_disable_captions = true;
464         // We don't want to convert dashes here. That's the only conversion we
465         // do for XHTML, so this is safe.
466         newrp.pass_thru = true;
467         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
468         out << xml::EndTag(tag);
469
470         if (isInline) {
471                 out << xml::CompTag("br");
472                 // escaping will already have been done
473                 os << XMLStream::ESCAPE_NONE << ods.str();
474         } else {
475                 out << xml::EndTag("div");
476                 // In this case, this needs to be deferred, but we'll put it
477                 // before anything the text itself deferred.
478                 def = ods.str() + '\n' + def;
479         }
480         return def;
481 }
482
483
484 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
485 {
486         InsetLayout const & il = getLayout();
487         bool isInline = params().isInline();
488
489         if (!isInline && !xs.isLastTagCR())
490                 xs << xml::CR();
491
492         // In case of caption, the code must be wrapped, for instance in a figure. Also detect if there is a label.
493         // http://www.sagehill.net/docbookxsl/ProgramListings.html
494         // TODO: parts of this code could be merged with InsetFloat and findLabelInParagraph.
495         InsetCaption const * caption = getCaptionInset();
496         if (caption) {
497                 InsetLabel const * label = getLabelInset();
498
499                 // Ensure that the label will not be output a second time as an anchor.
500                 OutputParams rpNoLabel = rp;
501                 if (label)
502                         rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
503
504                 // Prepare the right set of attributes, including the label.
505                 docstring attr = from_ascii("type='listing'");
506                 if (label)
507                         attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
508
509                 // Finally, generate the wrapper (including the label).
510                 xs << xml::StartTag("figure", attr);
511                 xs << xml::CR();
512                 xs << xml::StartTag("title");
513                 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
514                 xs << xml::EndTag("title");
515                 xs << xml::CR();
516         }
517
518         // Forge the attributes.
519         std::string attrs;
520         if (!il.docbookattr().empty())
521                 attrs += " role=\"" + il.docbookattr() + "\"";
522         std::string const lang = params().getParamValue("language");
523         if (!lang.empty())
524                 attrs += " language=\"" + lang + "\"";
525
526         // Determine the tag to use. Use the layout-defined value if outside a paragraph.
527         std::string tag = il.docbooktag();
528         if (isInline)
529                 tag = "code";
530
531         // Start the listing.
532         xs << xml::StartTag(tag, attrs);
533         xs.startDivision(false);
534
535         // Deal with the content of the listing.
536         OutputParams newrp = rp;
537         newrp.pass_thru = true;
538         newrp.docbook_make_pars = false;
539         newrp.par_begin = 0;
540         newrp.par_end = text().paragraphs().size();
541         newrp.docbook_in_listing = true;
542
543         docbookParagraphs(text(), buffer(), xs, newrp);
544
545         // Done with the listing.
546         xs.endDivision();
547         xs << xml::EndTag(tag);
548         if (!isInline)
549                 xs << xml::CR();
550
551         if (caption) {
552                 xs << xml::EndTag("figure");
553                 xs << xml::CR();
554         }
555 }
556
557
558 string InsetListings::contextMenuName() const
559 {
560         return "context-listings";
561 }
562
563
564 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
565 {
566         switch (cmd.action()) {
567
568         case LFUN_INSET_MODIFY: {
569                 cur.recordUndoInset(this);
570                 InsetListings::string2params(to_utf8(cmd.argument()), params());
571                 break;
572         }
573
574         case LFUN_INSET_DIALOG_UPDATE:
575                 cur.bv().updateDialog("listings", params2string(params()));
576                 break;
577
578         default:
579                 InsetCaptionable::doDispatch(cur, cmd);
580                 break;
581         }
582 }
583
584
585 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
586         FuncStatus & status) const
587 {
588         switch (cmd.action()) {
589                 case LFUN_INSET_MODIFY:
590                 case LFUN_INSET_DIALOG_UPDATE:
591                         status.setEnabled(true);
592                         return true;
593                 case LFUN_CAPTION_INSERT: {
594                         // the inset outputs at most one caption
595                         if (params().isInline() || getCaptionInset()) {
596                                 status.setEnabled(false);
597                                 return true;
598                         }
599                 }
600                 // fall through
601                 default:
602                         return InsetCaptionable::getStatus(cur, cmd, status);
603         }
604 }
605
606
607 docstring const InsetListings::buttonLabel(BufferView const & bv) const
608 {
609         // FIXME UNICODE
610         docstring const locked = tempfile_ ? docstring(1, 0x1F512) : docstring();
611         if (decoration() == InsetDecoration::CLASSIC)
612                 return locked + (isOpen(bv) ? _("Listing") : getNewLabel(_("Listing")));
613         return locked + getNewLabel(_("Listing"));
614 }
615
616
617 void InsetListings::validate(LaTeXFeatures & features) const
618 {
619         features.useInsetLayout(getLayout());
620         string param_string = params().params();
621         if (buffer().params().use_minted) {
622                 features.require("minted");
623                 OutputParams rp = features.runparams();
624                 if (!params().isFloat() && !getCaption(rp).str.empty())
625                         features.require("lyxmintcaption");
626                 if (features.usePolyglossia() && features.hasRTLLanguage())
627                         // minted loads color, but color must be loaded before bidi
628                         // (i.e., polyglossia)
629                         features.require("color");
630         } else {
631                 features.require("listings");
632                 if (contains(param_string, "\\color"))
633                         features.require("color");
634         }
635         InsetCaptionable::validate(features);
636 }
637
638
639 bool InsetListings::showInsetDialog(BufferView * bv) const
640 {
641         bv->showDialog("listings", params2string(params()),
642                 const_cast<InsetListings *>(this));
643         return true;
644 }
645
646
647 TexString InsetListings::getCaption(OutputParams const & runparams) const
648 {
649         InsetCaption const * ins = getCaptionInset();
650         if (ins == 0)
651                 return TexString();
652
653         otexstringstream os;
654         ins->getArgs(os, runparams);
655         ins->getArgument(os, runparams);
656
657         // TODO: The code below should be moved to support, and then the test
658         //       in ../tests should be moved there as well.
659
660         // the caption may contain \label{} but the listings
661         // package prefer caption={}, label={}
662         TexString cap = os.release();
663         if (buffer().params().use_minted
664             || !contains(cap.str, from_ascii("\\label{")))
665                 return cap;
666         // convert from
667         //     blah1\label{blah2} blah3
668         // to
669         //     blah1 blah3},label={blah2
670         // to form options
671         //     caption={blah1 blah3},label={blah2}
672         //
673         // NOTE that } is not allowed in blah2.
674         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
675         string const new_cap("$1$3},label={$2");
676         // Remove potential \protect'ion of \label.
677         docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
678                                  from_ascii("\\label"));
679         // TexString validity: the substitution preserves the number of newlines.
680         // Moreover we assume that $2 does not contain newlines, so that the texrow
681         // information remains accurate.
682         // Replace '\n' with an improbable character from Private Use Area-A
683         // and then return to '\n' after the regex replacement.
684         capstr = subst(capstr, char_type('\n'), 0xffffd);
685         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
686                         0xffffd, char_type('\n'));
687         return cap;
688 }
689
690
691 void InsetListings::string2params(string const & in,
692                                    InsetListingsParams & params)
693 {
694         params = InsetListingsParams();
695         if (in.empty())
696                 return;
697         istringstream data(in);
698         Lexer lex;
699         lex.setStream(data);
700         // discard "listings", which is only used to determine inset
701         lex.next();
702         params.read(lex);
703 }
704
705
706 string InsetListings::params2string(InsetListingsParams const & params)
707 {
708         ostringstream data;
709         data << "listings" << ' ';
710         params.write(data);
711         return data.str();
712 }
713
714
715 } // namespace lyx