]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Fix wrongly copy-pasted entries in SpellcheckerUi.ui
[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
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/lassert.h"
39
40 #include "frontends/alert.h"
41 #include "frontends/Application.h"
42
43 #include "support/regex.h"
44
45 #include <sstream>
46
47 using namespace std;
48 using namespace lyx::support;
49
50 namespace lyx {
51
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 =
78                 buffer().masterBuffer()->params().documentClass().counters();
79         string const saveflt = cnts.current_float();
80
81         // Tell to captions what the current float is
82         cnts.current_float("listing");
83
84         InsetCollapsable::updateBuffer(it, utype);
85
86         //reset afterwards
87         cnts.current_float(saveflt);
88 }
89
90
91 void InsetListings::write(ostream & os) const
92 {
93         os << "listings" << "\n";
94         InsetListingsParams const & par = params();
95         // parameter string is encoded to be a valid lyx token.
96         string opt = par.encodedString();
97         if (!opt.empty())
98                 os << "lstparams \"" << opt << "\"\n";
99         if (par.isInline())
100                 os << "inline true\n";
101         else
102                 os << "inline false\n";
103         InsetCollapsable::write(os);
104 }
105
106
107 void InsetListings::read(Lexer & lex)
108 {
109         while (lex.isOK()) {
110                 lex.next();
111                 string token = lex.getString();
112                 if (token == "lstparams") {
113                         lex.next();
114                         string const value = lex.getString();
115                         params().fromEncodedString(value);
116                 } else if (token == "inline") {
117                         lex.next();
118                         params().setInline(lex.getBool());
119                 } else {
120                         // no special option, push back 'status' etc
121                         lex.pushToken(token);
122                         break;
123                 }
124         }
125         InsetCollapsable::read(lex);
126 }
127
128
129 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
130 {
131         string param_string = params().params();
132         // NOTE: I use {} to quote text, which is an experimental feature
133         // of the listings package (see page 25 of the manual)
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.isFullUnicode()
146             && !runparams.encoding->hasFixedWidth()) {
147                 // We need to switch to a singlebyte encoding, since the
148                 // listings package cannot deal with multi-byte-encoded
149                 // glyphs (not needed with full-unicode aware backends
150                 // such as XeTeX).
151                 Language const * const outer_language =
152                         (runparams.local_font != 0) ?
153                                 runparams.local_font->language()
154                                 : buffer().params().language;
155                 // We try if there's a singlebyte encoding for the current
156                 // language; if not, fall back to latin1.
157                 Encoding const * const lstenc =
158                         (outer_language->encoding()->hasFixedWidth()) ?
159                                 outer_language->encoding() 
160                                 : encodings.fromLyXName("iso8859-1");
161                 pair<bool, int> const c = switchEncoding(os.os(),
162                                 buffer().params(), runparams, *lstenc, true);
163                 runparams.encoding = lstenc;
164                 encoding_switched = true;
165         }
166
167         while (par != end) {
168                 pos_type siz = par->size();
169                 bool captionline = false;
170                 for (pos_type i = 0; i < siz; ++i) {
171                         if (i == 0 && par->isInset(i) && i + 1 == siz)
172                                 captionline = true;
173                         // ignore all struck out text and (caption) insets
174                         if (par->isDeleted(i) || par->isInset(i))
175                                 continue;
176                         char_type c = par->getChar(i);
177                         // we can only output characters covered by the current
178                         // encoding!
179                         try {
180                                 if (runparams.encoding->latexChar(c) == docstring(1, c))
181                                         code += c;
182                                 else if (runparams.dryrun) {
183                                         code += "<" + _("LyX Warning: ")
184                                            + _("uncodable character") + " '";
185                                         code += docstring(1, c);
186                                         code += "'>";
187                                 } else
188                                         uncodable += c;
189                         } catch (EncodingException & /* e */) {
190                                 if (runparams.dryrun) {
191                                         code += "<" + _("LyX Warning: ")
192                                            + _("uncodable character") + " '";
193                                         code += docstring(1, c);
194                                         code += "'>";
195                                 } else
196                                         uncodable += c;
197                         }
198                 }
199                 ++par;
200                 // for the inline case, if there are multiple paragraphs
201                 // they are simply joined. Otherwise, expect latex errors.
202                 if (par != end && !isInline && !captionline)
203                         code += "\n";
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 << breakln << "\\begin{lstlisting}\n";
239                 else {
240                         os << breakln << "\\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                 os << code << breakln << "\\end{lstlisting}\n";
249         }
250
251         if (encoding_switched){
252                 // Switch back
253                 pair<bool, int> const c = switchEncoding(os.os(),
254                                 buffer().params(), runparams, *save_enc, true);
255                 runparams.encoding = save_enc;
256         }
257
258         if (!uncodable.empty()) {
259                 // issue a warning about omitted characters
260                 // FIXME: should be passed to the error dialog
261                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
262                         bformat(_("The following characters in one of the program listings are\n"
263                                   "not representable in the current encoding and have been omitted:\n%1$s."),
264                         uncodable));
265         }
266 }
267
268
269 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
270 {
271         odocstringstream ods;
272         XHTMLStream out(ods);
273
274         bool const isInline = params().isInline();
275         if (isInline) 
276                 out << html::CompTag("br");
277         else {
278                 out << html::StartTag("div", "class='float float-listings'");
279                 docstring caption = getCaptionHTML(rp);
280                 if (!caption.empty())
281                         out << html::StartTag("div", "class='float-caption'") 
282                             << caption << html::EndTag("div");
283         }
284
285         out << html::StartTag("pre");
286         OutputParams newrp = rp;
287         newrp.html_disable_captions = true;
288         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
289         out << html::EndTag("pre");
290
291         if (isInline) {
292                 out << html::CompTag("br");
293                 // escaping will already have been done
294                 os << XHTMLStream::ESCAPE_NONE << ods.str();
295         } else {
296                 out << html::EndTag("div");
297                 // In this case, this needs to be deferred, but we'll put it
298                 // before anything the text itself deferred.
299                 def = ods.str() + '\n' + def;
300         }
301         return def;
302 }
303
304
305 docstring InsetListings::contextMenuName() const
306 {
307         return from_ascii("context-listings");
308 }
309
310
311 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
312 {
313         switch (cmd.action()) {
314
315         case LFUN_INSET_MODIFY: {
316                 cur.recordUndoInset(ATOMIC_UNDO, this);
317                 InsetListings::string2params(to_utf8(cmd.argument()), params());
318                 break;
319         }
320
321         case LFUN_INSET_DIALOG_UPDATE:
322                 cur.bv().updateDialog("listings", params2string(params()));
323                 break;
324
325         default:
326                 InsetCollapsable::doDispatch(cur, cmd);
327                 break;
328         }
329 }
330
331
332 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
333         FuncStatus & status) const
334 {
335         switch (cmd.action()) {
336                 case LFUN_INSET_MODIFY:
337                 case LFUN_INSET_DIALOG_UPDATE:
338                         status.setEnabled(true);
339                         return true;
340                 case LFUN_CAPTION_INSERT:
341                         status.setEnabled(!params().isInline());
342                         return true;
343                 default:
344                         return InsetCollapsable::getStatus(cur, cmd, status);
345         }
346 }
347
348
349 docstring const InsetListings::buttonLabel(BufferView const & bv) const
350 {
351         // FIXME UNICODE
352         if (decoration() == InsetLayout::CLASSIC)
353                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
354         else
355                 return getNewLabel(_("Listing"));
356 }
357
358
359 void InsetListings::validate(LaTeXFeatures & features) const
360 {
361         features.require("listings");
362         string param_string = params().params();
363         if (param_string.find("\\color") != string::npos)
364                 features.require("color");
365         InsetCollapsable::validate(features);
366 }
367
368
369 bool InsetListings::showInsetDialog(BufferView * bv) const
370 {
371         bv->showDialog("listings", params2string(params()),
372                 const_cast<InsetListings *>(this));
373         return true;
374 }
375
376
377 docstring InsetListings::getCaption(OutputParams const & runparams) const
378 {
379         if (paragraphs().empty())
380                 return docstring();
381
382         InsetCaption const * ins = getCaptionInset();
383         if (ins == 0)
384                 return docstring();
385
386         TexRow texrow;
387         odocstringstream ods;
388         otexstream os(ods, texrow);
389         ins->getOptArg(os, runparams);
390         ins->getArgument(os, 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