]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Fix functions that used functions but did not defined it
[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 "output_latex.h"
29 #include "output_docbook.h"
30 #include "output_xhtml.h"
31 #include "TexRow.h"
32 #include "texstream.h"
33
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/Lexer.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
191             && runparams.local_font->isRightToLeft()) {
192                 // We need to use the *latin switches (#11554)
193                 smatch sub;
194                 if (regex_match(param_string, sub, reg1))
195                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
196                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
197                 if (regex_match(param_string, sub, reg2))
198                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
199                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
200                 if (regex_match(param_string, sub, reg3))
201                         param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
202                                         + "latin"  + sub.str(5) + sub.str(6) + sub.str(7);
203         }
204         string minted_language;
205         string float_placement;
206         bool const isfloat = params().isFloat();
207         if (use_minted && (isfloat || contains(param_string, "language="))) {
208                 // Get float placement and/or language of the code,
209                 // then remove the relative options.
210                 vector<string> opts =
211                         getVectorFromString(param_string, ",", false);
212                 for (size_t i = 0; i < opts.size(); ++i) {
213                         if (prefixIs(opts[i], "float")) {
214                                 if (prefixIs(opts[i], "float="))
215                                         float_placement = opts[i].substr(6);
216                                 opts.erase(opts.begin() + int(i--));
217                         }
218                         else if (prefixIs(opts[i], "language=")) {
219                                 minted_language = opts[i].substr(9);
220                                 opts.erase(opts.begin() + int(i--));
221                         }
222                 }
223                 param_string = getStringFromVector(opts, ",");
224         }
225         // Minted needs a language specification
226         if (minted_language.empty()) {
227                 // If a language has been set globally, use that,
228                 // otherwise use TeX by default
229                 string const & blp = buffer().params().listings_params;
230                 size_t start = blp.find("language=");
231                 if (start != string::npos) {
232                         start += strlen("language=");
233                         size_t len = blp.find(",", start);
234                         if (len != string::npos)
235                                 len -= start;
236                         minted_language = blp.substr(start, len);
237                 } else
238                         minted_language = "TeX";
239         }
240
241         // get the paragraphs. We can not output them directly to given odocstream
242         // because we can not yet determine the delimiter character of \lstinline
243         docstring code;
244         docstring uncodable;
245         ParagraphList::const_iterator par = paragraphs().begin();
246         ParagraphList::const_iterator end = paragraphs().end();
247
248         bool encoding_switched = false;
249         Encoding const * const save_enc = runparams.encoding;
250
251         Encoding const * const outer_encoding =
252                 getLocalOrDefaultLang(runparams)->encoding();
253         Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
254         if (fixedlstenc) {
255                 // We need to switch to a singlebyte encoding, due to
256                 // the restrictions of the listings package (see above).
257                 // This needs to be consistent with
258                 // LaTeXFeatures::getTClassI18nPreamble().
259                 // We need to put this into a group in order to prevent encoding leaks
260                 // (happens with cprotect).
261                 os << "\\bgroup";
262                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
263                 runparams.encoding = fixedlstenc;
264                 encoding_switched = true;
265         }
266
267         bool const captionfirst = !isfloat && par->isInset(0)
268                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
269
270         while (par != end) {
271                 pos_type const siz = par->size();
272                 bool captionline = false;
273                 for (pos_type i = 0; i < siz; ++i) {
274                         if (i == 0 && par->isInset(i) && i + 1 == siz)
275                                 captionline = true;
276                         // ignore all struck out text and (caption) insets
277                         if (par->isDeleted(i)
278                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
279                                 continue;
280                         if (par->isInset(i)) {
281                                 // Currently, this can only be a quote inset
282                                 // that is output as plain quote here, but
283                                 // we use more generic code anyway.
284                                 otexstringstream ots;
285                                 OutputParams rp = runparams;
286                                 rp.pass_thru = true;
287                                 par->getInset(i)->latex(ots, rp);
288                                 code += ots.str();
289                                 continue;
290                         }
291                         char_type c = par->getChar(i);
292                         // we can only output characters covered by the current
293                         // encoding!
294                         try {
295                                 if (runparams.encoding->encodable(c))
296                                         code += c;
297                                 else if (runparams.dryrun) {
298                                         code += "<" + _("LyX Warning: ")
299                                            + _("uncodable character") + " '";
300                                         code += docstring(1, c);
301                                         code += "'>";
302                                 } else
303                                         uncodable += c;
304                         } catch (EncodingException & /* e */) {
305                                 if (runparams.dryrun) {
306                                         code += "<" + _("LyX Warning: ")
307                                            + _("uncodable character") + " '";
308                                         code += docstring(1, c);
309                                         code += "'>";
310                                 } else
311                                         uncodable += c;
312                         }
313                 }
314                 ++par;
315                 // Add new line between paragraphs in displayed listings.
316                 // Exception: merged paragraphs in change tracking mode.
317                 // Also, for the inline case, if there are multiple paragraphs
318                 // they are simply joined. Otherwise, expect latex errors.
319                 if (par != end && !isInline && !captionline && !par->parEndChange().deleted())
320                         code += "\n";
321         }
322         if (isInline) {
323                 static const docstring delimiters =
324                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
325
326                 size_t pos = delimiters.find_first_not_of(code);
327
328                 // This code piece contains all possible special character? !!!
329                 // Replace ! with a warning message and use ! as delimiter.
330                 if (pos == string::npos) {
331                         docstring delim_error = "<" + _("LyX Warning: ")
332                                 + _("no more lstline delimiters available") + ">";
333                         code = subst(code, from_ascii("!"), delim_error);
334                         pos = 0;
335                         if (!runparams.dryrun && !runparams.silent) {
336                                 // FIXME: warning should be passed to the error dialog
337                                 frontend::Alert::warning(_("Running out of delimiters"),
338                                 _("For inline program listings, one character must be reserved\n"
339                                   "as a delimiter. One of the listings, however, uses all available\n"
340                                   "characters, so none is left for delimiting purposes.\n"
341                                   "For the time being, I have replaced '!' by a warning, but you\n"
342                                   "must investigate!"));
343                         }
344                 }
345                 docstring const delim(1, delimiters[pos]);
346                 if (use_minted) {
347                         os << "\\mintinline";
348                         if (!param_string.empty())
349                                 os << "[" << from_utf8(param_string) << "]";
350                         os << "{" << ascii_lowercase(minted_language) << "}";
351                 } else {
352                         os << "\\lstinline";
353                         if (!param_string.empty())
354                                 os << "[" << from_utf8(param_string) << "]";
355                         else if (pos >= delimiters.find('Q'))
356                                 // We need to terminate the command before
357                                 // the delimiter
358                                 os << " ";
359                 }
360                 os << delim << code << delim;
361         } else if (use_minted) {
362                 OutputParams rp = runparams;
363                 rp.moving_arg = true;
364                 TexString caption = getCaption(rp);
365                 if (isfloat) {
366                         os << breakln << "\\begin{listing}";
367                         if (!float_placement.empty())
368                                 os << '[' << float_placement << "]";
369                 } else if (captionfirst && !caption.str.empty()) {
370                         os << breakln << "\\lyxmintcaption[t]{"
371                            << std::move(caption) << "}\n";
372                 }
373                 os << breakln << "\\begin{minted}";
374                 if (!param_string.empty())
375                         os << "[" << param_string << "]";
376                 os << "{" << ascii_lowercase(minted_language) << "}\n"
377                    << code << breakln << "\\end{minted}\n";
378                 if (isfloat) {
379                         if (!caption.str.empty())
380                                 os << "\\caption{" << std::move(caption) << "}\n";
381                         os << "\\end{listing}\n";
382                 } else if (!captionfirst && !caption.str.empty()) {
383                         os << breakln << "\\lyxmintcaption[b]{"
384                            << std::move(caption) << "}";
385                 }
386         } else {
387                 OutputParams rp = runparams;
388                 rp.moving_arg = true;
389                 TexString caption = getCaption(rp);
390                 os << breakln << "\\begin{lstlisting}";
391                 if (param_string.empty() && caption.str.empty())
392                         os << "\n";
393                 else {
394                         if (!runparams.nice)
395                                 os << safebreakln;
396                         os << "[";
397                         if (!caption.str.empty()) {
398                                 os << "caption={" << std::move(caption) << '}';
399                                 if (!param_string.empty())
400                                         os << ',';
401                         }
402                         os << from_utf8(param_string) << "]\n";
403                 }
404                 os << code << breakln << "\\end{lstlisting}\n";
405         }
406
407         if (encoding_switched) {
408                 // Switch back
409                 switchEncoding(os.os(), buffer().params(),
410                                runparams, *save_enc, true, true);
411                 if (!isInline)
412                         // Go out of vertical mode. Otherwise \egroup
413                         // causes a paragraph break (#12821)
414                         os << "\\leavevmode";
415                 os << "\\egroup" << breakln;
416                 runparams.encoding = save_enc;
417         }
418
419         if (!uncodable.empty() && !runparams.silent) {
420                 // issue a warning about omitted characters
421                 // FIXME: should be passed to the error dialog
422                 if (fixedlstenc)
423                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
424                                 bformat(_("The following characters in one of the program listings are\n"
425                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
426                                           "This is due to a restriction of the listings package, which does\n"
427                                           "not support your encoding '%2$s'.\n"
428                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
429                                           "might help."),
430                                 uncodable, _(runparams.encoding->guiName())));
431                 else
432                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
433                                 bformat(_("The following characters in one of the program listings are\n"
434                                           "not representable in the current encoding and have been omitted:\n%1$s."),
435                                 uncodable));
436         }
437 }
438
439
440 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
441 {
442         bool const isInline = params().isInline();
443         if (!isInline) {
444                 os << xml::StartTag("div", "class='float-listings'");
445                 docstring caption = getCaptionHTML(rp);
446                 if (!caption.empty())
447                         os << xml::StartTag("div", "class='listings-caption'")
448                            << XMLStream::ESCAPE_NONE
449                            << caption << xml::EndTag("div");
450         }
451
452         string const & tag = getLayout().htmltag();
453         string attr = "class='listings";
454         string const lang = params().getParamValue("language");
455         if (!lang.empty())
456                 attr += " " + lang;
457         attr += "'";
458         os << xml::StartTag(tag, attr);
459         OutputParams newrp = rp;
460         newrp.html_disable_captions = true;
461         // We don't want to convert dashes here. That's the only conversion we
462         // do for XHTML, so this is safe.
463         newrp.pass_thru = true;
464         docstring def = InsetText::insetAsXHTML(os, newrp, InsetText::JustText);
465         os << xml::EndTag(tag);
466
467         if (!isInline) {
468                 if (!def.empty()) {
469                         os << '\n' << def;
470                 }
471                 os << xml::EndTag("div");
472         }
473         return {};
474 }
475
476
477 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
478 {
479         InsetLayout const & il = getLayout();
480         bool isInline = params().isInline();
481
482         if (!isInline && !xs.isLastTagCR())
483                 xs << xml::CR();
484
485         // In case of caption, the code must be wrapped, for instance in a figure. Also detect if there is a label.
486         // http://www.sagehill.net/docbookxsl/ProgramListings.html
487         // TODO: parts of this code could be merged with InsetFloat and findLabelInParagraph.
488         InsetCaption const * caption = getCaptionInset();
489         if (caption) {
490                 InsetLabel const * label = getLabelInset();
491
492                 // Ensure that the label will not be output a second time as an anchor.
493                 OutputParams rpNoLabel = rp;
494                 if (label)
495                         rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
496
497                 // Prepare the right set of attributes, including the label.
498                 docstring attr = from_ascii("type='listing'");
499                 if (label)
500                         attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
501
502                 // Finally, generate the wrapper (including the label).
503                 xs << xml::StartTag("figure", attr);
504                 xs << xml::CR();
505                 xs << xml::StartTag("title");
506                 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
507                 xs << xml::EndTag("title");
508                 xs << xml::CR();
509         }
510
511         // Forge the attributes.
512         std::string attrs;
513         if (!il.docbookattr().empty())
514                 attrs += " role=\"" + il.docbookattr() + "\"";
515         std::string const lang = params().getParamValue("language");
516         if (!lang.empty())
517                 attrs += " language=\"" + lang + "\"";
518
519         // Determine the tag to use. Use the layout-defined value if outside a paragraph.
520         std::string tag = il.docbooktag();
521         if (isInline)
522                 tag = "code";
523
524         // Start the listing.
525         xs << xml::StartTag(tag, attrs);
526         xs.startDivision(false);
527
528         // Deal with the content of the listing.
529         OutputParams newrp = rp;
530         newrp.pass_thru = true;
531         newrp.docbook_make_pars = false;
532         newrp.par_begin = 0;
533         newrp.par_end = text().paragraphs().size();
534         newrp.docbook_in_listing = true;
535
536         docbookParagraphs(text(), buffer(), xs, newrp);
537
538         // Done with the listing.
539         xs.endDivision();
540         xs << xml::EndTag(tag);
541         if (!isInline)
542                 xs << xml::CR();
543
544         if (caption) {
545                 xs << xml::EndTag("figure");
546                 xs << xml::CR();
547         }
548 }
549
550
551 string InsetListings::contextMenuName() const
552 {
553         return "context-listings";
554 }
555
556
557 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
558 {
559         switch (cmd.action()) {
560
561         case LFUN_INSET_MODIFY: {
562                 cur.recordUndoInset(this);
563                 InsetListings::string2params(to_utf8(cmd.argument()), params());
564                 break;
565         }
566
567         case LFUN_INSET_DIALOG_UPDATE:
568                 cur.bv().updateDialog("listings", params2string(params()));
569                 break;
570
571         default:
572                 InsetCaptionable::doDispatch(cur, cmd);
573                 break;
574         }
575 }
576
577
578 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
579         FuncStatus & status) const
580 {
581         switch (cmd.action()) {
582                 case LFUN_INSET_MODIFY:
583                 case LFUN_INSET_DIALOG_UPDATE:
584                         status.setEnabled(true);
585                         return true;
586                 case LFUN_CAPTION_INSERT: {
587                         // the inset outputs at most one caption
588                         if (params().isInline() || getCaptionInset()) {
589                                 status.setEnabled(false);
590                                 return true;
591                         }
592                 }
593                 // fall through
594                 default:
595                         return InsetCaptionable::getStatus(cur, cmd, status);
596         }
597 }
598
599
600 docstring const InsetListings::buttonLabel(BufferView const & bv) const
601 {
602         // FIXME UNICODE
603         docstring const locked = tempfile_ ? docstring(1, 0x1F512) : docstring();
604         if (decoration() == InsetDecoration::CLASSIC)
605                 return locked + (isOpen(bv) ? _("Listing") : getNewLabel(_("Listing")));
606         return locked + getNewLabel(_("Listing"));
607 }
608
609
610 void InsetListings::validate(LaTeXFeatures & features) const
611 {
612         features.useInsetLayout(getLayout());
613         string param_string = params().params();
614         if (buffer().params().use_minted) {
615                 features.require("minted");
616                 OutputParams rp = features.runparams();
617                 if (!params().isFloat() && !getCaption(rp).str.empty())
618                         features.require("lyxmintcaption");
619                 if (features.usePolyglossia() && features.hasRTLLanguage())
620                         // minted loads color, but color must be loaded before bidi
621                         // (i.e., polyglossia)
622                         features.require("color");
623         } else {
624                 features.require("listings");
625                 if (contains(param_string, "\\color"))
626                         features.require("color");
627         }
628         InsetCaptionable::validate(features);
629 }
630
631
632 bool InsetListings::showInsetDialog(BufferView * bv) const
633 {
634         bv->showDialog("listings", params2string(params()),
635                 const_cast<InsetListings *>(this));
636         return true;
637 }
638
639
640 TexString InsetListings::getCaption(OutputParams const & runparams) const
641 {
642         InsetCaption const * ins = getCaptionInset();
643         if (ins == 0)
644                 return TexString();
645
646         otexstringstream os;
647         ins->getArgs(os, runparams);
648         ins->getArgument(os, runparams);
649
650         // TODO: The code below should be moved to support, and then the test
651         //       in ../tests should be moved there as well.
652
653         // the caption may contain \label{} but the listings
654         // package prefer caption={}, label={}
655         TexString cap = os.release();
656         if (buffer().params().use_minted
657             || !contains(cap.str, from_ascii("\\label{")))
658                 return cap;
659         // convert from
660         //     blah1\label{blah2} blah3
661         // to
662         //     blah1 blah3},label={blah2
663         // to form options
664         //     caption={blah1 blah3},label={blah2}
665         //
666         // NOTE that } is not allowed in blah2.
667         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
668         string const new_cap("$1$3},label={$2");
669         // Remove potential \protect'ion of \label.
670         docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
671                                  from_ascii("\\label"));
672         // TexString validity: the substitution preserves the number of newlines.
673         // Moreover we assume that $2 does not contain newlines, so that the texrow
674         // information remains accurate.
675         // Replace '\n' with an improbable character from Private Use Area-A
676         // and then return to '\n' after the regex replacement.
677         capstr = subst(capstr, char_type('\n'), 0xffffd);
678         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
679                         0xffffd, char_type('\n'));
680         return cap;
681 }
682
683
684 void InsetListings::string2params(string const & in,
685                                    InsetListingsParams & params)
686 {
687         params = InsetListingsParams();
688         if (in.empty())
689                 return;
690         istringstream data(in);
691         Lexer lex;
692         lex.setStream(data);
693         // discard "listings", which is only used to determine inset
694         lex.next();
695         params.read(lex);
696 }
697
698
699 string InsetListings::params2string(InsetListingsParams const & params)
700 {
701         ostringstream data;
702         data << "listings" << ' ';
703         params.write(data);
704         return data.str();
705 }
706
707
708 } // namespace lyx