]> git.lyx.org Git - lyx.git/blob - src/insets/InsetListings.cpp
Listings: Move \label{} outside of caption={}
[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 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
201 {
202         switch (cmd.action) {
203
204         case LFUN_INSET_MODIFY: {
205                 InsetListingsMailer::string2params(to_utf8(cmd.argument()), params());
206                 break;
207         }
208         case LFUN_INSET_DIALOG_UPDATE:
209                 InsetListingsMailer(*this).updateDialog(&cur.bv());
210                 break;
211         case LFUN_MOUSE_RELEASE: {
212                 if (cmd.button() == mouse_button::button3 && hitButton(cmd)) {
213                         InsetListingsMailer(*this).showDialog(&cur.bv());
214                         break;
215                 }
216                 InsetCollapsable::doDispatch(cur, cmd);
217                 break;
218         }
219         default:
220                 InsetCollapsable::doDispatch(cur, cmd);
221                 break;
222         }
223 }
224
225
226 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
227         FuncStatus & status) const
228 {
229         switch (cmd.action) {
230                 case LFUN_INSET_DIALOG_UPDATE:
231                         status.enabled(true);
232                         return true;
233                 case LFUN_CAPTION_INSERT:
234                         status.enabled(!params().isInline());
235                         return true;
236                 default:
237                         return InsetCollapsable::getStatus(cur, cmd, status);
238         }
239 }
240
241
242 void InsetListings::setButtonLabel()
243 {
244         // FIXME UNICODE
245         if (decoration() == InsetLayout::Classic)
246                 setLabel(isOpen() ?  _("Listing") : getNewLabel(_("Listing")));
247         else
248                 setLabel(getNewLabel(_("Listing")));
249 }
250
251
252 void InsetListings::validate(LaTeXFeatures & features) const
253 {
254         features.require("listings");
255         InsetCollapsable::validate(features);
256 }
257
258
259 bool InsetListings::showInsetDialog(BufferView * bv) const
260 {
261         InsetListingsMailer(const_cast<InsetListings &>(*this)).showDialog(bv);
262         return true;
263 }
264
265
266 docstring InsetListings::getCaption(OutputParams const & runparams) const
267 {
268         if (paragraphs().empty())
269                 return docstring();
270
271         ParagraphList::const_iterator pit = paragraphs().begin();
272         for (; pit != paragraphs().end(); ++pit) {
273                 InsetList::const_iterator it = pit->insetList().begin();
274                 for (; it != pit->insetList().end(); ++it) {
275                         Inset & inset = *it->inset;
276                         if (inset.lyxCode() == CAPTION_CODE) {
277                                 odocstringstream ods;
278                                 InsetCaption * ins =
279                                         static_cast<InsetCaption *>(it->inset);
280                                 ins->getOptArg(ods, runparams);
281                                 ins->getArgument(ods, runparams);
282                                 // the caption may contain \label{} but the listings
283                                 // package prefer caption={}, label={}
284                                 docstring cap = ods.str();
285                                 if (!contains(to_utf8(cap), "\\label{"))
286                                         return cap;
287                                 // convert from
288                                 //     blah1\label{blah2} blah3
289                                 // to
290                                 //     blah1 blah3},label={blah2
291                                 // to form options
292                                 //     caption={blah1 blah3},label={blah2}
293                                 //
294                                 // NOTE that } is not allowed in blah2.
295                                 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
296                                 string const new_cap("\\1\\3},label={\\2");
297                                 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
298                         }
299                 }
300         }
301         return docstring();
302 }
303
304
305 string const InsetListingsMailer::name_("listings");
306
307 InsetListingsMailer::InsetListingsMailer(InsetListings & inset)
308         : inset_(inset)
309 {}
310
311
312 string const InsetListingsMailer::inset2string(Buffer const &) const
313 {
314         return params2string(inset_.params());
315 }
316
317
318 void InsetListingsMailer::string2params(string const & in,
319                                    InsetListingsParams & params)
320 {
321         params = InsetListingsParams();
322         if (in.empty())
323                 return;
324         istringstream data(in);
325         Lexer lex(0, 0);
326         lex.setStream(data);
327         // discard "listings", which is only used to determine inset
328         lex.next();
329         params.read(lex);
330 }
331
332
333 string const
334 InsetListingsMailer::params2string(InsetListingsParams const & params)
335 {
336         ostringstream data;
337         data << name_ << " ";
338         params.write(data);
339         return data.str();
340 }
341
342
343 } // namespace lyx