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