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 "texstream.h"
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40 #include "support/lassert.h"
42 #include "frontends/alert.h"
43 #include "frontends/Application.h"
45 #include "support/regex.h"
50 using namespace lyx::support;
55 InsetListings::InsetListings(Buffer * buf, InsetListingsParams const & par)
56 : InsetCaptionable(buf,"listing")
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::write(ostream & os) const
76 os << "listings" << "\n";
77 InsetListingsParams const & par = params();
78 // parameter string is encoded to be a valid lyx token.
79 string opt = par.encodedString();
81 os << "lstparams \"" << opt << "\"\n";
83 os << "inline true\n";
85 os << "inline false\n";
86 InsetCaptionable::write(os);
90 void InsetListings::read(Lexer & lex)
94 string token = lex.getString();
95 if (token == "lstparams") {
97 string const value = lex.getString();
98 params().fromEncodedString(value);
99 } else if (token == "inline") {
101 params().setInline(lex.getBool());
103 // no special option, push back 'status' etc
104 lex.pushToken(token);
108 InsetCaptionable::read(lex);
112 void InsetListings::latex(otexstream & os, OutputParams const & runparams) const
114 string param_string = params().params();
115 // NOTE: I use {} to quote text, which is an experimental feature
116 // of the listings package (see page 25 of the manual)
117 bool const isInline = params().isInline();
118 // get the paragraphs. We can not output them directly to given odocstream
119 // because we can not yet determine the delimiter character of \lstinline
122 ParagraphList::const_iterator par = paragraphs().begin();
123 ParagraphList::const_iterator end = paragraphs().end();
125 bool encoding_switched = false;
126 Encoding const * const save_enc = runparams.encoding;
127 // The listings package cannot deal with multi-byte-encoded
128 // glyphs, except if full-unicode aware backends
129 // such as XeTeX or LuaTeX are used, and with pLaTeX.
130 bool const multibyte_possible = runparams.isFullUnicode()
131 || (buffer().params().encoding().package() == Encoding::japanese
132 && runparams.encoding->package() == Encoding::japanese);
134 if (!multibyte_possible && !runparams.encoding->hasFixedWidth()) {
135 // We need to switch to a singlebyte encoding, due to
136 // the restrictions of the listings package (see above).
137 // This needs to be consistent with
138 // LaTeXFeatures::getTClassI18nPreamble().
139 Language const * const outer_language =
140 (runparams.local_font != 0) ?
141 runparams.local_font->language()
142 : buffer().params().language;
143 // We try if there's a singlebyte encoding for the current
144 // language; if not, fall back to latin1.
145 Encoding const * const lstenc =
146 (outer_language->encoding()->hasFixedWidth()) ?
147 outer_language->encoding()
148 : encodings.fromLyXName("iso8859-1");
149 switchEncoding(os.os(), buffer().params(), runparams, *lstenc, true);
150 runparams.encoding = lstenc;
151 encoding_switched = true;
155 pos_type siz = par->size();
156 bool captionline = false;
157 for (pos_type i = 0; i < siz; ++i) {
158 if (i == 0 && par->isInset(i) && i + 1 == siz)
160 // ignore all struck out text and (caption) insets
161 if (par->isDeleted(i) || par->isInset(i))
163 char_type c = par->getChar(i);
164 // we can only output characters covered by the current
167 if (runparams.encoding->encodable(c))
169 else if (runparams.dryrun) {
170 code += "<" + _("LyX Warning: ")
171 + _("uncodable character") + " '";
172 code += docstring(1, c);
176 } catch (EncodingException & /* e */) {
177 if (runparams.dryrun) {
178 code += "<" + _("LyX Warning: ")
179 + _("uncodable character") + " '";
180 code += docstring(1, c);
187 // for the inline case, if there are multiple paragraphs
188 // they are simply joined. Otherwise, expect latex errors.
189 if (par != end && !isInline && !captionline)
193 static const docstring delimiters =
194 from_utf8("!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm");
196 size_t pos = delimiters.find_first_not_of(code);
198 // This code piece contains all possible special character? !!!
199 // Replace ! with a warning message and use ! as delimiter.
200 if (pos == string::npos) {
201 docstring delim_error = "<" + _("LyX Warning: ")
202 + _("no more lstline delimiters available") + ">";
203 code = subst(code, from_ascii("!"), delim_error);
205 if (!runparams.dryrun && !runparams.silent) {
206 // FIXME: warning should be passed to the error dialog
207 frontend::Alert::warning(_("Running out of delimiters"),
208 _("For inline program listings, one character must be reserved\n"
209 "as a delimiter. One of the listings, however, uses all available\n"
210 "characters, so none is left for delimiting purposes.\n"
211 "For the time being, I have replaced '!' by a warning, but you\n"
212 "must investigate!"));
215 docstring const delim(1, delimiters[pos]);
217 if (!param_string.empty())
218 os << "[" << from_utf8(param_string) << "]";
219 else if (pos >= delimiters.find('Q'))
220 // We need to terminate the command before the delimiter
222 os << delim << code << delim;
224 OutputParams rp = runparams;
225 rp.moving_arg = true;
226 TexString caption = getCaption(rp);
227 os << breakln << "\\begin{lstlisting}";
228 if (param_string.empty() && caption.str.empty())
234 if (!caption.str.empty()) {
235 os << "caption={" << move(caption) << '}';
236 if (!param_string.empty())
239 os << from_utf8(param_string) << "]\n";
241 os << code << breakln << "\\end{lstlisting}\n";
244 if (encoding_switched){
246 switchEncoding(os.os(), buffer().params(), runparams, *save_enc, true);
247 runparams.encoding = save_enc;
250 if (!uncodable.empty() && !runparams.silent) {
251 // issue a warning about omitted characters
252 // FIXME: should be passed to the error dialog
253 if (!multibyte_possible && !runparams.encoding->hasFixedWidth())
254 frontend::Alert::warning(_("Uncodable characters in listings inset"),
255 bformat(_("The following characters in one of the program listings are\n"
256 "not representable in the current encoding and have been omitted:\n%1$s.\n"
257 "This is due to a restriction of the listings package, which does\n"
258 "not support your encoding '%2$s'.\n"
259 "Toggling 'Use non-TeX fonts' in Document > Settings...\n"
261 uncodable, _(runparams.encoding->guiName())));
263 frontend::Alert::warning(_("Uncodable characters in listings inset"),
264 bformat(_("The following characters in one of the program listings are\n"
265 "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-listings'");
281 docstring caption = getCaptionHTML(rp);
282 if (!caption.empty())
283 out << html::StartTag("div", "class='listings-caption'")
284 << XHTMLStream::ESCAPE_NONE
285 << caption << html::EndTag("div");
288 InsetLayout const & il = getLayout();
289 string const & tag = il.htmltag();
290 string attr = "class ='listings";
291 string const lang = params().getParamValue("language");
295 out << html::StartTag(tag, attr);
296 OutputParams newrp = rp;
297 newrp.html_disable_captions = true;
298 // We don't want to convert dashes here. That's the only conversion we
299 // do for XHTML, so this is safe.
300 newrp.pass_thru = true;
301 docstring def = InsetText::insetAsXHTML(out, newrp, InsetText::JustText);
302 out << html::EndTag(tag);
305 out << html::CompTag("br");
306 // escaping will already have been done
307 os << XHTMLStream::ESCAPE_NONE << ods.str();
309 out << html::EndTag("div");
310 // In this case, this needs to be deferred, but we'll put it
311 // before anything the text itself deferred.
312 def = ods.str() + '\n' + def;
318 string InsetListings::contextMenuName() const
320 return "context-listings";
324 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
326 switch (cmd.action()) {
328 case LFUN_INSET_MODIFY: {
329 cur.recordUndoInset(this);
330 InsetListings::string2params(to_utf8(cmd.argument()), params());
334 case LFUN_INSET_DIALOG_UPDATE:
335 cur.bv().updateDialog("listings", params2string(params()));
339 InsetCaptionable::doDispatch(cur, cmd);
345 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
346 FuncStatus & status) const
348 switch (cmd.action()) {
349 case LFUN_INSET_MODIFY:
350 case LFUN_INSET_DIALOG_UPDATE:
351 status.setEnabled(true);
353 case LFUN_CAPTION_INSERT: {
354 // the inset outputs at most one caption
355 if (params().isInline() || getCaptionInset()) {
356 status.setEnabled(false);
361 return InsetCaptionable::getStatus(cur, cmd, status);
366 docstring const InsetListings::buttonLabel(BufferView const & bv) const
369 if (decoration() == InsetLayout::CLASSIC)
370 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
372 return getNewLabel(_("Listing"));
376 void InsetListings::validate(LaTeXFeatures & features) const
378 features.require("listings");
379 features.useInsetLayout(getLayout());
380 string param_string = params().params();
381 if (param_string.find("\\color") != string::npos)
382 features.require("color");
383 InsetCaptionable::validate(features);
387 bool InsetListings::showInsetDialog(BufferView * bv) const
389 bv->showDialog("listings", params2string(params()),
390 const_cast<InsetListings *>(this));
395 TexString InsetListings::getCaption(OutputParams const & runparams) const
397 InsetCaption const * ins = getCaptionInset();
402 ins->getArgs(os, runparams);
403 ins->getArgument(os, runparams);
405 // TODO: The code below should be moved to support, and then the test
406 // in ../tests should be moved there as well.
408 // the caption may contain \label{} but the listings
409 // package prefer caption={}, label={}
410 TexString cap = os.release();
411 if (!contains(cap.str, from_ascii("\\label{")))
414 // blah1\label{blah2} blah3
416 // blah1 blah3},label={blah2
418 // caption={blah1 blah3},label={blah2}
420 // NOTE that } is not allowed in blah2.
421 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
422 string const new_cap("$1$3},label={$2");
423 // TexString validity: the substitution preserves the number of newlines.
424 // Moreover we assume that $2 does not contain newlines, so that the texrow
425 // information remains accurate.
426 cap.str = from_utf8(regex_replace(to_utf8(cap.str), reg, new_cap));
431 void InsetListings::string2params(string const & in,
432 InsetListingsParams & params)
434 params = InsetListingsParams();
437 istringstream data(in);
440 // discard "listings", which is only used to determine inset
446 string InsetListings::params2string(InsetListingsParams const & params)
449 data << "listings" << ' ';