]> git.lyx.org Git - lyx.git/blob - src/TextClass.cpp
do what the FIXME suggested
[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<LayoutPtr, bool> {
48 public:
49         LayoutNamesEqual(docstring const & name)
50                 : name_(name)
51         {}
52         bool operator()(LayoutPtr 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(boost::shared_ptr<Layout>(new Layout(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).get();
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(boost::shared_ptr<Layout>(new Layout(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         for (size_t i = 0; i != layoutCount(); ++i) {
535                 int const toclevel = layout(i)->toclevel;
536                 if (toclevel != Layout::NOT_IN_TOC) {
537                         if (min_toclevel_ == Layout::NOT_IN_TOC)
538                                 min_toclevel_ = toclevel;
539                         else
540                                 min_toclevel_ = min(min_toclevel_, toclevel);
541                         max_toclevel_ = max(max_toclevel_, toclevel);
542                 }
543         }
544         LYXERR(Debug::TCLASS, "Minimum TocLevel is " << min_toclevel_
545                 << ", maximum is " << max_toclevel_);
546
547         return !error;
548 }
549
550
551 void TextClass::readTitleType(Lexer & lexrc)
552 {
553         keyword_item titleTypeTags[] = {
554                 { "commandafter", TITLE_COMMAND_AFTER },
555                 { "environment", TITLE_ENVIRONMENT }
556         };
557
558         PushPopHelper pph(lexrc, titleTypeTags, TITLE_ENVIRONMENT);
559
560         int le = lexrc.lex();
561         switch (le) {
562         case Lexer::LEX_UNDEF:
563                 lexrc.printError("Unknown output type `$$Token'");
564                 return;
565         case TITLE_COMMAND_AFTER:
566         case TITLE_ENVIRONMENT:
567                 titletype_ = static_cast<TitleLatexType>(le);
568                 break;
569         default:
570                 lyxerr << "Unhandled value " << le
571                        << " in TextClass::readTitleType." << endl;
572
573                 break;
574         }
575 }
576
577
578 void TextClass::readOutputType(Lexer & lexrc)
579 {
580         keyword_item outputTypeTags[] = {
581                 { "docbook", DOCBOOK },
582                 { "latex", LATEX },
583                 { "literate", LITERATE }
584         };
585
586         PushPopHelper pph(lexrc, outputTypeTags, LITERATE);
587
588         int le = lexrc.lex();
589         switch (le) {
590         case Lexer::LEX_UNDEF:
591                 lexrc.printError("Unknown output type `$$Token'");
592                 return;
593         case LATEX:
594         case DOCBOOK:
595         case LITERATE:
596                 outputType_ = static_cast<OutputType>(le);
597                 break;
598         default:
599                 lyxerr << "Unhandled value " << le
600                        << " in TextClass::readOutputType." << endl;
601
602                 break;
603         }
604 }
605
606
607 enum ClassOptionsTags {
608         CO_FONTSIZE = 1,
609         CO_PAGESTYLE,
610         CO_OTHER,
611         CO_HEADER,
612         CO_END
613 };
614
615
616 void TextClass::readClassOptions(Lexer & lexrc)
617 {
618         keyword_item classOptionsTags[] = {
619                 {"end", CO_END },
620                 {"fontsize", CO_FONTSIZE },
621                 {"header", CO_HEADER },
622                 {"other", CO_OTHER },
623                 {"pagestyle", CO_PAGESTYLE }
624         };
625
626         lexrc.pushTable(classOptionsTags, CO_END);
627         bool getout = false;
628         while (!getout && lexrc.isOK()) {
629                 int le = lexrc.lex();
630                 switch (le) {
631                 case Lexer::LEX_UNDEF:
632                         lexrc.printError("Unknown ClassOption tag `$$Token'");
633                         continue;
634                 default: break;
635                 }
636                 switch (static_cast<ClassOptionsTags>(le)) {
637                 case CO_FONTSIZE:
638                         lexrc.next();
639                         opt_fontsize_ = rtrim(lexrc.getString());
640                         break;
641                 case CO_PAGESTYLE:
642                         lexrc.next();
643                         opt_pagestyle_ = rtrim(lexrc.getString());
644                         break;
645                 case CO_OTHER:
646                         lexrc.next();
647                         options_ = lexrc.getString();
648                         break;
649                 case CO_HEADER:
650                         lexrc.next();
651                         class_header_ = subst(lexrc.getString(), "&quot;", "\"");
652                         break;
653                 case CO_END:
654                         getout = true;
655                         break;
656                 }
657         }
658         lexrc.popTable();
659 }
660
661
662 enum FloatTags {
663         FT_TYPE = 1,
664         FT_NAME,
665         FT_PLACEMENT,
666         FT_EXT,
667         FT_WITHIN,
668         FT_STYLE,
669         FT_LISTNAME,
670         FT_BUILTIN,
671         FT_END
672 };
673
674
675 void TextClass::readFloat(Lexer & lexrc)
676 {
677         keyword_item floatTags[] = {
678                 { "end", FT_END },
679                 { "extension", FT_EXT },
680                 { "guiname", FT_NAME },
681                 { "latexbuiltin", FT_BUILTIN },
682                 { "listname", FT_LISTNAME },
683                 { "numberwithin", FT_WITHIN },
684                 { "placement", FT_PLACEMENT },
685                 { "style", FT_STYLE },
686                 { "type", FT_TYPE }
687         };
688
689         lexrc.pushTable(floatTags, FT_END);
690
691         string type;
692         string placement;
693         string ext;
694         string within;
695         string style;
696         string name;
697         string listName;
698         bool builtin = false;
699
700         bool getout = false;
701         while (!getout && lexrc.isOK()) {
702                 int le = lexrc.lex();
703                 switch (le) {
704                 case Lexer::LEX_UNDEF:
705                         lexrc.printError("Unknown float tag `$$Token'");
706                         continue;
707                 default: break;
708                 }
709                 switch (static_cast<FloatTags>(le)) {
710                 case FT_TYPE:
711                         lexrc.next();
712                         type = lexrc.getString();
713                         if (floatlist_->typeExist(type)) {
714                                 Floating const & fl = floatlist_->getType(type);
715                                 placement = fl.placement();
716                                 ext = fl.ext();
717                                 within = fl.within();
718                                 style = fl.style();
719                                 name = fl.name();
720                                 listName = fl.listName();
721                                 builtin = fl.builtin();
722                         } 
723                         break;
724                 case FT_NAME:
725                         lexrc.next();
726                         name = lexrc.getString();
727                         break;
728                 case FT_PLACEMENT:
729                         lexrc.next();
730                         placement = lexrc.getString();
731                         break;
732                 case FT_EXT:
733                         lexrc.next();
734                         ext = lexrc.getString();
735                         break;
736                 case FT_WITHIN:
737                         lexrc.next();
738                         within = lexrc.getString();
739                         if (within == "none")
740                                 within.erase();
741                         break;
742                 case FT_STYLE:
743                         lexrc.next();
744                         style = lexrc.getString();
745                         break;
746                 case FT_LISTNAME:
747                         lexrc.next();
748                         listName = lexrc.getString();
749                         break;
750                 case FT_BUILTIN:
751                         lexrc.next();
752                         builtin = lexrc.getBool();
753                         break;
754                 case FT_END:
755                         getout = true;
756                         break;
757                 }
758         }
759
760         // Here if have a full float if getout == true
761         if (getout) {
762                 Floating fl(type, placement, ext, within,
763                             style, name, listName, builtin);
764                 floatlist_->newFloat(fl);
765                 // each float has its own counter
766                 counters_->newCounter(from_ascii(type), from_ascii(within),
767                                       docstring(), docstring());
768                 // also define sub-float counters
769                 docstring const subtype = "sub-" + from_ascii(type);
770                 counters_->newCounter(subtype, from_ascii(type),
771                                       "\\alph{" + subtype + "}", docstring());
772         }
773
774         lexrc.popTable();
775 }
776
777
778 enum CounterTags {
779         CT_NAME = 1,
780         CT_WITHIN,
781         CT_LABELSTRING,
782         CT_LABELSTRING_APPENDIX,
783         CT_END
784 };
785
786
787 void TextClass::readCounter(Lexer & lexrc)
788 {
789         keyword_item counterTags[] = {
790                 { "end", CT_END },
791                 { "labelstring", CT_LABELSTRING },
792                 { "labelstringappendix", CT_LABELSTRING_APPENDIX },
793                 { "name", CT_NAME },
794                 { "within", CT_WITHIN }
795         };
796
797         lexrc.pushTable(counterTags, CT_END);
798
799         docstring name;
800         docstring within;
801         docstring labelstring;
802         docstring labelstring_appendix;
803
804         bool getout = false;
805         while (!getout && lexrc.isOK()) {
806                 int le = lexrc.lex();
807                 switch (le) {
808                 case Lexer::LEX_UNDEF:
809                         lexrc.printError("Unknown counter tag `$$Token'");
810                         continue;
811                 default: break;
812                 }
813                 switch (static_cast<CounterTags>(le)) {
814                 case CT_NAME:
815                         lexrc.next();
816                         name = lexrc.getDocString();
817                         if (counters_->hasCounter(name))
818                                 LYXERR(Debug::TCLASS, "Reading existing counter " << to_utf8(name));
819                         else
820                                 LYXERR(Debug::TCLASS, "Reading new counter " << to_utf8(name));
821                         break;
822                 case CT_WITHIN:
823                         lexrc.next();
824                         within = lexrc.getDocString();
825                         if (within == "none")
826                                 within.erase();
827                         break;
828                 case CT_LABELSTRING:
829                         lexrc.next();
830                         labelstring = lexrc.getDocString();
831                         labelstring_appendix = labelstring;
832                         break;
833                 case CT_LABELSTRING_APPENDIX:
834                         lexrc.next();
835                         labelstring_appendix = lexrc.getDocString();
836                         break;
837                 case CT_END:
838                         getout = true;
839                         break;
840                 }
841         }
842
843         // Here if have a full counter if getout == true
844         if (getout)
845                 counters_->newCounter(name, within, 
846                                       labelstring, labelstring_appendix);
847
848         lexrc.popTable();
849 }
850
851
852 bool TextClass::hasLayout(docstring const & n) const
853 {
854         docstring const name = n.empty() ? defaultLayoutName() : n;
855
856         return find_if(layoutlist_.begin(), layoutlist_.end(),
857                        LayoutNamesEqual(name))
858                 != layoutlist_.end();
859 }
860
861
862
863 LayoutPtr const & TextClass::operator[](docstring const & name) const
864 {
865         BOOST_ASSERT(!name.empty());
866
867         LayoutList::const_iterator cit =
868                 find_if(layoutlist_.begin(),
869                         layoutlist_.end(),
870                         LayoutNamesEqual(name));
871
872         if (cit == layoutlist_.end()) {
873                 lyxerr << "We failed to find the layout '" << to_utf8(name)
874                        << "' in the layout list. You MUST investigate!"
875                        << endl;
876                 for (LayoutList::const_iterator it = layoutlist_.begin();
877                          it != layoutlist_.end(); ++it)
878                         lyxerr  << " " << to_utf8(it->get()->name()) << endl;
879
880                 // we require the name to exist
881                 BOOST_ASSERT(false);
882         }
883
884         return *cit;
885 }
886
887
888 bool TextClass::deleteLayout(docstring const & name)
889 {
890         if (name == defaultLayoutName() || name == emptyLayoutName())
891                 return false;
892
893         LayoutList::iterator it =
894                 remove_if(layoutlist_.begin(), layoutlist_.end(),
895                           LayoutNamesEqual(name));
896
897         LayoutList::iterator end = layoutlist_.end();
898         bool const ret = (it != end);
899         layoutlist_.erase(it, end);
900         return ret;
901 }
902
903
904 // Load textclass info if not loaded yet
905 bool TextClass::load(string const & path) const
906 {
907         if (loaded_)
908                 return true;
909
910         // Read style-file, provided path is searched before the system ones
911         FileName layout_file;
912         if (!path.empty())
913                 layout_file = FileName(addName(path, name_ + ".layout"));
914         if (layout_file.empty() || !layout_file.exists())
915                 layout_file = libFileSearch("layouts", name_, "layout");
916         loaded_ = const_cast<TextClass*>(this)->read(layout_file);
917
918         if (!loaded_) {
919                 lyxerr << "Error reading `"
920                        << to_utf8(makeDisplayPath(layout_file.absFilename()))
921                        << "'\n(Check `" << name_
922                        << "')\nCheck your installation and "
923                         "try Options/Reconfigure..." << endl;
924         }
925
926         return loaded_;
927 }
928
929
930 InsetLayout const & DocumentClass::insetLayout(docstring const & name) const 
931 {
932         docstring n = name;
933         while (!n.empty()) {
934                 if (insetlayoutlist_.count(n) > 0)
935                         return insetlayoutlist_[n];
936                 size_t i = n.find(':');
937                 if (i == string::npos)
938                         break;
939                 n = n.substr(0,i);
940         }
941         return empty_insetlayout_;
942 }
943
944
945 docstring const & TextClass::defaultLayoutName() const
946 {
947         // This really should come from the actual layout... (Lgb)
948         return defaultlayout_;
949 }
950
951
952 LayoutPtr const & TextClass::defaultLayout() const
953 {
954         return operator[](defaultLayoutName());
955 }
956
957
958 DocumentClass & DocumentClassBundle::newClass(LayoutFile const & baseClass)
959 {
960         DocumentClass dc(baseClass);
961         tc_list_.push_back(dc);
962         return tc_list_.back();
963 }
964
965
966 DocumentClassBundle & DocumentClassBundle::get()
967 {
968         static DocumentClassBundle singleton; 
969         return singleton; 
970 }
971
972
973 DocumentClass::DocumentClass(LayoutFile const & tc)
974         : TextClass(tc)
975 {}
976
977
978 bool DocumentClass::hasLaTeXLayout(std::string const & lay) const
979 {
980         LayoutList::const_iterator it  = layoutlist_.begin();
981         LayoutList::const_iterator end = layoutlist_.end();
982         for (; it != end; ++it)
983                 if (it->get()->latexname() == lay)
984                         return true;
985         return false;
986 }
987
988
989 bool DocumentClass::provides(string const & p) const
990 {
991         return provides_.find(p) != provides_.end();
992 }
993
994
995 bool DocumentClass::hasTocLevels() const
996 {
997         return min_toclevel_ != Layout::NOT_IN_TOC;
998 }
999
1000
1001 ostream & operator<<(ostream & os, PageSides p)
1002 {
1003         switch (p) {
1004         case OneSide:
1005                 os << '1';
1006                 break;
1007         case TwoSides:
1008                 os << '2';
1009                 break;
1010         }
1011         return os;
1012 }
1013
1014
1015 } // namespace lyx