]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Fix bad cursor positioning when entering an inset
[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         // The listings package cannot deal with multi-byte-encoded
126         // glyphs, except if full-unicode aware backends
127         // such as XeTeX or LuaTeX are used, and with pLaTeX.
128         bool const multibyte_possible = runparams.isFullUnicode()
129             || (buffer().params().bufferFormat() == "platex"
130                 && runparams.encoding->package() == Encoding::japanese);
131
132         if (!multibyte_possible && !runparams.encoding->hasFixedWidth()) {
133                 // We need to switch to a singlebyte encoding, due to
134                 // the restrictions of the listings package (see above).
135                 // This needs to be consistent with
136                 // LaTeXFeatures::getTClassI18nPreamble().
137                 Language const * const outer_language =
138                         (runparams.local_font != 0) ?
139                                 runparams.local_font->language()
140                                 : buffer().params().language;
141                 // We try if there's a singlebyte encoding for the current
142                 // language; if not, fall back to latin1.
143                 Encoding const * const lstenc =
144                         (outer_language->encoding()->hasFixedWidth()) ?
145                                 outer_language->encoding()
146                                 : encodings.fromLyXName("iso8859-1");
147                 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
148                 runparams.encoding = lstenc;
149                 encoding_switched = true;
150         }
151
152         while (par != end) {
153                 pos_type siz = par->size();
154                 bool captionline = false;
155                 for (pos_type i = 0; i < siz; ++i) {
156                         if (i == 0 && par->isInset(i) && i + 1 == siz)
157                                 captionline = true;
158                         // ignore all struck out text and (caption) insets
159                         if (par->isDeleted(i) || par->isInset(i))
160                                 continue;
161                         char_type c = par->getChar(i);
162                         // we can only output characters covered by the current
163                         // encoding!
164                         try {
165                                 if (runparams.encoding->encodable(c))
166                                         code += c;
167                                 else if (runparams.dryrun) {
168                                         code += "<" + _("LyX Warning: ")
169                                            + _("uncodable character") + " '";
170                                         code += docstring(1, c);
171                                         code += "'>";
172                                 } else
173                                         uncodable += c;
174                         } catch (EncodingException & /* e */) {
175                                 if (runparams.dryrun) {
176                                         code += "<" + _("LyX Warning: ")
177                                            + _("uncodable character") + " '";
178                                         code += docstring(1, c);
179                                         code += "'>";
180                                 } else
181                                         uncodable += c;
182                         }
183                 }
184                 ++par;
185                 // for the inline case, if there are multiple paragraphs
186                 // they are simply joined. Otherwise, expect latex errors.
187                 if (par != end && !isInline && !captionline)
188                         code += "\n";
189         }
190         if (isInline) {
191                 static const docstring delimiters =
192                                 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
193
194                 size_t pos = delimiters.find_first_not_of(code);
195
196                 // This code piece contains all possible special character? !!!
197                 // Replace ! with a warning message and use ! as delimiter.
198                 if (pos == string::npos) {
199                         docstring delim_error = "<" + _("LyX Warning: ")
200                                 + _("no more lstline delimiters available") + ">";
201                         code = subst(code, from_ascii("!"), delim_error);
202                         pos = 0;
203                         if (!runparams.dryrun && !runparams.silent) {
204                                 // FIXME: warning should be passed to the error dialog
205                                 frontend::Alert::warning(_("Running out of delimiters"),
206                                 _("For inline program listings, one character must be reserved\n"
207                                   "as a delimiter. One of the listings, however, uses all available\n"
208                                   "characters, so none is left for delimiting purposes.\n"
209                                   "For the time being, I have replaced '!' by a warning, but you\n"
210                                   "must investigate!"));
211                         }
212                 }
213                 docstring const delim(1, delimiters[pos]);
214                 os << "\\lstinline";
215                 if (!param_string.empty())
216                         os << "[" << from_utf8(param_string) << "]";
217                 else if (pos >= delimiters.find('Q'))
218                         // We need to terminate the command before the delimiter
219                         os << " ";
220                 os << delim << code << delim;
221         } else {
222                 OutputParams rp = runparams;
223                 rp.moving_arg = true;
224                 docstring const caption = getCaption(rp);
225                 if (param_string.empty() && caption.empty())
226                         os << breakln << "\\begin{lstlisting}\n";
227                 else {
228                         os << breakln << "\\begin{lstlisting}[";
229                         if (!caption.empty()) {
230                                 os << "caption={" << caption << '}';
231                                 if (!param_string.empty())
232                                         os << ',';
233                         }
234                         os << from_utf8(param_string) << "]\n";
235                 }
236                 os << code << breakln << "\\end{lstlisting}\n";
237         }
238
239         if (encoding_switched){
240                 // Switch back
241                 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
242                 runparams.encoding = save_enc;
243         }
244
245         if (!uncodable.empty() && !runparams.silent) {
246                 // issue a warning about omitted characters
247                 // FIXME: should be passed to the error dialog
248                 if (!multibyte_possible && !runparams.encoding->hasFixedWidth())
249                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
250                                 bformat(_("The following characters in one of the program listings are\n"
251                                           "not representable in the current encoding and have been omitted:\n%1$s.\n"
252                                           "This is due to a restriction of the listings package, which does\n"
253                                           "not support your encoding '%2$s'.\n"
254                                           "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
255                                           "might help."),
256                                 uncodable, _(runparams.encoding->guiName())));
257                 else
258                         frontend::Alert::warning(_("Uncodable characters in listings inset"),
259                                 bformat(_("The following characters in one of the program listings are\n"
260                                           "not representable in the current encoding and have been omitted:\n%1$s."),
261                                 uncodable));
262         }
263 }
264
265
266 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
267 {
268         odocstringstream ods;
269         XHTMLStream out(ods);
270
271         bool const isInline = params().isInline();
272         if (isInline)
273                 out << html::CompTag("br");
274         else {
275                 out << html::StartTag("div", "class='float-listings'");
276                 docstring caption = getCaptionHTML(rp);
277                 if (!caption.empty())
278                         out << html::StartTag("div", "class='listings-caption'")
279                             << XHTMLStream::ESCAPE_NONE
280                             << caption << html::EndTag("div");
281         }
282
283         InsetLayout const & il = getLayout();
284         string const & tag = il.htmltag();
285         string attr = "class ='listings";
286         string const lang = params().getParamValue("language");
287         if (!lang.empty())
288                 attr += " " + lang;
289         attr += "'";
290         out << html::StartTag(tag, attr);
291         OutputParams newrp = rp;
292         newrp.html_disable_captions = true;
293         // We don't want to convert dashes here. That's the only conversion we
294         // do for XHTML, so this is safe.
295         newrp.pass_thru = true;
296         docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
297         out << html::EndTag(tag);
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 string InsetListings::contextMenuName() const
314 {
315         return "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(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                 InsetCaptionable::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                         // the inset outputs at most one caption
350                         if (params().isInline() || getCaptionInset()) {
351                                 status.setEnabled(false);
352                                 return true;
353                         }
354                 }
355                 default:
356                         return InsetCaptionable::getStatus(cur, cmd, status);
357         }
358 }
359
360
361 docstring const InsetListings::buttonLabel(BufferView const & bv) const
362 {
363         // FIXME UNICODE
364         if (decoration() == InsetLayout::CLASSIC)
365                 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
366         else
367                 return getNewLabel(_("Listing"));
368 }
369
370
371 void InsetListings::validate(LaTeXFeatures & features) const
372 {
373         features.require("listings");
374         features.useInsetLayout(getLayout());
375         string param_string = params().params();
376         if (param_string.find("\\color") != string::npos)
377                 features.require("color");
378         InsetCaptionable::validate(features);
379 }
380
381
382 bool InsetListings::showInsetDialog(BufferView * bv) const
383 {
384         bv->showDialog("listings", params2string(params()),
385                 const_cast<InsetListings *>(this));
386         return true;
387 }
388
389
390 docstring InsetListings::getCaption(OutputParams const & runparams) const
391 {
392         if (paragraphs().empty())
393                 return docstring();
394
395         InsetCaption const * ins = getCaptionInset();
396         if (ins == 0)
397                 return docstring();
398
399         TexRow texrow;
400         odocstringstream ods;
401         otexstream os(ods, texrow);
402         ins->getArgs(os, runparams);
403         ins->getArgument(os, runparams);
404
405         // TODO: The code below should be moved to support, and then the test
406         //       in ../tests should be moved there as well.
407
408         // the caption may contain \label{} but the listings
409         // package prefer caption={}, label={}
410         docstring cap = ods.str();
411         if (!contains(to_utf8(cap), "\\label{"))
412                 return cap;
413         // convert from
414         //     blah1\label{blah2} blah3
415         // to
416         //     blah1 blah3},label={blah2
417         // to form options
418         //     caption={blah1 blah3},label={blah2}
419         //
420         // NOTE that } is not allowed in blah2.
421         regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
422         string const new_cap("$1$3},label={$2");
423         return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
424 }
425
426
427 void InsetListings::string2params(string const & in,
428                                    InsetListingsParams & params)
429 {
430         params = InsetListingsParams();
431         if (in.empty())
432                 return;
433         istringstream data(in);
434         Lexer lex;
435         lex.setStream(data);
436         // discard "listings", which is only used to determine inset
437         lex.next();
438         params.read(lex);
439 }
440
441
442 string InsetListings::params2string(InsetListingsParams const & params)
443 {
444         ostringstream data;
445         data << "listings" << ' ';
446         params.write(data);
447         return data.str();
448 }
449
450
451 } // namespace lyx