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 "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
27 #include "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
34 #include "texstream.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40 #include "support/lassert.h"
42 #include "frontends/alert.h"
43 #include "frontends/Application.h"
45 #include "support/regex.h"
50 using namespace lyx::support;
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56 : InsetCaptionable(buf,"listing")
58 params_.setMinted(buffer().params().use_minted);
59 status_ = par.status();
63 InsetListings::~InsetListings()
65 hideDialogs("listings", this);
69 Inset::DisplayType InsetListings::display() const
71 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
75 docstring InsetListings::layoutName() const
77 if (buffer().params().use_minted)
78 return from_ascii("MintedListings");
80 return from_ascii("Listings");
84 void InsetListings::write(ostream & os) const
86 os << "listings" << "\n";
87 InsetListingsParams const & par = params();
88 // parameter string is encoded to be a valid lyx token.
89 string opt = par.encodedString();
91 os << "lstparams \"" << opt << "\"\n";
93 os << "inline true\n";
95 os << "inline false\n";
96 InsetCaptionable::write(os);
100 void InsetListings::read(Lexer & lex)
104 string token = lex.getString();
105 if (token == "lstparams") {
107 string const value = lex.getString();
108 params().fromEncodedString(value);
109 } else if (token == "inline") {
111 params().setInline(lex.getBool());
113 // no special option, push back 'status' etc
114 lex.pushToken(token);
118 InsetCaptionable::read(lex);
122 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
123 Encoding const * outer_enc) const
125 // The listings package cannot deal with multi-byte-encoded
126 // glyphs, except if full-unicode aware backends
127 // such as XeTeX or LuaTeX are used, and with pLaTeX.
128 // Minted can deal with all encodings.
129 if (buffer().params().use_minted
130 || inner_enc->name() == "utf8-plain"
131 || (buffer().params().encoding().package() == Encoding::japanese
132 && inner_enc->package() == Encoding::japanese)
133 || inner_enc->hasFixedWidth())
136 // We try if there's a singlebyte encoding for the outer
137 // language; if not, fall back to latin1.
138 return (outer_enc->hasFixedWidth()) ?
139 outer_enc : encodings.fromLyXName("iso8859-1");
143 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
145 string param_string = params().params();
146 // NOTE: I use {} to quote text, which is an experimental feature
147 // of the listings package (see page 25 of the manual)
148 bool const isInline = params().isInline();
149 bool const use_minted = buffer().params().use_minted;
150 string minted_language;
151 string float_placement;
152 bool const isfloat = params().isFloat();
153 if (use_minted && (isfloat || contains(param_string, "language="))) {
154 // Get float placement and/or language of the code,
155 // then remove the relative options.
156 vector<string> opts =
157 getVectorFromString(param_string, ",", false);
158 for (size_t i = 0; i < opts.size(); ++i) {
159 if (prefixIs(opts[i], "float")) {
160 if (prefixIs(opts[i], "float="))
161 float_placement = opts[i].substr(6);
162 opts.erase(opts.begin() + i--);
164 else if (prefixIs(opts[i], "language=")) {
165 minted_language = opts[i].substr(9);
166 opts.erase(opts.begin() + i--);
169 param_string = getStringFromVector(opts, ",");
171 // Minted needs a language specification
172 if (minted_language.empty())
173 minted_language = "TeX";
175 // get the paragraphs. We can not output them directly to given odocstream
176 // because we can not yet determine the delimiter character of \lstinline
179 ParagraphList::const_iterator par = paragraphs().begin();
180 ParagraphList::const_iterator end = paragraphs().end();
182 bool encoding_switched = false;
183 Encoding const * const save_enc = runparams.encoding;
185 Encoding const * const outer_encoding =
186 (runparams.local_font != 0) ?
187 runparams.local_font->language()->encoding()
188 : buffer().params().language->encoding();
189 Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
191 // We need to switch to a singlebyte encoding, due to
192 // the restrictions of the listings package (see above).
193 // This needs to be consistent with
194 // LaTeXFeatures::getTClassI18nPreamble().
195 // We need to put this into a group in order to prevent encoding leaks
196 // (happens with cprotect).
198 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
199 runparams.encoding = fixedlstenc;
200 encoding_switched = true;
203 bool const captionfirst = !isfloat && par->isInset(0)
204 && par->getInset(0)->lyxCode() == CAPTION_CODE;
207 pos_type const siz = par->size();
208 bool captionline = false;
209 for (pos_type i = 0; i < siz; ++i) {
210 if (i == 0 && par->isInset(i) && i + 1 == siz)
212 // ignore all struck out text and (caption) insets
213 if (par->isDeleted(i)
214 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
216 if (par->isInset(i)) {
217 // Currently, this can only be a quote inset
218 // that is output as plain quote here, but
219 // we use more generic code anyway.
220 otexstringstream ots;
221 OutputParams rp = runparams;
223 par->getInset(i)->latex(ots, rp);
227 char_type c = par->getChar(i);
228 // we can only output characters covered by the current
231 if (runparams.encoding->encodable(c))
233 else if (runparams.dryrun) {
234 code += "<" + _("LyX Warning: ")
235 + _("uncodable character") + " '";
236 code += docstring(1, c);
240 } catch (EncodingException & /* e */) {
241 if (runparams.dryrun) {
242 code += "<" + _("LyX Warning: ")
243 + _("uncodable character") + " '";
244 code += docstring(1, c);
251 // for the inline case, if there are multiple paragraphs
252 // they are simply joined. Otherwise, expect latex errors.
253 if (par != end && !isInline && !captionline)
257 static const docstring delimiters =
258 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
260 size_t pos = delimiters.find_first_not_of(code);
262 // This code piece contains all possible special character? !!!
263 // Replace ! with a warning message and use ! as delimiter.
264 if (pos == string::npos) {
265 docstring delim_error = "<" + _("LyX Warning: ")
266 + _("no more lstline delimiters available") + ">";
267 code = subst(code, from_ascii("!"), delim_error);
269 if (!runparams.dryrun && !runparams.silent) {
270 // FIXME: warning should be passed to the error dialog
271 frontend::Alert::warning(_("Running out of delimiters"),
272 _("For inline program listings, one character must be reserved\n"
273 "as a delimiter. One of the listings, however, uses all available\n"
274 "characters, so none is left for delimiting purposes.\n"
275 "For the time being, I have replaced '!' by a warning, but you\n"
276 "must investigate!"));
279 docstring const delim(1, delimiters[pos]);
281 os << "\\mintinline";
282 if (!param_string.empty())
283 os << "[" << from_utf8(param_string) << "]";
284 os << "{" << ascii_lowercase(minted_language) << "}";
287 if (!param_string.empty())
288 os << "[" << from_utf8(param_string) << "]";
289 else if (pos >= delimiters.find('Q'))
290 // We need to terminate the command before
294 os << delim << code << delim;
295 } else if (use_minted) {
296 OutputParams rp = runparams;
297 rp.moving_arg = true;
298 TexString caption = getCaption(rp);
300 os << breakln << "\\begin{listing}";
301 if (!float_placement.empty())
302 os << '[' << float_placement << "]";
303 } else if (captionfirst && !caption.str.empty()) {
304 os << breakln << "\\lyxmintcaption[t]{"
305 << move(caption) << "}\n";
307 os << breakln << "\\begin{minted}";
308 if (!param_string.empty())
309 os << "[" << param_string << "]";
310 os << "{" << ascii_lowercase(minted_language) << "}\n"
311 << code << breakln << "\\end{minted}\n";
313 if (!caption.str.empty())
314 os << "\\caption{" << move(caption) << "}\n";
315 os << "\\end{listing}\n";
316 } else if (!captionfirst && !caption.str.empty()) {
317 os << breakln << "\\lyxmintcaption[b]{"
318 << move(caption) << "}";
321 OutputParams rp = runparams;
322 rp.moving_arg = true;
323 TexString caption = getCaption(rp);
324 os << breakln << "\\begin{lstlisting}";
325 if (param_string.empty() && caption.str.empty())
331 if (!caption.str.empty()) {
332 os << "caption={" << move(caption) << '}';
333 if (!param_string.empty())
336 os << from_utf8(param_string) << "]\n";
338 os << code << "\\end{lstlisting}\n";
341 if (encoding_switched){
343 switchEncoding(os.os(), buffer().params(),
344 runparams, *save_enc, true, true);
345 os << "\\egroup" << breakln;
346 runparams.encoding = save_enc;
349 if (!uncodable.empty() && !runparams.silent) {
350 // issue a warning about omitted characters
351 // FIXME: should be passed to the error dialog
353 frontend::Alert::warning(_("Uncodable characters in listings inset"),
354 bformat(_("The following characters in one of the program listings are\n"
355 "not representable in the current encoding and have been omitted:\n%1$s.\n"
356 "This is due to a restriction of the listings package, which does\n"
357 "not support your encoding '%2$s'.\n"
358 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
360 uncodable, _(runparams.encoding->guiName())));
362 frontend::Alert::warning(_("Uncodable characters in listings inset"),
363 bformat(_("The following characters in one of the program listings are\n"
364 "not representable in the current encoding and have been omitted:\n%1$s."),
370 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
372 odocstringstream ods;
373 XHTMLStream out(ods);
375 bool const isInline = params().isInline();
377 out << html::CompTag("br");
379 out << html::StartTag("div", "class='float-listings'");
380 docstring caption = getCaptionHTML(rp);
381 if (!caption.empty())
382 out << html::StartTag("div", "class='listings-caption'")
383 << XHTMLStream::ESCAPE_NONE
384 << caption << html::EndTag("div");
387 InsetLayout const & il = getLayout();
388 string const & tag = il.htmltag();
389 string attr = "class ='listings";
390 string const lang = params().getParamValue("language");
394 out << html::StartTag(tag, attr);
395 OutputParams newrp = rp;
396 newrp.html_disable_captions = true;
397 // We don't want to convert dashes here. That's the only conversion we
398 // do for XHTML, so this is safe.
399 newrp.pass_thru = true;
400 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
401 out << html::EndTag(tag);
404 out << html::CompTag("br");
405 // escaping will already have been done
406 os << XHTMLStream::ESCAPE_NONE << ods.str();
408 out << html::EndTag("div");
409 // In this case, this needs to be deferred, but we'll put it
410 // before anything the text itself deferred.
411 def = ods.str() + '\n' + def;
417 string InsetListings::contextMenuName() const
419 return "context-listings";
423 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
425 switch (cmd.action()) {
427 case LFUN_INSET_MODIFY: {
428 cur.recordUndoInset(this);
429 InsetListings::string2params(to_utf8(cmd.argument()), params());
433 case LFUN_INSET_DIALOG_UPDATE:
434 cur.bv().updateDialog("listings", params2string(params()));
438 InsetCaptionable::doDispatch(cur, cmd);
444 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
445 FuncStatus & status) const
447 switch (cmd.action()) {
448 case LFUN_INSET_MODIFY:
449 case LFUN_INSET_DIALOG_UPDATE:
450 status.setEnabled(true);
452 case LFUN_CAPTION_INSERT: {
453 // the inset outputs at most one caption
454 if (params().isInline() || getCaptionInset()) {
455 status.setEnabled(false);
461 return InsetCaptionable::getStatus(cur, cmd, status);
466 docstring const InsetListings::buttonLabel(BufferView const & bv) const
469 if (decoration() == InsetLayout::CLASSIC)
470 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
472 return getNewLabel(_("Listing"));
476 void InsetListings::validate(LaTeXFeatures & features) const
478 features.useInsetLayout(getLayout());
479 string param_string = params().params();
480 if (buffer().params().use_minted) {
481 features.require("minted");
482 OutputParams rp = features.runparams();
483 if (!params().isFloat() && !getCaption(rp).str.empty())
484 features.require("lyxmintcaption");
486 features.require("listings");
487 if (contains(param_string, "\\color"))
488 features.require("color");
490 InsetCaptionable::validate(features);
494 bool InsetListings::showInsetDialog(BufferView * bv) const
496 bv->showDialog("listings", params2string(params()),
497 const_cast<InsetListings *>(this));
502 TexString InsetListings::getCaption(OutputParams const & runparams) const
504 InsetCaption const * ins = getCaptionInset();
509 ins->getArgs(os, runparams);
510 ins->getArgument(os, runparams);
512 // TODO: The code below should be moved to support, and then the test
513 // in ../tests should be moved there as well.
515 // the caption may contain \label{} but the listings
516 // package prefer caption={}, label={}
517 TexString cap = os.release();
518 if (buffer().params().use_minted
519 || !contains(cap.str, from_ascii("\\label{")))
522 // blah1\label{blah2} blah3
524 // blah1 blah3},label={blah2
526 // caption={blah1 blah3},label={blah2}
528 // NOTE that } is not allowed in blah2.
529 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
530 string const new_cap("$1$3},label={$2");
531 // TexString validity: the substitution preserves the number of newlines.
532 // Moreover we assume that $2 does not contain newlines, so that the texrow
533 // information remains accurate.
534 // Replace '\n' with an improbable character from Private Use Area-A
535 // and then return to '\n' after the regex replacement.
536 docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
537 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
538 0xffffd, char_type('\n'));
543 void InsetListings::string2params(string const & in,
544 InsetListingsParams & params)
546 params = InsetListingsParams();
549 istringstream data(in);
552 // discard "listings", which is only used to determine inset
558 string InsetListings::params2string(InsetListingsParams const & params)
561 data << "listings" << ' ';