]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Proper lfun handling naming for listing tabs.
[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 "InsetList.h"
27 #include "Language.h"
28 #include "MetricsInfo.h"
29 #include "output_latex.h"
30 #include "TextClass.h"
31
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/lassert.h"
37
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
40
41 #include <boost/regex.hpp>
42
43 #include <sstream>
44
45 using namespace std;
46 using namespace lyx::support;
47
48 namespace lyx {
49
50 using boost::regex;
51
52 char const lstinline_delimiters[] =
53         "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
54
55 InsetListings::InsetListings(Buffer const & buf, InsetListingsParams const & par)
56         : InsetCollapsable(buf, 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::updateLabels(ParIterator const & it)
73 {
74         Counters & cnts = buffer().params().documentClass().counters();
75         string const saveflt = cnts.current_float();
76
77         // Tell to captions what the current float is
78         cnts.current_float("listing");
79
80         InsetCollapsable::updateLabels(it);
81
82         //reset afterwards
83         cnts.current_float(saveflt);
84 }
85
86
87 void InsetListings::write(ostream & os) const
88 {
89         os << "listings" << "\n";
90         InsetListingsParams const & par = params();
91         // parameter string is encoded to be a valid lyx token.
92         string opt = par.encodedString();
93         if (!opt.empty())
94                 os << "lstparams \"" << opt << "\"\n";
95         if (par.isInline())
96                 os << "inline true\n";
97         else
98                 os << "inline false\n";
99         InsetCollapsable::write(os);
100 }
101
102
103 void InsetListings::read(Lexer & lex)
104 {
105         while (lex.isOK()) {
106                 lex.next();
107                 string token = lex.getString();
108                 if (token == "lstparams") {
109                         lex.next();
110                         string const value = lex.getString();
111                         params().fromEncodedString(value);
112                 } else if (token == "inline") {
113                         lex.next();
114                         params().setInline(lex.getBool());
115                 } else {
116                         // no special option, push back 'status' etc
117                         lex.pushToken(token);
118                         break;
119                 }
120         }
121         InsetCollapsable::read(lex);
122 }
123
124
125 docstring InsetListings::editMessage() const
126 {
127         return _("Opened Listing Inset");
128 }
129
130
131 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
132 {
133         string param_string = params().params();
134         // NOTE: I use {} to quote text, which is an experimental feature
135         // of the listings package (see page 25 of the manual)
136         int lines = 0;
137         bool isInline = params().isInline();
138         // get the paragraphs. We can not output them directly to given odocstream
139         // because we can not yet determine the delimiter character of \lstinline
140         docstring code;
141         docstring uncodable;
142         ParagraphList::const_iterator par = paragraphs().begin();
143         ParagraphList::const_iterator end = paragraphs().end();
144
145         bool encoding_switched = false;
146         Encoding const * const save_enc = runparams.encoding;
147
148         if (!runparams.encoding->hasFixedWidth()) {
149                 // We need to switch to a singlebyte encoding, since the listings
150                 // package cannot deal with multiple-byte-encoded glyphs
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, buffer().params(),
162                                 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                         ++lines;
205                 }
206         }
207         if (isInline) {
208                 char const * delimiter = lstinline_delimiters;
209                 for (; delimiter != '\0'; ++delimiter)
210                         if (!contains(code, *delimiter))
211                                 break;
212                 // This code piece contains all possible special character? !!!
213                 // Replace ! with a warning message and use ! as delimiter.
214                 if (*delimiter == '\0') {
215                         docstring delim_error = "<" + _("LyX Warning: ")
216                                 + _("no more lstline delimiters available") + ">";
217                         code = subst(code, from_ascii("!"), delim_error);
218                         delimiter = lstinline_delimiters;
219                         if (!runparams.dryrun) {
220                                 // FIXME: warning should be passed to the error dialog
221                                 frontend::Alert::warning(_("Running out of delimiters"),
222                                 _("For inline program listings, one character must be reserved\n"
223                                   "as a delimiter. One of the listings, however, uses all available\n"
224                                   "characters, so none is left for delimiting purposes.\n"
225                                   "For the time being, I have replaced '!' by a warning, but you\n"
226                                   "must investigate!"));
227                         }
228                 }
229                 if (param_string.empty())
230                         os << "\\lstinline" << *delimiter;
231                 else
232                         os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
233                 os << code
234                    << *delimiter;
235         } else {
236                 OutputParams rp = runparams;
237                 rp.moving_arg = true;
238                 docstring const caption = getCaption(rp);
239                 runparams.encoding = rp.encoding;
240                 if (param_string.empty() && caption.empty())
241                         os << "\n\\begin{lstlisting}\n";
242                 else {
243                         os << "\n\\begin{lstlisting}[";
244                         if (!caption.empty()) {
245                                 os << "caption={" << caption << '}';
246                                 if (!param_string.empty())
247                                         os << ',';
248                         }
249                         os << from_utf8(param_string) << "]\n";
250                 }
251                 lines += 2;
252                 os << code << "\n\\end{lstlisting}\n";
253                 lines += 2;
254         }
255
256         if (encoding_switched){
257                 // Switch back
258                 pair<bool, int> const c = switchEncoding(os, buffer().params(),
259                                 runparams, *save_enc, true);
260                 runparams.encoding = save_enc;
261         }
262
263         if (!uncodable.empty()) {
264                 // issue a warning about omitted characters
265                 // FIXME: should be passed to the error dialog
266                 frontend::Alert::warning(_("Uncodable characters in listings inset"),
267                         bformat(_("The following characters in one of the program listings are\n"
268                                   "not representable in the current encoding and have been omitted:\n%1$s."),
269                         uncodable));
270         }
271
272         return lines;
273 }
274
275
276 docstring InsetListings::contextMenu(BufferView const &, int, int) const
277 {
278         return from_ascii("context-listings");
279 }
280
281
282 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
283 {
284         switch (cmd.action) {
285
286         case LFUN_INSET_MODIFY: {
287                 InsetListings::string2params(to_utf8(cmd.argument()), params());
288                 break;
289         }
290         case LFUN_INSET_DIALOG_UPDATE:
291                 cur.bv().updateDialog("listings", params2string(params()));
292                 break;
293         case LFUN_TAB_INSERT:
294                 if (cur.selection()) {
295                         // If there is a selection, a tab is inserted at the
296                         // beginning of each paragraph.
297                         cur.recordUndoSelection();
298                         pit_type const pit_end = cur.selEnd().pit();
299                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
300                                 LASSERT(pit < paragraphs().size(), /**/);
301                                 paragraphs()[pit].insertChar(0, '\t', 
302                                         buffer().params().trackChanges);
303                                 // Update the selection pos to make sure the selection does not
304                                 // change as the inserted tab will increase the logical pos.
305                                 if (cur.anchor_.pit() == pit)
306                                         cur.anchor_.forwardPos();
307                                 if (cur.pit() == pit)
308                                         cur.forwardPos();
309                         }
310                         cur.finishUndo();
311                 } else {
312                         // Maybe we shouldn't allow tabs within a line, because they
313                         // are not (yet) aligned as one might do expect.
314                         cur.recordUndo();
315                         cur.insert(from_ascii("\t"));
316                         cur.finishUndo();
317                 }
318                 break;
319         case LFUN_TAB_DELETE:
320                 if (cur.selection()) {
321                         // If there is a selection, a tab (if present) is removed from
322                         // the beginning of each paragraph.
323                         cur.recordUndoSelection();
324                         pit_type const pit_end = cur.selEnd().pit();
325                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
326                                 LASSERT( pit < paragraphs().size(), /**/ );
327                                 Paragraph & par = paragraphs()[pit];
328                                 if (par.getChar(0) == '\t') {
329                                         if (cur.pit() == pit)
330                                                 cur.posBackward();
331                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
332                                                 cur.anchor_.backwardPos();
333
334                                         par.eraseChar(0, buffer().params().trackChanges);
335                                 } else 
336                                         // If no tab was present, try to remove up to four spaces.
337                                         for (int n_spaces = 0;
338                                                 par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
339                                                         if (cur.pit() == pit)
340                                                                 cur.posBackward();
341                                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
342                                                                 cur.anchor_.backwardPos();
343
344                                                         par.eraseChar(0, buffer().params().trackChanges);
345                                         }
346                         }
347                         cur.finishUndo();
348                 } else {
349                         // If there is no selection, try to remove a tab or some spaces 
350                         // before the position of the cursor.
351                         LASSERT(cur.pit() >= 0 && cur.pit() < paragraphs().size(), /**/);
352
353                         Paragraph & par = paragraphs()[cur.pit()];
354                         pos_type const pos = cur.pos();
355
356                         if (pos == 0)
357                                 break;
358
359                         char_type const c = par.getChar(pos - 1);
360                         cur.recordUndo();
361                         if (c == '\t') {
362                                 cur.posBackward();
363                                 par.eraseChar(cur.pos(), buffer().params().trackChanges);
364                         } else
365                                 for (int n_spaces = 0; cur.pos() > 0
366                                         && par.getChar(cur.pos() - 1) == ' ' && n_spaces < 4;
367                                         ++n_spaces) {
368                                                 cur.posBackward();
369                                                 par.eraseChar(cur.pos(), buffer().params().trackChanges);
370                                 }
371                                 cur.finishUndo();
372                 }
373                 break;
374         default:
375                 InsetCollapsable::doDispatch(cur, cmd);
376                 break;
377         }
378 }
379
380
381 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
382         FuncStatus & status) const
383 {
384         switch (cmd.action) {
385                 case LFUN_INSET_MODIFY:
386                 case LFUN_INSET_DIALOG_UPDATE:
387                         status.setEnabled(true);
388                         return true;
389                 case LFUN_CAPTION_INSERT:
390                         status.setEnabled(!params().isInline());
391                         return true;
392                         case LFUN_TAB_INSERT:
393                         case LFUN_TAB_DELETE:
394                                 status.setEnabled(true);
395                                 return true;
396                 default:
397                         return InsetCollapsable::getStatus(cur, cmd, status);
398         }
399 }
400
401
402 void InsetListings::setButtonLabel()
403 {
404         // FIXME UNICODE
405         if (decoration() == InsetLayout::Classic)
406                 setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
407         else
408                 setLabel(getNewLabel(_("Listing")));
409 }
410
411
412 void InsetListings::validate(LaTeXFeatures & features) const
413 {
414         features.require("listings");
415         string param_string = params().params();
416         if (param_string.find("\\color") != string::npos)
417                 features.require("color");
418         InsetCollapsable::validate(features);
419 }
420
421
422 bool InsetListings::showInsetDialog(BufferView * bv) const
423 {
424         bv->showDialog("listings", params2string(params()),
425                 const_cast<InsetListings *>(this));
426         return true;
427 }
428
429
430 docstring InsetListings::getCaption(OutputParams const & runparams) const
431 {
432         if (paragraphs().empty())
433                 return docstring();
434
435         ParagraphList::const_iterator pit = paragraphs().begin();
436         for (; pit != paragraphs().end(); ++pit) {
437                 InsetList::const_iterator it = pit->insetList().begin();
438                 for (; it != pit->insetList().end(); ++it) {
439                         Inset & inset = *it->inset;
440                         if (inset.lyxCode() == CAPTION_CODE) {
441                                 odocstringstream ods;
442                                 InsetCaption * ins =
443                                         static_cast<InsetCaption *>(it->inset);
444                                 ins->getOptArg(ods, runparams);
445                                 ins->getArgument(ods, runparams);
446                                 // the caption may contain \label{} but the listings
447                                 // package prefer caption={}, label={}
448                                 docstring cap = ods.str();
449                                 if (!contains(to_utf8(cap), "\\label{"))
450                                         return cap;
451                                 // convert from
452                                 //     blah1\label{blah2} blah3
453                                 // to
454                                 //     blah1 blah3},label={blah2
455                                 // to form options
456                                 //     caption={blah1 blah3},label={blah2}
457                                 //
458                                 // NOTE that } is not allowed in blah2.
459                                 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
460                                 string const new_cap("\\1\\3},label={\\2");
461                                 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
462                         }
463                 }
464         }
465         return docstring();
466 }
467
468
469 void InsetListings::string2params(string const & in,
470                                    InsetListingsParams & params)
471 {
472         params = InsetListingsParams();
473         if (in.empty())
474                 return;
475         istringstream data(in);
476         Lexer lex;
477         lex.setStream(data);
478         // discard "listings", which is only used to determine inset
479         lex.next();
480         params.read(lex);
481 }
482
483
484 string InsetListings::params2string(InsetListingsParams const & params)
485 {
486         ostringstream data;
487         data << "listings" << ' ';
488         params.write(data);
489         return data.str();
490 }
491
492
493 } // namespace lyx