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