]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
Abdel is right.
[lyx.git] / src / TextClass.cpp
1 /**
2  * \file TextClass.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 Jean-Marc Lasgouttes
8  * \author Angus Leeming
9  * \author John Levon
10  * \author André Pönitz
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "TextClass.h"
18
19 #include "BaseClassList.h"
20 #include "Color.h"
21 #include "Counters.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "Layout.h"
25 #include "Lexer.h"
26 #include "Font.h"
27
28 #include "frontends/alert.h"
29
30 #include "support/debug.h"
31 #include "support/ExceptionMessage.h"
32 #include "support/FileName.h"
33 #include "support/filetools.h"
34 #include "support/gettext.h"
35 #include "support/lstrings.h"
36 #include "support/os.h"
37
38 #include <sstream>
39
40 using namespace std;
41 using namespace lyx::support;
42
43 namespace lyx {
44
45 namespace {
46
47 class LayoutNamesEqual : public unary_function<Layout, bool> {
48 public:
49         LayoutNamesEqual(docstring const & name)
50                 : name_(name)
51         {}
52         bool operator()(Layout const & c) const
53         {
54                 return c.name() == name_;
55         }
56 private:
57         docstring name_;
58 };
59
60
61 int const FORMAT = 6;
62
63
64 bool layout2layout(FileName const & filename, FileName const & tempfile)
65 {
66         FileName const script = libFileSearch("scripts", "layout2layout.py");
67         if (script.empty()) {
68                 lyxerr << "Could not find layout conversion "
69                           "script layout2layout.py." << endl;
70                 return false;
71         }
72
73         ostringstream command;
74         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
75                 << ' ' << quoteName(filename.toFilesystemEncoding())
76                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
77         string const command_str = command.str();
78
79         LYXERR(Debug::TCLASS, "Running `" << command_str << '\'');
80
81         cmd_ret const ret =
82                 runCommand(command_str);
83         if (ret.first != 0) {
84                 lyxerr << "Could not run layout conversion "
85                           "script layout2layout.py." << endl;
86                 return false;
87         }
88         return true;
89 }
90
91
92 std::string translateRT(TextClass::ReadType rt) 
93 {
94         switch (rt) {
95         case TextClass::BASECLASS:
96                 return "textclass";
97         case TextClass::MERGE:
98                 return "input file";
99         case TextClass::MODULE:
100                 return "module file";
101         }
102         // shutup warning
103         return string();
104 }
105
106 } // namespace anon
107
108
109 docstring const TextClass::emptylayout_ = from_ascii("PlainLayout");
110
111
112 InsetLayout DocumentClass::empty_insetlayout_;
113
114
115 TextClass::TextClass()
116 {
117         floatlist_ = boost::shared_ptr<FloatList>(new FloatList);
118         counters_ = boost::shared_ptr<Counters>(new Counters);
119         outputType_ = LATEX;
120         columns_ = 1;
121         sides_ = OneSide;
122         secnumdepth_ = 3;
123         tocdepth_ = 3;
124         pagestyle_ = "default";
125         defaultfont_ = sane_font;
126         opt_fontsize_ = "10|11|12";
127         opt_pagestyle_ = "empty|plain|headings|fancy";
128         titletype_ = TITLE_COMMAND_AFTER;
129         titlename_ = "maketitle";
130         loaded_ = false;
131         // a hack to make this available for translation
132         // i'm sure there must be a better way (rgh)
133         _("PlainLayout");
134 }
135
136
137 bool TextClass::readStyle(Lexer & lexrc, Layout & lay)
138 {
139         LYXERR(Debug::TCLASS, "Reading style " << to_utf8(lay.name()));
140         if (!lay.read(lexrc, *this)) {
141                 lyxerr << "Error parsing style `" << to_utf8(lay.name()) << '\'' << endl;
142                 return false;
143         }
144         // Resolve fonts
145         lay.resfont = lay.font;
146         lay.resfont.realize(defaultfont_);
147         lay.reslabelfont = lay.labelfont;
148         lay.reslabelfont.realize(defaultfont_);
149         return true; // no errors
150 }
151
152
153 enum TextClassTags {
154         TC_OUTPUTTYPE = 1,
155         TC_INPUT,
156         TC_STYLE,
157         TC_DEFAULTSTYLE,
158         TC_INSETLAYOUT,
159         TC_ENVIRONMENT,
160         TC_NOSTYLE,
161         TC_COLUMNS,
162         TC_SIDES,
163         TC_PAGESTYLE,
164         TC_DEFAULTFONT,
165         TC_SECNUMDEPTH,
166         TC_TOCDEPTH,
167         TC_CLASSOPTIONS,
168         TC_PREAMBLE,
169         TC_PROVIDES,
170         TC_REQUIRES,
171         TC_LEFTMARGIN,
172         TC_RIGHTMARGIN,
173         TC_FLOAT,
174         TC_COUNTER,
175         TC_NOFLOAT,
176         TC_TITLELATEXNAME,
177         TC_TITLELATEXTYPE,
178         TC_FORMAT
179 };
180
181
182 // Reads a textclass structure from file.
183 bool TextClass::read(FileName const & filename, ReadType rt)
184 {
185         if (!filename.isReadableFile()) {
186                 lyxerr << "Cannot read layout file `" << filename << "'."
187                        << endl;
188                 return false;
189         }
190
191         keyword_item textClassTags[] = {
192                 { "classoptions",    TC_CLASSOPTIONS },
193                 { "columns",         TC_COLUMNS },
194                 { "counter",         TC_COUNTER },
195                 { "defaultfont",     TC_DEFAULTFONT },
196                 { "defaultstyle",    TC_DEFAULTSTYLE },
197                 { "environment",     TC_ENVIRONMENT },
198                 { "float",           TC_FLOAT },
199                 { "format",          TC_FORMAT },
200                 { "input",           TC_INPUT },
201                 { "insetlayout",     TC_INSETLAYOUT },
202                 { "leftmargin",      TC_LEFTMARGIN },
203                 { "nofloat",         TC_NOFLOAT },
204                 { "nostyle",         TC_NOSTYLE },
205                 { "outputtype",      TC_OUTPUTTYPE },
206                 { "pagestyle",       TC_PAGESTYLE },
207                 { "preamble",        TC_PREAMBLE },
208                 { "provides",        TC_PROVIDES },
209                 { "requires",        TC_REQUIRES },
210                 { "rightmargin",     TC_RIGHTMARGIN },
211                 { "secnumdepth",     TC_SECNUMDEPTH },
212                 { "sides",           TC_SIDES },
213                 { "style",           TC_STYLE },
214                 { "titlelatexname",  TC_TITLELATEXNAME },
215                 { "titlelatextype",  TC_TITLELATEXTYPE },
216                 { "tocdepth",        TC_TOCDEPTH }
217         };
218
219         LYXERR(Debug::TCLASS, "Reading " + translateRT(rt) + ": " +
220                 to_utf8(makeDisplayPath(filename.absFilename())));
221
222         // Define the `empty' layout used in table cells, ert, etc. Note that 
223         // we do this before loading any layout file, so that classes can 
224         // override features of this layout if they should choose to do so.
225         if (rt == BASECLASS) {
226                 static char const * s = "Margin Static\n"
227                         "LatexType Paragraph\n"
228                         "LatexName dummy\n"
229                         "Align Block\n"
230                         "AlignPossible Left, Right, Center\n"
231                         "LabelType No_Label\n"
232                         "End";
233                 istringstream ss(s);
234                 Lexer lex(textClassTags, sizeof(textClassTags) / sizeof(textClassTags[0]));
235                 lex.setStream(ss);
236                 Layout lay;
237                 lay.setName(emptylayout_);
238                 if (!readStyle(lex, lay)) {
239                         // The only way this happens is because the hardcoded layout above
240                         // is wrong.
241                         BOOST_ASSERT(false);
242                 };
243                 layoutlist_.push_back(lay);
244         }
245
246         Lexer lexrc(textClassTags,
247                 sizeof(textClassTags) / sizeof(textClassTags[0]));
248
249         lexrc.setFile(filename);
250         bool error = !lexrc.isOK();
251
252         // Format of files before the 'Format' tag was introduced
253         int format = 1;
254
255         // parsing
256         while (lexrc.isOK() && !error) {
257                 int le = lexrc.lex();
258
259                 switch (le) {
260                 case Lexer::LEX_FEOF:
261                         continue;
262
263                 case Lexer::LEX_UNDEF:
264                         lexrc.printError("Unknown TextClass tag `$$Token'");
265                         error = true;
266                         continue;
267
268                 default:
269                         break;
270                 }
271
272                 switch (static_cast<TextClassTags>(le)) {
273
274                 case TC_FORMAT:
275                         if (lexrc.next())
276                                 format = lexrc.getInteger();
277                         break;
278
279                 case TC_OUTPUTTYPE:   // output type definition
280                         readOutputType(lexrc);
281                         break;
282
283                 case TC_INPUT: // Include file
284                         if (lexrc.next()) {
285                                 string const inc = lexrc.getString();
286                                 FileName tmp = libFileSearch("layouts", inc,
287                                                             "layout");
288
289                                 if (tmp.empty()) {
290                                         lexrc.printError("Could not find input file: " + inc);
291                                         error = true;
292                                 } else if (!read(tmp, MERGE)) {
293                                         lexrc.printError("Error reading input"
294                                                          "file: " + tmp.absFilename());
295                                         error = true;
296                                 }
297                         }
298                         break;
299
300                 case TC_DEFAULTSTYLE:
301                         if (lexrc.next()) {
302                                 docstring const name = from_utf8(subst(lexrc.getString(),
303                                                           '_', ' '));
304                                 defaultlayout_ = name;
305                         }
306                         break;
307
308                 case TC_ENVIRONMENT:
309                 case TC_STYLE:
310                         if (lexrc.next()) {
311                                 docstring const name = from_utf8(subst(lexrc.getString(),
312                                                     '_', ' '));
313                                 if (name.empty()) {
314                                         string s = "Could not read name for style: `$$Token' "
315                                                 + lexrc.getString() + " is probably not valid UTF-8!";
316                                         lexrc.printError(s.c_str());
317                                         Layout lay;
318                                         //FIXME If we're just dropping this layout, do we really
319                                         //care whether there's an error?? Or should we just set
320                                         //error to true, since we couldn't even read the name?
321                                         error = !readStyle(lexrc, lay);
322                                 } else if (hasLayout(name)) {
323                                         Layout & lay = operator[](name);
324                                         error = !readStyle(lexrc, lay);
325                                 } else {
326                                         Layout lay;
327                                         lay.setName(name);
328                                         if (le == TC_ENVIRONMENT)
329                                                 lay.is_environment = true;
330                                         error = !readStyle(lexrc, lay);
331                                         if (!error)
332                                                 layoutlist_.push_back(lay);
333
334                                         if (defaultlayout_.empty()) {
335                                                 // We do not have a default layout yet, so we choose
336                                                 // the first layout we encounter.
337                                                 defaultlayout_ = name;
338                                         }
339                                 }
340                         }
341                         else {
342                                 //FIXME Should we also eat the style here? viz:
343                                 //Layout lay;
344                                 //readStyle(lexrc, lay);
345                                 //as above...
346                                 lexrc.printError("No name given for style: `$$Token'.");
347                                 error = true;
348                         }
349                         break;
350
351                 case TC_NOSTYLE:
352                         if (lexrc.next()) {
353                                 docstring const style = from_utf8(subst(lexrc.getString(),
354                                                      '_', ' '));
355                                 if (!deleteLayout(style))
356                                         lyxerr << "Cannot delete style `"
357                                                << to_utf8(style) << '\'' << endl;
358                         }
359                         break;
360
361                 case TC_COLUMNS:
362                         if (lexrc.next())
363                                 columns_ = lexrc.getInteger();
364                         break;
365
366                 case TC_SIDES:
367                         if (lexrc.next()) {
368                                 switch (lexrc.getInteger()) {
369                                 case 1: sides_ = OneSide; break;
370                                 case 2: sides_ = TwoSides; break;
371                                 default:
372                                         lyxerr << "Impossible number of page"
373                                                 " sides, setting to one."
374                                                << endl;
375                                         sides_ = OneSide;
376                                         break;
377                                 }
378                         }
379                         break;
380
381                 case TC_PAGESTYLE:
382                         lexrc.next();
383                         pagestyle_ = rtrim(lexrc.getString());
384                         break;
385
386                 case TC_DEFAULTFONT:
387                         defaultfont_ = lyxRead(lexrc);
388                         if (!defaultfont_.resolved()) {
389                                 lexrc.printError("Warning: defaultfont should "
390                                                  "be fully instantiated!");
391                                 defaultfont_.realize(sane_font);
392                         }
393                         break;
394
395                 case TC_SECNUMDEPTH:
396                         lexrc.next();
397                         secnumdepth_ = lexrc.getInteger();
398                         break;
399
400                 case TC_TOCDEPTH:
401                         lexrc.next();
402                         tocdepth_ = lexrc.getInteger();
403                         break;
404
405                 // First step to support options
406                 case TC_CLASSOPTIONS:
407                         readClassOptions(lexrc);
408                         break;
409
410                 case TC_PREAMBLE:
411                         preamble_ = from_utf8(lexrc.getLongString("EndPreamble"));
412                         break;
413
414                 case TC_PROVIDES: {
415                         lexrc.next();
416                         string const feature = lexrc.getString();
417                         lexrc.next();
418                         if (lexrc.getInteger())
419                                 provides_.insert(feature);
420                         else
421                                 provides_.erase(feature);
422                         break;
423                 }
424
425                 case TC_REQUIRES: {
426                         lexrc.eatLine();
427                         vector<string> const req 
428                                 = getVectorFromString(lexrc.getString());
429                         requires_.insert(req.begin(), req.end());
430                         break;
431                 }
432
433                 case TC_LEFTMARGIN:     // left margin type
434                         if (lexrc.next())
435                                 leftmargin_ = lexrc.getDocString();
436                         break;
437
438                 case TC_RIGHTMARGIN:    // right margin type
439                         if (lexrc.next())
440                                 rightmargin_ = lexrc.getDocString();
441                         break;
442
443                 case TC_INSETLAYOUT:
444                         if (lexrc.next()) {
445                                 InsetLayout il;
446                                 if (il.read(lexrc)) {
447                                         insetlayoutlist_[il.name()] = il;
448                                 }
449                                 // else there was an error, so forget it
450                         }
451                         break;
452
453                 case TC_FLOAT:
454                         readFloat(lexrc);
455                         break;
456
457                 case TC_COUNTER:
458                         readCounter(lexrc);
459                         break;
460
461                 case TC_TITLELATEXTYPE:
462                         readTitleType(lexrc);
463                         break;
464
465                 case TC_TITLELATEXNAME:
466                         if (lexrc.next())
467                                 titlename_ = lexrc.getString();
468                         break;
469
470                 case TC_NOFLOAT:
471                         if (lexrc.next()) {
472                                 string const nofloat = lexrc.getString();
473                                 floatlist_->erase(nofloat);
474                         }
475                         break;
476                 }
477
478                 //Note that this is triggered the first time through the loop unless
479                 //we hit a format tag.
480                 if (format != FORMAT)
481                         break;
482         }
483
484         if (format != FORMAT) {
485                 LYXERR(Debug::TCLASS, "Converting layout file from format "
486                                       << format << " to " << FORMAT);
487                 FileName const tempfile = FileName::tempName();
488                 bool success = layout2layout(filename, tempfile);
489                 if (success)
490                          read(tempfile, rt);
491                 tempfile.removeFile();
492                 return success;
493         }
494
495         LYXERR(Debug::TCLASS, "Finished reading " + translateRT(rt) + ": " +
496                         to_utf8(makeDisplayPath(filename.absFilename())));
497
498         if (rt != BASECLASS) 
499                 return !error;
500
501         if (defaultlayout_.empty()) {
502                 lyxerr << "Error: Textclass '" << name_
503                                                 << "' is missing a defaultstyle." << endl;
504                 error = true;
505         }
506                 
507         //Try to erase "stdinsets" from the provides_ set. 
508         //The
509         //  Provides stdinsets 1
510         //declaration simply tells us that the standard insets have been
511         //defined. (It's found in stdinsets.inc but could also be used in
512         //user-defined files.) There isn't really any such package. So we
513         //might as well go ahead and erase it.
514         //If we do not succeed, then it was not there, which means that
515         //the textclass did not provide the definitions of the standard
516         //insets. So we need to try to load them.
517         int erased = provides_.erase("stdinsets");
518         if (!erased) {
519                 FileName tmp = libFileSearch("layouts", "stdinsets.inc");
520
521                 if (tmp.empty()) {
522                         throw ExceptionMessage(WarningException, _("Missing File"),
523                                 _("Could not find stdinsets.inc! This may lead to data loss!"));
524                         error = true;
525                 } else if (!read(tmp, MERGE)) {
526                         throw ExceptionMessage(WarningException, _("Corrupt File"),
527                                 _("Could not read stdinsets.inc! This may lead to data loss!"));
528                         error = true;
529                 }
530         }
531
532         min_toclevel_ = Layout::NOT_IN_TOC;
533         max_toclevel_ = Layout::NOT_IN_TOC;
534         const_iterator lit = begin();
535         const_iterator len = end();
536         for (; lit != len; ++lit) {
537                 int const toclevel = lit->toclevel;
538                 if (toclevel != Layout::NOT_IN_TOC) {
539                         if (min_toclevel_ == Layout::NOT_IN_TOC)
540                                 min_toclevel_ = toclevel;
541                         else
542                                 min_toclevel_ = min(min_toclevel_, toclevel);
543                         max_toclevel_ = max(max_toclevel_, toclevel);
544                 }
545         }
546         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
547                 << ", maximum is " << max_toclevel_);
548
549         return !error;
550 }
551
552
553 void TextClass::readTitleType(Lexer & lexrc)
554 {
555         keyword_item titleTypeTags[] = {
556                 { "commandafter", TITLE_COMMAND_AFTER },
557                 { "environment", TITLE_ENVIRONMENT }
558         };
559
560         PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
561
562         int le = lexrc.lex();
563         switch (le) {
564         case Lexer::LEX_UNDEF:
565                 lexrc.printError("Unknown output type `$$Token'");
566                 return;
567         case TITLE_COMMAND_AFTER:
568         case TITLE_ENVIRONMENT:
569                 titletype_ = static_cast<TitleLatexType>(le);
570                 break;
571         default:
572                 lyxerr << "Unhandled value " << le
573                        << " in TextClass::readTitleType." << endl;
574
575                 break;
576         }
577 }
578
579
580 void TextClass::readOutputType(Lexer & lexrc)
581 {
582         keyword_item outputTypeTags[] = {
583                 { "docbook", DOCBOOK },
584                 { "latex", LATEX },
585                 { "literate", LITERATE }
586         };
587
588         PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
589
590         int le = lexrc.lex();
591         switch (le) {
592         case Lexer::LEX_UNDEF:
593                 lexrc.printError("Unknown output type `$$Token'");
594                 return;
595         case LATEX:
596         case DOCBOOK:
597         case LITERATE:
598                 outputType_ = static_cast<OutputType>(le);
599                 break;
600         default:
601                 lyxerr << "Unhandled value " << le
602                        << " in TextClass::readOutputType." << endl;
603
604                 break;
605         }
606 }
607
608
609 enum ClassOptionsTags {
610         CO_FONTSIZE = 1,
611         CO_PAGESTYLE,
612         CO_OTHER,
613         CO_HEADER,
614         CO_END
615 };
616
617
618 void TextClass::readClassOptions(Lexer & lexrc)
619 {
620         keyword_item classOptionsTags[] = {
621                 {"end", CO_END },
622                 {"fontsize", CO_FONTSIZE },
623                 {"header", CO_HEADER },
624                 {"other", CO_OTHER },
625                 {"pagestyle", CO_PAGESTYLE }
626         };
627
628         lexrc.pushTable(classOptionsTags, CO_END);
629         bool getout = false;
630         while (!getout && lexrc.isOK()) {
631                 int le = lexrc.lex();
632                 switch (le) {
633                 case Lexer::LEX_UNDEF:
634                         lexrc.printError("Unknown ClassOption tag `$$Token'");
635                         continue;
636                 default: break;
637                 }
638                 switch (static_cast<ClassOptionsTags>(le)) {
639                 case CO_FONTSIZE:
640                         lexrc.next();
641                         opt_fontsize_ = rtrim(lexrc.getString());
642                         break;
643                 case CO_PAGESTYLE:
644                         lexrc.next();
645                         opt_pagestyle_ = rtrim(lexrc.getString());
646                         break;
647                 case CO_OTHER:
648                         lexrc.next();
649                         options_ = lexrc.getString();
650                         break;
651                 case CO_HEADER:
652                         lexrc.next();
653                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
654                         break;
655                 case CO_END:
656                         getout = true;
657                         break;
658                 }
659         }
660         lexrc.popTable();
661 }
662
663
664 enum FloatTags {
665         FT_TYPE = 1,
666         FT_NAME,
667         FT_PLACEMENT,
668         FT_EXT,
669         FT_WITHIN,
670         FT_STYLE,
671         FT_LISTNAME,
672         FT_BUILTIN,
673         FT_END
674 };
675
676
677 void TextClass::readFloat(Lexer & lexrc)
678 {
679         keyword_item floatTags[] = {
680                 { "end", FT_END },
681                 { "extension", FT_EXT },
682                 { "guiname", FT_NAME },
683                 { "latexbuiltin", FT_BUILTIN },
684                 { "listname", FT_LISTNAME },
685                 { "numberwithin", FT_WITHIN },
686                 { "placement", FT_PLACEMENT },
687                 { "style", FT_STYLE },
688                 { "type", FT_TYPE }
689         };
690
691         lexrc.pushTable(floatTags, FT_END);
692
693         string type;
694         string placement;
695         string ext;
696         string within;
697         string style;
698         string name;
699         string listName;
700         bool builtin = false;
701
702         bool getout = false;
703         while (!getout && lexrc.isOK()) {
704                 int le = lexrc.lex();
705                 switch (le) {
706                 case Lexer::LEX_UNDEF:
707                         lexrc.printError("Unknown float tag `$$Token'");
708                         continue;
709                 default: break;
710                 }
711                 switch (static_cast<FloatTags>(le)) {
712                 case FT_TYPE:
713                         lexrc.next();
714                         type = lexrc.getString();
715                         if (floatlist_->typeExist(type)) {
716                                 Floating const & fl = floatlist_->getType(type);
717                                 placement = fl.placement();
718                                 ext = fl.ext();
719                                 within = fl.within();
720                                 style = fl.style();
721                                 name = fl.name();
722                                 listName = fl.listName();
723                                 builtin = fl.builtin();
724                         } 
725                         break;
726                 case FT_NAME:
727                         lexrc.next();
728                         name = lexrc.getString();
729                         break;
730                 case FT_PLACEMENT:
731                         lexrc.next();
732                         placement = lexrc.getString();
733                         break;
734                 case FT_EXT:
735                         lexrc.next();
736                         ext = lexrc.getString();
737                         break;
738                 case FT_WITHIN:
739                         lexrc.next();
740                         within = lexrc.getString();
741                         if (within == "none")
742                                 within.erase();
743                         break;
744                 case FT_STYLE:
745                         lexrc.next();
746                         style = lexrc.getString();
747                         break;
748                 case FT_LISTNAME:
749                         lexrc.next();
750                         listName = lexrc.getString();
751                         break;
752                 case FT_BUILTIN:
753                         lexrc.next();
754                         builtin = lexrc.getBool();
755                         break;
756                 case FT_END:
757                         getout = true;
758                         break;
759                 }
760         }
761
762         // Here if have a full float if getout == true
763         if (getout) {
764                 Floating fl(type, placement, ext, within,
765                             style, name, listName, builtin);
766                 floatlist_->newFloat(fl);
767                 // each float has its own counter
768                 counters_->newCounter(from_ascii(type), from_ascii(within),
769                                       docstring(), docstring());
770                 // also define sub-float counters
771                 docstring const subtype = "sub-" + from_ascii(type);
772                 counters_->newCounter(subtype, from_ascii(type),
773                                       "\\alph{" + subtype + "}", docstring());
774         }
775
776         lexrc.popTable();
777 }
778
779
780 enum CounterTags {
781         CT_NAME = 1,
782         CT_WITHIN,
783         CT_LABELSTRING,
784         CT_LABELSTRING_APPENDIX,
785         CT_END
786 };
787
788
789 void TextClass::readCounter(Lexer & lexrc)
790 {
791         keyword_item counterTags[] = {
792                 { "end", CT_END },
793                 { "labelstring", CT_LABELSTRING },
794                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
795                 { "name", CT_NAME },
796                 { "within", CT_WITHIN }
797         };
798
799         lexrc.pushTable(counterTags, CT_END);
800
801         docstring name;
802         docstring within;
803         docstring labelstring;
804         docstring labelstring_appendix;
805
806         bool getout = false;
807         while (!getout && lexrc.isOK()) {
808                 int le = lexrc.lex();
809                 switch (le) {
810                 case Lexer::LEX_UNDEF:
811                         lexrc.printError("Unknown counter tag `$$Token'");
812                         continue;
813                 default: break;
814                 }
815                 switch (static_cast<CounterTags>(le)) {
816                 case CT_NAME:
817                         lexrc.next();
818                         name = lexrc.getDocString();
819                         if (counters_->hasCounter(name))
820                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
821                         else
822                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
823                         break;
824                 case CT_WITHIN:
825                         lexrc.next();
826                         within = lexrc.getDocString();
827                         if (within == "none")
828                                 within.erase();
829                         break;
830                 case CT_LABELSTRING:
831                         lexrc.next();
832                         labelstring = lexrc.getDocString();
833                         labelstring_appendix = labelstring;
834                         break;
835                 case CT_LABELSTRING_APPENDIX:
836                         lexrc.next();
837                         labelstring_appendix = lexrc.getDocString();
838                         break;
839                 case CT_END:
840                         getout = true;
841                         break;
842                 }
843         }
844
845         // Here if have a full counter if getout == true
846         if (getout)
847                 counters_->newCounter(name, within, 
848                                       labelstring, labelstring_appendix);
849
850         lexrc.popTable();
851 }
852
853
854 bool TextClass::hasLayout(docstring const & n) const
855 {
856         docstring const name = n.empty() ? defaultLayoutName() : n;
857
858         return find_if(layoutlist_.begin(), layoutlist_.end(),
859                        LayoutNamesEqual(name))
860                 != layoutlist_.end();
861 }
862
863
864
865 Layout const & TextClass::operator[](docstring const & name) const
866 {
867         BOOST_ASSERT(!name.empty());
868
869         const_iterator it = 
870                 find_if(begin(), end(), LayoutNamesEqual(name));
871
872         if (it == end()) {
873                 lyxerr << "We failed to find the layout '" << to_utf8(name)
874                        << "' in the layout list. You MUST investigate!"
875                        << endl;
876                 for (const_iterator cit = begin(); cit != end(); ++cit)
877                         lyxerr  << " " << to_utf8(cit->name()) << endl;
878
879                 // we require the name to exist
880                 BOOST_ASSERT(false);
881         }
882
883         return *it;
884 }
885
886
887 Layout & TextClass::operator[](docstring const & name)
888 {
889         BOOST_ASSERT(!name.empty());
890
891         iterator it = find_if(begin(), end(), LayoutNamesEqual(name));
892
893         if (it == end()) {
894                 lyxerr << "We failed to find the layout '" << to_utf8(name)
895                        << "' in the layout list. You MUST investigate!"
896                        << endl;
897                 for (const_iterator cit = begin(); cit != end(); ++cit)
898                         lyxerr  << " " << to_utf8(cit->name()) << endl;
899
900                 // we require the name to exist
901                 BOOST_ASSERT(false);
902         }
903
904         return *it;
905 }
906
907
908 bool TextClass::deleteLayout(docstring const & name)
909 {
910         if (name == defaultLayoutName() || name == emptyLayoutName())
911                 return false;
912
913         LayoutList::iterator it =
914                 remove_if(layoutlist_.begin(), layoutlist_.end(),
915                           LayoutNamesEqual(name));
916
917         LayoutList::iterator end = layoutlist_.end();
918         bool const ret = (it != end);
919         layoutlist_.erase(it, end);
920         return ret;
921 }
922
923
924 // Load textclass info if not loaded yet
925 bool TextClass::load(string const & path) const
926 {
927         if (loaded_)
928                 return true;
929
930         // Read style-file, provided path is searched before the system ones
931         FileName layout_file;
932         if (!path.empty())
933                 layout_file = FileName(addName(path, name_ + ".layout"));
934         if (layout_file.empty() || !layout_file.exists())
935                 layout_file = libFileSearch("layouts", name_, "layout");
936         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
937
938         if (!loaded_) {
939                 lyxerr << "Error reading `"
940                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
941                        << "'\n(Check `" << name_
942                        << "')\nCheck your installation and "
943                         "try Options/Reconfigure..." << endl;
944         }
945
946         return loaded_;
947 }
948
949
950 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
951 {
952         docstring n = name;
953         while (!n.empty()) {
954                 if (insetlayoutlist_.count(n) > 0)
955                         return insetlayoutlist_[n];
956                 size_t i = n.find(':');
957                 if (i == string::npos)
958                         break;
959                 n = n.substr(0,i);
960         }
961         return empty_insetlayout_;
962 }
963
964
965 docstring const & TextClass::defaultLayoutName() const
966 {
967         // This really should come from the actual layout... (Lgb)
968         return defaultlayout_;
969 }
970
971
972 Layout const & TextClass::defaultLayout() const
973 {
974         return operator[](defaultLayoutName());
975 }
976
977
978 bool TextClass::isDefaultLayout(Layout const & lay) const 
979 {
980         return lay.name() == defaultLayoutName();
981 }
982
983
984 bool TextClass::isEmptyLayout(Layout const & lay) const 
985 {
986         return lay.name() == emptyLayoutName();
987 }
988
989
990 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
991 {
992         DocumentClass dc(baseClass);
993         tc_list_.push_back(dc);
994         return tc_list_.back();
995 }
996
997
998 DocumentClassBundle & DocumentClassBundle::get()
999 {
1000         static DocumentClassBundle singleton; 
1001         return singleton; 
1002 }
1003
1004
1005 DocumentClass::DocumentClass(LayoutFile const & tc)
1006         : TextClass(tc)
1007 {}
1008
1009
1010 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
1011 {
1012         LayoutList::const_iterator it  = layoutlist_.begin();
1013         LayoutList::const_iterator end = layoutlist_.end();
1014         for (; it != end; ++it)
1015                 if (it->latexname() == lay)
1016                         return true;
1017         return false;
1018 }
1019
1020
1021 bool DocumentClass::provides(string const & p) const
1022 {
1023         return provides_.find(p) != provides_.end();
1024 }
1025
1026
1027 bool DocumentClass::hasTocLevels() const
1028 {
1029         return min_toclevel_ != Layout::NOT_IN_TOC;
1030 }
1031
1032
1033 ostream & operator<<(ostream & os, PageSides p)
1034 {
1035         switch (p) {
1036         case OneSide:
1037                 os << '1';
1038                 break;
1039         case TwoSides:
1040                 os << '2';
1041                 break;
1042         }
1043         return os;
1044 }
1045
1046
1047 } // namespace lyx