]> git.lyx.org Git - lyx.git/blob - InsetListings.cpp
d106da39092d5ab721fd2f475bf0b9817cfd9757
[lyx.git] / 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 "Counters.h"
20 #include "Cursor.h"
21 #include "DispatchResult.h"
22 #include "Encoding.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
26 #include "Language.h"
27 #include "LaTeXFeatures.h"
28 #include "Lexer.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
33 #include "TexRow.h"
34 #include "texstream.h"
35
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"
41
42 #include "frontends/alert.h"
43 #include "frontends/Application.h"
44
45 #include "support/regex.h"
46
47 #include <sstream>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56         : InsetCaptionable(buf,"listing")
57 {
58         params_.setMinted(buffer().params().use_minted);
59         status_ = par.status();
60 }
61
62
63 InsetListings::~InsetListings()
64 {
65         hideDialogs("listings", this);
66 }
67
68
69 Inset::DisplayType InsetListings::display() const
70 {
71         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
72 }
73
74
75 docstring InsetListings::layoutName() const
76 {
77         if (buffer().params().use_minted)
78                 return from_ascii("MintedListings");
79         else
80                 return from_ascii("Listings");
81 }
82
83
84 void InsetListings::write(ostream & os) const
85 {
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();
90         if (!opt.empty())
91                 os << "lstparams \"" << opt << "\"\n";
92         if (par.isInline())
93                 os << "inline true\n";
94         else
95                 os << "inline false\n";
96         InsetCaptionable::write(os);
97 }
98
99
100 void InsetListings::read(Lexer & lex)
101 {
102         while (lex.isOK()) {
103                 lex.next();
104                 string token = lex.getString();
105                 if (token == "lstparams") {
106                         lex.next();
107                         string const value = lex.getString();
108                         params().fromEncodedString(value);
109                 } else if (token == "inline") {
110                         lex.next();
111                         params().setInline(lex.getBool());
112                 } else {
113                         // no special option, push back 'status' etc
114                         lex.pushToken(token);
115                         break;
116                 }
117         }
118         InsetCaptionable::read(lex);
119 }
120
121
122 Encoding const * InsetListings::forcedEncoding(Encoding const * inner_enc,
123                                                                                            Encoding const * outer_enc) const
124 {
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())
134                 return 0;
135
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");
140 }
141
142
143 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
144 {
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--);
163                         }
164                         else if (prefixIs(opts[i], "language=")) {
165                                 minted_language = opts[i].substr(9);
166                                 opts.erase(opts.begin() + i--);
167                         }
168                 }
169                 param_string = getStringFromVector(opts, ",");
170         }
171         // Minted needs a language specification
172         if (minted_language.empty())
173                 minted_language = "TeX";
174
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
177         docstring code;
178         docstring uncodable;
179         ParagraphList::const_iterator par = paragraphs().begin();
180         ParagraphList::const_iterator end = paragraphs().end();
181
182         bool encoding_switched = false;
183         Encoding const * const save_enc = runparams.encoding;
184
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);
190         if (fixedlstenc) {
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                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
196                 runparams.encoding = fixedlstenc;
197                 encoding_switched = true;
198         }
199
200         bool const captionfirst = !isfloat && par->isInset(0)
201                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
202
203         while (par != end) {
204                 pos_type siz = par->size();
205                 bool captionline = false;
206                 for (pos_type i = 0; i < siz; ++i) {
207                         if (i == 0 && par->isInset(i) && i + 1 == siz)
208                                 captionline = true;
209                         // ignore all struck out text and (caption) insets
210                         if (par->isDeleted(i)
211                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
212                                 continue;
213                         if (par->isInset(i)) {
214                                 // Currently, this can only be a quote inset
215                                 // that is output as plain quote here, but
216                                 // we use more generic code anyway.
217                                 otexstringstream ots;
218                                 OutputParams rp = runparams;
219                                 rp.pass_thru = true;
220                                 par->getInset(i)->latex(ots, rp);
221                                 code += ots.str();
222                                 continue;
223                         }
224                         char_type c = par->getChar(i);
225                         // we can only output characters covered by the current
226                         // encoding!
227                         try {
228                                 if (runparams.encoding->encodable(c))
229                                         code += c;
230                                 else if (runparams.dryrun) {
231                                         code += "<" + _("LyX Warning: ")
232                                            + _("uncodable character") + " '";
233                                         code += docstring(1, c);
234                                         code += "'>";
235                                 } else
236                                         uncodable += c;
237                         } catch (EncodingException & /* e */) {
238                                 if (runparams.dryrun) {
239                                         code += "<" + _("LyX Warning: ")
240                                            + _("uncodable character") + " '";
241                                         code += docstring(1, c);
242                                         code += "'>";
243                                 } else
244                                         uncodable += c;
245                         }
246                 }
247                 ++par;
248                 // for the inline case, if there are multiple paragraphs
249                 // they are simply joined. Otherwise, expect latex errors.
250                 if (par != end && !isInline && !captionline)
251                         code += "\n";
252         }
253         if (isInline) {
254                 static const docstring delimiters =
255                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
256
257                 size_t pos = delimiters.find_first_not_of(code);
258
259                 // This code piece contains all possible special character? !!!
260                 // Replace ! with a warning message and use ! as delimiter.
261                 if (pos == string::npos) {
262                         docstring delim_error = "<" + _("LyX Warning: ")
263                                 + _("no more lstline delimiters available") + ">";
264                         code = subst(code, from_ascii("!"), delim_error);
265                         pos = 0;
266                         if (!runparams.dryrun && !runparams.silent) {
267                                 // FIXME: warning should be passed to the error dialog
268                                 frontend::Alert::warning(_("Running out of delimiters"),
269                                 _("For inline program listings, one character must be reserved\n"
270                                   "as a delimiter. One of the listings, however, uses all available\n"
271                                   "characters, so none is left for delimiting purposes.\n"
272                                   "For the time being, I have replaced '!' by a warning, but you\n"
273                                   "must investigate!"));
274                         }
275                 }
276                 docstring const delim(1, delimiters[pos]);
277                 if (use_minted) {
278                         os << "\\mintinline";
279                         if (!param_string.empty())
280                                 os << "[" << from_utf8(param_string) << "]";
281                         os << "{" << ascii_lowercase(minted_language) << "}";
282                 } else {
283                         os << "\\lstinline";
284                         if (!param_string.empty())
285                                 os << "[" << from_utf8(param_string) << "]";
286                         else if (pos >= delimiters.find('Q'))
287                                 // We need to terminate the command before
288                                 // the delimiter
289                                 os << " ";
290                 }
291                 os << delim << code << delim;
292         } else if (use_minted) {
293                 OutputParams rp = runparams;
294                 rp.moving_arg = true;
295                 TexString caption = getCaption(rp);
296                 if (isfloat) {
297                         os << breakln << "\\begin{listing}";
298                         if (!float_placement.empty())
299                                 os << '[' << float_placement << "]";
300                 } else if (captionfirst && !caption.str.empty()) {
301                         os << breakln << "\\lyxmintcaption[t]{"
302                            << move(caption) << "}\n";
303                 }
304                 os << breakln << "\\begin{minted}";
305                 if (!param_string.empty())
306                         os << "[" << param_string << "]";
307                 os << "{" << ascii_lowercase(minted_language) << "}\n"
308                    << code << breakln << "\\end{minted}\n";
309                 if (isfloat) {
310                         if (!caption.str.empty())
311                                 os << "\\caption{" << move(caption) << "}\n";
312                         os << "\\end{listing}\n";
313                 } else if (!captionfirst && !caption.str.empty()) {
314                         os << breakln << "\\lyxmintcaption[b]{"
315                            << move(caption) << "}";
316                 }
317         } else {
318                 OutputParams rp = runparams;
319                 rp.moving_arg = true;
320                 TexString caption = getCaption(rp);
321                 os << breakln << "\\begin{lstlisting}";
322                 if (param_string.empty() && caption.str.empty())
323                         os << "\n";
324                 else {
325                         if (!runparams.nice)
326                                 os << safebreakln;
327                         os << "[";
328                         if (!caption.str.empty()) {
329                                 os << "caption={" << move(caption) << '}';
330                                 if (!param_string.empty())
331                                         os << ',';
332                         }
333                         os << from_utf8(param_string) << "]\n";
334                 }
335                 os << code << breakln << "\\end{lstlisting}\n";
336         }
337
338         if (encoding_switched){
339                 // Switch back
340                 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
341                 runparams.encoding = save_enc;
342         }
343
344         if (!uncodable.empty() && !runparams.silent) {
345                 // issue a warning about omitted characters
346                 // FIXME: should be passed to the error dialog
347                 if (fixedlstenc)
348                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
349                                 bformat(_("The following characters in one of the program listings are\n"
350                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
351                                           "This is due to a restriction of the listings package, which does\n"
352                                           "not support your encoding '%2$s'.\n"
353                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
354                                           "might help."),
355                                 uncodable, _(runparams.encoding->guiName())));
356                 else
357                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
358                                 bformat(_("The following characters in one of the program listings are\n"
359                                           "not representable in the current encoding and have been omitted:\n%1$s."),
360                                 uncodable));
361         }
362 }
363
364
365 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
366 {
367         odocstringstream ods;
368         XHTMLStream out(ods);
369
370         bool const isInline = params().isInline();
371         if (isInline)
372                 out << html::CompTag("br");
373         else {
374                 out << html::StartTag("div", "class='float-listings'");
375                 docstring caption = getCaptionHTML(rp);
376                 if (!caption.empty())
377                         out << html::StartTag("div", "class='listings-caption'")
378                             << XHTMLStream::ESCAPE_NONE
379                             << caption << html::EndTag("div");
380         }
381
382         InsetLayout const & il = getLayout();
383         string const & tag = il.htmltag();
384         string attr = "class ='listings";
385         string const lang = params().getParamValue("language");
386         if (!lang.empty())
387                 attr += " " + lang;
388         attr += "'";
389         out << html::StartTag(tag, attr);
390         OutputParams newrp = rp;
391         newrp.html_disable_captions = true;
392         // We don't want to convert dashes here. That's the only conversion we
393         // do for XHTML, so this is safe.
394         newrp.pass_thru = true;
395         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
396         out << html::EndTag(tag);
397
398         if (isInline) {
399                 out << html::CompTag("br");
400                 // escaping will already have been done
401                 os << XHTMLStream::ESCAPE_NONE << ods.str();
402         } else {
403                 out << html::EndTag("div");
404                 // In this case, this needs to be deferred, but we'll put it
405                 // before anything the text itself deferred.
406                 def = ods.str() + '\n' + def;
407         }
408         return def;
409 }
410
411
412 string InsetListings::contextMenuName() const
413 {
414         return "context-listings";
415 }
416
417
418 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
419 {
420         switch (cmd.action()) {
421
422         case LFUN_INSET_MODIFY: {
423                 cur.recordUndoInset(this);
424                 InsetListings::string2params(to_utf8(cmd.argument()), params());
425                 break;
426         }
427
428         case LFUN_INSET_DIALOG_UPDATE:
429                 cur.bv().updateDialog("listings", params2string(params()));
430                 break;
431
432         default:
433                 InsetCaptionable::doDispatch(cur, cmd);
434                 break;
435         }
436 }
437
438
439 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
440         FuncStatus & status) const
441 {
442         switch (cmd.action()) {
443                 case LFUN_INSET_MODIFY:
444                 case LFUN_INSET_DIALOG_UPDATE:
445                         status.setEnabled(true);
446                         return true;
447                 case LFUN_CAPTION_INSERT: {
448                         // the inset outputs at most one caption
449                         if (params().isInline() || getCaptionInset()) {
450                                 status.setEnabled(false);
451                                 return true;
452                         }
453                 }
454                 // fall through
455                 default:
456                         return InsetCaptionable::getStatus(cur, cmd, status);
457         }
458 }
459
460
461 docstring const InsetListings::buttonLabel(BufferView const & bv) const
462 {
463         // FIXME UNICODE
464         if (decoration() == InsetLayout::CLASSIC)
465                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
466         else
467                 return getNewLabel(_("Listing"));
468 }
469
470
471 void InsetListings::validate(LaTeXFeatures & features) const
472 {
473         features.useInsetLayout(getLayout());
474         string param_string = params().params();
475         if (buffer().params().use_minted) {
476                 features.require("minted");
477                 OutputParams rp = features.runparams();
478                 if (!params().isFloat() && !getCaption(rp).str.empty())
479                         features.require("lyxmintcaption");
480         } else {
481                 features.require("listings");
482                 if (contains(param_string, "\\color"))
483                         features.require("color");
484         }
485         InsetCaptionable::validate(features);
486 }
487
488
489 bool InsetListings::showInsetDialog(BufferView * bv) const
490 {
491         bv->showDialog("listings", params2string(params()),
492                 const_cast<InsetListings *>(this));
493         return true;
494 }
495
496
497 TexString InsetListings::getCaption(OutputParams const & runparams) const
498 {
499         InsetCaption const * ins = getCaptionInset();
500         if (ins == 0)
501                 return TexString();
502
503         otexstringstream os;
504         ins->getArgs(os, runparams);
505         ins->getArgument(os, runparams);
506
507         // TODO: The code below should be moved to support, and then the test
508         //       in ../tests should be moved there as well.
509
510         // the caption may contain \label{} but the listings
511         // package prefer caption={}, label={}
512         TexString cap = os.release();
513         if (buffer().params().use_minted
514             || !contains(cap.str, from_ascii("\\label{")))
515                 return cap;
516         // convert from
517         //     blah1\label{blah2} blah3
518         // to
519         //     blah1 blah3},label={blah2
520         // to form options
521         //     caption={blah1 blah3},label={blah2}
522         //
523         // NOTE that } is not allowed in blah2.
524         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
525         string const new_cap("$1$3},label={$2");
526         // TexString validity: the substitution preserves the number of newlines.
527         // Moreover we assume that $2 does not contain newlines, so that the texrow
528         // information remains accurate.
529         // Replace '\n' with an improbable character from Private Use Area-A
530         // and then return to '\n' after the regex replacement.
531         docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
532         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
533                         0xffffd, char_type('\n'));
534         return cap;
535 }
536
537
538 void InsetListings::string2params(string const & in,
539                                    InsetListingsParams & params)
540 {
541         params = InsetListingsParams();
542         if (in.empty())
543                 return;
544         istringstream data(in);
545         Lexer lex;
546         lex.setStream(data);
547         // discard "listings", which is only used to determine inset
548         lex.next();
549         params.read(lex);
550 }
551
552
553 string InsetListings::params2string(InsetListingsParams const & params)
554 {
555         ostringstream data;
556         data << "listings" << ' ';
557         params.write(data);
558         return data.str();
559 }
560
561
562 } // namespace lyx