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"
27 #include "MetricsInfo.h"
28 #include "output_latex.h"
29 #include "TextClass.h"
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35 #include "support/lassert.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)
57 status_ = par.status();
61 InsetListings::~InsetListings()
63 hideDialogs("listings", this);
67 Inset::DisplayType InsetListings::display() const
69 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
73 void InsetListings::updateLabels(ParIterator const & it)
75 Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
76 string const saveflt = cnts.current_float();
78 // Tell to captions what the current float is
79 cnts.current_float("listing");
81 InsetCollapsable::updateLabels(it);
84 cnts.current_float(saveflt);
88 void InsetListings::write(ostream & os) const
90 os << "listings" << "\n";
91 InsetListingsParams const & par = params();
92 // parameter string is encoded to be a valid lyx token.
93 string opt = par.encodedString();
95 os << "lstparams \"" << opt << "\"\n";
97 os << "inline true\n";
99 os << "inline false\n";
100 InsetCollapsable::write(os);
104 void InsetListings::read(Lexer & lex)
108 string token = lex.getString();
109 if (token == "lstparams") {
111 string const value = lex.getString();
112 params().fromEncodedString(value);
113 } else if (token == "inline") {
115 params().setInline(lex.getBool());
117 // no special option, push back 'status' etc
118 lex.pushToken(token);
122 InsetCollapsable::read(lex);
126 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
128 string param_string = params().params();
129 // NOTE: I use {} to quote text, which is an experimental feature
130 // of the listings package (see page 25 of the manual)
132 bool const isInline = params().isInline();
133 // get the paragraphs. We can not output them directly to given odocstream
134 // because we can not yet determine the delimiter character of \lstinline
137 ParagraphList::const_iterator par = paragraphs().begin();
138 ParagraphList::const_iterator end = paragraphs().end();
140 bool encoding_switched = false;
141 Encoding const * const save_enc = runparams.encoding;
143 if (!runparams.encoding->hasFixedWidth()) {
144 // We need to switch to a singlebyte encoding, since the listings
145 // package cannot deal with multiple-byte-encoded glyphs
146 Language const * const outer_language =
147 (runparams.local_font != 0) ?
148 runparams.local_font->language()
149 : buffer().params().language;
150 // We try if there's a singlebyte encoding for the current
151 // language; if not, fall back to latin1.
152 Encoding const * const lstenc =
153 (outer_language->encoding()->hasFixedWidth()) ?
154 outer_language->encoding()
155 : encodings.fromLyXName("iso8859-1");
156 pair<bool, int> const c = switchEncoding(os, buffer().params(),
157 runparams, *lstenc, true);
158 runparams.encoding = lstenc;
159 encoding_switched = true;
163 pos_type siz = par->size();
164 bool captionline = false;
165 for (pos_type i = 0; i < siz; ++i) {
166 if (i == 0 && par->isInset(i) && i + 1 == siz)
168 // ignore all struck out text and (caption) insets
169 if (par->isDeleted(i) || par->isInset(i))
171 char_type c = par->getChar(i);
172 // we can only output characters covered by the current
175 if (runparams.encoding->latexChar(c) == docstring(1, c))
177 else if (runparams.dryrun) {
178 code += "<" + _("LyX Warning: ")
179 + _("uncodable character") + " '";
180 code += docstring(1, c);
184 } catch (EncodingException & /* e */) {
185 if (runparams.dryrun) {
186 code += "<" + _("LyX Warning: ")
187 + _("uncodable character") + " '";
188 code += docstring(1, c);
195 // for the inline case, if there are multiple paragraphs
196 // they are simply joined. Otherwise, expect latex errors.
197 if (par != end && !isInline && !captionline) {
203 char const * delimiter = lstinline_delimiters;
204 for (; delimiter != '\0'; ++delimiter)
205 if (!contains(code, *delimiter))
207 // This code piece contains all possible special character? !!!
208 // Replace ! with a warning message and use ! as delimiter.
209 if (*delimiter == '\0') {
210 docstring delim_error = "<" + _("LyX Warning: ")
211 + _("no more lstline delimiters available") + ">";
212 code = subst(code, from_ascii("!"), delim_error);
213 delimiter = lstinline_delimiters;
214 if (!runparams.dryrun) {
215 // FIXME: warning should be passed to the error dialog
216 frontend::Alert::warning(_("Running out of delimiters"),
217 _("For inline program listings, one character must be reserved\n"
218 "as a delimiter. One of the listings, however, uses all available\n"
219 "characters, so none is left for delimiting purposes.\n"
220 "For the time being, I have replaced '!' by a warning, but you\n"
221 "must investigate!"));
224 if (param_string.empty())
225 os << "\\lstinline" << *delimiter;
227 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
231 OutputParams rp = runparams;
232 rp.moving_arg = true;
233 docstring const caption = getCaption(rp);
234 if (param_string.empty() && caption.empty())
235 os << "\n\\begin{lstlisting}\n";
237 os << "\n\\begin{lstlisting}[";
238 if (!caption.empty()) {
239 os << "caption={" << caption << '}';
240 if (!param_string.empty())
243 os << from_utf8(param_string) << "]\n";
246 os << code << "\n\\end{lstlisting}\n";
250 if (encoding_switched){
252 pair<bool, int> const c = switchEncoding(os, buffer().params(),
253 runparams, *save_enc, true);
254 runparams.encoding = save_enc;
257 if (!uncodable.empty()) {
258 // issue a warning about omitted characters
259 // FIXME: should be passed to the error dialog
260 frontend::Alert::warning(_("Uncodable characters in listings inset"),
261 bformat(_("The following characters in one of the program listings are\n"
262 "not representable in the current encoding and have been omitted:\n%1$s."),
270 docstring InsetListings::xhtml(odocstream & os, OutputParams const & rp) const
272 odocstringstream out;
274 bool const isInline = params().isInline();
278 out << "<div class='float float-listings'>\n";
279 docstring caption = getCaptionHTML(rp);
280 if (!caption.empty())
281 out << "<div class='float-caption'>" << caption << "</div>\n";
285 OutputParams newrp = rp;
286 newrp.disable_captions = true;
287 docstring def = InsetText::xhtml(out, newrp);
295 // In this case, this needs to be deferred, but we'll put it
296 // before anything the text itself deferred.
297 def = out.str() + '\n' + def;
303 docstring InsetListings::contextMenu(BufferView const &, int, int) const
305 return from_ascii("context-listings");
309 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
311 switch (cmd.action) {
313 case LFUN_INSET_MODIFY: {
314 InsetListings::string2params(to_utf8(cmd.argument()), params());
318 case LFUN_INSET_DIALOG_UPDATE:
319 cur.bv().updateDialog("listings", params2string(params()));
323 InsetCollapsable::doDispatch(cur, cmd);
329 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
330 FuncStatus & status) const
332 switch (cmd.action) {
333 case LFUN_INSET_MODIFY:
334 case LFUN_INSET_DIALOG_UPDATE:
335 status.setEnabled(true);
337 case LFUN_CAPTION_INSERT:
338 status.setEnabled(!params().isInline());
341 return InsetCollapsable::getStatus(cur, cmd, status);
346 docstring const InsetListings::buttonLabel(BufferView const & bv) const
349 if (decoration() == InsetLayout::CLASSIC)
350 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
352 return getNewLabel(_("Listing"));
356 void InsetListings::validate(LaTeXFeatures & features) const
358 features.require("listings");
359 string param_string = params().params();
360 if (param_string.find("\\color") != string::npos)
361 features.require("color");
362 InsetCollapsable::validate(features);
366 bool InsetListings::showInsetDialog(BufferView * bv) const
368 bv->showDialog("listings", params2string(params()),
369 const_cast<InsetListings *>(this));
374 docstring InsetListings::getCaption(OutputParams const & runparams) const
376 if (paragraphs().empty())
379 InsetCaption const * ins = getCaptionInset();
383 odocstringstream ods;
384 ins->getOptArg(ods, runparams);
385 ins->getArgument(ods, runparams);
386 // the caption may contain \label{} but the listings
387 // package prefer caption={}, label={}
388 docstring cap = ods.str();
389 if (!contains(to_utf8(cap), "\\label{"))
392 // blah1\label{blah2} blah3
394 // blah1 blah3},label={blah2
396 // caption={blah1 blah3},label={blah2}
398 // NOTE that } is not allowed in blah2.
399 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
400 string const new_cap("\\1\\3},label={\\2");
401 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
405 void InsetListings::string2params(string const & in,
406 InsetListingsParams & params)
408 params = InsetListingsParams();
411 istringstream data(in);
414 // discard "listings", which is only used to determine inset
420 string InsetListings::params2string(InsetListingsParams const & params)
423 data << "listings" << ' ';