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