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