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"
28 #include "output_latex.h"
29 #include "output_xhtml.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"
36 #include "support/lassert.h"
38 #include "frontends/alert.h"
39 #include "frontends/Application.h"
41 #include <boost/regex.hpp>
46 using namespace lyx::support;
52 char const lstinline_delimiters[] =
53 "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56 : InsetCollapsable(buf)
58 status_ = par.status();
62 InsetListings::~InsetListings()
64 hideDialogs("listings", this);
68 Inset::DisplayType InsetListings::display() const
70 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
74 void InsetListings::updateBuffer(ParIterator const & it, UpdateType utype)
77 buffer().masterBuffer()->params().documentClass().counters();
78 string const saveflt = cnts.current_float();
80 // Tell to captions what the current float is
81 cnts.current_float("listing");
83 InsetCollapsable::updateBuffer(it, utype);
86 cnts.current_float(saveflt);
90 void InsetListings::write(ostream & os) const
92 os << "listings" << "\n";
93 InsetListingsParams const & par = params();
94 // parameter string is encoded to be a valid lyx token.
95 string opt = par.encodedString();
97 os << "lstparams \"" << opt << "\"\n";
99 os << "inline true\n";
101 os << "inline false\n";
102 InsetCollapsable::write(os);
106 void InsetListings::read(Lexer & lex)
110 string token = lex.getString();
111 if (token == "lstparams") {
113 string const value = lex.getString();
114 params().fromEncodedString(value);
115 } else if (token == "inline") {
117 params().setInline(lex.getBool());
119 // no special option, push back 'status' etc
120 lex.pushToken(token);
124 InsetCollapsable::read(lex);
128 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
130 string param_string = params().params();
131 // NOTE: I use {} to quote text, which is an experimental feature
132 // of the listings package (see page 25 of the manual)
134 bool const isInline = params().isInline();
135 // get the paragraphs. We can not output them directly to given odocstream
136 // because we can not yet determine the delimiter character of \lstinline
139 ParagraphList::const_iterator par = paragraphs().begin();
140 ParagraphList::const_iterator end = paragraphs().end();
142 bool encoding_switched = false;
143 Encoding const * const save_enc = runparams.encoding;
145 if (runparams.flavor != OutputParams::XETEX
146 && !runparams.encoding->hasFixedWidth()) {
147 // We need to switch to a singlebyte encoding, since the
148 // listings package cannot deal with multi-byte-encoded
149 // glyphs (not needed with XeTeX).
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_utf8(param_string) << "]" << *delimiter;
235 OutputParams rp = runparams;
236 rp.moving_arg = true;
237 docstring const caption = getCaption(rp);
238 if (param_string.empty() && caption.empty())
239 os << "\n\\begin{lstlisting}\n";
241 os << "\n\\begin{lstlisting}[";
242 if (!caption.empty()) {
243 os << "caption={" << caption << '}';
244 if (!param_string.empty())
247 os << from_utf8(param_string) << "]\n";
250 os << code << "\n\\end{lstlisting}\n";
254 if (encoding_switched){
256 pair<bool, int> const c = switchEncoding(os, buffer().params(),
257 runparams, *save_enc, true);
258 runparams.encoding = save_enc;
261 if (!uncodable.empty()) {
262 // issue a warning about omitted characters
263 // FIXME: should be passed to the error dialog
264 frontend::Alert::warning(_("Uncodable characters in listings inset"),
265 bformat(_("The following characters in one of the program listings are\n"
266 "not representable in the current encoding and have been omitted:\n%1$s."),
274 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
276 odocstringstream ods;
277 XHTMLStream out(ods);
279 bool const isInline = params().isInline();
281 out << html::CompTag("br");
283 out << html::StartTag("div", "class='float float-listings'");
284 docstring caption = getCaptionHTML(rp);
285 if (!caption.empty())
286 out << html::StartTag("div", "class='float-caption'")
287 << caption << html::EndTag("div");
290 out << html::StartTag("pre");
291 OutputParams newrp = rp;
292 newrp.html_disable_captions = true;
293 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
294 out << html::EndTag("pre");
297 out << html::CompTag("br");
298 // escaping will already have been done
299 os << XHTMLStream::NextRaw() << ods.str();
301 out << html::EndTag("div");
302 // In this case, this needs to be deferred, but we'll put it
303 // before anything the text itself deferred.
304 def = ods.str() + '\n' + def;
310 docstring InsetListings::contextMenu(BufferView const &, int, int) const
312 return from_ascii("context-listings");
316 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
318 switch (cmd.action()) {
320 case LFUN_INSET_MODIFY: {
321 InsetListings::string2params(to_utf8(cmd.argument()), params());
325 case LFUN_INSET_DIALOG_UPDATE:
326 cur.bv().updateDialog("listings", params2string(params()));
330 InsetCollapsable::doDispatch(cur, cmd);
336 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
337 FuncStatus & status) const
339 switch (cmd.action()) {
340 case LFUN_INSET_MODIFY:
341 case LFUN_INSET_DIALOG_UPDATE:
342 status.setEnabled(true);
344 case LFUN_CAPTION_INSERT:
345 status.setEnabled(!params().isInline());
348 return InsetCollapsable::getStatus(cur, cmd, status);
353 docstring const InsetListings::buttonLabel(BufferView const & bv) const
356 if (decoration() == InsetLayout::CLASSIC)
357 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
359 return getNewLabel(_("Listing"));
363 void InsetListings::validate(LaTeXFeatures & features) const
365 features.require("listings");
366 string param_string = params().params();
367 if (param_string.find("\\color") != string::npos)
368 features.require("color");
369 InsetCollapsable::validate(features);
373 bool InsetListings::showInsetDialog(BufferView * bv) const
375 bv->showDialog("listings", params2string(params()),
376 const_cast<InsetListings *>(this));
381 docstring InsetListings::getCaption(OutputParams const & runparams) const
383 if (paragraphs().empty())
386 InsetCaption const * ins = getCaptionInset();
390 odocstringstream ods;
391 ins->getOptArg(ods, runparams);
392 ins->getArgument(ods, runparams);
393 // the caption may contain \label{} but the listings
394 // package prefer caption={}, label={}
395 docstring cap = ods.str();
396 if (!contains(to_utf8(cap), "\\label{"))
399 // blah1\label{blah2} blah3
401 // blah1 blah3},label={blah2
403 // caption={blah1 blah3},label={blah2}
405 // NOTE that } is not allowed in blah2.
406 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
407 string const new_cap("\\1\\3},label={\\2");
408 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
412 void InsetListings::string2params(string const & in,
413 InsetListingsParams & params)
415 params = InsetListingsParams();
418 istringstream data(in);
421 // discard "listings", which is only used to determine inset
427 string InsetListings::params2string(InsetListingsParams const & params)
430 data << "listings" << ' ';