]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Rewrite the label numbering code.
[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 #include "InsetCaption.h"
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "Counters.h"
20 #include "Language.h"
21 #include "gettext.h"
22 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "MetricsInfo.h"
26 #include "Cursor.h"
27 #include "support/lstrings.h"
28
29 #include <sstream>
30
31 namespace lyx {
32
33 using support::token;
34 using support::contains;
35 using support::subst;
36
37 using std::auto_ptr;
38 using std::istringstream;
39 using std::ostream;
40 using std::ostringstream;
41 using std::string;
42
43 char const lstinline_delimiters[] = "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
44
45 void InsetListings::init()
46 {
47         setButtonLabel();
48         Font font(Font::ALL_SANE);
49         font.decSize();
50         font.decSize();
51         font.setColor(Color::none);
52         setLabelFont(font);
53         text_.current_font.setLanguage(latex_language);
54         text_.real_current_font.setLanguage(latex_language);
55 }
56
57
58 InsetListings::InsetListings(BufferParams const & bp, InsetListingsParams const & par)
59         : InsetERT(bp, par.status())
60 {
61         init();
62 }
63
64
65 InsetListings::InsetListings(InsetListings const & in)
66         : InsetERT(in), params_(in.params_)
67 {
68         init();
69 }
70
71
72 auto_ptr<Inset> InsetListings::doClone() const
73 {
74         return auto_ptr<Inset>(new InsetListings(*this));
75 }
76
77
78 InsetListings::~InsetListings()
79 {
80         InsetListingsMailer(*this).hideDialog();
81 }
82
83
84 Inset::DisplayType InsetListings::display() const
85 {
86         return params().isInline() || params().isFloat() ? Inline : AlignLeft;
87 }
88
89
90 void InsetListings::updateLabels(Buffer const & buf, ParIterator const & it)
91 {
92         Counters & cnts = buf.params().getTextClass().counters();
93         string const saveflt = cnts.current_float();
94
95         // Tell to captions what the current float is
96         cnts.current_float("listing");
97
98         InsetCollapsable::updateLabels(buf, it);
99
100         //reset afterwards
101         cnts.current_float(saveflt);
102 }
103
104
105 void InsetListings::write(Buffer const & buf, ostream & os) const
106 {
107         os << "listings" << "\n";
108         InsetListingsParams const & par = params();
109         // parameter string is encoded to be a valid lyx token.
110         string opt = par.encodedString();
111         if (!opt.empty())
112                 os << "lstparams \"" << opt << "\"\n";
113         if (par.isInline())
114                 os << "inline true\n";
115         else
116                 os << "inline false\n";
117         InsetCollapsable::write(buf, os);
118 }
119
120
121 void InsetListings::read(Buffer const & buf, Lexer & lex)
122 {
123         while (lex.isOK()) {
124                 lex.next();
125                 string const token = lex.getString();
126                 if (token == "lstparams") {
127                         lex.next();
128                         string const value = lex.getString();
129                         params().fromEncodedString(value);
130                 } else if (token == "inline") {
131                         lex.next();
132                         params().setInline(lex.getBool());
133                 } else {
134                         // no special option, push back 'status' etc
135                         lex.pushToken(token);
136                         break;
137                 }
138         }
139         InsetERT::read(buf, lex);
140 }
141
142
143 docstring const InsetListings::editMessage() const
144 {
145         return _("Opened Listing Inset");
146 }
147
148
149 int InsetListings::latex(Buffer const & buf, odocstream & os,
150                     OutputParams const & runparams) const
151 {
152         string param_string = params().params();
153         // NOTE: I use {} to quote text, which is an experimental feature
154         // of the listings package (see page 25 of the manual)
155         int lines = 0;
156         bool isInline = params().isInline();
157         // get the paragraphs. We can not output them directly to given odocstream
158         // because we can not yet determine the delimiter character of \lstinline
159         docstring code;
160         ParagraphList::const_iterator par = paragraphs().begin();
161         ParagraphList::const_iterator end = paragraphs().end();
162
163         while (par != end) {
164                 pos_type siz = par->size();
165                 bool captionline = false;
166                 for (pos_type i = 0; i < siz; ++i) {
167                         if (i == 0 && par->isInset(i) && i + 1 == siz)
168                                 captionline = true;
169                         // ignore all struck out text and (caption) insets
170                         if (par->isDeleted(i) || par->isInset(i))
171                                 continue;
172                         code += par->getChar(i);
173                 }
174                 ++par;
175                 // for the inline case, if there are multiple paragraphs
176                 // they are simply joined. Otherwise, expect latex errors.
177                 if (par != end && !isInline && !captionline) {
178                         code += "\n";
179                         ++lines;
180                 }
181         }
182         if (isInline) {
183                 char const * delimiter = lstinline_delimiters;
184                 for (; delimiter != '\0'; ++delimiter)
185                         if (!contains(code, *delimiter))
186                                 break;
187                 // This code piece contains all possible special character? !!!
188                 // Replace ! with a warning message and use ! as delimiter.
189                 if (*delimiter == '\0') {
190                         code = subst(code, from_ascii("!"), from_ascii(" WARNING: no lstline delimiter can be used "));
191                         delimiter = lstinline_delimiters;
192                 }
193                 if (param_string.empty())
194                         os << "\\lstinline" << *delimiter;
195                 else
196                         os << "\\lstinline[" << from_ascii(param_string) << "]" << *delimiter;
197                 os << code
198                    << *delimiter;
199         } else {
200                 docstring const caption = getCaption(buf, runparams);
201                 if (param_string.empty() && caption.empty())
202                         os << "\n\\begingroup\n\\inputencoding{latin1}\n\\begin{lstlisting}\n";
203                 else {
204                         os << "\n\\begingroup\n\\inputencoding{latin1}\n\\begin{lstlisting}[";
205                         if (!caption.empty()) {
206                                 os << "caption={" << caption << '}';
207                                 if (!param_string.empty())
208                                         os << ',';
209                         }
210                         os << from_utf8(param_string) << "]\n";
211                 }
212                 lines += 4;
213                 os << code
214                    << "\n\\end{lstlisting}\n\\endgroup\n";
215                 lines += 3;
216         }
217
218         return lines;
219 }
220
221
222 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
223 {
224         switch (cmd.action) {
225
226         case LFUN_INSET_MODIFY: {
227                 InsetListingsMailer::string2params(to_utf8(cmd.argument()), params());
228                 break;
229         }
230         case LFUN_INSET_DIALOG_UPDATE:
231                 InsetListingsMailer(*this).updateDialog(&cur.bv());
232                 break;
233         case LFUN_MOUSE_RELEASE: {
234                 if (cmd.button() == mouse_button::button3 && hitButton(cmd)) {
235                         InsetListingsMailer(*this).showDialog(&cur.bv());
236                         break;
237                 }
238                 InsetERT::doDispatch(cur, cmd);
239                 break;
240         }
241         default:
242                 InsetERT::doDispatch(cur, cmd);
243                 break;
244         }
245 }
246
247
248 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
249         FuncStatus & status) const
250 {
251         switch (cmd.action) {
252                 case LFUN_INSET_DIALOG_UPDATE:
253                         status.enabled(true);
254                         return true;
255                 case LFUN_CAPTION_INSERT:
256                         status.enabled(!params().isInline());
257                         return true;
258                 default:
259                         return InsetERT::getStatus(cur, cmd, status);
260         }
261 }
262
263
264 void InsetListings::setButtonLabel()
265 {
266         // FIXME UNICODE
267         setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
268 }
269
270
271 bool InsetListings::metrics(MetricsInfo & mi, Dimension & dim) const
272 {
273         Font tmpfont = mi.base.font;
274         getDrawFont(mi.base.font);
275         mi.base.font.realize(tmpfont);
276         InsetCollapsable::metrics(mi, dim);
277         mi.base.font = tmpfont;
278         bool const changed = dim_ != dim;
279         dim_ = dim;
280         return changed;
281 }
282
283
284 void InsetListings::draw(PainterInfo & pi, int x, int y) const
285 {
286         Font tmpfont = pi.base.font;
287         getDrawFont(pi.base.font);
288         pi.base.font.realize(tmpfont);
289         InsetCollapsable::draw(pi, x, y);
290         pi.base.font = tmpfont;
291 }
292
293
294 void InsetListings::validate(LaTeXFeatures & features) const
295 {
296         features.require("listings");
297         InsetERT::validate(features);
298 }
299
300
301 bool InsetListings::showInsetDialog(BufferView * bv) const
302 {
303         InsetListingsMailer(const_cast<InsetListings &>(*this)).showDialog(bv);
304         return true;
305 }
306
307
308 void InsetListings::getDrawFont(Font & font) const
309 {
310         font = Font(Font::ALL_INHERIT, latex_language);
311         font.setFamily(Font::TYPEWRITER_FAMILY);
312         // FIXME: define Color::listing?
313         font.setColor(Color::foreground);
314 }
315
316
317 docstring InsetListings::getCaption(Buffer const & buf,
318                     OutputParams const & runparams) const
319 {
320         if (paragraphs().empty())
321                 return docstring();
322
323         ParagraphList::const_iterator pit = paragraphs().begin();
324         for (; pit != paragraphs().end(); ++pit) {
325                 InsetList::const_iterator it = pit->insetlist.begin();
326                 for (; it != pit->insetlist.end(); ++it) {
327                         Inset & inset = *it->inset;
328                         if (inset.lyxCode() == Inset::CAPTION_CODE) {
329                                 odocstringstream ods;
330                                 InsetCaption * ins =
331                                         static_cast<InsetCaption *>(it->inset);
332                                 ins->getOptArg(buf, ods, runparams);
333                                 ins->getArgument(buf, ods, runparams);
334                                 return ods.str();
335                         }
336                 }
337         }
338         return docstring();
339 }
340
341
342 string const InsetListingsMailer::name_("listings");
343
344 InsetListingsMailer::InsetListingsMailer(InsetListings & inset)
345         : inset_(inset)
346 {}
347
348
349 string const InsetListingsMailer::inset2string(Buffer const &) const
350 {
351         return params2string(inset_.params());
352 }
353
354
355 void InsetListingsMailer::string2params(string const & in,
356                                    InsetListingsParams & params)
357 {
358         params = InsetListingsParams();
359         if (in.empty())
360                 return;
361         istringstream data(in);
362         Lexer lex(0, 0);
363         lex.setStream(data);
364         // discard "listings", which is only used to determine inset
365         lex.next();
366         params.read(lex);
367 }
368
369
370 string const
371 InsetListingsMailer::params2string(InsetListingsParams const & params)
372 {
373         ostringstream data;
374         data << name_ << " ";
375         params.write(data);
376         return data.str();
377 }
378
379
380 } // namespace lyx