]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
How about if we write a script to do some of this and stop doing it
[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 ColorCode InsetIndex::labelColor() const
250 {
251         if (params_.index.empty() || params_.index == from_ascii("idx"))
252                 return InsetCollapsable::labelColor();
253         // FIXME UNICODE
254         ColorCode c = lcolor.getFromLyXName(to_utf8(params_.index));
255         if (c == Color_none)
256                 c = InsetCollapsable::labelColor();
257         return c;
258 }
259
260
261 docstring InsetIndex::toolTip(BufferView const &, int, int) const
262 {
263         docstring tip = _("Index Entry");
264         if (buffer().params().use_indices && !params_.index.empty()) {
265                 Buffer const & realbuffer = *buffer().masterBuffer();
266                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
267                 tip += " (";
268                 Index const * index = indiceslist.findShortcut(params_.index);
269                 if (!index)
270                         tip += _("unknown type!");
271                 else
272                         tip += index->index();
273                 tip += ")";
274         }
275         tip += ": ";
276         OutputParams rp(&buffer().params().encoding());
277         odocstringstream ods;
278         InsetText::plaintext(ods, rp);
279         tip += ods.str();
280         return wrapParas(tip);
281 }
282
283
284 void InsetIndex::write(ostream & os) const
285 {
286         os << to_utf8(name());
287         params_.write(os);
288         InsetCollapsable::write(os);
289 }
290
291
292 void InsetIndex::read(Lexer & lex)
293 {
294         params_.read(lex);
295         InsetCollapsable::read(lex);
296 }
297
298
299 string InsetIndex::params2string(InsetIndexParams const & params)
300 {
301         ostringstream data;
302         data << "index";
303         params.write(data);
304         return data.str();
305 }
306
307
308 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
309 {
310         params = InsetIndexParams();
311         if (in.empty())
312                 return;
313
314         istringstream data(in);
315         Lexer lex;
316         lex.setStream(data);
317         lex.setContext("InsetIndex::string2params");
318         lex >> "index";
319         params.read(lex);
320 }
321
322
323 void InsetIndex::addToToc(DocIterator const & cpit)
324 {
325         DocIterator pit = cpit;
326         pit.push_back(CursorSlice(*this));
327         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
328         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
329         // Proceed with the rest of the inset.
330         InsetCollapsable::addToToc(cpit);
331 }
332
333
334 void InsetIndex::validate(LaTeXFeatures & features) const
335 {
336         if (buffer().masterBuffer()->params().use_indices
337             && !params_.index.empty()
338             && params_.index != "idx")
339                 features.require("splitidx");
340 }
341
342
343 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
344 {
345         return from_ascii("context-index");
346 }
347
348
349 bool InsetIndex::hasSettings() const
350 {
351         return buffer().masterBuffer()->params().use_indices;
352 }
353
354
355
356
357 /////////////////////////////////////////////////////////////////////
358 //
359 // InsetIndexParams
360 //
361 ///////////////////////////////////////////////////////////////////////
362
363
364 void InsetIndexParams::write(ostream & os) const
365 {
366         os << ' ';
367         if (!index.empty())
368                 os << to_utf8(index);
369         else
370                 os << "idx";
371         os << '\n';
372 }
373
374
375 void InsetIndexParams::read(Lexer & lex)
376 {
377         if (lex.eatLine())
378                 index = lex.getDocString();
379         else
380                 index = from_ascii("idx");
381 }
382
383
384 /////////////////////////////////////////////////////////////////////
385 //
386 // InsetPrintIndex
387 //
388 ///////////////////////////////////////////////////////////////////////
389
390 InsetPrintIndex::InsetPrintIndex(Buffer * buf, InsetCommandParams const & p)
391         : InsetCommand(buf, p, "index_print")
392 {}
393
394
395 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
396 {
397         static ParamInfo param_info_;
398         if (param_info_.empty()) {
399                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
400                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
401         }
402         return param_info_;
403 }
404
405
406 docstring InsetPrintIndex::screenLabel() const
407 {
408         bool const printall = suffixIs(getCmdName(), '*');
409         bool const multind = buffer().masterBuffer()->params().use_indices;
410         if ((!multind
411              && getParam("type") == from_ascii("idx"))
412             || (getParam("type").empty() && !printall))
413                 return _("Index");
414         Buffer const & realbuffer = *buffer().masterBuffer();
415         IndicesList const & indiceslist = realbuffer.params().indiceslist();
416         Index const * index = indiceslist.findShortcut(getParam("type"));
417         if (!index && !printall)
418                 return _("Unknown index type!");
419         docstring res = printall ? _("All indices") : index->index();
420         if (!multind)
421                 res += " (" + _("non-active") + ")";
422         else if (contains(getCmdName(), "printsubindex"))
423                 res += " (" + _("subindex") + ")";
424         return res;
425 }
426
427
428 bool InsetPrintIndex::isCompatibleCommand(string const & s)
429 {
430         return s == "printindex" || s == "printsubindex"
431                 || s == "printindex*" || s == "printsubindex*";
432 }
433
434
435 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
436 {
437         switch (cmd.action) {
438
439         case LFUN_INSET_MODIFY: {
440                 if (cmd.argument() == from_ascii("toggle-subindex")) {
441                         string cmd = getCmdName();
442                         if (contains(cmd, "printindex"))
443                                 cmd = subst(cmd, "printindex", "printsubindex");
444                         else
445                                 cmd = subst(cmd, "printsubindex", "printindex");
446                         setCmdName(cmd);
447                         break;
448                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
449                         string cmd = getCmdName();
450                         if (suffixIs(cmd, '*'))
451                                 break;
452                         cmd += '*';
453                         setParam("type", docstring());
454                         setCmdName(cmd);
455                         break;
456                 }
457                 InsetCommandParams p(INDEX_PRINT_CODE);
458                 // FIXME UNICODE
459                 InsetCommand::string2params("index_print",
460                         to_utf8(cmd.argument()), p);
461                 if (p.getCmdName().empty()) {
462                         cur.noUpdate();
463                         break;
464                 }
465                 setParams(p);
466                 break;
467         }
468
469         default:
470                 InsetCommand::doDispatch(cur, cmd);
471                 break;
472         }
473 }
474
475
476 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
477         FuncStatus & status) const
478 {
479         switch (cmd.action) {
480
481         case LFUN_INSET_MODIFY: {
482                 if (cmd.argument() == from_ascii("toggle-subindex")) {
483                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
484                         status.setOnOff(contains(getCmdName(), "printsubindex"));
485                         return true;
486                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
487                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
488                         status.setOnOff(suffixIs(getCmdName(), '*'));
489                         return true;
490                 } if (cmd.getArg(0) == "index_print"
491                     && cmd.getArg(1) == "CommandInset") {
492                         InsetCommandParams p(INDEX_PRINT_CODE);
493                         InsetCommand::string2params("index_print",
494                                 to_utf8(cmd.argument()), p);
495                         if (suffixIs(p.getCmdName(), '*')) {
496                                 status.setEnabled(true);
497                                 status.setOnOff(false);
498                                 return true;
499                         }
500                         Buffer const & realbuffer = *buffer().masterBuffer();
501                         IndicesList const & indiceslist =
502                                 realbuffer.params().indiceslist();
503                         Index const * index = indiceslist.findShortcut(p["type"]);
504                         status.setEnabled(index != 0);
505                         status.setOnOff(p["type"] == getParam("type"));
506                         return true;
507                 } else
508                         return InsetCommand::getStatus(cur, cmd, status);
509         }
510         
511         case LFUN_INSET_DIALOG_UPDATE: {
512                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
513                 return true;
514         }
515
516         default:
517                 return InsetCommand::getStatus(cur, cmd, status);
518         }
519 }
520
521
522 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
523 {
524         if (!buffer().masterBuffer()->params().use_indices) {
525                 if (getParam("type") == from_ascii("idx"))
526                         os << "\\printindex{}";
527                 return 0;
528         }
529         os << getCommand();
530         return 0;
531 }
532
533
534 void InsetPrintIndex::validate(LaTeXFeatures & features) const
535 {
536         features.require("makeidx");
537         if (buffer().masterBuffer()->params().use_indices)
538                 features.require("splitidx");
539 }
540
541
542 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
543 {
544         return buffer().masterBuffer()->params().use_indices ?
545                 from_ascii("context-indexprint") : docstring();
546 }
547
548
549 bool InsetPrintIndex::hasSettings() const
550 {
551         return buffer().masterBuffer()->params().use_indices;
552 }
553
554
555 docstring InsetPrintIndex::xhtml(XHTMLStream &, OutputParams const &) const
556 {
557         return docstring();
558 }
559
560 } // namespace lyx