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"
48 using namespace lyx::support;
53 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
54 : InsetCaptionable(buf,"listing")
56 params_.setMinted(buffer().params().use_minted);
57 status_ = par.status();
61 InsetListings::~InsetListings()
63 hideDialogs("listings", this);
67 int InsetListings::rowFlags() const
69 return params().isInline() || params().isFloat() ? Inline : Display | AlignLeft;
73 docstring InsetListings::layoutName() const
75 if (buffer().params().use_minted)
76 return from_ascii("MintedListings");
78 return from_ascii("Listings");
82 void InsetListings::write(ostream & os) const
84 os << "listings" << "\n";
85 InsetListingsParams const & par = params();
86 // parameter string is encoded to be a valid lyx token.
87 string opt = par.encodedString();
89 os << "lstparams \"" << opt << "\"\n";
91 os << "inline true\n";
93 os << "inline false\n";
94 InsetCaptionable::write(os);
98 void InsetListings::read(Lexer & lex)
102 string token = lex.getString();
103 if (token == "lstparams") {
105 string const value = lex.getString();
106 params().fromEncodedString(value);
107 } else if (token == "inline") {
109 params().setInline(lex.getBool());
111 // no special option, push back 'status' etc
112 lex.pushToken(token);
116 InsetCaptionable::read(lex);
120 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
121 Encoding const * outer_enc) const
123 // The listings package cannot deal with multi-byte-encoded
124 // glyphs, except for Xe/LuaTeX (with non-TeX fonts) or pLaTeX.
125 // Minted can deal with all encodings.
126 if (buffer().params().use_minted
127 || inner_enc->name() == "utf8-plain"
128 || inner_enc->package() == Encoding::japanese
129 || inner_enc->hasFixedWidth())
132 // We try if there's a singlebyte encoding for the outer
133 // language; if not, fall back to latin1.
134 // Power-users can set inputenc to utf8-plain to bypass this workaround
135 // and provide alternatives in the user-preamble.
136 return (outer_enc->hasFixedWidth()) ?
137 outer_enc : encodings.fromLyXName("iso8859-1");
141 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
143 string param_string = params().params();
144 // NOTE: I use {} to quote text, which is an experimental feature
145 // of the listings package (see page 25 of the manual)
146 bool const isInline = params().isInline();
147 bool const use_minted = buffer().params().use_minted;
148 static regex const reg1("(.*)(basicstyle=\\{)([^\\}]*)(\\\\ttfamily)([^\\}]*)(\\})(.*)");
149 static regex const reg2("(.*)(basicstyle=\\{)([^\\}]*)(\\\\rmfamily)([^\\}]*)(\\})(.*)");
150 static regex const reg3("(.*)(basicstyle=\\{)([^\\}]*)(\\\\sffamily)([^\\}]*)(\\})(.*)");
151 static regex const reg4("(.*)(basicstyle=\\{)([^\\}]*)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))([^\\}]*)(\\})(.*)");
152 static regex const reg5("(.*)(fontfamily=)(tt|sf|rm)(.*)");
153 static regex const reg6("(.*)(fontsize=\\{)(\\\\(tiny|scriptsize|footnotesize|small|normalsize|large|Large))(\\})(.*)");
155 // If params have been entered with "listings", and then the user switched to "minted",
156 // we have params that need to be translated.
157 // FIXME: We should use a backend-abstract syntax in listings params instead!
158 // Substitute fontstyle option
160 if (regex_match(param_string, sub, reg1))
161 param_string = sub.str(1) + "fontfamily=tt," + sub.str(2) + sub.str(3)
162 + sub.str(5) + sub.str(6) + sub.str(7);
163 if (regex_match(param_string, sub, reg2))
164 param_string = sub.str(1) + "fontfamily=rm," + sub.str(2) + sub.str(3)
165 + sub.str(5) + sub.str(6) + sub.str(7);
166 if (regex_match(param_string, sub, reg3))
167 param_string = sub.str(1) + "fontfamily=sf," + sub.str(2) + sub.str(3)
168 + sub.str(5) + sub.str(6) + sub.str(7);
169 // as well as fontsize option
170 if (regex_match(param_string, sub, reg4))
171 param_string = sub.str(1) + "fontsize={" + sub.str(4) + sub.str(3) + sub.str(7) + sub.str(8);
173 // And the same vice versa
174 // Substitute fontstyle option
177 if (regex_match(param_string, sub, reg5)) {
178 basicstyle = "\\" + sub.str(3) + "family";
179 param_string = sub.str(1) + sub.str(4);
181 // as well as fontsize option
182 if (regex_match(param_string, sub, reg6)) {
183 basicstyle += sub.str(3);
184 param_string = sub.str(1) + sub.str(6);
186 if (!basicstyle.empty())
187 param_string = rtrim(param_string, ",") + ",basicstyle={" + basicstyle + "}";
189 if (runparams.use_polyglossia && runparams.local_font->isRightToLeft()) {
190 // We need to use the *latin switches (#11554)
192 if (regex_match(param_string, sub, reg1))
193 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
194 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
195 if (regex_match(param_string, sub, reg2))
196 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
197 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
198 if (regex_match(param_string, sub, reg3))
199 param_string = sub.str(1) + sub.str(2) + sub.str(3) + sub.str(4)
200 + "latin" + sub.str(5) + sub.str(6) + sub.str(7);
202 string minted_language;
203 string float_placement;
204 bool const isfloat = params().isFloat();
205 if (use_minted && (isfloat || contains(param_string, "language="))) {
206 // Get float placement and/or language of the code,
207 // then remove the relative options.
208 vector<string> opts =
209 getVectorFromString(param_string, ",", false);
210 for (size_t i = 0; i < opts.size(); ++i) {
211 if (prefixIs(opts[i], "float")) {
212 if (prefixIs(opts[i], "float="))
213 float_placement = opts[i].substr(6);
214 opts.erase(opts.begin() + int(i--));
216 else if (prefixIs(opts[i], "language=")) {
217 minted_language = opts[i].substr(9);
218 opts.erase(opts.begin() + int(i--));
221 param_string = getStringFromVector(opts, ",");
223 // Minted needs a language specification
224 if (minted_language.empty()) {
225 // If a language has been set globally, use that,
226 // otherwise use TeX by default
227 string const & blp = buffer().params().listings_params;
228 size_t start = blp.find("language=");
229 if (start != string::npos) {
230 start += strlen("language=");
231 size_t len = blp.find(",", start);
232 if (len != string::npos)
234 minted_language = blp.substr(start, len);
236 minted_language = "TeX";
239 // get the paragraphs. We can not output them directly to given odocstream
240 // because we can not yet determine the delimiter character of \lstinline
243 ParagraphList::const_iterator par = paragraphs().begin();
244 ParagraphList::const_iterator end = paragraphs().end();
246 bool encoding_switched = false;
247 Encoding const * const save_enc = runparams.encoding;
249 Encoding const * const outer_encoding =
250 (runparams.local_font != 0) ?
251 runparams.local_font->language()->encoding()
252 : buffer().params().language->encoding();
253 Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
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).
262 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
263 runparams.encoding = fixedlstenc;
264 encoding_switched = true;
267 bool const captionfirst = !isfloat && par->isInset(0)
268 && par->getInset(0)->lyxCode() == CAPTION_CODE;
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)
276 // ignore all struck out text and (caption) insets
277 if (par->isDeleted(i)
278 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
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;
287 par->getInset(i)->latex(ots, rp);
291 char_type c = par->getChar(i);
292 // we can only output characters covered by the current
295 if (runparams.encoding->encodable(c))
297 else if (runparams.dryrun) {
298 code += "<" + _("LyX Warning: ")
299 + _("uncodable character") + " '";
300 code += docstring(1, c);
304 } catch (EncodingException & /* e */) {
305 if (runparams.dryrun) {
306 code += "<" + _("LyX Warning: ")
307 + _("uncodable character") + " '";
308 code += docstring(1, c);
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())
323 static const docstring delimiters =
324 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
326 size_t pos = delimiters.find_first_not_of(code);
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);
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!"));
345 docstring const delim(1, delimiters[pos]);
347 os << "\\mintinline";
348 if (!param_string.empty())
349 os << "[" << from_utf8(param_string) << "]";
350 os << "{" << ascii_lowercase(minted_language) << "}";
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
360 os << delim << code << delim;
361 } else if (use_minted) {
362 OutputParams rp = runparams;
363 rp.moving_arg = true;
364 TexString caption = getCaption(rp);
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 << move(caption) << "}\n";
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";
379 if (!caption.str.empty())
380 os << "\\caption{" << move(caption) << "}\n";
381 os << "\\end{listing}\n";
382 } else if (!captionfirst && !caption.str.empty()) {
383 os << breakln << "\\lyxmintcaption[b]{"
384 << move(caption) << "}";
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())
397 if (!caption.str.empty()) {
398 os << "caption={" << move(caption) << '}';
399 if (!param_string.empty())
402 os << from_utf8(param_string) << "]\n";
404 os << code << breakln << "\\end{lstlisting}\n";
407 if (encoding_switched){
409 switchEncoding(os.os(), buffer().params(),
410 runparams, *save_enc, true, true);
411 os << "\\egroup" << breakln;
412 runparams.encoding = save_enc;
415 if (!uncodable.empty() && !runparams.silent) {
416 // issue a warning about omitted characters
417 // FIXME: should be passed to the error dialog
419 frontend::Alert::warning(_("Uncodable characters in listings inset"),
420 bformat(_("The following characters in one of the program listings are\n"
421 "not representable in the current encoding and have been omitted:\n%1$s.\n"
422 "This is due to a restriction of the listings package, which does\n"
423 "not support your encoding '%2$s'.\n"
424 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
426 uncodable, _(runparams.encoding->guiName())));
428 frontend::Alert::warning(_("Uncodable characters in listings inset"),
429 bformat(_("The following characters in one of the program listings are\n"
430 "not representable in the current encoding and have been omitted:\n%1$s."),
436 docstring InsetListings::xhtml(XMLStream & os, OutputParams const & rp) const
438 odocstringstream ods;
441 bool const isInline = params().isInline();
443 out << xml::CompTag("br");
445 out << xml::StartTag("div", "class='float-listings'");
446 docstring caption = getCaptionHTML(rp);
447 if (!caption.empty())
448 out << xml::StartTag("div", "class='listings-caption'")
449 << XMLStream::ESCAPE_NONE
450 << caption << xml::EndTag("div");
453 InsetLayout const & il = getLayout();
454 string const & tag = il.htmltag();
455 string attr = "class ='listings";
456 string const lang = params().getParamValue("language");
460 out << xml::StartTag(tag, attr);
461 OutputParams newrp = rp;
462 newrp.html_disable_captions = true;
463 // We don't want to convert dashes here. That's the only conversion we
464 // do for XHTML, so this is safe.
465 newrp.pass_thru = true;
466 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
467 out << xml::EndTag(tag);
470 out << xml::CompTag("br");
471 // escaping will already have been done
472 os << XMLStream::ESCAPE_NONE << ods.str();
474 out << xml::EndTag("div");
475 // In this case, this needs to be deferred, but we'll put it
476 // before anything the text itself deferred.
477 def = ods.str() + '\n' + def;
483 void InsetListings::docbook(XMLStream & xs, OutputParams const & rp) const
485 InsetLayout const & il = getLayout();
486 bool isInline = params().isInline();
488 if (!isInline && !xs.isLastTagCR())
491 // In case of caption, the code must be wrapped, for instance in a figure. Also detect if there is a label.
492 // http://www.sagehill.net/docbookxsl/ProgramListings.html
493 // TODO: parts of this code could be merged with InsetFloat and findLabelInParagraph.
494 InsetCaption const * caption = getCaptionInset();
496 InsetLabel const * label = getLabelInset();
498 // Ensure that the label will not be output a second time as an anchor.
499 OutputParams rpNoLabel = rp;
501 rpNoLabel.docbook_anchors_to_ignore.emplace(label->screenLabel());
503 // Prepare the right set of attributes, including the label.
504 docstring attr = from_ascii("type='listing'");
506 attr += " xml:id=\"" + xml::cleanID(label->screenLabel()) + "\"";
508 // Finally, generate the wrapper (including the label).
509 xs << xml::StartTag("figure", attr);
511 xs << xml::StartTag("title");
512 xs << XMLStream::ESCAPE_NONE << getCaptionDocBook(rpNoLabel);
513 xs << xml::EndTag("title");
517 // Forge the attributes.
519 if (!il.docbookattr().empty())
520 attrs += " role=\"" + il.docbookattr() + "\"";
521 std::string const lang = params().getParamValue("language");
523 attrs += " language=\"" + lang + "\"";
525 // Determine the tag to use. Use the layout-defined value if outside a paragraph.
526 std::string tag = il.docbooktag();
530 // Start the listing.
531 xs << xml::StartTag(tag, attrs);
532 xs.startDivision(false);
534 // Deal with the content of the listing.
535 OutputParams newrp = rp;
536 newrp.pass_thru = true;
537 newrp.docbook_make_pars = false;
539 newrp.par_end = text().paragraphs().size();
540 newrp.docbook_in_listing = true;
542 docbookParagraphs(text(), buffer(), xs, newrp);
544 // Done with the listing.
546 xs << xml::EndTag(tag);
551 xs << xml::EndTag("figure");
557 string InsetListings::contextMenuName() const
559 return "context-listings";
563 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
565 switch (cmd.action()) {
567 case LFUN_INSET_MODIFY: {
568 cur.recordUndoInset(this);
569 InsetListings::string2params(to_utf8(cmd.argument()), params());
573 case LFUN_INSET_DIALOG_UPDATE:
574 cur.bv().updateDialog("listings", params2string(params()));
578 InsetCaptionable::doDispatch(cur, cmd);
584 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
585 FuncStatus & status) const
587 switch (cmd.action()) {
588 case LFUN_INSET_MODIFY:
589 case LFUN_INSET_DIALOG_UPDATE:
590 status.setEnabled(true);
592 case LFUN_CAPTION_INSERT: {
593 // the inset outputs at most one caption
594 if (params().isInline() || getCaptionInset()) {
595 status.setEnabled(false);
601 return InsetCaptionable::getStatus(cur, cmd, status);
606 docstring const InsetListings::buttonLabel(BufferView const & bv) const
609 docstring const locked = tempfile_ ? docstring(1, 0x1F512) : docstring();
610 if (decoration() == InsetDecoration::CLASSIC)
611 return locked + (isOpen(bv) ? _("Listing") : getNewLabel(_("Listing")));
612 return locked + getNewLabel(_("Listing"));
616 void InsetListings::validate(LaTeXFeatures & features) const
618 features.useInsetLayout(getLayout());
619 string param_string = params().params();
620 if (buffer().params().use_minted) {
621 features.require("minted");
622 OutputParams rp = features.runparams();
623 if (!params().isFloat() && !getCaption(rp).str.empty())
624 features.require("lyxmintcaption");
625 if (features.usePolyglossia() && features.hasRTLLanguage())
626 // minted loads color, but color must be loaded before bidi
627 // (i.e., polyglossia)
628 features.require("color");
630 features.require("listings");
631 if (contains(param_string, "\\color"))
632 features.require("color");
634 InsetCaptionable::validate(features);
638 bool InsetListings::showInsetDialog(BufferView * bv) const
640 bv->showDialog("listings", params2string(params()),
641 const_cast<InsetListings *>(this));
646 TexString InsetListings::getCaption(OutputParams const & runparams) const
648 InsetCaption const * ins = getCaptionInset();
653 ins->getArgs(os, runparams);
654 ins->getArgument(os, runparams);
656 // TODO: The code below should be moved to support, and then the test
657 // in ../tests should be moved there as well.
659 // the caption may contain \label{} but the listings
660 // package prefer caption={}, label={}
661 TexString cap = os.release();
662 if (buffer().params().use_minted
663 || !contains(cap.str, from_ascii("\\label{")))
666 // blah1\label{blah2} blah3
668 // blah1 blah3},label={blah2
670 // caption={blah1 blah3},label={blah2}
672 // NOTE that } is not allowed in blah2.
673 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
674 string const new_cap("$1$3},label={$2");
675 // Remove potential \protect'ion of \label.
676 docstring capstr = subst(cap.str, from_ascii("\\protect\\label"),
677 from_ascii("\\label"));
678 // TexString validity: the substitution preserves the number of newlines.
679 // Moreover we assume that $2 does not contain newlines, so that the texrow
680 // information remains accurate.
681 // Replace '\n' with an improbable character from Private Use Area-A
682 // and then return to '\n' after the regex replacement.
683 capstr = subst(capstr, char_type('\n'), 0xffffd);
684 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
685 0xffffd, char_type('\n'));
690 void InsetListings::string2params(string const & in,
691 InsetListingsParams & params)
693 params = InsetListingsParams();
696 istringstream data(in);
699 // discard "listings", which is only used to determine inset
705 string InsetListings::params2string(InsetListingsParams const & params)
708 data << "listings" << ' ';