]> git.lyx.org Git - features.git/blob - src/insets/InsetIndex.cpp
Introduce splitindex support. File format change.
[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 "ColorSet.h"
18 #include "DispatchResult.h"
19 #include "Encoding.h"
20 #include "FuncRequest.h"
21 #include "FuncStatus.h"
22 #include "IndicesList.h"
23 #include "LaTeXFeatures.h"
24 #include "Lexer.h"
25 #include "MetricsInfo.h"
26 #include "sgml.h"
27 #include "TocBackend.h"
28
29 #include "support/debug.h"
30 #include "support/docstream.h"
31 #include "support/gettext.h"
32 #include "support/lstrings.h"
33
34 #include "frontends/alert.h"
35
36 #include <ostream>
37
38 using namespace std;
39 using namespace lyx::support;
40
41 namespace lyx {
42
43 /////////////////////////////////////////////////////////////////////
44 //
45 // InsetIndex
46 //
47 ///////////////////////////////////////////////////////////////////////
48
49
50 InsetIndex::InsetIndex(Buffer const & buf, InsetIndexParams const & params)
51         : InsetCollapsable(buf), params_(params)
52 {}
53
54
55 int InsetIndex::latex(odocstream & os,
56                       OutputParams const & runparams) const
57 {
58         if (buffer().masterBuffer()->params().use_indices && !params_.index.empty()
59             && params_.index != "idx") {
60                 os << "\\sindex[";
61                 os << params_.index;
62                 os << "]{";
63         } else {
64                 os << "\\index";
65                 os << '{';
66         }
67         int i = 0;
68
69         // get contents of InsetText as LaTeX and plaintext
70         odocstringstream ourlatex;
71         InsetText::latex(ourlatex, runparams);
72         odocstringstream ourplain;
73         InsetText::plaintext(ourplain, runparams);
74         docstring latexstr = ourlatex.str();
75         docstring plainstr = ourplain.str();
76
77         // this will get what follows | if anything does
78         docstring cmd;
79
80         // check for the | separator
81         // FIXME This would go wrong on an escaped "|", but
82         // how far do we want to go here?
83         size_t pos = latexstr.find(from_ascii("|"));
84         if (pos != docstring::npos) {
85                 // put the bit after "|" into cmd...
86                 cmd = latexstr.substr(pos + 1);
87                 // ...and erase that stuff from latexstr
88                 latexstr = latexstr.erase(pos);
89                 // ...and similarly from plainstr
90                 size_t ppos = plainstr.find(from_ascii("|"));
91                 if (ppos < plainstr.size())
92                         plainstr.erase(ppos);
93                 else
94                         LYXERR0("The `|' separator was not found in the plaintext version!");
95         }
96
97         // Separate the entires and subentries, i.e., split on "!"
98         // FIXME This would do the wrong thing with escaped ! characters
99         std::vector<docstring> const levels =
100                 getVectorFromString(latexstr, from_ascii("!"), true);
101         std::vector<docstring> const levels_plain =
102                 getVectorFromString(plainstr, from_ascii("!"), true);
103
104         vector<docstring>::const_iterator it = levels.begin();
105         vector<docstring>::const_iterator end = levels.end();
106         vector<docstring>::const_iterator it2 = levels_plain.begin();
107         bool first = true;
108         for (; it != end; ++it) {
109                 // write the separator except the first time
110                 if (!first)
111                         os << '!';
112                 else
113                         first = false;
114
115                 // correctly sort macros and formatted strings
116                 // if we do find a command, prepend a plain text
117                 // version of the content to get sorting right,
118                 // e.g. \index{LyX@\LyX}, \index{text@\textbf{text}}
119                 // Don't do that if the user entered '@' himself, though.
120                 if (contains(*it, '\\') && !contains(*it, '@')) {
121                         // Plaintext might return nothing (e.g. for ERTs)
122                         docstring const spart = 
123                                 (it2 < levels_plain.end() && !(*it2).empty())
124                                 ? *it2 : *it;
125                         // Now we need to validate that all characters in
126                         // the sorting part are representable in the current
127                         // encoding. If not try the LaTeX macro which might
128                         // or might not be a good choice, and issue a warning.
129                         docstring spart2;
130                         for (size_t n = 0; n < spart.size(); ++n) {
131                                 try {
132                                         spart2 += runparams.encoding->latexChar(spart[n]);
133                                 } catch (EncodingException & /* e */) {
134                                         LYXERR0("Uncodable character in index entry. Sorting might be wrong!");
135                                 }
136                         }
137                         if (spart != spart2 && !runparams.dryrun) {
138                                 // FIXME: warning should be passed to the error dialog
139                                 frontend::Alert::warning(_("Index sorting failed"),
140                                 bformat(_("LyX's automatic index sorting algorithm faced\n"
141                                   "problems with the entry '%1$s'.\n"
142                                   "Please specify the sorting of this entry manually, as\n"
143                                   "explained in the User Guide."), spart));
144                         }
145                         // remove remaining \'s for the sorting part
146                         docstring const ppart =
147                                 subst(spart2, from_ascii("\\"), docstring());
148                         os << ppart;
149                         os << '@';
150                 }
151                 docstring const tpart = *it;
152                 os << tpart;
153                 if (it2 < levels_plain.end())
154                         ++it2;
155         }
156         // write the bit that followed "|"
157         if (!cmd.empty())
158                 os << "|" << cmd;
159         os << '}';
160         return i;
161 }
162
163
164 int InsetIndex::docbook(odocstream & os, OutputParams const & runparams) const
165 {
166         os << "<indexterm><primary>";
167         int const i = InsetText::docbook(os, runparams);
168         os << "</primary></indexterm>";
169         return i;
170 }
171
172
173 void InsetIndex::doDispatch(Cursor & cur, FuncRequest & cmd)
174 {
175         switch (cmd.action) {
176
177         case LFUN_INSET_MODIFY: {
178                 if (cmd.getArg(0) == "changetype") {
179                         params_.index = from_utf8(cmd.getArg(1));
180                         setLayout(cur.buffer()->params());
181                         break;
182                 }
183         }
184
185         default:
186                 InsetCollapsable::doDispatch(cur, cmd);
187                 break;
188         }
189 }
190
191
192 bool InsetIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
193                 FuncStatus & flag) const
194 {
195         switch (cmd.action) {
196
197         case LFUN_INSET_MODIFY:
198                 if (cmd.getArg(0) == "changetype") {
199                         docstring const newtype = from_utf8(cmd.getArg(1));
200                         Buffer const & realbuffer = *buffer().masterBuffer();
201                         IndicesList const & indiceslist = realbuffer.params().indiceslist();
202                         Index const * index = indiceslist.findShortcut(newtype);
203                         flag.setEnabled(index != 0);
204                         flag.setOnOff(
205                                 from_utf8(cmd.getArg(1)) == params_.index);
206                         return true;
207                 }
208
209         default:
210                 return InsetCollapsable::getStatus(cur, cmd, flag);
211         }
212 }
213
214
215 docstring const InsetIndex::buttonLabel(BufferView const & bv) const
216 {
217         docstring s = _("Idx");
218         if (decoration() == InsetLayout::CLASSIC)
219                 return isOpen(bv) ? s : getNewLabel(s);
220         else
221                 return getNewLabel(s);
222 }
223
224
225 docstring InsetIndex::toolTip(BufferView const &, int, int) const
226 {
227         docstring tip = _("Index Entry");
228         if (buffer().params().use_indices && !params_.index.empty()) {
229                 Buffer const & realbuffer = *buffer().masterBuffer();
230                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
231                 tip += " (";
232                 Index const * index = indiceslist.findShortcut(params_.index);
233                 if (!index)
234                         tip += _("unknown type!");
235                 else
236                         tip += index->index();
237                 tip += ")";
238         }
239         tip += ": ";
240         OutputParams rp(&buffer().params().encoding());
241         odocstringstream ods;
242         InsetText::plaintext(ods, rp);
243         tip += ods.str();
244         // shorten it if necessary
245         if (tip.size() > 200)
246                 tip = tip.substr(0, 200) + "...";
247         return tip;
248 }
249
250
251 void InsetIndex::write(ostream & os) const
252 {
253         os << to_utf8(name());
254         params_.write(os);
255         InsetCollapsable::write(os);
256 }
257
258
259 void InsetIndex::read(Lexer & lex)
260 {
261         params_.read(lex);
262         InsetCollapsable::read(lex);
263 }
264
265
266 void InsetIndex::addToToc(DocIterator const & cpit)
267 {
268         DocIterator pit = cpit;
269         pit.push_back(CursorSlice(*this));
270         docstring const item = text().asString(0, 1, AS_STR_LABEL | AS_STR_INSETS);
271         buffer().tocBackend().toc("index").push_back(TocItem(pit, 0, item));
272         // Proceed with the rest of the inset.
273         InsetCollapsable::addToToc(cpit);
274 }
275
276
277 void InsetIndex::validate(LaTeXFeatures & features) const
278 {
279         if (buffer().masterBuffer()->params().use_indices
280             && !params_.index.empty()
281             && params_.index != "idx")
282                 features.require("splitidx");
283 }
284
285
286 docstring InsetIndex::contextMenu(BufferView const &, int, int) const
287 {
288         return from_ascii("context-index");
289 }
290
291
292 void InsetIndexParams::write(ostream & os) const
293 {
294         os << ' ';
295         if (!index.empty())
296                 os << to_utf8(index);
297         else
298                 os << "idx";
299         os << '\n';
300 }
301
302
303 void InsetIndexParams::read(Lexer & lex)
304 {
305         if (lex.eatLine())
306                 index = lex.getDocString();
307         else
308                 index = from_ascii("idx");
309 }
310
311
312 /////////////////////////////////////////////////////////////////////
313 //
314 // InsetPrintIndex
315 //
316 ///////////////////////////////////////////////////////////////////////
317
318 InsetPrintIndex::InsetPrintIndex(InsetCommandParams const & p)
319         : InsetCommand(p, "index_print")
320 {}
321
322
323 ParamInfo const & InsetPrintIndex::findInfo(string const & /* cmdName */)
324 {
325         static ParamInfo param_info_;
326         if (param_info_.empty()) {
327                 param_info_.add("type", ParamInfo::LATEX_OPTIONAL);
328                 param_info_.add("name", ParamInfo::LATEX_REQUIRED);
329         }
330         return param_info_;
331 }
332
333
334 docstring InsetPrintIndex::screenLabel() const
335 {
336         if ((!buffer().masterBuffer()->params().use_indices
337              && getParam("type") == from_ascii("idx"))
338             || getParam("type").empty())
339                 return _("Index");
340         Buffer const & realbuffer = *buffer().masterBuffer();
341         IndicesList const & indiceslist = realbuffer.params().indiceslist();
342         Index const * index = indiceslist.findShortcut(getParam("type"));
343         if (!index)
344                 return _("Unknown index type!");
345         docstring res = index->index();
346         if (!buffer().masterBuffer()->params().use_indices)
347                 res += " (" + _("non-active") + ")";
348         return res;
349 }
350
351
352 bool InsetPrintIndex::getStatus(Cursor & cur, FuncRequest const & cmd,
353         FuncStatus & status) const
354 {
355         switch (cmd.action) {
356
357         case LFUN_INSET_MODIFY: {
358                 InsetCommandParams p(INDEX_PRINT_CODE);
359                 InsetCommand::string2params("index_print", to_utf8(cmd.argument()), p);
360                 Buffer const & realbuffer = *buffer().masterBuffer();
361                 IndicesList const & indiceslist = realbuffer.params().indiceslist();
362                 Index const * index = indiceslist.findShortcut(p["type"]);
363                 status.setEnabled(index != 0);
364                 status.setOnOff(p["type"] == getParam("type"));
365                 return true;
366         } 
367
368         default:
369                 return InsetCommand::getStatus(cur, cmd, status);
370         }
371 }
372
373
374 int InsetPrintIndex::latex(odocstream & os, OutputParams const &) const
375 {
376         if (!buffer().masterBuffer()->params().use_indices) {
377                 if (getParam("type") == from_ascii("idx"))
378                         os << "\\printindex{}";
379                 return 0;
380         }
381         os << getCommand();
382         return 0;
383 }
384
385
386 void InsetPrintIndex::validate(LaTeXFeatures & features) const
387 {
388         features.require("makeidx");
389         if (buffer().masterBuffer()->params().use_indices)
390                 features.require("splitidx");
391 }
392
393
394 docstring InsetPrintIndex::contextMenu(BufferView const &, int, int) const
395 {
396         return buffer().masterBuffer()->params().use_indices ?
397                 from_ascii("context-indexprint") : docstring();
398 }
399
400 } // namespace lyx