]> git.lyx.org Git - lyx.git/blob - src/Counters.cpp
Add active refs to non-active labels to brokenrefs toc
[lyx.git] / src / Counters.cpp
1 /**
2  * \file Counters.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 Martin Vermeer
8  * \author André Pönitz
9  * \author Richard Heck (roman numerals)
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "Counters.h"
17 #include "Layout.h"
18 #include "Lexer.h"
19
20 #include "support/convert.h"
21 #include "support/debug.h"
22 #include "support/gettext.h"
23 #include "support/lassert.h"
24 #include "support/lstrings.h"
25
26 #include <algorithm>
27 #include <sstream>
28
29 using namespace std;
30 using namespace lyx::support;
31
32 namespace lyx {
33
34
35 Counter::Counter()
36         : initial_value_(0)
37 {
38         reset();
39 }
40
41
42 Counter::Counter(docstring const & mc, docstring const & ls,
43                 docstring const & lsa)
44         : initial_value_(0), master_(mc), labelstring_(ls), labelstringappendix_(lsa)
45 {
46         reset();
47 }
48
49
50 bool Counter::read(Lexer & lex)
51 {
52         enum {
53                 CT_WITHIN = 1,
54                 CT_LABELSTRING,
55                 CT_LABELSTRING_APPENDIX,
56                 CT_PRETTYFORMAT,
57                 CT_INITIALVALUE,
58                 CT_END
59         };
60
61         LexerKeyword counterTags[] = {
62                 { "end", CT_END },
63           { "initialvalue", CT_INITIALVALUE},
64                 { "labelstring", CT_LABELSTRING },
65                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
66                 { "prettyformat", CT_PRETTYFORMAT },
67                 { "within", CT_WITHIN }
68         };
69
70         lex.pushTable(counterTags);
71
72         bool getout = false;
73         while (!getout && lex.isOK()) {
74                 int le = lex.lex();
75                 switch (le) {
76                         case Lexer::LEX_UNDEF:
77                                 lex.printError("Unknown counter tag `$$Token'");
78                                 continue;
79                         default:
80                                 break;
81                 }
82                 switch (le) {
83                         case CT_WITHIN:
84                                 lex.next();
85                                 master_ = lex.getDocString();
86                                 if (master_ == "none")
87                                         master_.erase();
88                                 break;
89                         case CT_INITIALVALUE:
90                                 lex.next();
91                                 initial_value_ = lex.getInteger();
92                                 // getInteger() returns -1 on error, and larger
93                                 // negative values do not make much sense.
94                                 // In the other case, we subtract one, since the
95                                 // counter will be incremented before its first use.
96                                 if (initial_value_ <= -1)
97                                         initial_value_ = 0;
98                                 else
99                                         initial_value_ -= 1;
100                                 break;
101                         case CT_PRETTYFORMAT:
102                                 lex.next();
103                                 prettyformat_ = lex.getDocString();
104                                 break;
105                         case CT_LABELSTRING:
106                                 lex.next();
107                                 labelstring_ = lex.getDocString();
108                                 labelstringappendix_ = labelstring_;
109                                 break;
110                         case CT_LABELSTRING_APPENDIX:
111                                 lex.next();
112                                 labelstringappendix_ = lex.getDocString();
113                                 break;
114                         case CT_END:
115                                 getout = true;
116                                 break;
117                 }
118         }
119
120         // Here if have a full counter if getout == true
121         if (!getout)
122                 LYXERR0("No End tag found for counter!");
123         lex.popTable();
124         return getout;
125 }
126
127
128 void Counter::set(int v)
129 {
130         value_ = v;
131 }
132
133
134 void Counter::addto(int v)
135 {
136         value_ += v;
137 }
138
139
140 int Counter::value() const
141 {
142         return value_;
143 }
144
145
146 void Counter::step()
147 {
148         ++value_;
149 }
150
151
152 void Counter::reset()
153 {
154         value_ = initial_value_;
155 }
156
157
158 docstring const & Counter::master() const
159 {
160         return master_;
161 }
162
163
164 bool Counter::checkAndRemoveMaster(docstring const & cnt)
165 {
166         if (master_ != cnt)
167                 return false;
168         master_ = docstring();
169         return true;
170 }
171
172
173 docstring const & Counter::labelString(bool in_appendix) const
174 {
175         return in_appendix ? labelstringappendix_ : labelstring_;
176 }
177
178
179 Counter::StringMap & Counter::flatLabelStrings(bool in_appendix) const
180 {
181         return in_appendix ? flatlabelstringappendix_ : flatlabelstring_;
182 }
183
184
185 Counters::Counters() : appendix_(false), subfloat_(false), longtable_(false)
186 {
187         layout_stack_.push_back(nullptr);
188         counter_stack_.push_back(from_ascii(""));
189 }
190
191
192 void Counters::newCounter(docstring const & newc,
193                           docstring const & masterc,
194                           docstring const & ls,
195                           docstring const & lsa)
196 {
197         if (!masterc.empty() && !hasCounter(masterc)) {
198                 lyxerr << "Master counter does not exist: "
199                        << to_utf8(masterc)
200                        << endl;
201                 return;
202         }
203         counterList_[newc] = Counter(masterc, ls, lsa);
204 }
205
206
207 bool Counters::hasCounter(docstring const & c) const
208 {
209         return counterList_.find(c) != counterList_.end();
210 }
211
212
213 bool Counters::read(Lexer & lex, docstring const & name, bool makenew)
214 {
215         if (hasCounter(name)) {
216                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
217                 return counterList_[name].read(lex);
218         }
219
220         LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
221         Counter cnt;
222         bool success = cnt.read(lex);
223         // if makenew is false, we will just discard what we read
224         if (success && makenew)
225                 counterList_[name] = cnt;
226         else if (!success)
227                 LYXERR0("Error reading counter `" << name << "'!");
228         return success;
229 }
230
231
232 void Counters::set(docstring const & ctr, int const val)
233 {
234         CounterList::iterator const it = counterList_.find(ctr);
235         if (it == counterList_.end()) {
236                 lyxerr << "set: Counter does not exist: "
237                        << to_utf8(ctr) << endl;
238                 return;
239         }
240         it->second.set(val);
241 }
242
243
244 void Counters::addto(docstring const & ctr, int const val)
245 {
246         CounterList::iterator const it = counterList_.find(ctr);
247         if (it == counterList_.end()) {
248                 lyxerr << "addto: Counter does not exist: "
249                        << to_utf8(ctr) << endl;
250                 return;
251         }
252         it->second.addto(val);
253 }
254
255
256 int Counters::value(docstring const & ctr) const
257 {
258         CounterList::const_iterator const cit = counterList_.find(ctr);
259         if (cit == counterList_.end()) {
260                 lyxerr << "value: Counter does not exist: "
261                        << to_utf8(ctr) << endl;
262                 return 0;
263         }
264         return cit->second.value();
265 }
266
267
268 void Counters::resetSlaves(docstring const & count)
269 {
270         for (auto & ctr : counterList_) {
271                 if (ctr.second.master() == count) {
272                         ctr.second.reset();
273                         resetSlaves(ctr.first);
274                 }
275         }
276 }
277
278
279 void Counters::stepMaster(docstring const & ctr, UpdateType utype)
280 {
281         CounterList::iterator it = counterList_.find(ctr);
282         if (it == counterList_.end()) {
283                 lyxerr << "step: Counter does not exist: "
284                        << to_utf8(ctr) << endl;
285                 return;
286         }
287         step(it->second.master(), utype);
288 }
289
290
291 void Counters::step(docstring const & ctr, UpdateType utype)
292 {
293         CounterList::iterator it = counterList_.find(ctr);
294         if (it == counterList_.end()) {
295                 lyxerr << "step: Counter does not exist: "
296                        << to_utf8(ctr) << endl;
297                 return;
298         }
299
300         it->second.step();
301         if (utype == OutputUpdate) {
302                 LBUFERR(!counter_stack_.empty());
303                 counter_stack_.pop_back();
304                 counter_stack_.push_back(ctr);
305         }
306
307         resetSlaves(ctr);
308 }
309
310
311 void Counters::reset()
312 {
313         appendix_ = false;
314         subfloat_ = false;
315         current_float_.erase();
316         for (auto & ctr : counterList_)
317                 ctr.second.reset();
318         counter_stack_.clear();
319         counter_stack_.push_back(from_ascii(""));
320         layout_stack_.clear();
321         layout_stack_.push_back(nullptr);
322 }
323
324
325 void Counters::reset(docstring const & match)
326 {
327         LASSERT(!match.empty(), return);
328
329         for (auto & ctr : counterList_) {
330                 if (ctr.first.find(match) != string::npos)
331                         ctr.second.reset();
332         }
333 }
334
335
336 bool Counters::remove(docstring const & cnt)
337 {
338         bool retval = counterList_.erase(cnt);
339         if (!retval)
340                 return false;
341         for (auto & ctr : counterList_) {
342                 if (ctr.second.checkAndRemoveMaster(cnt))
343                         LYXERR(Debug::TCLASS, "Removed master counter `" +
344                                         to_utf8(cnt) + "' from counter: " + to_utf8(ctr.first));
345         }
346         return retval;
347 }
348
349
350 void Counters::copy(Counters & from, Counters & to, docstring const & match)
351 {
352         for (auto const & ctr : counterList_) {
353                 if (ctr.first.find(match) != string::npos || match == "") {
354                         to.set(ctr.first, from.value(ctr.first));
355                 }
356         }
357 }
358
359
360 namespace {
361
362 char loweralphaCounter(int const n)
363 {
364         if (n < 1 || n > 26)
365                 return '?';
366         return 'a' + n - 1;
367 }
368
369
370 char alphaCounter(int const n)
371 {
372         if (n < 1 || n > 26)
373                 return '?';
374         return 'A' + n - 1;
375 }
376
377
378 char hebrewCounter(int const n)
379 {
380         static const char hebrew[22] = {
381                 '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8',
382                 '\xe9', '\xeb', '\xec', '\xee', '\xf0', '\xf1', '\xf2', '\xf4', '\xf6',
383                 '\xf7', '\xf8', '\xf9', '\xfa'
384         };
385
386         if (n < 1 || n > 22)
387                 return '?';
388         return hebrew[n - 1];
389 }
390
391
392 // On the special cases, see http://mathworld.wolfram.com/RomanNumerals.html
393 // and for a list of roman numerals up to and including 3999, see
394 // http://www.research.att.com/~njas/sequences/a006968.txt. (Thanks to Joost
395 // for this info.)
396 docstring const romanCounter(int const n)
397 {
398         static char const * const ones[9] = {
399                 "I",   "II",  "III", "IV", "V",
400                 "VI",  "VII", "VIII", "IX"
401         };
402
403         static char const * const tens[9] = {
404                 "X", "XX", "XXX", "XL", "L",
405                 "LX", "LXX", "LXXX", "XC"
406         };
407
408         static char const * const hunds[9] = {
409                 "C", "CC", "CCC", "CD", "D",
410                 "DC", "DCC", "DCCC", "CM"
411         };
412
413         if (n >= 1000 || n < 1)
414                 return from_ascii("??");
415
416         int val = n;
417         string roman;
418         switch (n) {
419         //special cases
420         case 900:
421                 roman = "CM";
422                 break;
423         case 400:
424                 roman = "CD";
425                 break;
426         default:
427                 if (val >= 100) {
428                         int hundreds = val / 100;
429                         roman = hunds[hundreds - 1];
430                         val = val % 100;
431                 }
432                 if (val >= 10) {
433                         switch (val) {
434                         //special case
435                         case 90:
436                                 roman = roman + "XC";
437                                 val = 0; //skip next
438                                 break;
439                         default:
440                                 int tensnum = val / 10;
441                                 roman = roman + tens[tensnum - 1];
442                                 val = val % 10;
443                         } // end switch
444                 } // end tens
445                 if (val > 0)
446                         roman = roman + ones[val -1];
447         }
448         return from_ascii(roman);
449 }
450
451
452 docstring const lowerromanCounter(int const n)
453 {
454         return lowercase(romanCounter(n));
455 }
456
457
458 docstring const fnsymbolCounter(int const n)
459 {
460         switch(n) {
461         case 1: return docstring(1, 0x002a); //*
462         case 2: return docstring(1, 0x2020); // dagger
463         case 3: return docstring(1, 0x2021); // double dagger
464         case 4: return docstring(1, 0x00A7); // section sign
465         case 5: return docstring(1, 0x00B6); // pilcrow sign
466         case 6: return docstring(1, 0x2016); // vertical bar
467         case 7: return docstring(2, 0x002a); // two *
468         case 8: return docstring(2, 0x2020); // two daggers
469         case 9: return docstring(2, 0x2021); // two double daggers
470         default:
471                 return from_ascii("?");
472         };
473 }
474
475 } // namespace
476
477
478 docstring Counters::labelItem(docstring const & ctr,
479                               docstring const & numbertype) const
480 {
481         CounterList::const_iterator const cit = counterList_.find(ctr);
482         if (cit == counterList_.end()) {
483                 lyxerr << "Counter "
484                        << to_utf8(ctr)
485                        << " does not exist." << endl;
486                 return docstring();
487         }
488
489         int val = cit->second.value();
490
491         if (numbertype == "hebrew")
492                 return docstring(1, hebrewCounter(val));
493
494         if (numbertype == "alph")
495                 return docstring(1, loweralphaCounter(val));
496
497         if (numbertype == "Alph")
498                 return docstring(1, alphaCounter(val));
499
500         if (numbertype == "roman")
501                 return lowerromanCounter(val);
502
503         if (numbertype == "Roman")
504                 return romanCounter(val);
505
506         if (numbertype == "fnsymbol")
507                 return fnsymbolCounter(val);
508
509         return convert<docstring>(val);
510 }
511
512
513 docstring Counters::theCounter(docstring const & counter,
514                                string const & lang) const
515 {
516         CounterList::const_iterator it = counterList_.find(counter);
517         if (it == counterList_.end())
518                 return from_ascii("#");
519         Counter const & ctr = it->second;
520         Counter::StringMap & sm = ctr.flatLabelStrings(appendix());
521         Counter::StringMap::iterator smit = sm.find(lang);
522         if (smit != sm.end())
523                 return counterLabel(smit->second, lang);
524
525         vector<docstring> callers;
526         docstring const & fls = flattenLabelString(counter, appendix(),
527                                                    lang, callers);
528         sm[lang] = fls;
529         return counterLabel(fls, lang);
530 }
531
532
533 docstring Counters::flattenLabelString(docstring const & counter,
534                                        bool in_appendix,
535                                        string const & lang,
536                                        vector<docstring> & callers) const
537 {
538         if (find(callers.begin(), callers.end(), counter) != callers.end()) {
539                 // recursion detected
540                 lyxerr << "Warning: Recursion in label for counter `"
541                        << counter << "' detected"
542                        << endl;
543                 return from_ascii("??");
544         }
545
546         CounterList::const_iterator it = counterList_.find(counter);
547         if (it == counterList_.end())
548                 return from_ascii("#");
549         Counter const & c = it->second;
550
551         docstring ls = translateIfPossible(c.labelString(in_appendix), lang);
552
553         callers.push_back(counter);
554         if (ls.empty()) {
555                 if (!c.master().empty())
556                         ls = flattenLabelString(c.master(), in_appendix, lang, callers)
557                                 + from_ascii(".");
558                 callers.pop_back();
559                 return ls + from_ascii("\\arabic{") + counter + "}";
560         }
561
562         while (true) {
563                 //lyxerr << "ls=" << to_utf8(ls) << endl;
564                 size_t const i = ls.find(from_ascii("\\the"), 0);
565                 if (i == docstring::npos)
566                         break;
567                 size_t const j = i + 4;
568                 size_t k = j;
569                 while (k < ls.size() && lowercase(ls[k]) >= 'a'
570                        && lowercase(ls[k]) <= 'z')
571                         ++k;
572                 docstring const newc = ls.substr(j, k - j);
573                 docstring const repl = flattenLabelString(newc, in_appendix,
574                                                           lang, callers);
575                 ls.replace(i, k - j + 4, repl);
576         }
577         callers.pop_back();
578
579         return ls;
580 }
581
582
583 docstring Counters::counterLabel(docstring const & format,
584                                  string const & lang) const
585 {
586         docstring label = format;
587
588         // FIXME: Using regexps would be better, but we compile boost without
589         // wide regexps currently.
590         docstring const the = from_ascii("\\the");
591         while (true) {
592                 //lyxerr << "label=" << label << endl;
593                 size_t const i = label.find(the, 0);
594                 if (i == docstring::npos)
595                         break;
596                 size_t const j = i + 4;
597                 size_t k = j;
598                 while (k < label.size() && lowercase(label[k]) >= 'a'
599                        && lowercase(label[k]) <= 'z')
600                         ++k;
601                 docstring const newc(label, j, k - j);
602                 label.replace(i, k - i, theCounter(newc, lang));
603         }
604         while (true) {
605                 //lyxerr << "label=" << label << endl;
606
607                 size_t const i = label.find('\\', 0);
608                 if (i == docstring::npos)
609                         break;
610                 size_t const j = label.find('{', i + 1);
611                 if (j == docstring::npos)
612                         break;
613                 size_t const k = label.find('}', j + 1);
614                 if (k == docstring::npos)
615                         break;
616                 docstring const numbertype(label, i + 1, j - i - 1);
617                 docstring const counter(label, j + 1, k - j - 1);
618                 label.replace(i, k + 1 - i, labelItem(counter, numbertype));
619         }
620         //lyxerr << "DONE! label=" << label << endl;
621         return label;
622 }
623
624
625 docstring Counters::prettyCounter(docstring const & name,
626                                string const & lang) const
627 {
628         CounterList::const_iterator it = counterList_.find(name);
629         if (it == counterList_.end())
630                 return from_ascii("#");
631         Counter const & ctr = it->second;
632
633         docstring const value = theCounter(name, lang);
634         docstring const & format =
635             translateIfPossible(ctr.prettyFormat(), lang);
636         if (format.empty())
637                 return value;
638         return subst(format, from_ascii("##"), value);
639 }
640
641
642 docstring Counters::currentCounter() const
643 {
644         LBUFERR(!counter_stack_.empty());
645         return counter_stack_.back();
646 }
647
648
649 void Counters::setActiveLayout(Layout const & lay)
650 {
651         LASSERT(!layout_stack_.empty(), return);
652         Layout const * const lastlay = layout_stack_.back();
653         // we want to check whether the layout has changed and, if so,
654         // whether we are coming out of or going into an environment.
655         if (!lastlay) {
656                 layout_stack_.pop_back();
657                 layout_stack_.push_back(&lay);
658                 if (lay.isEnvironment())
659                         beginEnvironment();
660         } else if (lastlay->name() != lay.name()) {
661                 layout_stack_.pop_back();
662                 layout_stack_.push_back(&lay);
663                 if (lastlay->isEnvironment()) {
664                         // we are coming out of an environment
665                         // LYXERR0("Out: " << lastlay->name());
666                         endEnvironment();
667                 }
668                 if (lay.isEnvironment()) {
669                         // we are going into a new environment
670                         // LYXERR0("In: " << lay.name());
671                         beginEnvironment();
672                 }
673         }
674 }
675
676
677 void Counters::beginEnvironment()
678 {
679         counter_stack_.push_back(counter_stack_.back());
680 }
681
682
683 void Counters::endEnvironment()
684 {
685         LASSERT(!counter_stack_.empty(), return);
686         counter_stack_.pop_back();
687 }
688
689
690 } // namespace lyx