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 "CutAndPaste.h"
22 #include "DispatchResult.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "InsetCaption.h"
27 #include "InsetList.h"
29 #include "MetricsInfo.h"
30 #include "output_latex.h"
31 #include "TextClass.h"
33 #include "support/debug.h"
34 #include "support/docstream.h"
35 #include "support/gettext.h"
36 #include "support/lstrings.h"
37 #include "support/lassert.h"
39 #include "frontends/alert.h"
40 #include "frontends/Application.h"
42 #include <boost/regex.hpp>
47 using namespace lyx::support;
53 char const lstinline_delimiters[] =
54 "!*()-=+|;:'\"`,<.>/?QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
56 InsetListings::InsetListings(Buffer const & buf, InsetListingsParams const & par)
57 : InsetCollapsable(buf)
59 status_ = par.status();
63 InsetListings::~InsetListings()
65 hideDialogs("listings", this);
69 Inset::DisplayType InsetListings::display() const
71 return params().isInline() || params().isFloat() ? Inline : AlignLeft;
75 void InsetListings::updateLabels(ParIterator const & it)
77 Counters & cnts = 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::updateLabels(it);
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 docstring InsetListings::editMessage() const
130 return _("Opened Listing Inset");
134 int InsetListings::latex(odocstream & os, OutputParams const & runparams) const
136 string param_string = params().params();
137 // NOTE: I use {} to quote text, which is an experimental feature
138 // of the listings package (see page 25 of the manual)
140 bool isInline = params().isInline();
141 // get the paragraphs. We can not output them directly to given odocstream
142 // because we can not yet determine the delimiter character of \lstinline
145 ParagraphList::const_iterator par = paragraphs().begin();
146 ParagraphList::const_iterator end = paragraphs().end();
148 bool encoding_switched = false;
149 Encoding const * const save_enc = runparams.encoding;
151 if (!runparams.encoding->hasFixedWidth()) {
152 // We need to switch to a singlebyte encoding, since the listings
153 // package cannot deal with multiple-byte-encoded glyphs
154 Language const * const outer_language =
155 (runparams.local_font != 0) ?
156 runparams.local_font->language()
157 : buffer().params().language;
158 // We try if there's a singlebyte encoding for the current
159 // language; if not, fall back to latin1.
160 Encoding const * const lstenc =
161 (outer_language->encoding()->hasFixedWidth()) ?
162 outer_language->encoding()
163 : encodings.fromLyXName("iso8859-1");
164 pair<bool, int> const c = switchEncoding(os, buffer().params(),
165 runparams, *lstenc, true);
166 runparams.encoding = lstenc;
167 encoding_switched = true;
171 pos_type siz = par->size();
172 bool captionline = false;
173 for (pos_type i = 0; i < siz; ++i) {
174 if (i == 0 && par->isInset(i) && i + 1 == siz)
176 // ignore all struck out text and (caption) insets
177 if (par->isDeleted(i) || par->isInset(i))
179 char_type c = par->getChar(i);
180 // we can only output characters covered by the current
183 if (runparams.encoding->latexChar(c) == docstring(1, c))
185 else if (runparams.dryrun) {
186 code += "<" + _("LyX Warning: ")
187 + _("uncodable character") + " '";
188 code += docstring(1, c);
192 } catch (EncodingException & /* e */) {
193 if (runparams.dryrun) {
194 code += "<" + _("LyX Warning: ")
195 + _("uncodable character") + " '";
196 code += docstring(1, c);
203 // for the inline case, if there are multiple paragraphs
204 // they are simply joined. Otherwise, expect latex errors.
205 if (par != end && !isInline && !captionline) {
211 char const * delimiter = lstinline_delimiters;
212 for (; delimiter != '\0'; ++delimiter)
213 if (!contains(code, *delimiter))
215 // This code piece contains all possible special character? !!!
216 // Replace ! with a warning message and use ! as delimiter.
217 if (*delimiter == '\0') {
218 docstring delim_error = "<" + _("LyX Warning: ")
219 + _("no more lstline delimiters available") + ">";
220 code = subst(code, from_ascii("!"), delim_error);
221 delimiter = lstinline_delimiters;
222 if (!runparams.dryrun) {
223 // FIXME: warning should be passed to the error dialog
224 frontend::Alert::warning(_("Running out of delimiters"),
225 _("For inline program listings, one character must be reserved\n"
226 "as a delimiter. One of the listings, however, uses all available\n"
227 "characters, so none is left for delimiting purposes.\n"
228 "For the time being, I have replaced '!' by a warning, but you\n"
229 "must investigate!"));
232 if (param_string.empty())
233 os << "\\lstinline" << *delimiter;
235 os << "\\lstinline[" << from_utf8(param_string) << "]" << *delimiter;
239 OutputParams rp = runparams;
240 rp.moving_arg = true;
241 docstring const caption = getCaption(rp);
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());
293 case LFUN_INSET_DIALOG_UPDATE:
294 cur.bv().updateDialog("listings", params2string(params()));
297 case LFUN_TAB_INSERT: {
298 bool const multi_par_selection = cur.selection() &&
299 cur.selBegin().pit() != cur.selEnd().pit();
300 if (multi_par_selection) {
301 // If there is a multi-paragraph selection, a tab is inserted
302 // at the beginning of each paragraph.
303 cur.recordUndoSelection();
304 pit_type const pit_end = cur.selEnd().pit();
305 for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
306 paragraphs()[pit].insertChar(0, '\t',
307 buffer().params().trackChanges);
308 // Update the selection pos to make sure the selection does not
309 // change as the inserted tab will increase the logical pos.
310 if (cur.anchor_.pit() == pit)
311 cur.anchor_.forwardPos();
312 if (cur.pit() == pit)
317 // Maybe we shouldn't allow tabs within a line, because they
318 // are not (yet) aligned as one might do expect.
321 cap::cutSelection(cur, false, false);
322 cur.insert(from_ascii("\t"));
328 case LFUN_TAB_DELETE:
329 if (cur.selection()) {
330 // If there is a selection, a tab (if present) is removed from
331 // the beginning of each paragraph.
332 cur.recordUndoSelection();
333 pit_type const pit_end = cur.selEnd().pit();
334 for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
335 Paragraph & par = paragraphs()[pit];
336 if (par.getChar(0) == '\t') {
337 if (cur.pit() == pit)
339 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
340 cur.anchor_.backwardPos();
342 par.eraseChar(0, buffer().params().trackChanges);
344 // If no tab was present, try to remove up to four spaces.
345 for (int n_spaces = 0;
346 par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
347 if (cur.pit() == pit)
349 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
350 cur.anchor_.backwardPos();
352 par.eraseChar(0, buffer().params().trackChanges);
357 // If there is no selection, try to remove a tab or some spaces
358 // before the position of the cursor.
359 Paragraph & par = paragraphs()[cur.pit()];
360 pos_type const pos = cur.pos();
365 char_type const c = par.getChar(pos - 1);
369 par.eraseChar(cur.pos(), buffer().params().trackChanges);
371 for (int n_spaces = 0; cur.pos() > 0
372 && par.getChar(cur.pos() - 1) == ' ' && n_spaces < 4;
375 par.eraseChar(cur.pos(), buffer().params().trackChanges);
381 InsetCollapsable::doDispatch(cur, cmd);
387 bool InsetListings::getStatus(Cursor & cur, FuncRequest const & cmd,
388 FuncStatus & status) const
390 switch (cmd.action) {
391 case LFUN_INSET_MODIFY:
392 case LFUN_INSET_DIALOG_UPDATE:
393 case LFUN_INSET_SETTINGS:
394 status.setEnabled(true);
396 case LFUN_CAPTION_INSERT:
397 status.setEnabled(!params().isInline());
399 case LFUN_TAB_INSERT:
400 case LFUN_TAB_DELETE:
401 status.setEnabled(true);
404 return InsetCollapsable::getStatus(cur, cmd, status);
409 docstring const InsetListings::buttonLabel(BufferView const & bv) const
412 if (decoration() == InsetLayout::CLASSIC)
413 return isOpen(bv) ? _("Listing") : getNewLabel(_("Listing"));
415 return getNewLabel(_("Listing"));
419 void InsetListings::validate(LaTeXFeatures & features) const
421 features.require("listings");
422 string param_string = params().params();
423 if (param_string.find("\\color") != string::npos)
424 features.require("color");
425 InsetCollapsable::validate(features);
429 bool InsetListings::showInsetDialog(BufferView * bv) const
431 bv->showDialog("listings", params2string(params()),
432 const_cast<InsetListings *>(this));
437 docstring InsetListings::getCaption(OutputParams const & runparams) const
439 if (paragraphs().empty())
442 ParagraphList::const_iterator pit = paragraphs().begin();
443 for (; pit != paragraphs().end(); ++pit) {
444 InsetList::const_iterator it = pit->insetList().begin();
445 for (; it != pit->insetList().end(); ++it) {
446 Inset & inset = *it->inset;
447 if (inset.lyxCode() == CAPTION_CODE) {
448 odocstringstream ods;
450 static_cast<InsetCaption *>(it->inset);
451 ins->getOptArg(ods, runparams);
452 ins->getArgument(ods, runparams);
453 // the caption may contain \label{} but the listings
454 // package prefer caption={}, label={}
455 docstring cap = ods.str();
456 if (!contains(to_utf8(cap), "\\label{"))
459 // blah1\label{blah2} blah3
461 // blah1 blah3},label={blah2
463 // caption={blah1 blah3},label={blah2}
465 // NOTE that } is not allowed in blah2.
466 regex const reg("(.*)\\\\label\\{(.*?)\\}(.*)");
467 string const new_cap("\\1\\3},label={\\2");
468 return from_utf8(regex_replace(to_utf8(cap), reg, new_cap));
476 void InsetListings::string2params(string const & in,
477 InsetListingsParams & params)
479 params = InsetListingsParams();
482 istringstream data(in);
485 // discard "listings", which is only used to determine inset
491 string InsetListings::params2string(InsetListingsParams const & params)
494 data << "listings" << ' ';