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