]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
InsetBox.cpp: only shaded boxes can have multiple paragraphs when there is no inner box
[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 "Lexer.h"
28 #include "output_latex.h"
29 #include "output_xhtml.h"
30 #include "TextClass.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/lassert.h"
37
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
40
41 #include "support/regex.h"
42
43 #include <sstream>
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50
51 char const lstinline_delimiters[] =
52         "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
53
54 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
55         : InsetCollapsable(buf)
56 {
57         status_ = par.status();
58 }
59
60
61 InsetListings::~InsetListings()
62 {
63         hideDialogs("listings", this);
64 }
65
66
67 Inset::DisplayType InsetListings::display() const
68 {
69         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
70 }
71
72
73 void InsetListings::updateBuffer(ParIterator const & it, UpdateType utype)
74 {
75         Counters & cnts =
76                 buffer().masterBuffer()->params().documentClass().counters();
77         string const saveflt = cnts.current_float();
78
79         // Tell to captions what the current float is
80         cnts.current_float("listing");
81
82         InsetCollapsable::updateBuffer(it, utype);
83
84         //reset afterwards
85         cnts.current_float(saveflt);
86 }
87
88
89 void InsetListings::write(ostream & os) const
90 {
91         os << "listings" << "\n";
92         InsetListingsParams const & par = params();
93         // parameter string is encoded to be a valid lyx token.
94         string opt = par.encodedString();
95         if (!opt.empty())
96                 os << "lstparams \"" << opt << "\"\n";
97         if (par.isInline())
98                 os << "inline true\n";
99         else
100                 os << "inline false\n";
101         InsetCollapsable::write(os);
102 }
103
104
105 void InsetListings::read(Lexer & lex)
106 {
107         while (lex.isOK()) {
108                 lex.next();
109                 string token = lex.getString();
110                 if (token == "lstparams") {
111                         lex.next();
112                         string const value = lex.getString();
113                         params().fromEncodedString(value);
114                 } else if (token == "inline") {
115                         lex.next();
116                         params().setInline(lex.getBool());
117                 } else {
118                         // no special option, push back 'status' etc
119                         lex.pushToken(token);
120                         break;
121                 }
122         }
123         InsetCollapsable::read(lex);
124 }
125
126
127 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
128 {
129         string param_string = params().params();
130         // NOTE: I use {} to quote text, which is an experimental feature
131         // of the listings package (see page 25 of the manual)
132         int lines = 0;
133         bool const isInline = params().isInline();
134         // get the paragraphs. We can not output them directly to given odocstream
135         // because we can not yet determine the delimiter character of \lstinline
136         docstring code;
137         docstring uncodable;
138         ParagraphList::const_iterator par = paragraphs().begin();
139         ParagraphList::const_iterator end = paragraphs().end();
140
141         bool encoding_switched = false;
142         Encoding const * const save_enc = runparams.encoding;
143
144         if (runparams.flavor != OutputParams::XETEX
145             && !runparams.encoding->hasFixedWidth()) {
146                 // We need to switch to a singlebyte encoding, since the
147                 // listings package cannot deal with multi-byte-encoded
148                 // glyphs (not needed with XeTeX).
149                 Language const * const outer_language =
150                         (runparams.local_font != 0) ?
151                                 runparams.local_font->language()
152                                 : buffer().params().language;
153                 // We try if there's a singlebyte encoding for the current
154                 // language; if not, fall back to latin1.
155                 Encoding const * const lstenc =
156                         (outer_language->encoding()->hasFixedWidth()) ?
157                                 outer_language->encoding() 
158                                 : encodings.fromLyXName("iso8859-1");
159                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
160                                 runparams, *lstenc, true);
161                 runparams.encoding = lstenc;
162                 encoding_switched = true;
163         }
164
165         while (par != end) {
166                 pos_type siz = par->size();
167                 bool captionline = false;
168                 for (pos_type i = 0; i < siz; ++i) {
169                         if (i == 0 && par->isInset(i) && i + 1 == siz)
170                                 captionline = true;
171                         // ignore all struck out text and (caption) insets
172                         if (par->isDeleted(i) || par->isInset(i))
173                                 continue;
174                         char_type c = par->getChar(i);
175                         // we can only output characters covered by the current
176                         // encoding!
177                         try {
178                                 if (runparams.encoding->latexChar(c) == docstring(1, c))
179                                         code += c;
180                                 else if (runparams.dryrun) {
181                                         code += "<" + _("LyX Warning: ")
182                                            + _("uncodable character") + " '";
183                                         code += docstring(1, c);
184                                         code += "'>";
185                                 } else
186                                         uncodable += c;
187                         } catch (EncodingException & /* e */) {
188                                 if (runparams.dryrun) {
189                                         code += "<" + _("LyX Warning: ")
190                                            + _("uncodable character") + " '";
191                                         code += docstring(1, c);
192                                         code += "'>";
193                                 } else
194                                         uncodable += c;
195                         }
196                 }
197                 ++par;
198                 // for the inline case, if there are multiple paragraphs
199                 // they are simply joined. Otherwise, expect latex errors.
200                 if (par != end && !isInline && !captionline) {
201                         code += "\n";
202                         ++lines;
203                 }
204         }
205         if (isInline) {
206                 char const * delimiter = lstinline_delimiters;
207                 for (; delimiter != '\0'; ++delimiter)
208                         if (!contains(code, *delimiter))
209                                 break;
210                 // This code piece contains all possible special character? !!!
211                 // Replace ! with a warning message and use ! as delimiter.
212                 if (*delimiter == '\0') {
213                         docstring delim_error = "<" + _("LyX Warning: ")
214                                 + _("no more lstline delimiters available") + ">";
215                         code = subst(code, from_ascii("!"), delim_error);
216                         delimiter = lstinline_delimiters;
217                         if (!runparams.dryrun) {
218                                 // FIXME: warning should be passed to the error dialog
219                                 frontend::Alert::warning(_("Running out of delimiters"),
220                                 _("For inline program listings, one character must be reserved\n"
221                                   "as a delimiter. One of the listings, however, uses all available\n"
222                                   "characters, so none is left for delimiting purposes.\n"
223                                   "For the time being, I have replaced '!' by a warning, but you\n"
224                                   "must investigate!"));
225                         }
226                 }
227                 if (param_string.empty())
228                         os << "\\lstinline" << *delimiter;
229                 else
230                         os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
231                 os << code
232                    << *delimiter;
233         } else {
234                 OutputParams rp = runparams;
235                 rp.moving_arg = true;
236                 docstring const caption = getCaption(rp);
237                 if (param_string.empty() && caption.empty())
238                         os << "\n\\begin{lstlisting}\n";
239                 else {
240                         os << "\n\\begin{lstlisting}[";
241                         if (!caption.empty()) {
242                                 os << "caption={" << caption << '}';
243                                 if (!param_string.empty())
244                                         os << ',';
245                         }
246                         os << from_utf8(param_string) << "]\n";
247                 }
248                 lines += 2;
249                 os << code << "\n\\end{lstlisting}\n";
250                 lines += 2;
251         }
252
253         if (encoding_switched){
254                 // Switch back
255                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
256                                 runparams, *save_enc, true);
257                 runparams.encoding = save_enc;
258         }
259
260         if (!uncodable.empty()) {
261                 // issue a warning about omitted characters
262                 // FIXME: should be passed to the error dialog
263                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
264                         bformat(_("The following characters in one of the program listings are\n"
265                                   "not representable in the current encoding and have been omitted:\n%1$s."),
266                         uncodable));
267         }
268
269         return lines;
270 }
271
272
273 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
274 {
275         odocstringstream ods;
276         XHTMLStream out(ods);
277
278         bool const isInline = params().isInline();
279         if (isInline) 
280                 out << html::CompTag("br");
281         else {
282                 out << html::StartTag("div", "class='float float-listings'");
283                 docstring caption = getCaptionHTML(rp);
284                 if (!caption.empty())
285                         out << html::StartTag("div", "class='float-caption'") 
286                             << caption << html::EndTag("div");
287         }
288
289         out << html::StartTag("pre");
290         OutputParams newrp = rp;
291         newrp.html_disable_captions = true;
292         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
293         out << html::EndTag("pre");
294
295         if (isInline) {
296                 out << html::CompTag("br");
297                 // escaping will already have been done
298                 os << XHTMLStream::NextRaw() << ods.str();
299         } else {
300                 out << html::EndTag("div");
301                 // In this case, this needs to be deferred, but we'll put it
302                 // before anything the text itself deferred.
303                 def = ods.str() + '\n' + def;
304         }
305         return def;
306 }
307
308
309 docstring InsetListings::contextMenu(BufferView const &, int, int) const
310 {
311         return from_ascii("context-listings");
312 }
313
314
315 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
316 {
317         switch (cmd.action()) {
318
319         case LFUN_INSET_MODIFY: {
320                 InsetListings::string2params(to_utf8(cmd.argument()), params());
321                 break;
322         }
323
324         case LFUN_INSET_DIALOG_UPDATE:
325                 cur.bv().updateDialog("listings", params2string(params()));
326                 break;
327
328         default:
329                 InsetCollapsable::doDispatch(cur, cmd);
330                 break;
331         }
332 }
333
334
335 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
336         FuncStatus & status) const
337 {
338         switch (cmd.action()) {
339                 case LFUN_INSET_MODIFY:
340                 case LFUN_INSET_DIALOG_UPDATE:
341                         status.setEnabled(true);
342                         return true;
343                 case LFUN_CAPTION_INSERT:
344                         status.setEnabled(!params().isInline());
345                         return true;
346                 default:
347                         return InsetCollapsable::getStatus(cur, cmd, status);
348         }
349 }
350
351
352 docstring const InsetListings::buttonLabel(BufferView const & bv) const
353 {
354         // FIXME UNICODE
355         if (decoration() == InsetLayout::CLASSIC)
356                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
357         else
358                 return getNewLabel(_("Listing"));
359 }
360
361
362 void InsetListings::validate(LaTeXFeatures & features) const
363 {
364         features.require("listings");
365         string param_string = params().params();
366         if (param_string.find("\\color") != string::npos)
367                 features.require("color");
368         InsetCollapsable::validate(features);
369 }
370
371
372 bool InsetListings::showInsetDialog(BufferView * bv) const
373 {
374         bv->showDialog("listings", params2string(params()),
375                 const_cast<InsetListings *>(this));
376         return true;
377 }
378
379
380 docstring InsetListings::getCaption(OutputParams const & runparams) const
381 {
382         if (paragraphs().empty())
383                 return docstring();
384
385         InsetCaption const * ins = getCaptionInset();
386         if (ins == 0)
387                 return docstring();
388
389         odocstringstream ods;
390         ins->getOptArg(ods, runparams);
391         ins->getArgument(ods, runparams);
392         // the caption may contain \label{} but the listings
393         // package prefer caption={}, label={}
394         docstring cap = ods.str();
395         if (!contains(to_utf8(cap), "\\label{"))
396                 return cap;
397         // convert from
398         //     blah1\label{blah2} blah3
399         // to
400         //     blah1 blah3},label={blah2
401         // to form options
402         //     caption={blah1 blah3},label={blah2}
403         //
404         // NOTE that } is not allowed in blah2.
405         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
406         string const new_cap("\\1\\3},label={\\2");
407         return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
408 }
409
410
411 void InsetListings::string2params(string const & in,
412                                    InsetListingsParams & params)
413 {
414         params = InsetListingsParams();
415         if (in.empty())
416                 return;
417         istringstream data(in);
418         Lexer lex;
419         lex.setStream(data);
420         // discard "listings", which is only used to determine inset
421         lex.next();
422         params.read(lex);
423 }
424
425
426 string InsetListings::params2string(InsetListingsParams const & params)
427 {
428         ostringstream data;
429         data << "listings" << ' ';
430         params.write(data);
431         return data.str();
432 }
433
434
435 } // namespace lyx