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 || (buffer().params().encoding().package() == Encoding::japanese
131 && inner_enc->package() == Encoding::japanese)
132 || inner_enc->hasFixedWidth())
135 // We try if there's a singlebyte encoding for the outer
136 // language; if not, fall back to latin1.
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 string minted_language;
150 string float_placement;
151 bool const isfloat = params().isFloat();
152 if (use_minted && (isfloat || contains(param_string, "language="))) {
153 // Get float placement and/or language of the code,
154 // then remove the relative options.
155 vector<string> opts =
156 getVectorFromString(param_string, ",", false);
157 for (size_t i = 0; i < opts.size(); ++i) {
158 if (prefixIs(opts[i], "float")) {
159 if (prefixIs(opts[i], "float="))
160 float_placement = opts[i].substr(6);
161 opts.erase(opts.begin() + i--);
163 else if (prefixIs(opts[i], "language=")) {
164 minted_language = opts[i].substr(9);
165 opts.erase(opts.begin() + i--);
168 param_string = getStringFromVector(opts, ",");
170 // Minted needs a language specification
171 if (minted_language.empty())
172 minted_language = "TeX";
174 // get the paragraphs. We can not output them directly to given odocstream
175 // because we can not yet determine the delimiter character of \lstinline
178 ParagraphList::const_iterator par = paragraphs().begin();
179 ParagraphList::const_iterator end = paragraphs().end();
181 bool encoding_switched = false;
182 Encoding const * const save_enc = runparams.encoding;
184 Encoding const * const outer_encoding =
185 (runparams.local_font != 0) ?
186 runparams.local_font->language()->encoding()
187 : buffer().params().language->encoding();
188 Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
190 // We need to switch to a singlebyte encoding, due to
191 // the restrictions of the listings package (see above).
192 // This needs to be consistent with
193 // LaTeXFeatures::getTClassI18nPreamble().
194 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
195 runparams.encoding = fixedlstenc;
196 encoding_switched = true;
199 bool const captionfirst = !isfloat && par->isInset(0)
200 && par->getInset(0)->lyxCode() == CAPTION_CODE;
203 pos_type siz = par->size();
204 bool captionline = false;
205 for (pos_type i = 0; i < siz; ++i) {
206 if (i == 0 && par->isInset(i) && i + 1 == siz)
208 // ignore all struck out text and (caption) insets
209 if (par->isDeleted(i)
210 || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
212 if (par->isInset(i)) {
213 // Currently, this can only be a quote inset
214 // that is output as plain quote here, but
215 // we use more generic code anyway.
216 otexstringstream ots;
217 OutputParams rp = runparams;
219 par->getInset(i)->latex(ots, rp);
223 char_type c = par->getChar(i);
224 // we can only output characters covered by the current
227 if (runparams.encoding->encodable(c))
229 else if (runparams.dryrun) {
230 code += "<" + _("LyX Warning: ")
231 + _("uncodable character") + " '";
232 code += docstring(1, c);
236 } catch (EncodingException & /* e */) {
237 if (runparams.dryrun) {
238 code += "<" + _("LyX Warning: ")
239 + _("uncodable character") + " '";
240 code += docstring(1, c);
247 // for the inline case, if there are multiple paragraphs
248 // they are simply joined. Otherwise, expect latex errors.
249 if (par != end && !isInline && !captionline)
253 static const docstring delimiters =
254 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
256 size_t pos = delimiters.find_first_not_of(code);
258 // This code piece contains all possible special character? !!!
259 // Replace ! with a warning message and use ! as delimiter.
260 if (pos == string::npos) {
261 docstring delim_error = "<" + _("LyX Warning: ")
262 + _("no more lstline delimiters available") + ">";
263 code = subst(code, from_ascii("!"), delim_error);
265 if (!runparams.dryrun && !runparams.silent) {
266 // FIXME: warning should be passed to the error dialog
267 frontend::Alert::warning(_("Running out of delimiters"),
268 _("For inline program listings, one character must be reserved\n"
269 "as a delimiter. One of the listings, however, uses all available\n"
270 "characters, so none is left for delimiting purposes.\n"
271 "For the time being, I have replaced '!' by a warning, but you\n"
272 "must investigate!"));
275 docstring const delim(1, delimiters[pos]);
277 os << "\\mintinline";
278 if (!param_string.empty())
279 os << "[" << from_utf8(param_string) << "]";
280 os << "{" << ascii_lowercase(minted_language) << "}";
283 if (!param_string.empty())
284 os << "[" << from_utf8(param_string) << "]";
285 else if (pos >= delimiters.find('Q'))
286 // We need to terminate the command before
290 os << delim << code << delim;
291 } else if (use_minted) {
292 OutputParams rp = runparams;
293 rp.moving_arg = true;
294 TexString caption = getCaption(rp);
296 os << breakln << "\\begin{listing}";
297 if (!float_placement.empty())
298 os << '[' << float_placement << "]";
299 } else if (captionfirst && !caption.str.empty()) {
300 os << breakln << "\\lyxmintcaption[t]{"
301 << move(caption) << "}\n";
303 os << breakln << "\\begin{minted}";
304 if (!param_string.empty())
305 os << "[" << param_string << "]";
306 os << "{" << ascii_lowercase(minted_language) << "}\n"
307 << code << breakln << "\\end{minted}\n";
309 if (!caption.str.empty())
310 os << "\\caption{" << move(caption) << "}\n";
311 os << "\\end{listing}\n";
312 } else if (!captionfirst && !caption.str.empty()) {
313 os << breakln << "\\lyxmintcaption[b]{"
314 << move(caption) << "}";
317 OutputParams rp = runparams;
318 rp.moving_arg = true;
319 TexString caption = getCaption(rp);
320 os << breakln << "\\begin{lstlisting}";
321 if (param_string.empty() && caption.str.empty())
327 if (!caption.str.empty()) {
328 os << "caption={" << move(caption) << '}';
329 if (!param_string.empty())
332 os << from_utf8(param_string) << "]\n";
334 os << code << breakln << "\\end{lstlisting}\n";
337 if (encoding_switched){
339 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
340 runparams.encoding = save_enc;
343 if (!uncodable.empty() && !runparams.silent) {
344 // issue a warning about omitted characters
345 // FIXME: should be passed to the error dialog
347 frontend::Alert::warning(_("Uncodable characters in listings inset"),
348 bformat(_("The following characters in one of the program listings are\n"
349 "not representable in the current encoding and have been omitted:\n%1$s.\n"
350 "This is due to a restriction of the listings package, which does\n"
351 "not support your encoding '%2$s'.\n"
352 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
354 uncodable, _(runparams.encoding->guiName())));
356 frontend::Alert::warning(_("Uncodable characters in listings inset"),
357 bformat(_("The following characters in one of the program listings are\n"
358 "not representable in the current encoding and have been omitted:\n%1$s."),
364 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
366 odocstringstream ods;
367 XHTMLStream out(ods);
369 bool const isInline = params().isInline();
371 out << html::CompTag("br");
373 out << html::StartTag("div", "class='float-listings'");
374 docstring caption = getCaptionHTML(rp);
375 if (!caption.empty())
376 out << html::StartTag("div", "class='listings-caption'")
377 << XHTMLStream::ESCAPE_NONE
378 << caption << html::EndTag("div");
381 InsetLayout const & il = getLayout();
382 string const & tag = il.htmltag();
383 string attr = "class ='listings";
384 string const lang = params().getParamValue("language");
388 out << html::StartTag(tag, attr);
389 OutputParams newrp = rp;
390 newrp.html_disable_captions = true;
391 // We don't want to convert dashes here. That's the only conversion we
392 // do for XHTML, so this is safe.
393 newrp.pass_thru = true;
394 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
395 out << html::EndTag(tag);
398 out << html::CompTag("br");
399 // escaping will already have been done
400 os << XHTMLStream::ESCAPE_NONE << ods.str();
402 out << html::EndTag("div");
403 // In this case, this needs to be deferred, but we'll put it
404 // before anything the text itself deferred.
405 def = ods.str() + '\n' + def;
411 string InsetListings::contextMenuName() const
413 return "context-listings";
417 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
419 switch (cmd.action()) {
421 case LFUN_INSET_MODIFY: {
422 cur.recordUndoInset(this);
423 InsetListings::string2params(to_utf8(cmd.argument()), params());
427 case LFUN_INSET_DIALOG_UPDATE:
428 cur.bv().updateDialog("listings", params2string(params()));
432 InsetCaptionable::doDispatch(cur, cmd);
438 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
439 FuncStatus & status) const
441 switch (cmd.action()) {
442 case LFUN_INSET_MODIFY:
443 case LFUN_INSET_DIALOG_UPDATE:
444 status.setEnabled(true);
446 case LFUN_CAPTION_INSERT: {
447 // the inset outputs at most one caption
448 if (params().isInline() || getCaptionInset()) {
449 status.setEnabled(false);
455 return InsetCaptionable::getStatus(cur, cmd, status);
460 docstring const InsetListings::buttonLabel(BufferView const & bv) const
463 if (decoration() == InsetLayout::CLASSIC)
464 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
466 return getNewLabel(_("Listing"));
470 void InsetListings::validate(LaTeXFeatures & features) const
472 features.useInsetLayout(getLayout());
473 string param_string = params().params();
474 if (buffer().params().use_minted) {
475 features.require("minted");
476 OutputParams rp = features.runparams();
477 if (!params().isFloat() && !getCaption(rp).str.empty())
478 features.require("lyxmintcaption");
480 features.require("listings");
481 if (contains(param_string, "\\color"))
482 features.require("color");
484 InsetCaptionable::validate(features);
488 bool InsetListings::showInsetDialog(BufferView * bv) const
490 bv->showDialog("listings", params2string(params()),
491 const_cast<InsetListings *>(this));
496 TexString InsetListings::getCaption(OutputParams const & runparams) const
498 InsetCaption const * ins = getCaptionInset();
503 ins->getArgs(os, runparams);
504 ins->getArgument(os, runparams);
506 // TODO: The code below should be moved to support, and then the test
507 // in ../tests should be moved there as well.
509 // the caption may contain \label{} but the listings
510 // package prefer caption={}, label={}
511 TexString cap = os.release();
512 if (buffer().params().use_minted
513 || !contains(cap.str, from_ascii("\\label{")))
516 // blah1\label{blah2} blah3
518 // blah1 blah3},label={blah2
520 // caption={blah1 blah3},label={blah2}
522 // NOTE that } is not allowed in blah2.
523 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
524 string const new_cap("$1$3},label={$2");
525 // TexString validity: the substitution preserves the number of newlines.
526 // Moreover we assume that $2 does not contain newlines, so that the texrow
527 // information remains accurate.
528 // Replace '\n' with an improbable character from Private Use Area-A
529 // and then return to '\n' after the regex replacement.
530 docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
531 cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
532 0xffffd, char_type('\n'));
537 void InsetListings::string2params(string const & in,
538 InsetListingsParams & params)
540 params = InsetListingsParams();
543 istringstream data(in);
546 // discard "listings", which is only used to determine inset
552 string InsetListings::params2string(InsetListingsParams const & params)
555 data << "listings" << ' ';