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