]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
Restore XHTML output for InsetListings.
[lyx.git] / src / insets / InsetIndex.cpp
1 /**
2  * \file InsetIndex.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Jürgen Spitzmüller
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11 #include <config.h>
12
13 #include "InsetIndex.h"
14
15 #include "Buffer.h"
16 #include "BufferParams.h"
17 #include "BufferView.h"
18 #include "ColorSet.h"
19 #include "DispatchResult.h"
20 #include "Encoding.h"
21 #include "FuncRequest.h"
22 #include "FuncStatus.h"
23 #include "IndicesList.h"
24 #include "LaTeXFeatures.h"
25 #include "Lexer.h"
26 #include "MetricsInfo.h"
27 #include "output_latex.h"
28 #include "sgml.h"
29 #include "TocBackend.h"
30
31 #include "support/debug.h"
32 #include "support/docstream.h"
33 #include "support/gettext.h"
34 #include "support/lstrings.h"
35
36 #include "frontends/alert.h"
37
38 #include <ostream>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 /////////////////////////////////////////////////////////////////////
46 //
47 // InsetIndex
48 //
49 ///////////////////////////////////////////////////////////////////////
50
51
52 InsetIndex::InsetIndex(Buffer * buf, InsetIndexParams const & params)
53         : InsetCollapsable(buf), params_(params)
54 {}
55
56
57 int InsetIndex::latex(odocstream & os,
58                       OutputParams const & runparams_in) const
59 {
60         OutputParams runparams(runparams_in);
61         runparams.inIndexEntry = true;
62
63         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
64             && params_.index != "idx") {
65                 os << "\\sindex[";
66                 os << params_.index;
67                 os << "]{";
68         } else {
69                 os << "\\index";
70                 os << '{';
71         }
72         int i = 0;
73
74         // get contents of InsetText as LaTeX and plaintext
75         odocstringstream ourlatex;
76         InsetText::latex(ourlatex, runparams);
77         odocstringstream ourplain;
78         InsetText::plaintext(ourplain, runparams);
79         docstring latexstr = ourlatex.str();
80         docstring plainstr = ourplain.str();
81
82         // this will get what follows | if anything does
83         docstring cmd;
84
85         // check for the | separator
86         // FIXME This would go wrong on an escaped "|", but
87         // how far do we want to go here?
88         size_t pos = latexstr.find(from_ascii("|"));
89         if (pos != docstring::npos) {
90                 // put the bit after "|" into cmd...
91                 cmd = latexstr.substr(pos + 1);
92                 // ...and erase that stuff from latexstr
93                 latexstr = latexstr.erase(pos);
94                 // ...and similarly from plainstr
95                 size_t ppos = plainstr.find(from_ascii("|"));
96                 if (ppos < plainstr.size())
97                         plainstr.erase(ppos);
98                 else
99                         LYXERR0("The `|' separator was not found in the plaintext version!");
100         }
101
102         // Separate the entires and subentries, i.e., split on "!"
103         // FIXME This would do the wrong thing with escaped ! characters
104         std::vector<docstring> const levels =
105                 getVectorFromString(latexstr, from_ascii("!"), true);
106         std::vector<docstring> const levels_plain =
107                 getVectorFromString(plainstr, from_ascii("!"), true);
108
109         vector<docstring>::const_iterator it = levels.begin();
110         vector<docstring>::const_iterator end = levels.end();
111         vector<docstring>::const_iterator it2 = levels_plain.begin();
112         bool first = true;
113         for (; it != end; ++it) {
114                 // write the separator except the first time
115                 if (!first)
116                         os << '!';
117                 else
118                         first = false;
119
120                 // correctly sort macros and formatted strings
121                 // if we do find a command, prepend a plain text
122                 // version of the content to get sorting right,
123                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
124                 // Don't do that if the user entered '@' himself, though.
125                 if (contains(*it, '\\') && !contains(*it, '@')) {
126                         // Plaintext might return nothing (e.g. for ERTs)
127                         docstring const spart = 
128                                 (it2 < levels_plain.end() && !(*it2).empty())
129                                 ? *it2 : *it;
130                         // Now we need to validate that all characters in
131                         // the sorting part are representable in the current
132                         // encoding. If not try the LaTeX macro which might
133                         // or might not be a good choice, and issue a warning.
134                         docstring spart2;
135                         for (size_t n = 0; n < spart.size(); ++n) {
136                                 try {
137                                         spart2 += runparams.encoding->latexChar(spart[n]);
138                                 } catch (EncodingException & /* e */) {
139                                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
140                                 }
141                         }
142                         if (spart != spart2 && !runparams.dryrun) {
143                                 // FIXME: warning should be passed to the error dialog
144                                 frontend::Alert::warning(_("Index sorting failed"),
145                                 bformat(_("LyX's automatic index sorting algorithm faced\n"
146                                   "problems with the entry '%1$s'.\n"
147                                   "Please specify the sorting of this entry manually, as\n"
148                                   "explained in the User Guide."), spart));
149                         }
150                         // remove remaining \'s for the sorting part
151                         docstring const ppart =
152                                 subst(spart2, from_ascii("\\"), docstring());
153                         os << ppart;
154                         os << '@';
155                 }
156                 docstring const tpart = *it;
157                 os << tpart;
158                 if (it2 < levels_plain.end())
159                         ++it2;
160         }
161         // write the bit that followed "|"
162         if (!cmd.empty())
163                 os << "|" << cmd;
164         os << '}';
165         return i;
166 }
167
168
169 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
170 {
171         os << "<indexterm><primary>";
172         int const i = InsetText::docbook(os, runparams);
173         os << "</primary></indexterm>";
174         return i;
175 }
176
177
178 docstring InsetIndex::xhtml(XHTMLStream &, OutputParams const &) const
179 {
180         return docstring();
181 }
182
183
184 bool InsetIndex::showInsetDialog(BufferView * bv) const
185 {
186         bv->showDialog("index", params2string(params_),
187                         const_cast<InsetIndex *>(this));
188         return true;
189 }
190
191
192 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
193 {
194         switch (cmd.action) {
195
196         case LFUN_INSET_MODIFY: {
197                 if (cmd.getArg(0) == "changetype") {
198                         params_.index = from_utf8(cmd.getArg(1));
199                         break;
200                 }
201                 InsetIndexParams params;
202                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
203                 params_.index = params.index;
204                 break;
205         }
206
207         case LFUN_INSET_DIALOG_UPDATE:
208                 cur.bv().updateDialog("index", params2string(params_));
209                 break;
210
211         default:
212                 InsetCollapsable::doDispatch(cur, cmd);
213                 break;
214         }
215 }
216
217
218 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
219                 FuncStatus & flag) const
220 {
221         switch (cmd.action) {
222
223         case LFUN_INSET_MODIFY:
224                 if (cmd.getArg(0) == "changetype") {
225                         docstring const newtype = from_utf8(cmd.getArg(1));
226                         Buffer const & realbuffer = *buffer().masterBuffer();
227                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
228                         Index const * index = indiceslist.findShortcut(newtype);
229                         flag.setEnabled(index != 0);
230                         flag.setOnOff(
231                                 from_utf8(cmd.getArg(1)) == params_.index);
232                         return true;
233                 }
234                 flag.setEnabled(true);
235                 return true;
236
237         case LFUN_INSET_DIALOG_UPDATE: {
238                 Buffer const & realbuffer = *buffer().masterBuffer();
239                 flag.setEnabled(realbuffer.params().use_indices);
240                 return true;
241         }
242
243         default:
244                 return InsetCollapsable::getStatus(cur, cmd, flag);
245         }
246 }
247
248
249 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
250 {
251         docstring s = _("Idx");
252         if (decoration() == InsetLayout::CLASSIC)
253                 return isOpen(bv) ? s : getNewLabel(s);
254         else
255                 return getNewLabel(s);
256 }
257
258
259 ColorCode InsetIndex::labelColor() const
260 {
261         if (params_.index.empty() || params_.index == from_ascii("idx"))
262                 return InsetCollapsable::labelColor();
263         // FIXME UNICODE
264         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
265         if (c == Color_none)
266                 c = InsetCollapsable::labelColor();
267         return c;
268 }
269
270
271 docstring InsetIndex::toolTip(BufferView const &, int, int) const
272 {
273         docstring tip = _("Index Entry");
274         if (buffer().params().use_indices && !params_.index.empty()) {
275                 Buffer const & realbuffer = *buffer().masterBuffer();
276                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
277                 tip += " (";
278                 Index const * index = indiceslist.findShortcut(params_.index);
279                 if (!index)
280                         tip += _("unknown type!");
281                 else
282                         tip += index->index();
283                 tip += ")";
284         }
285         tip += ": ";
286         OutputParams rp(&buffer().params().encoding());
287         odocstringstream ods;
288         InsetText::plaintext(ods, rp);
289         tip += ods.str();
290         return wrapParas(tip);
291 }
292
293
294 void InsetIndex::write(ostream & os) const
295 {
296         os << to_utf8(name());
297         params_.write(os);
298         InsetCollapsable::write(os);
299 }
300
301
302 void InsetIndex::read(Lexer & lex)
303 {
304         params_.read(lex);
305         InsetCollapsable::read(lex);
306 }
307
308
309 string InsetIndex::params2string(InsetIndexParams const & params)
310 {
311         ostringstream data;
312         data << "index";
313         params.write(data);
314         return data.str();
315 }
316
317
318 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
319 {
320         params = InsetIndexParams();
321         if (in.empty())
322                 return;
323
324         istringstream data(in);
325         Lexer lex;
326         lex.setStream(data);
327         lex.setContext("InsetIndex::string2params");
328         lex >> "index";
329         params.read(lex);
330 }
331
332
333 void InsetIndex::addToToc(DocIterator const & cpit)
334 {
335         DocIterator pit = cpit;
336         pit.push_back(CursorSlice(*this));
337         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
338         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
339         // Proceed with the rest of the inset.
340         InsetCollapsable::addToToc(cpit);
341 }
342
343
344 void InsetIndex::validate(LaTeXFeatures & features) const
345 {
346         if (buffer().masterBuffer()->params().use_indices
347             && !params_.index.empty()
348             && params_.index != "idx")
349                 features.require("splitidx");
350 }
351
352
353 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
354 {
355         return from_ascii("context-index");
356 }
357
358
359 bool InsetIndex::hasSettings() const
360 {
361         return buffer().masterBuffer()->params().use_indices;
362 }
363
364
365
366
367 /////////////////////////////////////////////////////////////////////
368 //
369 // InsetIndexParams
370 //
371 ///////////////////////////////////////////////////////////////////////
372
373
374 void InsetIndexParams::write(ostream & os) const
375 {
376         os << ' ';
377         if (!index.empty())
378                 os << to_utf8(index);
379         else
380                 os << "idx";
381         os << '\n';
382 }
383
384
385 void InsetIndexParams::read(Lexer & lex)
386 {
387         if (lex.eatLine())
388                 index = lex.getDocString();
389         else
390                 index = from_ascii("idx");
391 }
392
393
394 /////////////////////////////////////////////////////////////////////
395 //
396 // InsetPrintIndex
397 //
398 ///////////////////////////////////////////////////////////////////////
399
400 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
401         : InsetCommand(buf, p, "index_print")
402 {}
403
404
405 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
406 {
407         static ParamInfo param_info_;
408         if (param_info_.empty()) {
409                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
410                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
411         }
412         return param_info_;
413 }
414
415
416 docstring InsetPrintIndex::screenLabel() const
417 {
418         bool const printall = suffixIs(getCmdName(), '*');
419         bool const multind = buffer().masterBuffer()->params().use_indices;
420         if ((!multind
421              && getParam("type") == from_ascii("idx"))
422             || (getParam("type").empty() && !printall))
423                 return _("Index");
424         Buffer const & realbuffer = *buffer().masterBuffer();
425         IndicesList const & indiceslist = realbuffer.params().indiceslist();
426         Index const * index = indiceslist.findShortcut(getParam("type"));
427         if (!index && !printall)
428                 return _("Unknown index type!");
429         docstring res = printall ? _("All indices") : index->index();
430         if (!multind)
431                 res += " (" + _("non-active") + ")";
432         else if (contains(getCmdName(), "printsubindex"))
433                 res += " (" + _("subindex") + ")";
434         return res;
435 }
436
437
438 bool InsetPrintIndex::isCompatibleCommand(string const & s)
439 {
440         return s == "printindex" || s == "printsubindex"
441                 || s == "printindex*" || s == "printsubindex*";
442 }
443
444
445 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
446 {
447         switch (cmd.action) {
448
449         case LFUN_INSET_MODIFY: {
450                 if (cmd.argument() == from_ascii("toggle-subindex")) {
451                         string cmd = getCmdName();
452                         if (contains(cmd, "printindex"))
453                                 cmd = subst(cmd, "printindex", "printsubindex");
454                         else
455                                 cmd = subst(cmd, "printsubindex", "printindex");
456                         setCmdName(cmd);
457                         break;
458                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
459                         string cmd = getCmdName();
460                         if (suffixIs(cmd, '*'))
461                                 break;
462                         cmd += '*';
463                         setParam("type", docstring());
464                         setCmdName(cmd);
465                         break;
466                 }
467                 InsetCommandParams p(INDEX_PRINT_CODE);
468                 // FIXME UNICODE
469                 InsetCommand::string2params("index_print",
470                         to_utf8(cmd.argument()), p);
471                 if (p.getCmdName().empty()) {
472                         cur.noUpdate();
473                         break;
474                 }
475                 setParams(p);
476                 break;
477         }
478
479         default:
480                 InsetCommand::doDispatch(cur, cmd);
481                 break;
482         }
483 }
484
485
486 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
487         FuncStatus & status) const
488 {
489         switch (cmd.action) {
490
491         case LFUN_INSET_MODIFY: {
492                 if (cmd.argument() == from_ascii("toggle-subindex")) {
493                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
494                         status.setOnOff(contains(getCmdName(), "printsubindex"));
495                         return true;
496                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
497                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
498                         status.setOnOff(suffixIs(getCmdName(), '*'));
499                         return true;
500                 } if (cmd.getArg(0) == "index_print"
501                     && cmd.getArg(1) == "CommandInset") {
502                         InsetCommandParams p(INDEX_PRINT_CODE);
503                         InsetCommand::string2params("index_print",
504                                 to_utf8(cmd.argument()), p);
505                         if (suffixIs(p.getCmdName(), '*')) {
506                                 status.setEnabled(true);
507                                 status.setOnOff(false);
508                                 return true;
509                         }
510                         Buffer const & realbuffer = *buffer().masterBuffer();
511                         IndicesList const & indiceslist =
512                                 realbuffer.params().indiceslist();
513                         Index const * index = indiceslist.findShortcut(p["type"]);
514                         status.setEnabled(index != 0);
515                         status.setOnOff(p["type"] == getParam("type"));
516                         return true;
517                 } else
518                         return InsetCommand::getStatus(cur, cmd, status);
519         }
520         
521         case LFUN_INSET_DIALOG_UPDATE: {
522                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
523                 return true;
524         }
525
526         default:
527                 return InsetCommand::getStatus(cur, cmd, status);
528         }
529 }
530
531
532 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
533 {
534         if (!buffer().masterBuffer()->params().use_indices) {
535                 if (getParam("type") == from_ascii("idx"))
536                         os << "\\printindex{}";
537                 return 0;
538         }
539         os << getCommand();
540         return 0;
541 }
542
543
544 void InsetPrintIndex::validate(LaTeXFeatures & features) const
545 {
546         features.require("makeidx");
547         if (buffer().masterBuffer()->params().use_indices)
548                 features.require("splitidx");
549 }
550
551
552 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
553 {
554         return buffer().masterBuffer()->params().use_indices ?
555                 from_ascii("context-indexprint") : docstring();
556 }
557
558
559 bool InsetPrintIndex::hasSettings() const
560 {
561         return buffer().masterBuffer()->params().use_indices;
562 }
563
564
565 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const &) const
566 {
567         return docstring();
568 }
569
570 } // namespace lyx