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