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 "LaTeXFeatures.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "TextClass.h"
34 #include "support/debug.h"
35 #include "support/docstream.h"
36 #include "support/gettext.h"
37 #include "support/lstrings.h"
38 #include "support/lassert.h"
40 #include "frontends/alert.h"
41 #include "frontends/Application.h"
43 #include "support/regex.h"
48 using namespace lyx::support;
53 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
54 : InsetCollapsable(buf)
56 status_ = par.status();
60 InsetListings::~InsetListings()
62 hideDialogs("listings", this);
66 Inset::DisplayType InsetListings::display() const
68 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
72 void InsetListings::updateBuffer(ParIterator const & it, UpdateType utype)
75 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::updateBuffer(it, utype);
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 void InsetListings::latex(otexstream & 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)
131 bool const isInline = params().isInline();
132 // get the paragraphs. We can not output them directly to given odocstream
133 // because we can not yet determine the delimiter character of \lstinline
136 ParagraphList::const_iterator par = paragraphs().begin();
137 ParagraphList::const_iterator end = paragraphs().end();
139 bool encoding_switched = false;
140 Encoding const * const save_enc = runparams.encoding;
142 if (!runparams.isFullUnicode()
143 && !runparams.encoding->hasFixedWidth()) {
144 // We need to switch to a singlebyte encoding, since the
145 // listings package cannot deal with multi-byte-encoded
146 // glyphs (not needed with full-unicode aware backends
148 // This needs to be consistent with
149 // LaTeXFeatures::getTClassI18nPreamble().
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 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
161 runparams.encoding = lstenc;
162 encoding_switched = true;
166 pos_type siz = par->size();
167 bool captionline = false;
168 for (pos_type i = 0; i < siz; ++i) {
169 if (i == 0 && par->isInset(i) && i + 1 == siz)
171 // ignore all struck out text and (caption) insets
172 if (par->isDeleted(i) || par->isInset(i))
174 char_type c = par->getChar(i);
175 // we can only output characters covered by the current
178 if (runparams.encoding->encodable(c))
180 else if (runparams.dryrun) {
181 code += "<" + _("LyX Warning: ")
182 + _("uncodable character") + " '";
183 code += docstring(1, c);
187 } catch (EncodingException & /* e */) {
188 if (runparams.dryrun) {
189 code += "<" + _("LyX Warning: ")
190 + _("uncodable character") + " '";
191 code += docstring(1, c);
198 // for the inline case, if there are multiple paragraphs
199 // they are simply joined. Otherwise, expect latex errors.
200 if (par != end && !isInline && !captionline)
204 static const docstring delimiters =
205 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
207 size_t pos = delimiters.find_first_not_of(code);
209 // This code piece contains all possible special character? !!!
210 // Replace ! with a warning message and use ! as delimiter.
211 if (pos == string::npos) {
212 docstring delim_error = "<" + _("LyX Warning: ")
213 + _("no more lstline delimiters available") + ">";
214 code = subst(code, from_ascii("!"), delim_error);
216 if (!runparams.dryrun && !runparams.silent) {
217 // FIXME: warning should be passed to the error dialog
218 frontend::Alert::warning(_("Running out of delimiters"),
219 _("For inline program listings, one character must be reserved\n"
220 "as a delimiter. One of the listings, however, uses all available\n"
221 "characters, so none is left for delimiting purposes.\n"
222 "For the time being, I have replaced '!' by a warning, but you\n"
223 "must investigate!"));
226 docstring const delim(1, delimiters[pos]);
228 if (!param_string.empty())
229 os << "[" << from_utf8(param_string) << "]";
230 else if (pos >= delimiters.find('Q'))
231 // We need to terminate the command before the delimiter
233 os << delim << code << delim;
235 OutputParams rp = runparams;
236 rp.moving_arg = true;
237 docstring const caption = getCaption(rp);
238 if (param_string.empty() && caption.empty())
239 os << breakln << "\\begin{lstlisting}\n";
241 os << breakln << "\\begin{lstlisting}[";
242 if (!caption.empty()) {
243 os << "caption={" << caption << '}';
244 if (!param_string.empty())
247 os << from_utf8(param_string) << "]\n";
249 os << code << breakln << "\\end{lstlisting}\n";
252 if (encoding_switched){
254 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
255 runparams.encoding = save_enc;
258 if (!uncodable.empty() && !runparams.silent) {
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."),
269 docstring InsetListings::xhtml(XHTMLStream & os, OutputParams const & rp) const
271 odocstringstream ods;
272 XHTMLStream out(ods);
274 bool const isInline = params().isInline();
276 out << html::CompTag("br");
278 out << html::StartTag("div", "class='float float-listings'");
279 docstring caption = getCaptionHTML(rp);
280 if (!caption.empty())
281 out << html::StartTag("div", "class='float-caption'")
282 << XHTMLStream::ESCAPE_NONE
283 << caption << html::EndTag("div");
286 InsetLayout const & il = getLayout();
287 string const & tag = il.htmltag();
288 string attr = "class ='listings";
289 string const lang = params().getParamValue("language");
293 out << html::StartTag(tag, attr);
294 OutputParams newrp = rp;
295 newrp.html_disable_captions = true;
296 // We don't want to convert dashes here. That's the only conversion we
297 // do for XHTML, so this is safe.
298 newrp.pass_thru = true;
299 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
300 out << html::EndTag(tag);
303 out << html::CompTag("br");
304 // escaping will already have been done
305 os << XHTMLStream::ESCAPE_NONE << ods.str();
307 out << html::EndTag("div");
308 // In this case, this needs to be deferred, but we'll put it
309 // before anything the text itself deferred.
310 def = ods.str() + '\n' + def;
316 string InsetListings::contextMenuName() const
318 return "context-listings";
322 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
324 switch (cmd.action()) {
326 case LFUN_INSET_MODIFY: {
327 cur.recordUndoInset(this);
328 InsetListings::string2params(to_utf8(cmd.argument()), params());
332 case LFUN_INSET_DIALOG_UPDATE:
333 cur.bv().updateDialog("listings", params2string(params()));
337 InsetCollapsable::doDispatch(cur, cmd);
343 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
344 FuncStatus & status) const
346 switch (cmd.action()) {
347 case LFUN_INSET_MODIFY:
348 case LFUN_INSET_DIALOG_UPDATE:
349 status.setEnabled(true);
351 case LFUN_CAPTION_INSERT: {
352 if (params().isInline()) {
353 status.setEnabled(false);
358 return InsetCollapsable::getStatus(cur, cmd, status);
363 docstring const InsetListings::buttonLabel(BufferView const & bv) const
366 if (decoration() == InsetLayout::CLASSIC)
367 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
369 return getNewLabel(_("Listing"));
373 void InsetListings::validate(LaTeXFeatures & features) const
375 features.require("listings");
376 string param_string = params().params();
377 if (param_string.find("\\color") != string::npos)
378 features.require("color");
379 InsetCollapsable::validate(features);
383 bool InsetListings::showInsetDialog(BufferView * bv) const
385 bv->showDialog("listings", params2string(params()),
386 const_cast<InsetListings *>(this));
391 docstring InsetListings::getCaption(OutputParams const & runparams) const
393 if (paragraphs().empty())
396 InsetCaption const * ins = getCaptionInset();
401 odocstringstream ods;
402 otexstream os(ods, texrow);
403 ins->getArgs(os, runparams);
404 ins->getArgument(os, runparams);
405 // the caption may contain \label{} but the listings
406 // package prefer caption={}, label={}
407 docstring cap = ods.str();
408 if (!contains(to_utf8(cap), "\\label{"))
411 // blah1\label{blah2} blah3
413 // blah1 blah3},label={blah2
415 // caption={blah1 blah3},label={blah2}
417 // NOTE that } is not allowed in blah2.
418 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
419 string const new_cap("\\1\\3},label={\\2");
420 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
424 void InsetListings::string2params(string const & in,
425 InsetListingsParams & params)
427 params = InsetListingsParams();
430 istringstream data(in);
433 // discard "listings", which is only used to determine inset
439 string InsetListings::params2string(InsetListingsParams const & params)
442 data << "listings" << ' ';