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