]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
c10c54bdd1455f0a886faffb6ed0832b5d75bcd5
[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 int 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         int lines = 0;
135         bool const isInline = params().isInline();
136         // get the paragraphs. We can not output them directly to given odocstream
137         // because we can not yet determine the delimiter character of \lstinline
138         docstring code;
139         docstring uncodable;
140         ParagraphList::const_iterator par = paragraphs().begin();
141         ParagraphList::const_iterator end = paragraphs().end();
142
143         bool encoding_switched = false;
144         Encoding const * const save_enc = runparams.encoding;
145
146         if (!runparams.isFullUnicode()
147             && !runparams.encoding->hasFixedWidth()) {
148                 // We need to switch to a singlebyte encoding, since the
149                 // listings package cannot deal with multi-byte-encoded
150                 // glyphs (not needed with full-unicode aware backends
151                 // such as XeTeX).
152                 Language const * const outer_language =
153                         (runparams.local_font != 0) ?
154                                 runparams.local_font->language()
155                                 : buffer().params().language;
156                 // We try if there's a singlebyte encoding for the current
157                 // language; if not, fall back to latin1.
158                 Encoding const * const lstenc =
159                         (outer_language->encoding()->hasFixedWidth()) ?
160                                 outer_language->encoding() 
161                                 : encodings.fromLyXName("iso8859-1");
162                 pair<bool, int> const c = switchEncoding(os.os(),
163                                 buffer().params(), runparams, *lstenc, true);
164                 runparams.encoding = lstenc;
165                 encoding_switched = true;
166         }
167
168         while (par != end) {
169                 pos_type siz = par->size();
170                 bool captionline = false;
171                 for (pos_type i = 0; i < siz; ++i) {
172                         if (i == 0 && par->isInset(i) && i + 1 == siz)
173                                 captionline = true;
174                         // ignore all struck out text and (caption) insets
175                         if (par->isDeleted(i) || par->isInset(i))
176                                 continue;
177                         char_type c = par->getChar(i);
178                         // we can only output characters covered by the current
179                         // encoding!
180                         try {
181                                 if (runparams.encoding->latexChar(c) == docstring(1, c))
182                                         code += c;
183                                 else if (runparams.dryrun) {
184                                         code += "<" + _("LyX Warning: ")
185                                            + _("uncodable character") + " '";
186                                         code += docstring(1, c);
187                                         code += "'>";
188                                 } else
189                                         uncodable += c;
190                         } catch (EncodingException & /* e */) {
191                                 if (runparams.dryrun) {
192                                         code += "<" + _("LyX Warning: ")
193                                            + _("uncodable character") + " '";
194                                         code += docstring(1, c);
195                                         code += "'>";
196                                 } else
197                                         uncodable += c;
198                         }
199                 }
200                 ++par;
201                 // for the inline case, if there are multiple paragraphs
202                 // they are simply joined. Otherwise, expect latex errors.
203                 if (par != end && !isInline && !captionline) {
204                         code += "\n";
205                         ++lines;
206                 }
207         }
208         if (isInline) {
209                 char const * delimiter = lstinline_delimiters;
210                 for (; delimiter != '\0'; ++delimiter)
211                         if (!contains(code, *delimiter))
212                                 break;
213                 // This code piece contains all possible special character? !!!
214                 // Replace ! with a warning message and use ! as delimiter.
215                 if (*delimiter == '\0') {
216                         docstring delim_error = "<" + _("LyX Warning: ")
217                                 + _("no more lstline delimiters available") + ">";
218                         code = subst(code, from_ascii("!"), delim_error);
219                         delimiter = lstinline_delimiters;
220                         if (!runparams.dryrun) {
221                                 // FIXME: warning should be passed to the error dialog
222                                 frontend::Alert::warning(_("Running out of delimiters"),
223                                 _("For inline program listings, one character must be reserved\n"
224                                   "as a delimiter. One of the listings, however, uses all available\n"
225                                   "characters, so none is left for delimiting purposes.\n"
226                                   "For the time being, I have replaced '!' by a warning, but you\n"
227                                   "must investigate!"));
228                         }
229                 }
230                 if (param_string.empty())
231                         os << "\\lstinline" << *delimiter;
232                 else
233                         os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
234                 os << code
235                    << *delimiter;
236         } else {
237                 OutputParams rp = runparams;
238                 rp.moving_arg = true;
239                 docstring const caption = getCaption(rp);
240                 // clear counter
241                 os.countLines();
242                 if (param_string.empty() && caption.empty())
243                         os << breakln << "\\begin{lstlisting}\n";
244                 else {
245                         os << breakln << "\\begin{lstlisting}[";
246                         if (!caption.empty()) {
247                                 os << "caption={" << caption << '}';
248                                 if (!param_string.empty())
249                                         os << ',';
250                         }
251                         os << from_utf8(param_string) << "]\n";
252                 }
253                 os << code << breakln << "\\end{lstlisting}\n";
254                 lines += os.countLines();
255         }
256
257         if (encoding_switched){
258                 // Switch back
259                 pair<bool, int> const c = switchEncoding(os.os(),
260                                 buffer().params(), runparams, *save_enc, true);
261                 runparams.encoding = save_enc;
262         }
263
264         if (!uncodable.empty()) {
265                 // issue a warning about omitted characters
266                 // FIXME: should be passed to the error dialog
267                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
268                         bformat(_("The following characters in one of the program listings are\n"
269                                   "not representable in the current encoding and have been omitted:\n%1$s."),
270                         uncodable));
271         }
272
273         return lines;
274 }
275
276
277 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
278 {
279         odocstringstream ods;
280         XHTMLStream out(ods);
281
282         bool const isInline = params().isInline();
283         if (isInline) 
284                 out << html::CompTag("br");
285         else {
286                 out << html::StartTag("div", "class='float float-listings'");
287                 docstring caption = getCaptionHTML(rp);
288                 if (!caption.empty())
289                         out << html::StartTag("div", "class='float-caption'") 
290                             << caption << html::EndTag("div");
291         }
292
293         out << html::StartTag("pre");
294         OutputParams newrp = rp;
295         newrp.html_disable_captions = true;
296         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
297         out << html::EndTag("pre");
298
299         if (isInline) {
300                 out << html::CompTag("br");
301                 // escaping will already have been done
302                 os << XHTMLStream::ESCAPE_NONE << ods.str();
303         } else {
304                 out << html::EndTag("div");
305                 // In this case, this needs to be deferred, but we'll put it
306                 // before anything the text itself deferred.
307                 def = ods.str() + '\n' + def;
308         }
309         return def;
310 }
311
312
313 docstring InsetListings::contextMenuName() const
314 {
315         return from_ascii("context-listings");
316 }
317
318
319 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
320 {
321         switch (cmd.action()) {
322
323         case LFUN_INSET_MODIFY: {
324                 cur.recordUndoInset(ATOMIC_UNDO, this);
325                 InsetListings::string2params(to_utf8(cmd.argument()), params());
326                 break;
327         }
328
329         case LFUN_INSET_DIALOG_UPDATE:
330                 cur.bv().updateDialog("listings", params2string(params()));
331                 break;
332
333         default:
334                 InsetCollapsable::doDispatch(cur, cmd);
335                 break;
336         }
337 }
338
339
340 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
341         FuncStatus & status) const
342 {
343         switch (cmd.action()) {
344                 case LFUN_INSET_MODIFY:
345                 case LFUN_INSET_DIALOG_UPDATE:
346                         status.setEnabled(true);
347                         return true;
348                 case LFUN_CAPTION_INSERT:
349                         status.setEnabled(!params().isInline());
350                         return true;
351                 default:
352                         return InsetCollapsable::getStatus(cur, cmd, status);
353         }
354 }
355
356
357 docstring const InsetListings::buttonLabel(BufferView const & bv) const
358 {
359         // FIXME UNICODE
360         if (decoration() == InsetLayout::CLASSIC)
361                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
362         else
363                 return getNewLabel(_("Listing"));
364 }
365
366
367 void InsetListings::validate(LaTeXFeatures & features) const
368 {
369         features.require("listings");
370         string param_string = params().params();
371         if (param_string.find("\\color") != string::npos)
372                 features.require("color");
373         InsetCollapsable::validate(features);
374 }
375
376
377 bool InsetListings::showInsetDialog(BufferView * bv) const
378 {
379         bv->showDialog("listings", params2string(params()),
380                 const_cast<InsetListings *>(this));
381         return true;
382 }
383
384
385 docstring InsetListings::getCaption(OutputParams const & runparams) const
386 {
387         if (paragraphs().empty())
388                 return docstring();
389
390         InsetCaption const * ins = getCaptionInset();
391         if (ins == 0)
392                 return docstring();
393
394         odocstringstream ods;
395         otexstream os(ods);
396         ins->getOptArg(os, runparams);
397         ins->getArgument(os, runparams);
398         // the caption may contain \label{} but the listings
399         // package prefer caption={}, label={}
400         docstring cap = ods.str();
401         if (!contains(to_utf8(cap), "\\label{"))
402                 return cap;
403         // convert from
404         //     blah1\label{blah2} blah3
405         // to
406         //     blah1 blah3},label={blah2
407         // to form options
408         //     caption={blah1 blah3},label={blah2}
409         //
410         // NOTE that } is not allowed in blah2.
411         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
412         string const new_cap("\\1\\3},label={\\2");
413         return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
414 }
415
416
417 void InsetListings::string2params(string const & in,
418                                    InsetListingsParams & params)
419 {
420         params = InsetListingsParams();
421         if (in.empty())
422                 return;
423         istringstream data(in);
424         Lexer lex;
425         lex.setStream(data);
426         // discard "listings", which is only used to determine inset
427         lex.next();
428         params.read(lex);
429 }
430
431
432 string InsetListings::params2string(InsetListingsParams const & params)
433 {
434         ostringstream data;
435         data << "listings" << ' ';
436         params.write(data);
437         return data.str();
438 }
439
440
441 } // namespace lyx