2 * \file InsetListings.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
14 #include "InsetListings.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "InsetCaption.h"
24 #include "InsetLabel.h"
25 #include "InsetLayout.h"
27 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_docbook.h"
31 #include "output_xhtml.h"
33 #include "texstream.h"
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"
41 #include "frontends/alert.h"
42 #include "frontends/Application.h"
49 using namespace lyx::support;
54 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
55 : InsetCaptionable(buf,"listing")
57 params_.setMinted(buffer().params().use_minted);
58 status_ = par.status();
62 InsetListings::~InsetListings()
64 hideDialogs("listings", this);
68 int InsetListings::rowFlags() const
70 return params().isInline() || params().isFloat() ? Inline : Display | AlignLeft;
74 docstring InsetListings::layoutName() const
76 if (buffer().params().use_minted)
77 return from_ascii("MintedListings");
79 return from_ascii("Listings");
83 void InsetListings::write(ostream & os) const
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();
90 os << "lstparams \"" << opt << "\"\n";
92 os << "inline true\n";
94 os << "inline false\n";
95 InsetCaptionable::write(os);
99 void InsetListings::read(Lexer & lex)
103 string token = lex.getString();
104 if (token == "lstparams") {
106 string const value = lex.getString();
107 params().fromEncodedString(value);
108 } else if (token == "inline") {
110 params().setInline(lex.getBool());
112 // no special option, push back 'status' etc
113 lex.pushToken(token);
117 InsetCaptionable::read(lex);
121 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
122 Encoding const * outer_enc) const
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())
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");
142 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
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))(\\})(.*)");
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
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);
174 // And the same vice versa
175 // Substitute fontstyle option
178 if (regex_match(param_string, sub, reg5)) {
179 basicstyle = "\\" + sub.str(3) + "family";
180 param_string = sub.str(1) + sub.str(4);
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);
187 if (!basicstyle.empty())
188 param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
190 if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
191 // We need to use the *latin switches (#11554)
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);
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--));
217 else if (prefixIs(opts[i], "language=")) {
218 minted_language = opts[i].substr(9);
219 opts.erase(opts.begin() + int(i--));
222 param_string = getStringFromVector(opts, ",");
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)
235 minted_language = blp.substr(start, len);
237 minted_language = "TeX";
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
244 ParagraphList::const_iterator par = paragraphs().begin();
245 ParagraphList::const_iterator end = paragraphs().end();
247 bool encoding_switched = false;
248 Encoding const * const save_enc = runparams.encoding;
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);
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).
263 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
264 runparams.encoding = fixedlstenc;
265 encoding_switched = true;
268 bool const captionfirst = !isfloat && par->isInset(0)
269 && par->getInset(0)->lyxCode() == CAPTION_CODE;
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)
277 // ignore all struck out text and (caption) insets
278 if (par->isDeleted(i)
279 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
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;
288 par->getInset(i)->latex(ots, rp);
292 char_type c = par->getChar(i);
293 // we can only output characters covered by the current
296 if (runparams.encoding->encodable(c))
298 else if (runparams.dryrun) {
299 code += "<" + _("LyX Warning: ")
300 + _("uncodable character") + " '";
301 code += docstring(1, c);
305 } catch (EncodingException & /* e */) {
306 if (runparams.dryrun) {
307 code += "<" + _("LyX Warning: ")
308 + _("uncodable character") + " '";
309 code += docstring(1, c);
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())
324 static const docstring delimiters =
325 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
327 size_t pos = delimiters.find_first_not_of(code);
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);
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!"));
346 docstring const delim(1, delimiters[pos]);
348 os << "\\mintinline";
349 if (!param_string.empty())
350 os << "[" << from_utf8(param_string) << "]";
351 os << "{" << ascii_lowercase(minted_language) << "}";
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
361 os << delim << code << delim;
362 } else if (use_minted) {
363 OutputParams rp = runparams;
364 rp.moving_arg = true;
365 TexString caption = getCaption(rp);
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";
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";
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) << "}";
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())
398 if (!caption.str.empty()) {
399 os << "caption={" << move(caption) << '}';
400 if (!param_string.empty())
403 os << from_utf8(param_string) << "]\n";
405 os << code << breakln << "\\end{lstlisting}\n";
408 if (encoding_switched){
410 switchEncoding(os.os(), buffer().params(),
411 runparams, *save_enc, true, true);
412 os << "\\egroup" << breakln;
413 runparams.encoding = save_enc;
416 if (!uncodable.empty() && !runparams.silent) {
417 // issue a warning about omitted characters
418 // FIXME: should be passed to the error dialog
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"
427 uncodable, _(runparams.encoding->guiName())));
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."),
437 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
439 odocstringstream ods;
442 bool const isInline = params().isInline();
444 out << xml::CompTag("br");
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");
454 InsetLayout const & il = getLayout();
455 string const & tag = il.htmltag();
456 string attr = "class ='listings";
457 string const lang = params().getParamValue("language");
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);
471 out << xml::CompTag("br");
472 // escaping will already have been done
473 os << XMLStream::ESCAPE_NONE << ods.str();
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;
484 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
486 InsetLayout const & il = getLayout();
487 bool isInline = params().isInline();
489 if (!isInline && !xs.isLastTagCR())
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();
497 InsetLabel const * label = getLabelInset();
499 // Ensure that the label will not be output a second time as an anchor.
500 OutputParams rpNoLabel = rp;
502 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
504 // Prepare the right set of attributes, including the label.
505 docstring attr = from_ascii("type='listing'");
507 attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
509 // Finally, generate the wrapper (including the label).
510 xs << xml::StartTag("figure", attr);
512 xs << xml::StartTag("title");
513 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
514 xs << xml::EndTag("title");
518 // Forge the attributes.
520 if (!il.docbookattr().empty())
521 attrs += " role=\"" + il.docbookattr() + "\"";
522 std::string const lang = params().getParamValue("language");
524 attrs += " language=\"" + lang + "\"";
526 // Determine the tag to use. Use the layout-defined value if outside a paragraph.
527 std::string tag = il.docbooktag();
531 // Start the listing.
532 xs << xml::StartTag(tag, attrs);
533 xs.startDivision(false);
535 // Deal with the content of the listing.
536 OutputParams newrp = rp;
537 newrp.pass_thru = true;
538 newrp.docbook_make_pars = false;
540 newrp.par_end = text().paragraphs().size();
541 newrp.docbook_in_listing = true;
543 docbookParagraphs(text(), buffer(), xs, newrp);
545 // Done with the listing.
547 xs << xml::EndTag(tag);
552 xs << xml::EndTag("figure");
558 string InsetListings::contextMenuName() const
560 return "context-listings";
564 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
566 switch (cmd.action()) {
568 case LFUN_INSET_MODIFY: {
569 cur.recordUndoInset(this);
570 InsetListings::string2params(to_utf8(cmd.argument()), params());
574 case LFUN_INSET_DIALOG_UPDATE:
575 cur.bv().updateDialog("listings", params2string(params()));
579 InsetCaptionable::doDispatch(cur, cmd);
585 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
586 FuncStatus & status) const
588 switch (cmd.action()) {
589 case LFUN_INSET_MODIFY:
590 case LFUN_INSET_DIALOG_UPDATE:
591 status.setEnabled(true);
593 case LFUN_CAPTION_INSERT: {
594 // the inset outputs at most one caption
595 if (params().isInline() || getCaptionInset()) {
596 status.setEnabled(false);
602 return InsetCaptionable::getStatus(cur, cmd, status);
607 docstring const InsetListings::buttonLabel(BufferView const & bv) const
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"));
617 void InsetListings::validate(LaTeXFeatures & features) const
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");
631 features.require("listings");
632 if (contains(param_string, "\\color"))
633 features.require("color");
635 InsetCaptionable::validate(features);
639 bool InsetListings::showInsetDialog(BufferView * bv) const
641 bv->showDialog("listings", params2string(params()),
642 const_cast<InsetListings *>(this));
647 TexString InsetListings::getCaption(OutputParams const & runparams) const
649 InsetCaption const * ins = getCaptionInset();
654 ins->getArgs(os, runparams);
655 ins->getArgument(os, runparams);
657 // TODO: The code below should be moved to support, and then the test
658 // in ../tests should be moved there as well.
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{")))
667 // blah1\label{blah2} blah3
669 // blah1 blah3},label={blah2
671 // caption={blah1 blah3},label={blah2}
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'));
691 void InsetListings::string2params(string const & in,
692 InsetListingsParams & params)
694 params = InsetListingsParams();
697 istringstream data(in);
700 // discard "listings", which is only used to determine inset
706 string InsetListings::params2string(InsetListingsParams const & params)
709 data << "listings" << ' ';