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