]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
InsetInfo: enable inset dissolve
[lyx.git] / src / insets / 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                 // If a language has been set globally, use that,
174                 // otherwise use TeX by default
175                 string const & blp = buffer().params().listings_params;
176                 size_t start = blp.find("language=");
177                 if (start != string::npos) {
178                         start += strlen("language=");
179                         size_t len = blp.find(",", start);
180                         if (len != string::npos)
181                                 len -= start;
182                         minted_language = blp.substr(start, len);
183                 } else
184                         minted_language = "TeX";
185         }
186
187         // get the paragraphs. We can not output them directly to given odocstream
188         // because we can not yet determine the delimiter character of \lstinline
189         docstring code;
190         docstring uncodable;
191         ParagraphList::const_iterator par = paragraphs().begin();
192         ParagraphList::const_iterator end = paragraphs().end();
193
194         bool encoding_switched = false;
195         Encoding const * const save_enc = runparams.encoding;
196
197         Encoding const * const outer_encoding =
198                 (runparams.local_font != 0) ?
199                         runparams.local_font->language()->encoding()
200                         : buffer().params().language->encoding();
201         Encoding const * fixedlstenc = forcedEncoding(runparams.encoding, outer_encoding);
202         if (fixedlstenc) {
203                 // We need to switch to a singlebyte encoding, due to
204                 // the restrictions of the listings package (see above).
205                 // This needs to be consistent with
206                 // LaTeXFeatures::getTClassI18nPreamble().
207                 // We need to put this into a group in order to prevent encoding leaks
208                 // (happens with cprotect).
209                 os << "\\bgroup";
210                 switchEncoding(os.os(), buffer().params(), runparams, *fixedlstenc, true);
211                 runparams.encoding = fixedlstenc;
212                 encoding_switched = true;
213         }
214
215         bool const captionfirst = !isfloat && par->isInset(0)
216                                 && par->getInset(0)->lyxCode() == CAPTION_CODE;
217
218         while (par != end) {
219                 pos_type const siz = par->size();
220                 bool captionline = false;
221                 for (pos_type i = 0; i < siz; ++i) {
222                         if (i == 0 && par->isInset(i) && i + 1 == siz)
223                                 captionline = true;
224                         // ignore all struck out text and (caption) insets
225                         if (par->isDeleted(i)
226                             || (par->isInset(i) && par->getInset(i)->lyxCode() == CAPTION_CODE))
227                                 continue;
228                         if (par->isInset(i)) {
229                                 // Currently, this can only be a quote inset
230                                 // that is output as plain quote here, but
231                                 // we use more generic code anyway.
232                                 otexstringstream ots;
233                                 OutputParams rp = runparams;
234                                 rp.pass_thru = true;
235                                 par->getInset(i)->latex(ots, rp);
236                                 code += ots.str();
237                                 continue;
238                         }
239                         char_type c = par->getChar(i);
240                         // we can only output characters covered by the current
241                         // encoding!
242                         try {
243                                 if (runparams.encoding->encodable(c))
244                                         code += c;
245                                 else if (runparams.dryrun) {
246                                         code += "<" + _("LyX Warning: ")
247                                            + _("uncodable character") + " '";
248                                         code += docstring(1, c);
249                                         code += "'>";
250                                 } else
251                                         uncodable += c;
252                         } catch (EncodingException & /* e */) {
253                                 if (runparams.dryrun) {
254                                         code += "<" + _("LyX Warning: ")
255                                            + _("uncodable character") + " '";
256                                         code += docstring(1, c);
257                                         code += "'>";
258                                 } else
259                                         uncodable += c;
260                         }
261                 }
262                 ++par;
263                 // for the inline case, if there are multiple paragraphs
264                 // they are simply joined. Otherwise, expect latex errors.
265                 if (par != end && !isInline && !captionline)
266                         code += "\n";
267         }
268         if (isInline) {
269                 static const docstring delimiters =
270                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
271
272                 size_t pos = delimiters.find_first_not_of(code);
273
274                 // This code piece contains all possible special character? !!!
275                 // Replace ! with a warning message and use ! as delimiter.
276                 if (pos == string::npos) {
277                         docstring delim_error = "<" + _("LyX Warning: ")
278                                 + _("no more lstline delimiters available") + ">";
279                         code = subst(code, from_ascii("!"), delim_error);
280                         pos = 0;
281                         if (!runparams.dryrun && !runparams.silent) {
282                                 // FIXME: warning should be passed to the error dialog
283                                 frontend::Alert::warning(_("Running out of delimiters"),
284                                 _("For inline program listings, one character must be reserved\n"
285                                   "as a delimiter. One of the listings, however, uses all available\n"
286                                   "characters, so none is left for delimiting purposes.\n"
287                                   "For the time being, I have replaced '!' by a warning, but you\n"
288                                   "must investigate!"));
289                         }
290                 }
291                 docstring const delim(1, delimiters[pos]);
292                 if (use_minted) {
293                         os << "\\mintinline";
294                         if (!param_string.empty())
295                                 os << "[" << from_utf8(param_string) << "]";
296                         os << "{" << ascii_lowercase(minted_language) << "}";
297                 } else {
298                         os << "\\lstinline";
299                         if (!param_string.empty())
300                                 os << "[" << from_utf8(param_string) << "]";
301                         else if (pos >= delimiters.find('Q'))
302                                 // We need to terminate the command before
303                                 // the delimiter
304                                 os << " ";
305                 }
306                 os << delim << code << delim;
307         } else if (use_minted) {
308                 OutputParams rp = runparams;
309                 rp.moving_arg = true;
310                 TexString caption = getCaption(rp);
311                 if (isfloat) {
312                         os << breakln << "\\begin{listing}";
313                         if (!float_placement.empty())
314                                 os << '[' << float_placement << "]";
315                 } else if (captionfirst && !caption.str.empty()) {
316                         os << breakln << "\\lyxmintcaption[t]{"
317                            << move(caption) << "}\n";
318                 }
319                 os << breakln << "\\begin{minted}";
320                 if (!param_string.empty())
321                         os << "[" << param_string << "]";
322                 os << "{" << ascii_lowercase(minted_language) << "}\n"
323                    << code << breakln << "\\end{minted}\n";
324                 if (isfloat) {
325                         if (!caption.str.empty())
326                                 os << "\\caption{" << move(caption) << "}\n";
327                         os << "\\end{listing}\n";
328                 } else if (!captionfirst && !caption.str.empty()) {
329                         os << breakln << "\\lyxmintcaption[b]{"
330                            << move(caption) << "}";
331                 }
332         } else {
333                 OutputParams rp = runparams;
334                 rp.moving_arg = true;
335                 TexString caption = getCaption(rp);
336                 os << breakln << "\\begin{lstlisting}";
337                 if (param_string.empty() && caption.str.empty())
338                         os << "\n";
339                 else {
340                         if (!runparams.nice)
341                                 os << safebreakln;
342                         os << "[";
343                         if (!caption.str.empty()) {
344                                 os << "caption={" << move(caption) << '}';
345                                 if (!param_string.empty())
346                                         os << ',';
347                         }
348                         os << from_utf8(param_string) << "]\n";
349                 }
350                 os << code << breakln << "\\end{lstlisting}\n";
351         }
352
353         if (encoding_switched){
354                 // Switch back
355                 switchEncoding(os.os(), buffer().params(),
356                                runparams, *save_enc, true, true);
357                 os << "\\egroup" << breakln;
358                 runparams.encoding = save_enc;
359         }
360
361         if (!uncodable.empty() && !runparams.silent) {
362                 // issue a warning about omitted characters
363                 // FIXME: should be passed to the error dialog
364                 if (fixedlstenc)
365                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
366                                 bformat(_("The following characters in one of the program listings are\n"
367                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
368                                           "This is due to a restriction of the listings package, which does\n"
369                                           "not support your encoding '%2$s'.\n"
370                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
371                                           "might help."),
372                                 uncodable, _(runparams.encoding->guiName())));
373                 else
374                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
375                                 bformat(_("The following characters in one of the program listings are\n"
376                                           "not representable in the current encoding and have been omitted:\n%1$s."),
377                                 uncodable));
378         }
379 }
380
381
382 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
383 {
384         odocstringstream ods;
385         XHTMLStream out(ods);
386
387         bool const isInline = params().isInline();
388         if (isInline)
389                 out << html::CompTag("br");
390         else {
391                 out << html::StartTag("div", "class='float-listings'");
392                 docstring caption = getCaptionHTML(rp);
393                 if (!caption.empty())
394                         out << html::StartTag("div", "class='listings-caption'")
395                             << XHTMLStream::ESCAPE_NONE
396                             << caption << html::EndTag("div");
397         }
398
399         InsetLayout const & il = getLayout();
400         string const & tag = il.htmltag();
401         string attr = "class ='listings";
402         string const lang = params().getParamValue("language");
403         if (!lang.empty())
404                 attr += " " + lang;
405         attr += "'";
406         out << html::StartTag(tag, attr);
407         OutputParams newrp = rp;
408         newrp.html_disable_captions = true;
409         // We don't want to convert dashes here. That's the only conversion we
410         // do for XHTML, so this is safe.
411         newrp.pass_thru = true;
412         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
413         out << html::EndTag(tag);
414
415         if (isInline) {
416                 out << html::CompTag("br");
417                 // escaping will already have been done
418                 os << XHTMLStream::ESCAPE_NONE << ods.str();
419         } else {
420                 out << html::EndTag("div");
421                 // In this case, this needs to be deferred, but we'll put it
422                 // before anything the text itself deferred.
423                 def = ods.str() + '\n' + def;
424         }
425         return def;
426 }
427
428
429 string InsetListings::contextMenuName() const
430 {
431         return "context-listings";
432 }
433
434
435 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
436 {
437         switch (cmd.action()) {
438
439         case LFUN_INSET_MODIFY: {
440                 cur.recordUndoInset(this);
441                 InsetListings::string2params(to_utf8(cmd.argument()), params());
442                 break;
443         }
444
445         case LFUN_INSET_DIALOG_UPDATE:
446                 cur.bv().updateDialog("listings", params2string(params()));
447                 break;
448
449         default:
450                 InsetCaptionable::doDispatch(cur, cmd);
451                 break;
452         }
453 }
454
455
456 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
457         FuncStatus & status) const
458 {
459         switch (cmd.action()) {
460                 case LFUN_INSET_MODIFY:
461                 case LFUN_INSET_DIALOG_UPDATE:
462                         status.setEnabled(true);
463                         return true;
464                 case LFUN_CAPTION_INSERT: {
465                         // the inset outputs at most one caption
466                         if (params().isInline() || getCaptionInset()) {
467                                 status.setEnabled(false);
468                                 return true;
469                         }
470                 }
471                 // fall through
472                 default:
473                         return InsetCaptionable::getStatus(cur, cmd, status);
474         }
475 }
476
477
478 docstring const InsetListings::buttonLabel(BufferView const & bv) const
479 {
480         // FIXME UNICODE
481         if (decoration() == InsetLayout::CLASSIC)
482                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
483         else
484                 return getNewLabel(_("Listing"));
485 }
486
487
488 void InsetListings::validate(LaTeXFeatures & features) const
489 {
490         features.useInsetLayout(getLayout());
491         string param_string = params().params();
492         if (buffer().params().use_minted) {
493                 features.require("minted");
494                 OutputParams rp = features.runparams();
495                 if (!params().isFloat() && !getCaption(rp).str.empty())
496                         features.require("lyxmintcaption");
497         } else {
498                 features.require("listings");
499                 if (contains(param_string, "\\color"))
500                         features.require("color");
501         }
502         InsetCaptionable::validate(features);
503 }
504
505
506 bool InsetListings::showInsetDialog(BufferView * bv) const
507 {
508         bv->showDialog("listings", params2string(params()),
509                 const_cast<InsetListings *>(this));
510         return true;
511 }
512
513
514 TexString InsetListings::getCaption(OutputParams const & runparams) const
515 {
516         InsetCaption const * ins = getCaptionInset();
517         if (ins == 0)
518                 return TexString();
519
520         otexstringstream os;
521         ins->getArgs(os, runparams);
522         ins->getArgument(os, runparams);
523
524         // TODO: The code below should be moved to support, and then the test
525         //       in ../tests should be moved there as well.
526
527         // the caption may contain \label{} but the listings
528         // package prefer caption={}, label={}
529         TexString cap = os.release();
530         if (buffer().params().use_minted
531             || !contains(cap.str, from_ascii("\\label{")))
532                 return cap;
533         // convert from
534         //     blah1\label{blah2} blah3
535         // to
536         //     blah1 blah3},label={blah2
537         // to form options
538         //     caption={blah1 blah3},label={blah2}
539         //
540         // NOTE that } is not allowed in blah2.
541         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
542         string const new_cap("$1$3},label={$2");
543         // TexString validity: the substitution preserves the number of newlines.
544         // Moreover we assume that $2 does not contain newlines, so that the texrow
545         // information remains accurate.
546         // Replace '\n' with an improbable character from Private Use Area-A
547         // and then return to '\n' after the regex replacement.
548         docstring const capstr = subst(cap.str, char_type('\n'), 0xffffd);
549         cap.str = subst(from_utf8(regex_replace(to_utf8(capstr), reg, new_cap)),
550                         0xffffd, char_type('\n'));
551         return cap;
552 }
553
554
555 void InsetListings::string2params(string const & in,
556                                    InsetListingsParams & params)
557 {
558         params = InsetListingsParams();
559         if (in.empty())
560                 return;
561         istringstream data(in);
562         Lexer lex;
563         lex.setStream(data);
564         // discard "listings", which is only used to determine inset
565         lex.next();
566         params.read(lex);
567 }
568
569
570 string InsetListings::params2string(InsetListingsParams const & params)
571 {
572         ostringstream data;
573         data << "listings" << ' ';
574         params.write(data);
575         return data.str();
576 }
577
578
579 } // namespace lyx