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