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