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)
76 Counters & cnts = buffer().masterBuffer()->params().documentClass().counters();
77 string const saveflt = cnts.current_float();
79 // Tell to captions what the current float is
80 cnts.current_float("listing");
82 InsetCollapsable::updateBuffer(it, utype);
85 cnts.current_float(saveflt);
89 void InsetListings::write(ostream & os) const
91 os << "listings" << "\n";
92 InsetListingsParams const & par = params();
93 // parameter string is encoded to be a valid lyx token.
94 string opt = par.encodedString();
96 os << "lstparams \"" << opt << "\"\n";
98 os << "inline true\n";
100 os << "inline false\n";
101 InsetCollapsable::write(os);
105 void InsetListings::read(Lexer & lex)
109 string token = lex.getString();
110 if (token == "lstparams") {
112 string const value = lex.getString();
113 params().fromEncodedString(value);
114 } else if (token == "inline") {
116 params().setInline(lex.getBool());
118 // no special option, push back 'status' etc
119 lex.pushToken(token);
123 InsetCollapsable::read(lex);
127 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
129 string param_string = params().params();
130 // NOTE: I use {} to quote text, which is an experimental feature
131 // of the listings package (see page 25 of the manual)
133 bool const isInline = params().isInline();
134 // get the paragraphs. We can not output them directly to given odocstream
135 // because we can not yet determine the delimiter character of \lstinline
138 ParagraphList::const_iterator par = paragraphs().begin();
139 ParagraphList::const_iterator end = paragraphs().end();
141 bool encoding_switched = false;
142 Encoding const * const save_enc = runparams.encoding;
144 if (!runparams.encoding->hasFixedWidth()) {
145 // We need to switch to a singlebyte encoding, since the listings
146 // package cannot deal with multiple-byte-encoded glyphs
147 Language const * const outer_language =
148 (runparams.local_font != 0) ?
149 runparams.local_font->language()
150 : buffer().params().language;
151 // We try if there's a singlebyte encoding for the current
152 // language; if not, fall back to latin1.
153 Encoding const * const lstenc =
154 (outer_language->encoding()->hasFixedWidth()) ?
155 outer_language->encoding()
156 : encodings.fromLyXName("iso8859-1");
157 pair<bool, int> const c = switchEncoding(os, buffer().params(),
158 runparams, *lstenc, true);
159 runparams.encoding = lstenc;
160 encoding_switched = true;
164 pos_type siz = par->size();
165 bool captionline = false;
166 for (pos_type i = 0; i < siz; ++i) {
167 if (i == 0 && par->isInset(i) && i + 1 == siz)
169 // ignore all struck out text and (caption) insets
170 if (par->isDeleted(i) || par->isInset(i))
172 char_type c = par->getChar(i);
173 // we can only output characters covered by the current
176 if (runparams.encoding->latexChar(c) == docstring(1, c))
178 else if (runparams.dryrun) {
179 code += "<" + _("LyX Warning: ")
180 + _("uncodable character") + " '";
181 code += docstring(1, c);
185 } catch (EncodingException & /* e */) {
186 if (runparams.dryrun) {
187 code += "<" + _("LyX Warning: ")
188 + _("uncodable character") + " '";
189 code += docstring(1, c);
196 // for the inline case, if there are multiple paragraphs
197 // they are simply joined. Otherwise, expect latex errors.
198 if (par != end && !isInline && !captionline) {
204 char const * delimiter = lstinline_delimiters;
205 for (; delimiter != '\0'; ++delimiter)
206 if (!contains(code, *delimiter))
208 // This code piece contains all possible special character? !!!
209 // Replace ! with a warning message and use ! as delimiter.
210 if (*delimiter == '\0') {
211 docstring delim_error = "<" + _("LyX Warning: ")
212 + _("no more lstline delimiters available") + ">";
213 code = subst(code, from_ascii("!"), delim_error);
214 delimiter = lstinline_delimiters;
215 if (!runparams.dryrun) {
216 // FIXME: warning should be passed to the error dialog
217 frontend::Alert::warning(_("Running out of delimiters"),
218 _("For inline program listings, one character must be reserved\n"
219 "as a delimiter. One of the listings, however, uses all available\n"
220 "characters, so none is left for delimiting purposes.\n"
221 "For the time being, I have replaced '!' by a warning, but you\n"
222 "must investigate!"));
225 if (param_string.empty())
226 os << "\\lstinline" << *delimiter;
228 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
232 OutputParams rp = runparams;
233 rp.moving_arg = true;
234 docstring const caption = getCaption(rp);
235 if (param_string.empty() && caption.empty())
236 os << "\n\\begin{lstlisting}\n";
238 os << "\n\\begin{lstlisting}[";
239 if (!caption.empty()) {
240 os << "caption={" << caption << '}';
241 if (!param_string.empty())
244 os << from_utf8(param_string) << "]\n";
247 os << code << "\n\\end{lstlisting}\n";
251 if (encoding_switched){
253 pair<bool, int> const c = switchEncoding(os, buffer().params(),
254 runparams, *save_enc, true);
255 runparams.encoding = save_enc;
258 if (!uncodable.empty()) {
259 // issue a warning about omitted characters
260 // FIXME: should be passed to the error dialog
261 frontend::Alert::warning(_("Uncodable characters in listings inset"),
262 bformat(_("The following characters in one of the program listings are\n"
263 "not representable in the current encoding and have been omitted:\n%1$s."),
271 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
273 odocstringstream ods;
274 XHTMLStream out(ods);
276 bool const isInline = params().isInline();
278 out << html::CompTag("br");
280 out << html::StartTag("div", "class='float float-listings'");
281 docstring caption = getCaptionHTML(rp);
282 if (!caption.empty())
283 out << html::StartTag("div", "class='float-caption'")
284 << caption << html::EndTag("div");
287 out << html::StartTag("pre");
288 OutputParams newrp = rp;
289 newrp.html_disable_captions = true;
290 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
291 out << html::EndTag("pre");
294 out << html::CompTag("br");
295 // escaping will already have been done
296 os << XHTMLStream::NextRaw() << ods.str();
298 out << html::EndTag("div");
299 // In this case, this needs to be deferred, but we'll put it
300 // before anything the text itself deferred.
301 def = ods.str() + '\n' + def;
307 docstring InsetListings::contextMenu(BufferView const &, int, int) const
309 return from_ascii("context-listings");
313 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
315 switch (cmd.action()) {
317 case LFUN_INSET_MODIFY: {
318 InsetListings::string2params(to_utf8(cmd.argument()), params());
322 case LFUN_INSET_DIALOG_UPDATE:
323 cur.bv().updateDialog("listings", params2string(params()));
327 InsetCollapsable::doDispatch(cur, cmd);
333 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
334 FuncStatus & status) const
336 switch (cmd.action()) {
337 case LFUN_INSET_MODIFY:
338 case LFUN_INSET_DIALOG_UPDATE:
339 status.setEnabled(true);
341 case LFUN_CAPTION_INSERT:
342 status.setEnabled(!params().isInline());
345 return InsetCollapsable::getStatus(cur, cmd, status);
350 docstring const InsetListings::buttonLabel(BufferView const & bv) const
353 if (decoration() == InsetLayout::CLASSIC)
354 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
356 return getNewLabel(_("Listing"));
360 void InsetListings::validate(LaTeXFeatures & features) const
362 features.require("listings");
363 string param_string = params().params();
364 if (param_string.find("\\color") != string::npos)
365 features.require("color");
366 InsetCollapsable::validate(features);
370 bool InsetListings::showInsetDialog(BufferView * bv) const
372 bv->showDialog("listings", params2string(params()),
373 const_cast<InsetListings *>(this));
378 docstring InsetListings::getCaption(OutputParams const & runparams) const
380 if (paragraphs().empty())
383 InsetCaption const * ins = getCaptionInset();
387 odocstringstream ods;
388 ins->getOptArg(ods, runparams);
389 ins->getArgument(ods, runparams);
390 // the caption may contain \label{} but the listings
391 // package prefer caption={}, label={}
392 docstring cap = ods.str();
393 if (!contains(to_utf8(cap), "\\label{"))
396 // blah1\label{blah2} blah3
398 // blah1 blah3},label={blah2
400 // caption={blah1 blah3},label={blah2}
402 // NOTE that } is not allowed in blah2.
403 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
404 string const new_cap("\\1\\3},label={\\2");
405 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
409 void InsetListings::string2params(string const & in,
410 InsetListingsParams & params)
412 params = InsetListingsParams();
415 istringstream data(in);
418 // discard "listings", which is only used to determine inset
424 string InsetListings::params2string(InsetListingsParams const & params)
427 data << "listings" << ' ';