]> git.lyx.org Git - lyx.git/blob - src/insets/InsetIndex.cpp
adjust comment.
[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 "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 bool InsetIndex::showInsetDialog(BufferView * bv) const
175 {
176         bv->showDialog("index", params2string(params_),
177                         const_cast<InsetIndex *>(this));
178         return true;
179 }
180
181
182 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
183 {
184         switch (cmd.action) {
185
186         case LFUN_INSET_MODIFY: {
187                 if (cmd.getArg(0) == "changetype") {
188                         params_.index = from_utf8(cmd.getArg(1));
189                         setLayout(cur.buffer()->params());
190                         break;
191                 }
192                 InsetIndexParams params;
193                 InsetIndex::string2params(to_utf8(cmd.argument()), params);
194                 params_.index = params.index;
195                 setLayout(cur.buffer()->params());
196                 break;
197         }
198
199         case LFUN_INSET_DIALOG_UPDATE:
200                 cur.bv().updateDialog("index", params2string(params_));
201                 break;
202
203         default:
204                 InsetCollapsable::doDispatch(cur, cmd);
205                 break;
206         }
207 }
208
209
210 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
211                 FuncStatus & flag) const
212 {
213         switch (cmd.action) {
214
215         case LFUN_INSET_MODIFY:
216                 if (cmd.getArg(0) == "changetype") {
217                         docstring const newtype = from_utf8(cmd.getArg(1));
218                         Buffer const & realbuffer = *buffer().masterBuffer();
219                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
220                         Index const * index = indiceslist.findShortcut(newtype);
221                         flag.setEnabled(index != 0);
222                         flag.setOnOff(
223                                 from_utf8(cmd.getArg(1)) == params_.index);
224                         return true;
225                 }
226                 flag.setEnabled(true);
227                 return true;
228
229         case LFUN_INSET_DIALOG_UPDATE: {
230                 Buffer const & realbuffer = *buffer().masterBuffer();
231                 flag.setEnabled(realbuffer.params().use_indices);
232                 return true;
233         }
234
235         default:
236                 return InsetCollapsable::getStatus(cur, cmd, flag);
237         }
238 }
239
240
241 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
242 {
243         docstring s = _("Idx");
244         if (decoration() == InsetLayout::CLASSIC)
245                 return isOpen(bv) ? s : getNewLabel(s);
246         else
247                 return getNewLabel(s);
248 }
249
250
251 docstring InsetIndex::toolTip(BufferView const &, int, int) const
252 {
253         docstring tip = _("Index Entry");
254         if (buffer().params().use_indices && !params_.index.empty()) {
255                 Buffer const & realbuffer = *buffer().masterBuffer();
256                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
257                 tip += " (";
258                 Index const * index = indiceslist.findShortcut(params_.index);
259                 if (!index)
260                         tip += _("unknown type!");
261                 else
262                         tip += index->index();
263                 tip += ")";
264         }
265         tip += ": ";
266         OutputParams rp(&buffer().params().encoding());
267         odocstringstream ods;
268         InsetText::plaintext(ods, rp);
269         tip += ods.str();
270         // shorten it if necessary
271         if (tip.size() > 200)
272                 tip = tip.substr(0, 200) + "...";
273         return tip;
274 }
275
276
277 void InsetIndex::write(ostream & os) const
278 {
279         os << to_utf8(name());
280         params_.write(os);
281         InsetCollapsable::write(os);
282 }
283
284
285 void InsetIndex::read(Lexer & lex)
286 {
287         params_.read(lex);
288         InsetCollapsable::read(lex);
289 }
290
291
292 string InsetIndex::params2string(InsetIndexParams const & params)
293 {
294         ostringstream data;
295         data << "index";
296         params.write(data);
297         return data.str();
298 }
299
300
301 void InsetIndex::string2params(string const & in, InsetIndexParams & params)
302 {
303         params = InsetIndexParams();
304         if (in.empty())
305                 return;
306
307         istringstream data(in);
308         Lexer lex;
309         lex.setStream(data);
310         lex.setContext("InsetIndex::string2params");
311         lex >> "index";
312         params.read(lex);
313 }
314
315
316 void InsetIndex::addToToc(DocIterator const & cpit)
317 {
318         DocIterator pit = cpit;
319         pit.push_back(CursorSlice(*this));
320         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
321         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
322         // Proceed with the rest of the inset.
323         InsetCollapsable::addToToc(cpit);
324 }
325
326
327 void InsetIndex::validate(LaTeXFeatures & features) const
328 {
329         if (buffer().masterBuffer()->params().use_indices
330             && !params_.index.empty()
331             && params_.index != "idx")
332                 features.require("splitidx");
333 }
334
335
336 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
337 {
338         return from_ascii("context-index");
339 }
340
341
342 bool InsetIndex::hasSettings() const
343 {
344         return buffer().masterBuffer()->params().use_indices;
345 }
346
347
348
349
350 /////////////////////////////////////////////////////////////////////
351 //
352 // InsetIndexParams
353 //
354 ///////////////////////////////////////////////////////////////////////
355
356
357 void InsetIndexParams::write(ostream & os) const
358 {
359         os << ' ';
360         if (!index.empty())
361                 os << to_utf8(index);
362         else
363                 os << "idx";
364         os << '\n';
365 }
366
367
368 void InsetIndexParams::read(Lexer & lex)
369 {
370         if (lex.eatLine())
371                 index = lex.getDocString();
372         else
373                 index = from_ascii("idx");
374 }
375
376
377 /////////////////////////////////////////////////////////////////////
378 //
379 // InsetPrintIndex
380 //
381 ///////////////////////////////////////////////////////////////////////
382
383 InsetPrintIndex::InsetPrintIndex(InsetCommandParams const & p)
384         : InsetCommand(p, "index_print")
385 {}
386
387
388 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
389 {
390         static ParamInfo param_info_;
391         if (param_info_.empty()) {
392                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
393                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
394         }
395         return param_info_;
396 }
397
398
399 docstring InsetPrintIndex::screenLabel() const
400 {
401         bool const printall = suffixIs(getCmdName(), '*');
402         bool const multind = buffer().masterBuffer()->params().use_indices;
403         if ((!multind
404              && getParam("type") == from_ascii("idx"))
405             || (getParam("type").empty() && !printall))
406                 return _("Index");
407         Buffer const & realbuffer = *buffer().masterBuffer();
408         IndicesList const & indiceslist = realbuffer.params().indiceslist();
409         Index const * index = indiceslist.findShortcut(getParam("type"));
410         if (!index && !printall)
411                 return _("Unknown index type!");
412         docstring res = printall ? _("All indices") : index->index();
413         if (!multind)
414                 res += " (" + _("non-active") + ")";
415         else if (contains(getCmdName(), "printsubindex"))
416                 res += " (" + _("subindex") + ")";
417         return res;
418 }
419
420
421 bool InsetPrintIndex::isCompatibleCommand(string const & s)
422 {
423         return s == "printindex" || s == "printsubindex"
424                 || s == "printindex*" || s == "printsubindex*";
425 }
426
427
428 void InsetPrintIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
429 {
430         switch (cmd.action) {
431
432         case LFUN_INSET_MODIFY: {
433                 if (cmd.argument() == from_ascii("toggle-subindex")) {
434                         string cmd = getCmdName();
435                         if (contains(cmd, "printindex"))
436                                 cmd = subst(cmd, "printindex", "printsubindex");
437                         else
438                                 cmd = subst(cmd, "printsubindex", "printindex");
439                         setCmdName(cmd);
440                         break;
441                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
442                         string cmd = getCmdName();
443                         if (suffixIs(cmd, '*'))
444                                 break;
445                         cmd += '*';
446                         setParam("type", docstring());
447                         setCmdName(cmd);
448                         break;
449                 }
450                 InsetCommandParams p(INDEX_PRINT_CODE);
451                 // FIXME UNICODE
452                 InsetCommand::string2params("index_print",
453                         to_utf8(cmd.argument()), p);
454                 if (p.getCmdName().empty()) {
455                         cur.noUpdate();
456                         break;
457                 }
458                 setParams(p);
459                 break;
460         }
461
462         default:
463                 InsetCommand::doDispatch(cur, cmd);
464                 break;
465         }
466 }
467
468
469 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
470         FuncStatus & status) const
471 {
472         switch (cmd.action) {
473
474         case LFUN_INSET_MODIFY: {
475                 if (cmd.argument() == from_ascii("toggle-subindex")) {
476                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
477                         status.setOnOff(contains(getCmdName(), "printsubindex"));
478                         return true;
479                 } else if (cmd.argument() == from_ascii("check-printindex*")) {
480                         status.setEnabled(buffer().masterBuffer()->params().use_indices);
481                         status.setOnOff(suffixIs(getCmdName(), '*'));
482                         return true;
483                 } if (cmd.getArg(0) == "index_print"
484                     && cmd.getArg(1) == "CommandInset") {
485                         InsetCommandParams p(INDEX_PRINT_CODE);
486                         InsetCommand::string2params("index_print",
487                                 to_utf8(cmd.argument()), p);
488                         if (suffixIs(p.getCmdName(), '*')) {
489                                 status.setEnabled(true);
490                                 status.setOnOff(false);
491                                 return true;
492                         }
493                         Buffer const & realbuffer = *buffer().masterBuffer();
494                         IndicesList const & indiceslist =
495                                 realbuffer.params().indiceslist();
496                         Index const * index = indiceslist.findShortcut(p["type"]);
497                         status.setEnabled(index != 0);
498                         status.setOnOff(p["type"] == getParam("type"));
499                         return true;
500                 } else
501                         return InsetCommand::getStatus(cur, cmd, status);
502         }
503         
504         case LFUN_INSET_DIALOG_UPDATE: {
505                 status.setEnabled(buffer().masterBuffer()->params().use_indices);
506                 return true;
507         }
508
509         default:
510                 return InsetCommand::getStatus(cur, cmd, status);
511         }
512 }
513
514
515 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
516 {
517         if (!buffer().masterBuffer()->params().use_indices) {
518                 if (getParam("type") == from_ascii("idx"))
519                         os << "\\printindex{}";
520                 return 0;
521         }
522         os << getCommand();
523         return 0;
524 }
525
526
527 void InsetPrintIndex::validate(LaTeXFeatures & features) const
528 {
529         features.require("makeidx");
530         if (buffer().masterBuffer()->params().use_indices)
531                 features.require("splitidx");
532 }
533
534
535 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
536 {
537         return buffer().masterBuffer()->params().use_indices ?
538                 from_ascii("context-indexprint") : docstring();
539 }
540
541
542 bool InsetPrintIndex::hasSettings() const
543 {
544         return buffer().masterBuffer()->params().use_indices;
545 }
546
547
548 } // namespace lyx