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"
26 #include "InsetList.h"
28 #include "MetricsInfo.h"
29 #include "output_latex.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 const & 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::updateLabels(ParIterator const & it)
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::updateLabels(it);
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 docstring InsetListings::editMessage() const
129 return _("Opened Listing Inset");
133 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
135 string param_string = params().params();
136 // NOTE: I use {} to quote text, which is an experimental feature
137 // of the listings package (see page 25 of the manual)
139 bool isInline = params().isInline();
140 // get the paragraphs. We can not output them directly to given odocstream
141 // because we can not yet determine the delimiter character of \lstinline
144 ParagraphList::const_iterator par = paragraphs().begin();
145 ParagraphList::const_iterator end = paragraphs().end();
147 bool encoding_switched = false;
148 Encoding const * const save_enc = runparams.encoding;
150 if (!runparams.encoding->hasFixedWidth()) {
151 // We need to switch to a singlebyte encoding, since the listings
152 // package cannot deal with multiple-byte-encoded glyphs
153 Language const * const outer_language =
154 (runparams.local_font != 0) ?
155 runparams.local_font->language()
156 : buffer().params().language;
157 // We try if there's a singlebyte encoding for the current
158 // language; if not, fall back to latin1.
159 Encoding const * const lstenc =
160 (outer_language->encoding()->hasFixedWidth()) ?
161 outer_language->encoding()
162 : encodings.fromLyXName("iso8859-1");
163 pair<bool, int> const c = switchEncoding(os, buffer().params(),
164 runparams, *lstenc, true);
165 runparams.encoding = lstenc;
166 encoding_switched = true;
170 pos_type siz = par->size();
171 bool captionline = false;
172 for (pos_type i = 0; i < siz; ++i) {
173 if (i == 0 && par->isInset(i) && i + 1 == siz)
175 // ignore all struck out text and (caption) insets
176 if (par->isDeleted(i) || par->isInset(i))
178 char_type c = par->getChar(i);
179 // we can only output characters covered by the current
182 if (runparams.encoding->latexChar(c) == docstring(1, c))
184 else if (runparams.dryrun) {
185 code += "<" + _("LyX Warning: ")
186 + _("uncodable character") + " '";
187 code += docstring(1, c);
191 } catch (EncodingException & /* e */) {
192 if (runparams.dryrun) {
193 code += "<" + _("LyX Warning: ")
194 + _("uncodable character") + " '";
195 code += docstring(1, c);
202 // for the inline case, if there are multiple paragraphs
203 // they are simply joined. Otherwise, expect latex errors.
204 if (par != end && !isInline && !captionline) {
210 char const * delimiter = lstinline_delimiters;
211 for (; delimiter != '\0'; ++delimiter)
212 if (!contains(code, *delimiter))
214 // This code piece contains all possible special character? !!!
215 // Replace ! with a warning message and use ! as delimiter.
216 if (*delimiter == '\0') {
217 docstring delim_error = "<" + _("LyX Warning: ")
218 + _("no more lstline delimiters available") + ">";
219 code = subst(code, from_ascii("!"), delim_error);
220 delimiter = lstinline_delimiters;
221 if (!runparams.dryrun) {
222 // FIXME: warning should be passed to the error dialog
223 frontend::Alert::warning(_("Running out of delimiters"),
224 _("For inline program listings, one character must be reserved\n"
225 "as a delimiter. One of the listings, however, uses all available\n"
226 "characters, so none is left for delimiting purposes.\n"
227 "For the time being, I have replaced '!' by a warning, but you\n"
228 "must investigate!"));
231 if (param_string.empty())
232 os << "\\lstinline" << *delimiter;
234 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
238 OutputParams rp = runparams;
239 rp.moving_arg = true;
240 docstring const caption = getCaption(rp);
241 runparams.encoding = rp.encoding;
242 if (param_string.empty() && caption.empty())
243 os << "\n\\begin{lstlisting}\n";
245 os << "\n\\begin{lstlisting}[";
246 if (!caption.empty()) {
247 os << "caption={" << caption << '}';
248 if (!param_string.empty())
251 os << from_utf8(param_string) << "]\n";
254 os << code << "\n\\end{lstlisting}\n";
258 if (encoding_switched){
260 pair<bool, int> const c = switchEncoding(os, buffer().params(),
261 runparams, *save_enc, true);
262 runparams.encoding = save_enc;
265 if (!uncodable.empty()) {
266 // issue a warning about omitted characters
267 // FIXME: should be passed to the error dialog
268 frontend::Alert::warning(_("Uncodable characters in listings inset"),
269 bformat(_("The following characters in one of the program listings are\n"
270 "not representable in the current encoding and have been omitted:\n%1$s."),
278 docstring InsetListings::contextMenu(BufferView const &, int, int) const
280 return from_ascii("context-listings");
284 void InsetListings::doDispatch(Cursor & cur, FuncRequest & cmd)
286 switch (cmd.action) {
288 case LFUN_INSET_MODIFY: {
289 InsetListings::string2params(to_utf8(cmd.argument()), params());
292 case LFUN_INSET_DIALOG_UPDATE:
293 cur.bv().updateDialog("listings", params2string(params()));
295 case LFUN_TAB_INSERT:
296 if (cur.selection()) {
297 // If there is a selection, a tab is inserted at the
298 // beginning of each paragraph.
299 cur.recordUndoSelection();
300 pit_type const pit_end = cur.selEnd().pit();
301 for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
302 paragraphs()[pit].insertChar(0, '\t',
303 buffer().params().trackChanges);
304 // Update the selection pos to make sure the selection does not
305 // change as the inserted tab will increase the logical pos.
306 if (cur.anchor_.pit() == pit)
307 cur.anchor_.forwardPos();
308 if (cur.pit() == pit)
313 // Maybe we shouldn't allow tabs within a line, because they
314 // are not (yet) aligned as one might do expect.
316 cur.insert(from_ascii("\t"));
320 case LFUN_TAB_DELETE:
321 if (cur.selection()) {
322 // If there is a selection, a tab (if present) is removed from
323 // the beginning of each paragraph.
324 cur.recordUndoSelection();
325 pit_type const pit_end = cur.selEnd().pit();
326 for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
327 Paragraph & par = paragraphs()[pit];
328 if (par.getChar(0) == '\t') {
329 if (cur.pit() == pit)
331 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
332 cur.anchor_.backwardPos();
334 par.eraseChar(0, buffer().params().trackChanges);
336 // If no tab was present, try to remove up to four spaces.
337 for (int n_spaces = 0;
338 par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
339 if (cur.pit() == pit)
341 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
342 cur.anchor_.backwardPos();
344 par.eraseChar(0, buffer().params().trackChanges);
349 // If there is no selection, try to remove a tab or some spaces
350 // before the position of the cursor.
351 Paragraph & par = paragraphs()[cur.pit()];
352 pos_type const pos = cur.pos();
357 char_type const c = par.getChar(pos - 1);
361 par.eraseChar(cur.pos(), buffer().params().trackChanges);
363 for (int n_spaces = 0; cur.pos() > 0
364 && par.getChar(cur.pos() - 1) == ' ' && n_spaces < 4;
367 par.eraseChar(cur.pos(), buffer().params().trackChanges);
373 InsetCollapsable::doDispatch(cur, cmd);
379 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
380 FuncStatus & status) const
382 switch (cmd.action) {
383 case LFUN_INSET_MODIFY:
384 case LFUN_INSET_DIALOG_UPDATE:
385 status.setEnabled(true);
387 case LFUN_CAPTION_INSERT:
388 status.setEnabled(!params().isInline());
390 case LFUN_TAB_INSERT:
391 case LFUN_TAB_DELETE:
392 status.setEnabled(true);
395 return InsetCollapsable::getStatus(cur, cmd, status);
400 void InsetListings::setButtonLabel(BufferView const & bv)
403 if (decoration() == InsetLayout::CLASSIC)
404 setLabel(isOpen(bv) ? _("Listing") : getNewLabel(_("Listing")));
406 setLabel(getNewLabel(_("Listing")));
410 void InsetListings::validate(LaTeXFeatures & features) const
412 features.require("listings");
413 string param_string = params().params();
414 if (param_string.find("\\color") != string::npos)
415 features.require("color");
416 InsetCollapsable::validate(features);
420 bool InsetListings::showInsetDialog(BufferView * bv) const
422 bv->showDialog("listings", params2string(params()),
423 const_cast<InsetListings *>(this));
428 docstring InsetListings::getCaption(OutputParams const & runparams) const
430 if (paragraphs().empty())
433 ParagraphList::const_iterator pit = paragraphs().begin();
434 for (; pit != paragraphs().end(); ++pit) {
435 InsetList::const_iterator it = pit->insetList().begin();
436 for (; it != pit->insetList().end(); ++it) {
437 Inset & inset = *it->inset;
438 if (inset.lyxCode() == CAPTION_CODE) {
439 odocstringstream ods;
441 static_cast<InsetCaption *>(it->inset);
442 ins->getOptArg(ods, runparams);
443 ins->getArgument(ods, runparams);
444 // the caption may contain \label{} but the listings
445 // package prefer caption={}, label={}
446 docstring cap = ods.str();
447 if (!contains(to_utf8(cap), "\\label{"))
450 // blah1\label{blah2} blah3
452 // blah1 blah3},label={blah2
454 // caption={blah1 blah3},label={blah2}
456 // NOTE that } is not allowed in blah2.
457 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
458 string const new_cap("\\1\\3},label={\\2");
459 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
467 void InsetListings::string2params(string const & in,
468 InsetListingsParams & params)
470 params = InsetListingsParams();
473 istringstream data(in);
476 // discard "listings", which is only used to determine inset
482 string InsetListings::params2string(InsetListingsParams const & params)
485 data << "listings" << ' ';