2 * \file InsetListings.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Jürgen Spitzmüller
9 * Full author contact details are available in file CREDITS.
14 #include "InsetListings.h"
17 #include "BufferView.h"
18 #include "BufferParams.h"
21 #include "DispatchResult.h"
23 #include "FuncRequest.h"
24 #include "FuncStatus.h"
25 #include "InsetCaption.h"
26 #include "InsetList.h"
28 #include "MetricsInfo.h"
29 #include "output_latex.h"
30 #include "TextClass.h"
32 #include "support/debug.h"
33 #include "support/docstream.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
37 #include "frontends/alert.h"
38 #include "frontends/Application.h"
40 #include <boost/regex.hpp>
45 using namespace lyx::support;
51 char const lstinline_delimiters[] =
52 "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
54 InsetListings::InsetListings(Buffer const & buf, InsetListingsParams const & par)
55 : InsetCollapsable(buf, par.status())
59 InsetListings::~InsetListings()
61 hideDialogs("listings", this);
65 Inset::DisplayType InsetListings::display() const
67 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
71 void InsetListings::updateLabels(ParIterator const & it)
73 Counters & cnts = buffer().params().documentClass().counters();
74 string const saveflt = cnts.current_float();
76 // Tell to captions what the current float is
77 cnts.current_float("listing");
79 InsetCollapsable::updateLabels(it);
82 cnts.current_float(saveflt);
86 void InsetListings::write(ostream & os) const
88 os << "listings" << "\n";
89 InsetListingsParams const & par = params();
90 // parameter string is encoded to be a valid lyx token.
91 string opt = par.encodedString();
93 os << "lstparams \"" << opt << "\"\n";
95 os << "inline true\n";
97 os << "inline false\n";
98 InsetCollapsable::write(os);
102 void InsetListings::read(Lexer & lex)
106 string token = lex.getString();
107 if (token == "lstparams") {
109 string const value = lex.getString();
110 params().fromEncodedString(value);
111 } else if (token == "inline") {
113 params().setInline(lex.getBool());
115 // no special option, push back 'status' etc
116 lex.pushToken(token);
120 InsetCollapsable::read(lex);
124 docstring InsetListings::editMessage() const
126 return _("Opened Listing Inset");
130 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
132 string param_string = params().params();
133 // NOTE: I use {} to quote text, which is an experimental feature
134 // of the listings package (see page 25 of the manual)
136 bool isInline = params().isInline();
137 // get the paragraphs. We can not output them directly to given odocstream
138 // because we can not yet determine the delimiter character of \lstinline
141 ParagraphList::const_iterator par = paragraphs().begin();
142 ParagraphList::const_iterator end = paragraphs().end();
144 bool encoding_switched = false;
145 Encoding const * const save_enc = runparams.encoding;
147 if (!runparams.encoding->hasFixedWidth()) {
148 // We need to switch to a singlebyte encoding, since the listings
149 // package cannot deal with multiple-byte-encoded glyphs
150 Language const * const outer_language =
151 (runparams.local_font != 0) ?
152 runparams.local_font->language()
153 : buffer().params().language;
154 // We try if there's a singlebyte encoding for the current
155 // language; if not, fall back to latin1.
156 Encoding const * const lstenc =
157 (outer_language->encoding()->hasFixedWidth()) ?
158 outer_language->encoding()
159 : encodings.fromLyXName("iso8859-1");
160 pair<bool, int> const c = switchEncoding(os, buffer().params(),
161 runparams, *lstenc, true);
162 runparams.encoding = lstenc;
163 encoding_switched = true;
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)
172 // ignore all struck out text and (caption) insets
173 if (par->isDeleted(i) || par->isInset(i))
175 char_type c = par->getChar(i);
176 // we can only output characters covered by the current
179 if (runparams.encoding->latexChar(c) == docstring(1, c))
181 else if (runparams.dryrun) {
182 code += "<" + _("LyX Warning: ")
183 + _("uncodable character") + " '";
184 code += docstring(1, c);
188 } catch (EncodingException & /* e */) {
189 if (runparams.dryrun) {
190 code += "<" + _("LyX Warning: ")
191 + _("uncodable character") + " '";
192 code += docstring(1, c);
199 // for the inline case, if there are multiple paragraphs
200 // they are simply joined. Otherwise, expect latex errors.
201 if (par != end && !isInline && !captionline) {
207 char const * delimiter = lstinline_delimiters;
208 for (; delimiter != '\0'; ++delimiter)
209 if (!contains(code, *delimiter))
211 // This code piece contains all possible special character? !!!
212 // Replace ! with a warning message and use ! as delimiter.
213 if (*delimiter == '\0') {
214 docstring delim_error = "<" + _("LyX Warning: ")
215 + _("no more lstline delimiters available") + ">";
216 code = subst(code, from_ascii("!"), delim_error);
217 delimiter = lstinline_delimiters;
218 if (!runparams.dryrun) {
219 // FIXME: warning should be passed to the error dialog
220 frontend::Alert::warning(_("Running out of delimiters"),
221 _("For inline program listings, one character must be reserved\n"
222 "as a delimiter. One of the listings, however, uses all available\n"
223 "characters, so none is left for delimiting purposes.\n"
224 "For the time being, I have replaced '!' by a warning, but you\n"
225 "must investigate!"));
228 if (param_string.empty())
229 os << "\\lstinline" << *delimiter;
231 os << "\\lstinline[" << from_ascii(param_string) << "]" << *delimiter;
235 OutputParams rp = runparams;
236 rp.moving_arg = true;
237 docstring const caption = getCaption(rp);
238 runparams.encoding = rp.encoding;
239 if (param_string.empty() && caption.empty())
240 os << "\n\\begin{lstlisting}\n";
242 os << "\n\\begin{lstlisting}[";
243 if (!caption.empty()) {
244 os << "caption={" << caption << '}';
245 if (!param_string.empty())
248 os << from_utf8(param_string) << "]\n";
251 os << code << "\n\\end{lstlisting}\n";
255 if (encoding_switched){
257 pair<bool, int> const c = switchEncoding(os, buffer().params(),
258 runparams, *save_enc, true);
259 runparams.encoding = save_enc;
262 if (!uncodable.empty()) {
263 // issue a warning about omitted characters
264 // FIXME: should be passed to the error dialog
265 frontend::Alert::warning(_("Uncodable characters in listings inset"),
266 bformat(_("The following characters in one of the program listings are\n"
267 "not representable in the current encoding and have been omitted:\n%1$s."),
275 docstring InsetListings::contextMenu(BufferView const &, int, int) const
277 return from_ascii("context-listings");
281 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
283 switch (cmd.action) {
285 case LFUN_INSET_MODIFY: {
286 InsetListings::string2params(to_utf8(cmd.argument()), params());
289 case LFUN_INSET_DIALOG_UPDATE:
290 cur.bv().updateDialog("listings", params2string(params()));
293 InsetCollapsable::doDispatch(cur, cmd);
299 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
300 FuncStatus & status) const
302 switch (cmd.action) {
303 case LFUN_INSET_MODIFY:
304 case LFUN_INSET_DIALOG_UPDATE:
305 status.setEnabled(true);
307 case LFUN_CAPTION_INSERT:
308 status.setEnabled(!params().isInline());
311 return InsetCollapsable::getStatus(cur, cmd, status);
316 void InsetListings::setButtonLabel()
319 if (decoration() == InsetLayout::Classic)
320 setLabel(isOpen() ? _("Listing") : getNewLabel(_("Listing")));
322 setLabel(getNewLabel(_("Listing")));
326 void InsetListings::validate(LaTeXFeatures & features) const
328 features.require("listings");
329 InsetCollapsable::validate(features);
333 bool InsetListings::showInsetDialog(BufferView * bv) const
335 bv->showDialog("listings", params2string(params()),
336 const_cast<InsetListings *>(this));
341 docstring InsetListings::getCaption(OutputParams const & runparams) const
343 if (paragraphs().empty())
346 ParagraphList::const_iterator pit = paragraphs().begin();
347 for (; pit != paragraphs().end(); ++pit) {
348 InsetList::const_iterator it = pit->insetList().begin();
349 for (; it != pit->insetList().end(); ++it) {
350 Inset & inset = *it->inset;
351 if (inset.lyxCode() == CAPTION_CODE) {
352 odocstringstream ods;
354 static_cast<InsetCaption *>(it->inset);
355 ins->getOptArg(ods, runparams);
356 ins->getArgument(ods, runparams);
357 // the caption may contain \label{} but the listings
358 // package prefer caption={}, label={}
359 docstring cap = ods.str();
360 if (!contains(to_utf8(cap), "\\label{"))
363 // blah1\label{blah2} blah3
365 // blah1 blah3},label={blah2
367 // caption={blah1 blah3},label={blah2}
369 // NOTE that } is not allowed in blah2.
370 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
371 string const new_cap("\\1\\3},label={\\2");
372 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
380 void InsetListings::string2params(string const & in,
381 InsetListingsParams & params)
383 params = InsetListingsParams();
386 istringstream data(in);
389 // discard "listings", which is only used to determine inset
395 string InsetListings::params2string(InsetListingsParams const & params)
398 data << "listings" << ' ';