]> git.lyx.org Git - lyx.git/blob - src/Counters.cpp
Update bindfiles to latest fileformat
[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)
186 {
187         layout_stack_.push_back(0);
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::step(docstring const & ctr, UpdateType utype)
269 {
270         CounterList::iterator it = counterList_.find(ctr);
271         if (it == counterList_.end()) {
272                 lyxerr << "step: Counter does not exist: "
273                        << to_utf8(ctr) << endl;
274                 return;
275         }
276
277         it->second.step();
278         if (utype == OutputUpdate) {
279                 LBUFERR(!counter_stack_.empty());
280                 counter_stack_.pop_back();
281                 counter_stack_.push_back(ctr);
282         }
283         it = counterList_.begin();
284         CounterList::iterator const end = counterList_.end();
285         for (; it != end; ++it) {
286                 if (it->second.master() == ctr) {
287                         it->second.reset();
288                 }
289         }
290 }
291
292
293 void Counters::reset()
294 {
295         appendix_ = false;
296         subfloat_ = false;
297         current_float_.erase();
298         CounterList::iterator it = counterList_.begin();
299         CounterList::iterator const end = counterList_.end();
300         for (; it != end; ++it)
301                 it->second.reset();
302         counter_stack_.clear();
303         counter_stack_.push_back(from_ascii(""));
304         layout_stack_.clear();
305         layout_stack_.push_back(0);
306 }
307
308
309 void Counters::reset(docstring const & match)
310 {
311         LASSERT(!match.empty(), return);
312
313         CounterList::iterator it = counterList_.begin();
314         CounterList::iterator end = counterList_.end();
315         for (; it != end; ++it) {
316                 if (it->first.find(match) != string::npos)
317                         it->second.reset();
318         }
319 }
320
321
322 bool Counters::remove(docstring const & cnt)
323 {
324         bool retval = counterList_.erase(cnt);
325         if (!retval)
326                 return false;
327         CounterList::iterator it = counterList_.begin();
328         CounterList::iterator end = counterList_.end();
329         for (; it != end; ++it) {
330                 if (it->second.checkAndRemoveMaster(cnt))
331                         LYXERR(Debug::TCLASS, "Removed master counter `" +
332                                         to_utf8(cnt) + "' from counter: " + to_utf8(it->first));
333         }
334         return retval;
335 }
336
337
338 void Counters::copy(Counters & from, Counters & to, docstring const & match)
339 {
340         CounterList::iterator it = counterList_.begin();
341         CounterList::iterator end = counterList_.end();
342         for (; it != end; ++it) {
343                 if (it->first.find(match) != string::npos || match == "") {
344                         to.set(it->first, from.value(it->first));
345                 }
346         }
347 }
348
349
350 namespace {
351
352 char loweralphaCounter(int const n)
353 {
354         if (n < 1 || n > 26)
355                 return '?';
356         return 'a' + n - 1;
357 }
358
359
360 char alphaCounter(int const n)
361 {
362         if (n < 1 || n > 26)
363                 return '?';
364         return 'A' + n - 1;
365 }
366
367
368 char hebrewCounter(int const n)
369 {
370         static const char hebrew[22] = {
371                 '\xe0', '\xe1', '\xe2', '\xe3', '\xe4', '\xe5', '\xe6', '\xe7', '\xe8',
372                 '\xe9', '\xeb', '\xec', '\xee', '\xf0', '\xf1', '\xf2', '\xf4', '\xf6',
373                 '\xf7', '\xf8', '\xf9', '\xfa'
374         };
375
376         if (n < 1 || n > 22)
377                 return '?';
378         return hebrew[n - 1];
379 }
380
381
382 // On the special cases, see http://mathworld.wolfram.com/RomanNumerals.html
383 // and for a list of roman numerals up to and including 3999, see 
384 // http://www.research.att.com/~njas/sequences/a006968.txt. (Thanks to Joost
385 // for this info.)
386 docstring const romanCounter(int const n)
387 {
388         static char const * const ones[9] = {
389                 "I",   "II",  "III", "IV", "V",
390                 "VI",  "VII", "VIII", "IX"
391         };
392         
393         static char const * const tens[9] = {
394                 "X", "XX", "XXX", "XL", "L",
395                 "LX", "LXX", "LXXX", "XC"
396         };
397         
398         static char const * const hunds[9] = {
399                 "C", "CC", "CCC", "CD", "D",
400                 "DC", "DCC", "DCCC", "CM"
401         };
402         
403         if (n > 1000 || n < 1) 
404                 return from_ascii("??");
405         
406         int val = n;
407         string roman;
408         switch (n) {
409         //special cases
410         case 900: 
411                 roman = "CM";
412                 break;
413         case 400:
414                 roman = "CD";
415                 break;
416         default:
417                 if (val >= 100) {
418                         int hundreds = val / 100;
419                         roman = hunds[hundreds - 1];
420                         val = val % 100;
421                 }
422                 if (val >= 10) {
423                         switch (val) {
424                         //special case
425                         case 90:
426                                 roman = roman + "XC";
427                                 val = 0; //skip next
428                                 break;
429                         default:
430                                 int tensnum = val / 10;
431                                 roman = roman + tens[tensnum - 1];
432                                 val = val % 10;
433                         } // end switch
434                 } // end tens
435                 if (val > 0)
436                         roman = roman + ones[val -1];
437         }
438         return from_ascii(roman);
439 }
440
441
442 docstring const lowerromanCounter(int const n)
443 {
444         return lowercase(romanCounter(n));
445 }
446
447 } // namespace anon
448
449
450 docstring Counters::labelItem(docstring const & ctr,
451                               docstring const & numbertype) const
452 {
453         CounterList::const_iterator const cit = counterList_.find(ctr);
454         if (cit == counterList_.end()) {
455                 lyxerr << "Counter "
456                        << to_utf8(ctr)
457                        << " does not exist." << endl;
458                 return docstring();
459         }
460
461         int val = cit->second.value();
462
463         if (numbertype == "hebrew")
464                 return docstring(1, hebrewCounter(val));
465
466         if (numbertype == "alph")
467                 return docstring(1, loweralphaCounter(val));
468
469         if (numbertype == "Alph")
470                 return docstring(1, alphaCounter(val));
471
472         if (numbertype == "roman")
473                 return lowerromanCounter(val);
474
475         if (numbertype == "Roman")
476                 return romanCounter(val);
477
478         return convert<docstring>(val);
479 }
480
481
482 docstring Counters::theCounter(docstring const & counter,
483                                string const & lang) const
484 {
485         CounterList::const_iterator it = counterList_.find(counter); 
486         if (it == counterList_.end())
487                 return from_ascii("#");
488         Counter const & ctr = it->second;
489         Counter::StringMap & sm = ctr.flatLabelStrings(appendix());
490         Counter::StringMap::iterator smit = sm.find(lang);
491         if (smit != sm.end())
492                 return counterLabel(smit->second, lang);
493
494         vector<docstring> callers;
495         docstring const & fls = flattenLabelString(counter, appendix(),
496                                                    lang, callers);
497         sm[lang] = fls;
498         return counterLabel(fls, lang);
499 }
500
501
502 docstring Counters::flattenLabelString(docstring const & counter, 
503                                        bool in_appendix,
504                                        string const & lang,
505                                        vector<docstring> & callers) const
506 {
507         docstring label;
508
509         if (find(callers.begin(), callers.end(), counter) != callers.end()) {
510                 // recursion detected
511                 lyxerr << "Warning: Recursion in label for counter `"
512                        << counter << "' detected"
513                        << endl;
514                 return from_ascii("??");
515         }
516                 
517         CounterList::const_iterator it = counterList_.find(counter); 
518         if (it == counterList_.end())
519                 return from_ascii("#");
520         Counter const & c = it->second;
521
522         docstring ls = translateIfPossible(c.labelString(in_appendix), lang);
523
524         callers.push_back(counter);
525         if (ls.empty()) {
526                 if (!c.master().empty())
527                         ls = flattenLabelString(c.master(), in_appendix, lang, callers) 
528                                 + from_ascii(".");
529                 callers.pop_back();
530                 return ls + from_ascii("\\arabic{") + counter + "}";
531         }
532
533         while (true) {
534                 //lyxerr << "ls=" << to_utf8(ls) << endl;
535                 size_t const i = ls.find(from_ascii("\\the"), 0);
536                 if (i == docstring::npos)
537                         break;
538                 size_t const j = i + 4;
539                 size_t k = j;
540                 while (k < ls.size() && lowercase(ls[k]) >= 'a' 
541                        && lowercase(ls[k]) <= 'z')
542                         ++k;
543                 docstring const newc = ls.substr(j, k - j);
544                 docstring const repl = flattenLabelString(newc, in_appendix,
545                                                           lang, callers);
546                 ls.replace(i, k - j + 4, repl);
547         }
548         callers.pop_back();
549
550         return ls;
551 }
552
553
554 docstring Counters::counterLabel(docstring const & format,
555                                  string const & lang) const
556 {
557         docstring label = format;
558
559         // FIXME: Using regexps would be better, but we compile boost without
560         // wide regexps currently.
561         docstring const the = from_ascii("\\the");
562         while (true) {
563                 //lyxerr << "label=" << label << endl;
564                 size_t const i = label.find(the, 0);
565                 if (i == docstring::npos)
566                         break;
567                 size_t const j = i + 4;
568                 size_t k = j;
569                 while (k < label.size() && lowercase(label[k]) >= 'a' 
570                        && lowercase(label[k]) <= 'z')
571                         ++k;
572                 docstring const newc(label, j, k - j);
573                 label.replace(i, k - i, theCounter(newc, lang));
574         }
575         while (true) {
576                 //lyxerr << "label=" << label << endl;
577
578                 size_t const i = label.find('\\', 0);
579                 if (i == docstring::npos)
580                         break;
581                 size_t const j = label.find('{', i + 1);
582                 if (j == docstring::npos)
583                         break;
584                 size_t const k = label.find('}', j + 1);
585                 if (k == docstring::npos)
586                         break;
587                 docstring const numbertype(label, i + 1, j - i - 1);
588                 docstring const counter(label, j + 1, k - j - 1);
589                 label.replace(i, k + 1 - i, labelItem(counter, numbertype));
590         }
591         //lyxerr << "DONE! label=" << label << endl;
592         return label;
593 }
594
595
596 docstring Counters::prettyCounter(docstring const & name,
597                                string const & lang) const
598 {
599         CounterList::const_iterator it = counterList_.find(name); 
600         if (it == counterList_.end())
601                 return from_ascii("#");
602         Counter const & ctr = it->second;
603
604         docstring const value = theCounter(name, lang);
605         docstring const & format =
606             translateIfPossible(ctr.prettyFormat(), lang);
607         if (format.empty())
608                 return value;
609         return subst(format, from_ascii("##"), value);
610 }
611
612
613 docstring Counters::currentCounter() const
614
615         LBUFERR(!counter_stack_.empty());
616         return counter_stack_.back(); 
617 }
618
619
620 void Counters::setActiveLayout(Layout const & lay)
621 {
622         LASSERT(!layout_stack_.empty(), return);
623         Layout const * const lastlay = layout_stack_.back();
624         // we want to check whether the layout has changed and, if so,
625         // whether we are coming out of or going into an environment.
626         if (!lastlay) { 
627                 layout_stack_.pop_back();
628                 layout_stack_.push_back(&lay);
629                 if (lay.isEnvironment())
630                         beginEnvironment();
631         } else if (lastlay->name() != lay.name()) {
632                 layout_stack_.pop_back();
633                 layout_stack_.push_back(&lay);
634                 if (lastlay->isEnvironment()) {
635                         // we are coming out of an environment
636                         // LYXERR0("Out: " << lastlay->name());
637                         endEnvironment();
638                 }
639                 if (lay.isEnvironment()) {
640                         // we are going into a new environment
641                         // LYXERR0("In: " << lay.name());
642                         beginEnvironment();
643                 }
644         } 
645 }
646
647
648 void Counters::beginEnvironment()
649 {
650         counter_stack_.push_back(counter_stack_.back());
651 }
652
653
654 void Counters::endEnvironment()
655 {
656         LASSERT(!counter_stack_.empty(), return);
657         counter_stack_.pop_back();
658 }
659
660
661 } // namespace lyx