]> git.lyx.org Git - lyx.git/blob - src/buffer.C
layout as string
[lyx.git] / src / buffer.C
1 /* This file is part of
2  * ====================================================== 
3  * 
4  *           LyX, The Document Processor
5  *
6  *           Copyright 1995 Matthias Ettrich
7  *           Copyright 1995-2001 The LyX Team.
8  *
9  *           This file is Copyright 1996-2001
10  *           Lars Gullik Bjønnes
11  *
12  * ====================================================== 
13  */
14
15 #include <config.h>
16
17 #ifdef __GNUG__
18 #pragma implementation
19 #endif
20
21 #include "buffer.h"
22 #include "bufferlist.h"
23 #include "lyx_main.h"
24 #include "LyXAction.h"
25 #include "lyxrc.h"
26 #include "lyxlex.h"
27 #include "tex-strings.h"
28 #include "layout.h"
29 #include "bufferview_funcs.h"
30 #include "lyxfont.h"
31 #include "version.h"
32 #include "LaTeX.h"
33 #include "Chktex.h"
34 #include "LyXView.h"
35 #include "debug.h"
36 #include "LaTeXFeatures.h"
37 #include "lyxtext.h"
38 #include "gettext.h"
39 #include "language.h"
40 #include "encoding.h"
41 #include "exporter.h"
42 #include "Lsstream.h"
43 #include "converter.h"
44 #include "BufferView.h"
45 #include "ParagraphParameters.h"
46 #include "iterators.h"
47 #include "lyxtextclasslist.h"
48
49 #include "mathed/formulamacro.h"
50 #include "mathed/formula.h"
51
52 #include "insets/inset.h"
53 #include "insets/inseterror.h"
54 #include "insets/insetlabel.h"
55 #include "insets/insetref.h"
56 #include "insets/inseturl.h"
57 #include "insets/insetnote.h"
58 #include "insets/insetquotes.h"
59 #include "insets/insetlatexaccent.h"
60 #include "insets/insetbib.h" 
61 #include "insets/insetcite.h" 
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h" 
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettext.h"
69 #include "insets/insetert.h"
70 #include "insets/insetgraphics.h"
71 #include "insets/insetfoot.h"
72 #include "insets/insetmarginal.h"
73 #include "insets/insetminipage.h"
74 #include "insets/insetfloat.h"
75 #include "insets/insettabular.h"
76 #if 0
77 #include "insets/insettheorem.h"
78 #include "insets/insetlist.h"
79 #endif
80 #include "insets/insetcaption.h"
81 #include "insets/insetfloatlist.h"
82
83 #include "frontends/Dialogs.h"
84 #include "frontends/Alert.h"
85
86 #include "support/textutils.h"
87 #include "support/filetools.h"
88 #include "support/path.h"
89 #include "support/os.h"
90 #include "support/lyxlib.h"
91 #include "support/FileInfo.h"
92 #include "support/lyxmanip.h"
93 #include "support/lyxalgo.h" // for lyx::count
94
95 #include <fstream>
96 #include <iomanip>
97 #include <map>
98 #include <stack>
99 #include <list>
100 #include <algorithm>
101
102 #include <cstdlib>
103 #include <cmath>
104 #include <unistd.h>
105 #include <sys/types.h>
106 #include <utime.h>
107
108
109 #ifdef HAVE_LOCALE
110 #include <locale>
111 #endif
112
113
114 using std::ostream;
115 using std::ofstream;
116 using std::ifstream;
117 using std::fstream;
118 using std::ios;
119 using std::setw;
120 using std::endl;
121 using std::pair;
122 using std::make_pair;
123 using std::vector;
124 using std::map;
125 using std::max;
126 using std::set;
127 using std::stack;
128 using std::list;
129
130 using lyx::pos_type;
131 using lyx::textclass_type;
132
133 // all these externs should eventually be removed.
134 extern BufferList bufferlist;
135
136 extern LyXAction lyxaction;
137
138 namespace {
139
140 const int LYX_FORMAT = 220;
141
142 } // namespace anon
143
144 extern int tex_code_break_column;
145
146
147 Buffer::Buffer(string const & file, bool ronly)
148         : paragraph(0), lyx_clean(true), bak_clean(true),
149           unnamed(false), dep_clean(0), read_only(ronly),
150           filename_(file), users(0)
151 {
152         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
153 //      filename = file;
154         filepath_ = OnlyPath(file);
155 //      paragraph = 0;
156 //      lyx_clean = true;
157 //      bak_clean = true;
158 //      dep_clean = 0;
159 //      read_only = ronly;
160 //      unnamed = false;
161 //      users = 0;
162         lyxvc.buffer(this);
163         if (read_only || lyxrc.use_tempdir) {
164                 tmppath = CreateBufferTmpDir();
165         } else {
166                 tmppath.erase();
167         }
168 }
169
170
171 Buffer::~Buffer()
172 {
173         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
174         // here the buffer should take care that it is
175         // saved properly, before it goes into the void.
176
177         // make sure that views using this buffer
178         // forgets it.
179         if (users)
180                 users->buffer(0);
181         
182         if (!tmppath.empty()) {
183                 DestroyBufferTmpDir(tmppath);
184         }
185         
186         Paragraph * par = paragraph;
187         Paragraph * tmppar;
188         while (par) {
189                 tmppar = par->next();
190                 delete par;
191                 par = tmppar;
192         }
193         paragraph = 0;
194 }
195
196
197 string const Buffer::getLatexName(bool no_path) const
198 {
199         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
200         if (no_path)
201                 return OnlyFilename(name);
202         else
203                 return name;
204 }
205
206
207 pair<Buffer::LogType, string> const Buffer::getLogName(void) const
208 {
209         string const filename = getLatexName(false);
210
211         if (filename.empty())
212                 return make_pair(Buffer::latexlog, string());
213
214         string path = OnlyPath(filename);
215
216         if (lyxrc.use_tempdir || !IsDirWriteable(path))
217                 path = tmppath;
218
219         string const fname = AddName(path,
220                                      OnlyFilename(ChangeExtension(filename,
221                                                                   ".log")));
222         string const bname =
223                 AddName(path, OnlyFilename(
224                         ChangeExtension(filename,
225                                         formats.extension("literate") + ".out")));
226
227         // If no Latex log or Build log is newer, show Build log
228
229         FileInfo const f_fi(fname);
230         FileInfo const b_fi(bname);
231
232         if (b_fi.exist() &&
233             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
234                 lyxerr[Debug::FILES] << "Log name calculated as : " << bname << endl;
235                 return make_pair(Buffer::buildlog, bname);
236         }
237         lyxerr[Debug::FILES] << "Log name calculated as : " << fname << endl;
238         return make_pair(Buffer::latexlog, fname);
239 }
240
241
242 void Buffer::setReadonly(bool flag)
243 {
244         if (read_only != flag) {
245                 read_only = flag; 
246                 updateTitles();
247                 users->owner()->getDialogs()->updateBufferDependent(false);
248         }
249 }
250
251
252 /// Update window titles of all users
253 // Should work on a list
254 void Buffer::updateTitles() const
255 {
256         if (users)
257                 users->owner()->updateWindowTitle();
258 }
259
260
261 /// Reset autosave timer of all users
262 // Should work on a list
263 void Buffer::resetAutosaveTimers() const
264 {
265         if (users)
266                 users->owner()->resetAutosaveTimer();
267 }
268
269
270 void Buffer::setFileName(string const & newfile)
271 {
272         filename_ = MakeAbsPath(newfile);
273         filepath_ = OnlyPath(filename_);
274         setReadonly(IsFileWriteable(filename_) == 0);
275         updateTitles();
276 }
277
278
279 // We'll remove this later. (Lgb)
280 namespace {
281
282 string last_inset_read;
283
284 #ifndef NO_COMPABILITY
285 struct ErtComp 
286 {
287         ErtComp() : active(false), in_tabular(false) {
288         }
289         string contents;
290         bool active;
291         bool in_tabular;
292         LyXFont font;
293 };
294
295 std::stack<ErtComp> ert_stack;
296 ErtComp ert_comp;
297 #endif
298
299 #ifdef WITH_WARNINGS
300 #warning And _why_ is this here? (Lgb)
301 #endif
302 int unknown_layouts;
303 int unknown_tokens;
304
305 } // anon
306
307
308 // candidate for move to BufferView
309 // (at least some parts in the beginning of the func)
310 //
311 // Uwe C. Schroeder
312 // changed to be public and have one parameter
313 // if par = 0 normal behavior
314 // else insert behavior
315 // Returns false if "\the_end" is not read for formats >= 2.13. (Asger)
316 bool Buffer::readLyXformat2(LyXLex & lex, Paragraph * par)
317 {
318         unknown_layouts = 0;
319         unknown_tokens = 0;
320 #ifndef NO_COMPABILITY
321         ert_comp.contents.erase();
322         ert_comp.active = false;
323         ert_comp.in_tabular = false;
324 #endif
325         int pos = 0;
326         Paragraph::depth_type depth = 0; 
327         bool the_end_read = false;
328
329         Paragraph * first_par = 0;
330         LyXFont font(LyXFont::ALL_INHERIT, params.language);
331         if (file_format < 216 && params.language->lang() == "hebrew")
332                 font.setLanguage(default_language);
333
334         if (!par) {
335                 par = new Paragraph;
336         } else {
337                 // We are inserting into an existing document
338                 users->text->breakParagraph(users);
339                 first_par = users->text->ownerParagraph();
340                 pos = 0;
341                 markDirty();
342                 // We don't want to adopt the parameters from the
343                 // document we insert, so we skip until the text begins:
344                 while (lex.isOK()) {
345                         lex.nextToken();
346                         string const pretoken = lex.getString();
347                         if (pretoken == "\\layout") {
348                                 lex.pushToken(pretoken);
349                                 break;
350                         }
351                 }
352         }
353
354         while (lex.isOK()) {
355                 lex.nextToken();
356                 string const token = lex.getString();
357
358                 if (token.empty()) continue;
359
360                 lyxerr[Debug::PARSER] << "Handling token: `"
361                                       << token << "'" << endl;
362                 
363                 the_end_read =
364                         parseSingleLyXformat2Token(lex, par, first_par,
365                                                    token, pos, depth,
366                                                    font);
367         }
368    
369         if (!first_par)
370                 first_par = par;
371
372         paragraph = first_par;
373
374         if (unknown_layouts > 0) {
375                 string s = _("Couldn't set the layout for ");
376                 if (unknown_layouts == 1) {
377                         s += _("one paragraph");
378                 } else {
379                         s += tostr(unknown_layouts);
380                         s += _(" paragraphs");
381                 }
382                 Alert::alert(_("Textclass Loading Error!"), s,
383                            _("When reading " + fileName()));
384         }
385
386         if (unknown_tokens > 0) {
387                 string s = _("Encountered ");
388                 if (unknown_tokens == 1) {
389                         s += _("one unknown token");
390                 } else {
391                         s += tostr(unknown_tokens);
392                         s += _(" unknown tokens");
393                 }
394                 Alert::alert(_("Textclass Loading Error!"), s,
395                            _("When reading " + fileName()));
396         }
397
398         return the_end_read;
399 }
400
401
402 #ifndef NO_COMPABILITY
403 void Buffer::insertErtContents(Paragraph * par, int & pos, bool set_inactive) 
404 {
405         if (!ert_comp.contents.empty()) {
406                 lyxerr[Debug::INSETS] << "ERT contents:\n'"
407                                       << ert_comp.contents << "'" << endl;
408                 Inset * inset = new InsetERT(params.language, ert_comp.contents, true);
409                 par->insertInset(pos++, inset, ert_comp.font);
410                 ert_comp.contents.erase();
411         }
412         if (set_inactive) {
413                 ert_comp.active = false;
414         }
415 }
416 #endif
417
418
419 bool
420 Buffer::parseSingleLyXformat2Token(LyXLex & lex, Paragraph *& par,
421                                    Paragraph *& first_par,
422                                    string const & token, int & pos,
423                                    Paragraph::depth_type & depth, 
424                                    LyXFont & font
425         )
426 {
427         bool the_end_read = false;
428 #ifndef NO_COMPABILITY
429 #ifndef NO_PEXTRA_REALLY
430         // This is super temporary but is needed to get the compability
431         // mode for minipages work correctly together with new tabulars.
432         static int call_depth;
433         ++call_depth;
434         bool checkminipage = false;
435         static Paragraph * minipar;
436         static Paragraph * parBeforeMinipage;
437 #endif
438 #endif
439         if (token[0] != '\\') {
440 #ifndef NO_COMPABILITY
441                 if (ert_comp.active) {
442                         ert_comp.contents += token;
443                 } else {
444 #endif
445                 for (string::const_iterator cit = token.begin();
446                      cit != token.end(); ++cit) {
447                         par->insertChar(pos, (*cit), font);
448                         ++pos;
449                 }
450 #ifndef NO_COMPABILITY
451                 }
452 #endif
453         } else if (token == "\\i") {
454                 Inset * inset = new InsetLatexAccent;
455                 inset->read(this, lex);
456                 par->insertInset(pos, inset, font);
457                 ++pos;
458         } else if (token == "\\layout") {
459 #ifndef NO_COMPABILITY
460                 ert_comp.in_tabular = false;
461                 // Do the insetert.
462                 insertErtContents(par, pos);
463 #endif
464                 lex.eatLine();
465                 string const layoutname = lex.getString();
466                 //lyxerr << "Looking for layout '"
467                 // << layoutname << "'!" << endl;
468
469                 //lyxerr << "Result: " << pp.first << "/" << pp.second << endl;
470                 
471 #ifndef NO_COMPABILITY
472                 if (compare_no_case(layoutname, "latex") == 0) {
473                         ert_comp.active = true;
474                         ert_comp.font = font;
475                 }
476 #endif
477 #ifdef USE_CAPTION
478                 // The is the compability reading of layout caption.
479                 // It can be removed in LyX version 1.3.0. (Lgb)
480                 if (compare_no_case(layoutname, "caption") == 0) {
481                         // We expect that the par we are now working on is
482                         // really inside a InsetText inside a InsetFloat.
483                         // We also know that captions can only be
484                         // one paragraph. (Lgb)
485                         
486                         // We should now read until the next "\layout"
487                         // is reached.
488                         // This is probably not good enough, what if the
489                         // caption is the last par in the document (Lgb)
490                         istream & ist = lex.getStream();
491                         stringstream ss;
492                         string line;
493                         int begin = 0;
494                         while (true) {
495                                 getline(ist, line);
496                                 if (prefixIs(line, "\\layout")) {
497                                         lex.pushToken(line);
498                                         break;
499                                 }
500                                 if (prefixIs(line, "\\begin_inset"))
501                                         ++begin;
502                                 if (prefixIs(line, "\\end_inset")) {
503                                         if (begin)
504                                                 --begin;
505                                         else {
506                                                 lex.pushToken(line);
507                                                 break;
508                                         }
509                                 }
510                                 
511                                 ss << line << '\n';
512                         }
513                         // Now we should have the whole layout in ss
514                         // we should now be able to give this to the
515                         // caption inset.
516                         ss << "\\end_inset\n";
517                         
518                         // This seems like a bug in stringstream.
519                         // We really should be able to use ss
520                         // directly. (Lgb)
521                         istringstream is(ss.str());
522                         LyXLex tmplex(0, 0);
523                         tmplex.setStream(is);
524                         Inset * inset = new InsetCaption;
525                         inset->Read(this, tmplex);
526                         par->InsertInset(pos, inset, font);
527                         ++pos;
528                 } else {
529 #endif
530                         if (!first_par)
531                                 first_par = par;
532                         else {
533                                 par = new Paragraph(par);
534                         }
535                         pos = 0;
536                         par->layout(layoutname);
537                         // Test whether the layout is obsolete.
538                         LyXLayout const & layout =
539                                 textclasslist[params.textclass][par->layout()];
540                         if (!layout.obsoleted_by().empty())
541                                 par->layout(layout.obsoleted_by());
542                         par->params().depth(depth);
543                         font = LyXFont(LyXFont::ALL_INHERIT, params.language);
544                         if (file_format < 216
545                             && params.language->lang() == "hebrew")
546                                 font.setLanguage(default_language);
547 #if USE_CAPTION
548                 }
549 #endif
550
551 #ifndef NO_COMPABILITY
552         } else if (token == "\\begin_float") {
553                 insertErtContents(par, pos);
554                 //insertErtContents(par, pos, false);
555                 //ert_stack.push(ert_comp);
556                 //ert_comp = ErtComp();
557                 
558                 // This is the compability reader. It can be removed in
559                 // LyX version 1.3.0. (Lgb)
560                 lex.next();
561                 string const tmptok = lex.getString();
562                 //lyxerr << "old float: " << tmptok << endl;
563                 
564                 Inset * inset = 0;
565                 stringstream old_float;
566                 
567                 if (tmptok == "footnote") {
568                         inset = new InsetFoot;
569                         old_float << "collapsed true\n";
570                 } else if (tmptok == "margin") {
571                         inset = new InsetMarginal;
572                         old_float << "collapsed true\n";
573                 } else if (tmptok == "fig") {
574                         inset = new InsetFloat("figure");
575                         old_float << "placement htbp\n"
576                                   << "wide false\n"
577                                   << "collapsed false\n";
578                 } else if (tmptok == "tab") {
579                         inset = new InsetFloat("table");
580                         old_float << "placement htbp\n"
581                                   << "wide false\n"
582                                   << "collapsed false\n";
583                 } else if (tmptok == "alg") {
584                         inset = new InsetFloat("algorithm");
585                         old_float << "placement htbp\n"
586                                   << "wide false\n"
587                                   << "collapsed false\n";
588                 } else if (tmptok == "wide-fig") {
589                         inset = new InsetFloat("figure");
590                         //InsetFloat * tmp = new InsetFloat("figure");
591                         //tmp->wide(true);
592                         //inset = tmp;
593                         old_float << "placement htbp\n"
594                                   << "wide true\n"
595                                   << "collapsed false\n";
596                 } else if (tmptok == "wide-tab") {
597                         inset = new InsetFloat("table");
598                         //InsetFloat * tmp = new InsetFloat("table");
599                         //tmp->wide(true);
600                         //inset = tmp;
601                         old_float << "placement htbp\n"
602                                   << "wide true\n"
603                                   << "collapsed false\n";
604                 }
605
606                 if (!inset) {
607 #ifndef NO_PEXTRA_REALLY
608                         --call_depth;
609 #endif
610                         return false; // no end read yet
611                 }
612
613                 // Here we need to check for \end_deeper and handle that
614                 // before we do the footnote parsing.
615                 // This _is_ a hack! (Lgb)
616                 while (true) {
617                         lex.next();
618                         string const tmp = lex.getString();
619                         if (tmp == "\\end_deeper") {
620                                 //lyxerr << "\\end_deeper caught!" << endl;
621                                 if (!depth) {
622                                         lex.printError("\\end_deeper: "
623                                                        "depth is already null");
624                                 } else
625                                         --depth;
626                                 
627                         } else {
628                                 old_float << tmp << ' ';
629                                 break;
630                         }
631                 }
632                 
633                 old_float << lex.getLongString("\\end_float")
634                           << "\n\\end_inset\n";
635                 //lyxerr << "Float Body:\n" << old_float.str() << endl;
636                 // That this does not work seems like a bug
637                 // in stringstream. (Lgb)
638                 istringstream istr(old_float.str());
639                 LyXLex nylex(0, 0);
640                 nylex.setStream(istr);
641                 inset->read(this, nylex);
642                 par->insertInset(pos, inset, font);
643                 ++pos;
644                 insertErtContents(par, pos);
645 #endif
646         } else if (token == "\\begin_deeper") {
647                 ++depth;
648         } else if (token == "\\end_deeper") {
649                 if (!depth) {
650                         lex.printError("\\end_deeper: "
651                                        "depth is already null");
652                 }
653                 else
654                         --depth;
655         } else if (token == "\\begin_preamble") {
656                 params.readPreamble(lex);
657         } else if (token == "\\textclass") {
658                 lex.eatLine();
659                 pair<bool, textclass_type> pp = 
660                         textclasslist.NumberOfClass(lex.getString());
661                 if (pp.first) {
662                         params.textclass = pp.second;
663                 } else {
664                         Alert::alert(string(_("Textclass error")), 
665                                 string(_("The document uses an unknown textclass \"")) + 
666                                 lex.getString() + string("\"."),
667                                 string(_("LyX will not be able to produce output correctly.")));
668                         params.textclass = 0;
669                 }
670                 if (!textclasslist[params.textclass].load()) {
671                         // if the textclass wasn't loaded properly
672                         // we need to either substitute another
673                         // or stop loading the file.
674                         // I can substitute but I don't see how I can
675                         // stop loading... ideas??  ARRae980418
676                         Alert::alert(_("Textclass Loading Error!"),
677                                    string(_("Can't load textclass ")) +
678                                    textclasslist[params.textclass].name(),
679                                    _("-- substituting default"));
680                         params.textclass = 0;
681                 }
682         } else if (token == "\\options") {
683                 lex.eatLine();
684                 params.options = lex.getString();
685         } else if (token == "\\language") {
686                 params.readLanguage(lex);    
687         } else if (token == "\\fontencoding") {
688                 lex.eatLine();
689         } else if (token == "\\inputencoding") {
690                 lex.eatLine();
691                 params.inputenc = lex.getString();
692         } else if (token == "\\graphics") {
693                 params.readGraphicsDriver(lex);
694         } else if (token == "\\fontscheme") {
695                 lex.eatLine();
696                 params.fonts = lex.getString();
697         } else if (token == "\\noindent") {
698                 par->params().noindent(true);
699         } else if (token == "\\fill_top") {
700                 par->params().spaceTop(VSpace(VSpace::VFILL));
701         } else if (token == "\\fill_bottom") {
702                 par->params().spaceBottom(VSpace(VSpace::VFILL));
703         } else if (token == "\\line_top") {
704                 par->params().lineTop(true);
705         } else if (token == "\\line_bottom") {
706                 par->params().lineBottom(true);
707         } else if (token == "\\pagebreak_top") {
708                 par->params().pagebreakTop(true);
709         } else if (token == "\\pagebreak_bottom") {
710                 par->params().pagebreakBottom(true);
711         } else if (token == "\\start_of_appendix") {
712                 par->params().startOfAppendix(true);
713         } else if (token == "\\paragraph_separation") {
714                 int tmpret = lex.findToken(string_paragraph_separation);
715                 if (tmpret == -1)
716                         ++tmpret;
717                 if (tmpret != LYX_LAYOUT_DEFAULT) 
718                         params.paragraph_separation =
719                                 static_cast<BufferParams::PARSEP>(tmpret);
720         } else if (token == "\\defskip") {
721                 lex.nextToken();
722                 params.defskip = VSpace(lex.getString());
723 #ifndef NO_COMPABILITY
724         } else if (token == "\\epsfig") { // obsolete
725                 // Indeed it is obsolete, but we HAVE to be backwards
726                 // compatible until 0.14, because otherwise all figures
727                 // in existing documents are irretrivably lost. (Asger)
728                 params.readGraphicsDriver(lex);
729 #endif
730         } else if (token == "\\quotes_language") {
731                 int tmpret = lex.findToken(string_quotes_language);
732                 if (tmpret == -1)
733                         ++tmpret;
734                 if (tmpret != LYX_LAYOUT_DEFAULT) {
735                         InsetQuotes::quote_language tmpl = 
736                                 InsetQuotes::EnglishQ;
737                         switch (tmpret) {
738                         case 0:
739                                 tmpl = InsetQuotes::EnglishQ;
740                                 break;
741                         case 1:
742                                 tmpl = InsetQuotes::SwedishQ;
743                                 break;
744                         case 2:
745                                 tmpl = InsetQuotes::GermanQ;
746                                 break;
747                         case 3:
748                                 tmpl = InsetQuotes::PolishQ;
749                                 break;
750                         case 4:
751                                 tmpl = InsetQuotes::FrenchQ;
752                                 break;
753                         case 5:
754                                 tmpl = InsetQuotes::DanishQ;
755                                 break;  
756                         }
757                         params.quotes_language = tmpl;
758                 }
759         } else if (token == "\\quotes_times") {
760                 lex.nextToken();
761                 switch (lex.getInteger()) {
762                 case 1: 
763                         params.quotes_times = InsetQuotes::SingleQ; 
764                         break;
765                 case 2: 
766                         params.quotes_times = InsetQuotes::DoubleQ; 
767                         break;
768                 }
769         } else if (token == "\\papersize") {
770                 int tmpret = lex.findToken(string_papersize);
771                 if (tmpret == -1)
772                         ++tmpret;
773                 else
774                         params.papersize2 = tmpret;
775         } else if (token == "\\paperpackage") {
776                 int tmpret = lex.findToken(string_paperpackages);
777                 if (tmpret == -1) {
778                         ++tmpret;
779                         params.paperpackage = BufferParams::PACKAGE_NONE;
780                 } else
781                         params.paperpackage = tmpret;
782         } else if (token == "\\use_geometry") {
783                 lex.nextToken();
784                 params.use_geometry = lex.getInteger();
785         } else if (token == "\\use_amsmath") {
786                 lex.nextToken();
787                 params.use_amsmath = lex.getInteger();
788         } else if (token == "\\use_natbib") {
789                 lex.nextToken();
790                 params.use_natbib = lex.getInteger();
791         } else if (token == "\\use_numerical_citations") {
792                 lex.nextToken();
793                 params.use_numerical_citations = lex.getInteger();
794         } else if (token == "\\paperorientation") {
795                 int tmpret = lex.findToken(string_orientation);
796                 if (tmpret == -1)
797                         ++tmpret;
798                 if (tmpret != LYX_LAYOUT_DEFAULT) 
799                         params.orientation = static_cast<BufferParams::PAPER_ORIENTATION>(tmpret);
800         } else if (token == "\\paperwidth") {
801                 lex.next();
802                 params.paperwidth = lex.getString();
803         } else if (token == "\\paperheight") {
804                 lex.next();
805                 params.paperheight = lex.getString();
806         } else if (token == "\\leftmargin") {
807                 lex.next();
808                 params.leftmargin = lex.getString();
809         } else if (token == "\\topmargin") {
810                 lex.next();
811                 params.topmargin = lex.getString();
812         } else if (token == "\\rightmargin") {
813                 lex.next();
814                 params.rightmargin = lex.getString();
815         } else if (token == "\\bottommargin") {
816                 lex.next();
817                 params.bottommargin = lex.getString();
818         } else if (token == "\\headheight") {
819                 lex.next();
820                 params.headheight = lex.getString();
821         } else if (token == "\\headsep") {
822                 lex.next();
823                 params.headsep = lex.getString();
824         } else if (token == "\\footskip") {
825                 lex.next();
826                 params.footskip = lex.getString();
827         } else if (token == "\\paperfontsize") {
828                 lex.nextToken();
829                 params.fontsize = strip(lex.getString());
830         } else if (token == "\\papercolumns") {
831                 lex.nextToken();
832                 params.columns = lex.getInteger();
833         } else if (token == "\\papersides") {
834                 lex.nextToken();
835                 switch (lex.getInteger()) {
836                 default:
837                 case 1: params.sides = LyXTextClass::OneSide; break;
838                 case 2: params.sides = LyXTextClass::TwoSides; break;
839                 }
840         } else if (token == "\\paperpagestyle") {
841                 lex.nextToken();
842                 params.pagestyle = strip(lex.getString());
843         } else if (token == "\\bullet") {
844                 lex.nextToken();
845                 int const index = lex.getInteger();
846                 lex.nextToken();
847                 int temp_int = lex.getInteger();
848                 params.user_defined_bullets[index].setFont(temp_int);
849                 params.temp_bullets[index].setFont(temp_int);
850                 lex.nextToken();
851                 temp_int = lex.getInteger();
852                 params.user_defined_bullets[index].setCharacter(temp_int);
853                 params.temp_bullets[index].setCharacter(temp_int);
854                 lex.nextToken();
855                 temp_int = lex.getInteger();
856                 params.user_defined_bullets[index].setSize(temp_int);
857                 params.temp_bullets[index].setSize(temp_int);
858                 lex.nextToken();
859                 string const temp_str = lex.getString();
860                 if (temp_str != "\\end_bullet") {
861                                 // this element isn't really necessary for
862                                 // parsing but is easier for humans
863                                 // to understand bullets. Put it back and
864                                 // set a debug message?
865                         lex.printError("\\end_bullet expected, got" + temp_str);
866                                 //how can I put it back?
867                 }
868         } else if (token == "\\bulletLaTeX") {
869                 // The bullet class should be able to read this.
870                 lex.nextToken();
871                 int const index = lex.getInteger();
872                 lex.next();
873                 string temp_str = lex.getString();
874                 string sum_str;
875                 while (temp_str != "\\end_bullet") {
876                                 // this loop structure is needed when user
877                                 // enters an empty string since the first
878                                 // thing returned will be the \\end_bullet
879                                 // OR
880                                 // if the LaTeX entry has spaces. Each element
881                                 // therefore needs to be read in turn
882                         sum_str += temp_str;
883                         lex.next();
884                         temp_str = lex.getString();
885                 }
886
887                 params.user_defined_bullets[index].setText(sum_str);
888                 params.temp_bullets[index].setText(sum_str);
889         } else if (token == "\\secnumdepth") {
890                 lex.nextToken();
891                 params.secnumdepth = lex.getInteger();
892         } else if (token == "\\tocdepth") {
893                 lex.nextToken();
894                 params.tocdepth = lex.getInteger();
895         } else if (token == "\\spacing") {
896                 lex.next();
897                 string const tmp = strip(lex.getString());
898                 Spacing::Space tmp_space = Spacing::Default;
899                 float tmp_val = 0.0;
900                 if (tmp == "single") {
901                         tmp_space = Spacing::Single;
902                 } else if (tmp == "onehalf") {
903                         tmp_space = Spacing::Onehalf;
904                 } else if (tmp == "double") {
905                         tmp_space = Spacing::Double;
906                 } else if (tmp == "other") {
907                         lex.next();
908                         tmp_space = Spacing::Other;
909                         tmp_val = lex.getFloat();
910                 } else {
911                         lex.printError("Unknown spacing token: '$$Token'");
912                 }
913                 // Small hack so that files written with klyx will be
914                 // parsed correctly.
915                 if (first_par) {
916                         par->params().spacing(Spacing(tmp_space, tmp_val));
917                 } else {
918                         params.spacing.set(tmp_space, tmp_val);
919                 }
920         } else if (token == "\\paragraph_spacing") {
921                 lex.next();
922                 string const tmp = strip(lex.getString());
923                 if (tmp == "single") {
924                         par->params().spacing(Spacing(Spacing::Single));
925                 } else if (tmp == "onehalf") {
926                         par->params().spacing(Spacing(Spacing::Onehalf));
927                 } else if (tmp == "double") {
928                         par->params().spacing(Spacing(Spacing::Double));
929                 } else if (tmp == "other") {
930                         lex.next();
931                         par->params().spacing(Spacing(Spacing::Other,
932                                          lex.getFloat()));
933                 } else {
934                         lex.printError("Unknown spacing token: '$$Token'");
935                 }
936         } else if (token == "\\float_placement") {
937                 lex.nextToken();
938                 params.float_placement = lex.getString();
939         } else if (token == "\\family") { 
940                 lex.next();
941                 font.setLyXFamily(lex.getString());
942         } else if (token == "\\series") {
943                 lex.next();
944                 font.setLyXSeries(lex.getString());
945         } else if (token == "\\shape") {
946                 lex.next();
947                 font.setLyXShape(lex.getString());
948         } else if (token == "\\size") {
949                 lex.next();
950                 font.setLyXSize(lex.getString());
951 #ifndef NO_COMPABILITY
952         } else if (token == "\\latex") {
953                 lex.next();
954                 string const tok = lex.getString();
955                 if (tok == "no_latex") {
956                         // Do the insetert.
957                         insertErtContents(par, pos);
958                 } else if (tok == "latex") {
959                         ert_comp.active = true;
960                         ert_comp.font = font;
961                 } else if (tok == "default") {
962                         // Do the insetert.
963                         insertErtContents(par, pos);
964                 } else {
965                         lex.printError("Unknown LaTeX font flag "
966                                        "`$$Token'");
967                 }
968 #endif
969         } else if (token == "\\lang") {
970                 lex.next();
971                 string const tok = lex.getString();
972                 Language const * lang = languages.getLanguage(tok);
973                 if (lang) {
974                         font.setLanguage(lang);
975                 } else {
976                         font.setLanguage(params.language);
977                         lex.printError("Unknown language `$$Token'");
978                 }
979         } else if (token == "\\numeric") {
980                 lex.next();
981                 font.setNumber(font.setLyXMisc(lex.getString()));
982         } else if (token == "\\emph") {
983                 lex.next();
984                 font.setEmph(font.setLyXMisc(lex.getString()));
985         } else if (token == "\\bar") {
986                 lex.next();
987                 string const tok = lex.getString();
988                 // This is dirty, but gone with LyX3. (Asger)
989                 if (tok == "under")
990                         font.setUnderbar(LyXFont::ON);
991                 else if (tok == "no")
992                         font.setUnderbar(LyXFont::OFF);
993                 else if (tok == "default")
994                         font.setUnderbar(LyXFont::INHERIT);
995                 else
996                         lex.printError("Unknown bar font flag "
997                                        "`$$Token'");
998         } else if (token == "\\noun") {
999                 lex.next();
1000                 font.setNoun(font.setLyXMisc(lex.getString()));
1001         } else if (token == "\\color") {
1002                 lex.next();
1003                 font.setLyXColor(lex.getString());
1004         } else if (token == "\\align") {
1005                 int tmpret = lex.findToken(string_align);
1006                 if (tmpret == -1) ++tmpret;
1007                 if (tmpret != LYX_LAYOUT_DEFAULT) { // tmpret != 99 ???
1008                         int const tmpret2 = int(pow(2.0, tmpret));
1009                         //lyxerr << "Tmpret2 = " << tmpret2 << endl;
1010                         par->params().align(LyXAlignment(tmpret2));
1011                 }
1012         } else if (token == "\\added_space_top") {
1013                 lex.nextToken();
1014                 VSpace value = VSpace(lex.getString());
1015                 if ((value.length().len().value() != 0) ||
1016                     (value.kind() != VSpace::LENGTH))
1017                     par->params().spaceTop(value);
1018         } else if (token == "\\added_space_bottom") {
1019                 lex.nextToken();
1020                 VSpace value = VSpace(lex.getString());
1021                 if ((value.length().len().value() != 0) ||
1022                     (value.kind() != VSpace::LENGTH))
1023                     par->params().spaceBottom(value);
1024 #ifndef NO_COMPABILITY
1025 #ifndef NO_PEXTRA_REALLY
1026         } else if (token == "\\pextra_type") {
1027                 lex.nextToken();
1028                 par->params().pextraType(lex.getInteger());
1029         } else if (token == "\\pextra_width") {
1030                 lex.nextToken();
1031                 par->params().pextraWidth(lex.getString());
1032         } else if (token == "\\pextra_widthp") {
1033                 lex.nextToken();
1034                 par->params().pextraWidthp(lex.getString());
1035         } else if (token == "\\pextra_alignment") {
1036                 lex.nextToken();
1037                 par->params().pextraAlignment(lex.getInteger());
1038         } else if (token == "\\pextra_hfill") {
1039                 lex.nextToken();
1040                 par->params().pextraHfill(lex.getInteger());
1041         } else if (token == "\\pextra_start_minipage") {
1042                 lex.nextToken();
1043                 par->params().pextraStartMinipage(lex.getInteger());
1044 #endif
1045 #endif
1046         } else if (token == "\\labelwidthstring") {
1047                 lex.eatLine();
1048                 par->params().labelWidthString(lex.getString());
1049                 // do not delete this token, it is still needed!
1050         } else if (token == "\\end_inset") {
1051                 lyxerr << "Solitary \\end_inset. Missing \\begin_inset?.\n"
1052                        << "Last inset read was: " << last_inset_read
1053                        << endl;
1054                 // Simply ignore this. The insets do not have
1055                 // to read this.
1056                 // But insets should read it, it is a part of
1057                 // the inset isn't it? Lgb.
1058         } else if (token == "\\begin_inset") {
1059 #ifndef NO_COMPABILITY
1060                 insertErtContents(par, pos, false);
1061                 ert_stack.push(ert_comp);
1062                 ert_comp = ErtComp();
1063 #endif
1064                 readInset(lex, par, pos, font);
1065 #ifndef NO_COMPABILITY
1066                 ert_comp = ert_stack.top();
1067                 ert_stack.pop();
1068                 insertErtContents(par, pos);
1069 #endif
1070         } else if (token == "\\SpecialChar") {
1071                 LyXLayout const & layout =
1072                         textclasslist[params.textclass][par->layout()];
1073
1074                 // Insets don't make sense in a free-spacing context! ---Kayvan
1075                 if (layout.free_spacing || par->isFreeSpacing()) {
1076                         if (lex.isOK()) {
1077                                 lex.next();
1078                                 string next_token = lex.getString();
1079                                 if (next_token == "\\-") {
1080                                         par->insertChar(pos, '-', font);
1081                                 } else if (next_token == "\\protected_separator"
1082                                         || next_token == "~") {
1083                                         par->insertChar(pos, ' ', font);
1084                                 } else {
1085                                         lex.printError("Token `$$Token' "
1086                                                        "is in free space "
1087                                                        "paragraph layout!");
1088                                         --pos;
1089                                 }
1090                         }
1091                 } else {
1092                         Inset * inset = new InsetSpecialChar;
1093                         inset->read(this, lex);
1094                         par->insertInset(pos, inset, font);
1095                 }
1096                 ++pos;
1097         } else if (token == "\\newline") {
1098 #ifndef NO_COMPABILITY
1099                 if (!ert_comp.in_tabular && ert_comp.active) {
1100                         ert_comp.contents += char(Paragraph::META_NEWLINE);
1101                 } else {
1102                         // Since we cannot know it this is only a regular
1103                         // newline or a tabular cell delimter we have to
1104                         // handle the ERT here.
1105                         insertErtContents(par, pos, false);
1106
1107                         par->insertChar(pos, Paragraph::META_NEWLINE, font);
1108                         ++pos;
1109                 }
1110 #else
1111                 par->insertChar(pos, Paragraph::META_NEWLINE, font);
1112                 ++pos;
1113 #endif
1114         } else if (token == "\\LyXTable") {
1115 #ifndef NO_COMPABILITY
1116                 ert_comp.in_tabular = true;
1117 #endif
1118                 Inset * inset = new InsetTabular(*this);
1119                 inset->read(this, lex);
1120                 par->insertInset(pos, inset, font);
1121                 ++pos;
1122         } else if (token == "\\hfill") {
1123                 par->insertChar(pos, Paragraph::META_HFILL, font);
1124                 ++pos;
1125         } else if (token == "\\protected_separator") { // obsolete
1126                 // This is a backward compability thingie. (Lgb)
1127                 // Remove it later some time...introduced with fileformat
1128                 // 2.16. (Lgb)
1129                 LyXLayout const & layout =
1130                         textclasslist[params.textclass][par->layout()];
1131
1132                 if (layout.free_spacing || par->isFreeSpacing()) {
1133                         par->insertChar(pos, ' ', font);
1134                 } else {
1135                         Inset * inset = new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
1136                         par->insertInset(pos, inset, font);
1137                 }
1138                 ++pos;
1139         } else if (token == "\\bibitem") {  // ale970302
1140                 if (!par->bibkey) {
1141                         InsetCommandParams p("bibitem", "dummy");
1142                         par->bibkey = new InsetBibKey(p);
1143                 }
1144                 par->bibkey->read(this, lex);                   
1145         } else if (token == "\\backslash") {
1146 #ifndef NO_COMPABILITY
1147                 if (ert_comp.active) {
1148                         ert_comp.contents += "\\";
1149                 } else {
1150 #endif
1151                 par->insertChar(pos, '\\', font);
1152                 ++pos;
1153 #ifndef NO_COMPABILITY
1154                 }
1155 #endif
1156         } else if (token == "\\the_end") {
1157 #ifndef NO_COMPABILITY
1158                 // If we still have some ert active here we have to insert
1159                 // it so we don't loose it. (Lgb)
1160                 insertErtContents(par, pos);
1161 #endif
1162                 the_end_read = true;
1163 #ifndef NO_COMPABILITY
1164 #ifndef NO_PEXTRA_REALLY
1165                 minipar = parBeforeMinipage = 0;
1166 #endif
1167 #endif
1168         } else {
1169 #ifndef NO_COMPABILITY
1170                 if (ert_comp.active) {
1171                         ert_comp.contents += token;
1172                 } else {
1173 #endif
1174                 // This should be insurance for the future: (Asger)
1175                 ++unknown_tokens;
1176                 lex.eatLine();
1177                 string const s = _("Unknown token: ") + token
1178                         + " " + lex.text()  + "\n";
1179
1180                 InsetError * new_inset = new InsetError(s);
1181                 par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
1182                                                          params.language));
1183
1184 #ifndef NO_COMPABILITY
1185                 }
1186 #endif
1187         }
1188
1189 #ifndef NO_COMPABILITY
1190 #ifndef NO_PEXTRA_REALLY
1191         // I wonder if we could use this blanket fix for all the
1192         // checkminipage cases...
1193         // don't forget about ert paragraphs and compatibility read for'em
1194         if (par && (par->size() || !ert_comp.contents.empty())) {
1195                 // It is possible that this will check to often,
1196                 // but that should not be an correctness issue.
1197                 // Only a speed issue.
1198                 checkminipage = true;
1199         }
1200         
1201         // now check if we have a minipage paragraph as at this
1202         // point we already read all the necessary data!
1203         // this cannot be done in layout because there we did
1204         // not read yet the paragraph PEXTRA-params (Jug)
1205         //
1206         // BEGIN pextra_minipage compability
1207         // This should be removed in 1.3.x (Lgb)
1208         // I don't think we should remove this so fast (Jug)
1209         
1210         // This compability code is not perfect. In a couple
1211         // of rand cases it fails. When the minipage par is
1212         // the first par in the document, and when there are
1213         // none or only one regular paragraphs after the
1214         // minipage. Currently I am not investing any effort
1215         // in fixing those cases.
1216
1217         //lyxerr << "Call depth: " << call_depth << endl;
1218         if (checkminipage && (call_depth == 1)) {
1219         checkminipage = false;
1220         if (minipar && (minipar != par) &&
1221             (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE)) {
1222                 lyxerr << "minipages in a row" << endl;
1223                 if (par->params().pextraStartMinipage()) {
1224                         lyxerr << "start new minipage" << endl;
1225                         // minipages in a row
1226                         par->previous()->next(0);
1227                         par->previous(0);
1228                                 
1229                         Paragraph * tmp = minipar;
1230                         while (tmp) {
1231                                 tmp->params().pextraType(0);
1232                                 tmp->params().pextraWidth(string());
1233                                 tmp->params().pextraWidthp(string());
1234                                 tmp->params().pextraAlignment(0);
1235                                 tmp->params().pextraHfill(false);
1236                                 tmp->params().pextraStartMinipage(false);
1237                                 tmp = tmp->next();
1238                         }
1239                         // create a new paragraph to insert the
1240                         // minipages in the following case
1241                         if (par->params().pextraStartMinipage() &&
1242                             !par->params().pextraHfill()) {
1243                                 Paragraph * p = new Paragraph;
1244                                 p->layout(textclasslist[params.textclass].defaultLayoutName());
1245                                 
1246                                 p->previous(parBeforeMinipage);
1247                                 parBeforeMinipage->next(p);
1248                                 p->next(0);
1249                                 p->params().depth(parBeforeMinipage->params().depth());
1250                                 parBeforeMinipage = p;
1251                         }
1252                         InsetMinipage * mini = new InsetMinipage;
1253                         mini->pos(static_cast<InsetMinipage::Position>(par->params().pextraAlignment()));
1254                         mini->pageWidth(LyXLength(par->params().pextraWidth()));
1255                         if (!par->params().pextraWidthp().empty()) {
1256                             lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1257                             mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1258                         }
1259                         Paragraph * op = mini->firstParagraph();
1260                         mini->inset.paragraph(par);
1261                         //
1262                         // and free the old ones!
1263                         //
1264                         while(op) {
1265                                 Paragraph * pp = op->next();
1266                                 delete op;
1267                                 op = pp;
1268                         }
1269                         // Insert the minipage last in the
1270                         // previous paragraph.
1271                         if (par->params().pextraHfill()) {
1272                                 parBeforeMinipage->insertChar
1273                                         (parBeforeMinipage->size(), Paragraph::META_HFILL);
1274                         }
1275                         parBeforeMinipage->insertInset
1276                                 (parBeforeMinipage->size(), mini);
1277                                 
1278                         minipar = par;
1279                 } else {
1280                         lyxerr << "new minipage par" << endl;
1281                         //nothing to do just continue reading
1282                 }
1283                         
1284         } else if (minipar && (minipar != par)) {
1285                 lyxerr << "last minipage par read" << endl;
1286                 // The last paragraph read was not part of a
1287                 // minipage but the par linked list is...
1288                 // So we need to remove the last par from the
1289                 // rest
1290                 if (par->previous())
1291                         par->previous()->next(0);
1292                 par->previous(parBeforeMinipage);
1293                 parBeforeMinipage->next(par);
1294                 Paragraph * tmp = minipar;
1295                 while (tmp) {
1296                         tmp->params().pextraType(0);
1297                         tmp->params().pextraWidth(string());
1298                         tmp->params().pextraWidthp(string());
1299                         tmp->params().pextraAlignment(0);
1300                         tmp->params().pextraHfill(false);
1301                         tmp->params().pextraStartMinipage(false);
1302                         tmp = tmp->next();
1303                 }
1304                 depth = parBeforeMinipage->params().depth();
1305                 // and set this depth on the par as it has not been set already
1306                 par->params().depth(depth);
1307                 minipar = parBeforeMinipage = 0;
1308         } else if (!minipar &&
1309                    (par->params().pextraType() == Paragraph::PEXTRA_MINIPAGE))
1310         {
1311                 // par is the first paragraph in a minipage
1312                 lyxerr << "begin minipage" << endl;
1313                 // To minimize problems for
1314                 // the users we will insert
1315                 // the first minipage in
1316                 // a sequence of minipages
1317                 // in its own paragraph.
1318                 Paragraph * p = new Paragraph;
1319                 p->layout(textclasslist[params.textclass].defaultLayoutName());
1320                 p->previous(par->previous());
1321                 p->next(0);
1322                 p->params().depth(depth);
1323                 par->params().depth(0);
1324                 depth = 0;
1325                 if (par->previous())
1326                         par->previous()->next(p);
1327                 par->previous(0);
1328                 parBeforeMinipage = p;
1329                 minipar = par;
1330                 if (!first_par || (first_par == par))
1331                         first_par = p;
1332
1333                 InsetMinipage * mini = new InsetMinipage;
1334                 mini->pos(static_cast<InsetMinipage::Position>(minipar->params().pextraAlignment()));
1335                 mini->pageWidth(LyXLength(minipar->params().pextraWidth()));
1336                 if (!par->params().pextraWidthp().empty()) {
1337                     lyxerr << "WP:" << mini->pageWidth().asString() << endl;
1338                     mini->pageWidth(LyXLength((par->params().pextraWidthp())+"%"));
1339                 }
1340                 mini->inset.paragraph(minipar);
1341                         
1342                 // Insert the minipage last in the
1343                 // previous paragraph.
1344                 if (minipar->params().pextraHfill()) {
1345                         parBeforeMinipage->insertChar
1346                                 (parBeforeMinipage->size(),Paragraph::META_HFILL);
1347                 }
1348                 parBeforeMinipage->insertInset
1349                         (parBeforeMinipage->size(), mini);
1350         }
1351         }
1352         // End of pextra_minipage compability
1353         --call_depth;
1354 #endif
1355 #endif
1356         return the_end_read;
1357 }
1358
1359 // needed to insert the selection
1360 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
1361                                  LyXFont const & fn,string const & str) const
1362 {
1363         LyXLayout const & layout =
1364                 textclasslist[params.textclass][par->layout()];
1365         LyXFont font = fn;
1366         
1367         par->checkInsertChar(font);
1368         // insert the string, don't insert doublespace
1369         bool space_inserted = true;
1370         for(string::const_iterator cit = str.begin(); 
1371             cit != str.end(); ++cit) {
1372                 if (*cit == '\n') {
1373                         if (par->size() || layout.keepempty) { 
1374                                 par->breakParagraph(params, pos, 
1375                                                     layout.isEnvironment());
1376                                 par = par->next();
1377                                 pos = 0;
1378                                 space_inserted = true;
1379                         } else {
1380                                 continue;
1381                         }
1382                         // do not insert consecutive spaces if !free_spacing
1383                 } else if ((*cit == ' ' || *cit == '\t') &&
1384                            space_inserted && !layout.free_spacing &&
1385                                    !par->isFreeSpacing())
1386                 {
1387                         continue;
1388                 } else if (*cit == '\t') {
1389                         if (!layout.free_spacing && !par->isFreeSpacing()) {
1390                                 // tabs are like spaces here
1391                                 par->insertChar(pos, ' ', font);
1392                                 ++pos;
1393                                 space_inserted = true;
1394                         } else {
1395                                 const pos_type nb = 8 - pos % 8;
1396                                 for (pos_type a = 0; a < nb ; ++a) {
1397                                         par->insertChar(pos, ' ', font);
1398                                         ++pos;
1399                                 }
1400                                 space_inserted = true;
1401                         }
1402                 } else if (!IsPrintable(*cit)) {
1403                         // Ignore unprintables
1404                         continue;
1405                 } else {
1406                         // just insert the character
1407                         par->insertChar(pos, *cit, font);
1408                         ++pos;
1409                         space_inserted = (*cit == ' ');
1410                 }
1411
1412         }       
1413 }
1414
1415
1416 void Buffer::readInset(LyXLex & lex, Paragraph *& par,
1417                        int & pos, LyXFont & font)
1418 {
1419         // consistency check
1420         if (lex.getString() != "\\begin_inset") {
1421                 lyxerr << "Buffer::readInset: Consistency check failed."
1422                        << endl;
1423         }
1424         
1425         Inset * inset = 0;
1426
1427         lex.next();
1428         string const tmptok = lex.getString();
1429         last_inset_read = tmptok;
1430
1431         // test the different insets
1432         if (tmptok == "LatexCommand") {
1433                 InsetCommandParams inscmd;
1434                 inscmd.read(lex);
1435
1436                 string const cmdName = inscmd.getCmdName();
1437                 
1438                 // This strange command allows LyX to recognize "natbib" style
1439                 // citations: citet, citep, Citet etc.
1440                 if (compare_no_case(cmdName, "cite", 4) == 0) {
1441                         inset = new InsetCitation(inscmd);
1442                 } else if (cmdName == "bibitem") {
1443                         lex.printError("Wrong place for bibitem");
1444                         inset = new InsetBibKey(inscmd);
1445                 } else if (cmdName == "BibTeX") {
1446                         inset = new InsetBibtex(inscmd);
1447                 } else if (cmdName == "index") {
1448                         inset = new InsetIndex(inscmd);
1449                 } else if (cmdName == "include") {
1450                         inset = new InsetInclude(inscmd, *this);
1451                 } else if (cmdName == "label") {
1452                         inset = new InsetLabel(inscmd);
1453                 } else if (cmdName == "url"
1454                            || cmdName == "htmlurl") {
1455                         inset = new InsetUrl(inscmd);
1456                 } else if (cmdName == "ref"
1457                            || cmdName == "pageref"
1458                            || cmdName == "vref"
1459                            || cmdName == "vpageref"
1460                            || cmdName == "prettyref") {
1461                         if (!inscmd.getOptions().empty()
1462                             || !inscmd.getContents().empty()) {
1463                                 inset = new InsetRef(inscmd, *this);
1464                         }
1465                 } else if (cmdName == "tableofcontents") {
1466                         inset = new InsetTOC(inscmd);
1467                 } else if (cmdName == "listofalgorithms") {
1468                         inset = new InsetFloatList("algorithm");
1469                 } else if (cmdName == "listoffigures") {
1470                         inset = new InsetFloatList("figure");
1471                 } else if (cmdName == "listoftables") {
1472                         inset = new InsetFloatList("table");
1473                 } else if (cmdName == "printindex") {
1474                         inset = new InsetPrintIndex(inscmd);
1475                 } else if (cmdName == "lyxparent") {
1476                         inset = new InsetParent(inscmd, *this);
1477                 }
1478         } else {
1479                 bool alreadyread = false;
1480                 if (tmptok == "Quotes") {
1481                         inset = new InsetQuotes;
1482                 } else if (tmptok == "External") {
1483                         inset = new InsetExternal;
1484                 } else if (tmptok == "FormulaMacro") {
1485                         inset = new InsetFormulaMacro;
1486                 } else if (tmptok == "Formula") {
1487                         inset = new InsetFormula;
1488                 } else if (tmptok == "Figure") { // Backward compatibility
1489 //                      inset = new InsetFig(100, 100, *this);
1490                         inset = new InsetGraphics;
1491                 } else if (tmptok == "Graphics") {
1492                         inset = new InsetGraphics;
1493                 } else if (tmptok == "Info") {// backwards compatibility
1494                         inset = new InsetNote(this,
1495                                               lex.getLongString("\\end_inset"),
1496                                               true);
1497                         alreadyread = true;
1498                 } else if (tmptok == "Note") {
1499                         inset = new InsetNote;
1500                 } else if (tmptok == "Include") {
1501                         InsetCommandParams p("Include");
1502                         inset = new InsetInclude(p, *this);
1503                 } else if (tmptok == "ERT") {
1504                         inset = new InsetERT;
1505                 } else if (tmptok == "Tabular") {
1506                         inset = new InsetTabular(*this);
1507                 } else if (tmptok == "Text") {
1508                         inset = new InsetText;
1509                 } else if (tmptok == "Foot") {
1510                         inset = new InsetFoot;
1511                 } else if (tmptok == "Marginal") {
1512                         inset = new InsetMarginal;
1513                 } else if (tmptok == "Minipage") {
1514                         inset = new InsetMinipage;
1515                 } else if (tmptok == "Float") {
1516                         lex.next();
1517                         string tmptok = lex.getString();
1518                         inset = new InsetFloat(tmptok);
1519 #if 0
1520                 } else if (tmptok == "List") {
1521                         inset = new InsetList;
1522                 } else if (tmptok == "Theorem") {
1523                         inset = new InsetList;
1524 #endif
1525                 } else if (tmptok == "Caption") {
1526                         inset = new InsetCaption;
1527                 } else if (tmptok == "FloatList") {
1528                         inset = new InsetFloatList;
1529                 }
1530                 
1531                 if (inset && !alreadyread) inset->read(this, lex);
1532         }
1533         
1534         if (inset) {
1535                 par->insertInset(pos, inset, font);
1536                 ++pos;
1537         }
1538 }
1539
1540
1541 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1542 {
1543         if (lex.isOK()) {
1544                 lex.next();
1545                 string const token(lex.getString());
1546                 if (token == "\\lyxformat") { // the first token _must_ be...
1547                         lex.eatLine();
1548                         string tmp_format = lex.getString();
1549                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1550                         // if present remove ".," from string.
1551                         string::size_type dot = tmp_format.find_first_of(".,");
1552                         //lyxerr << "           dot found at " << dot << endl;
1553                         if (dot != string::npos)
1554                                 tmp_format.erase(dot, 1);
1555                         file_format = strToInt(tmp_format);
1556                         if (file_format == LYX_FORMAT) {
1557                                 // current format
1558                         } else if (file_format > LYX_FORMAT) {
1559                                 // future format
1560                                 Alert::alert(_("Warning!"),
1561                                            _("LyX file format is newer that what"),
1562                                            _("is supported in this LyX version. Expect some problems."));
1563                                 
1564                         } else if (file_format < LYX_FORMAT) {
1565                                 // old formats
1566                                 if (file_format < 200) {
1567                                         Alert::alert(_("ERROR!"),
1568                                                    _("Old LyX file format found. "
1569                                                      "Use LyX 0.10.x to read this!"));
1570                                         return false;
1571                                 }
1572                         }
1573                         bool the_end = readLyXformat2(lex, par);
1574                         params.setPaperStuff();
1575                         // the_end was added in 213
1576                         if (file_format < 213)
1577                                 the_end = true;
1578
1579                         if (!the_end) {
1580                                 Alert::alert(_("Warning!"),
1581                                            _("Reading of document is not complete"),
1582                                            _("Maybe the document is truncated"));
1583                         }
1584                         return true;
1585                 } else { // "\\lyxformat" not found
1586                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1587                 }
1588         } else
1589                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1590         return false;
1591 }
1592                     
1593
1594 // Should probably be moved to somewhere else: BufferView? LyXView?
1595 bool Buffer::save() const
1596 {
1597         // We don't need autosaves in the immediate future. (Asger)
1598         resetAutosaveTimers();
1599
1600         // make a backup
1601         string s;
1602         if (lyxrc.make_backup) {
1603                 s = fileName() + '~';
1604                 if (!lyxrc.backupdir_path.empty())
1605                         s = AddName(lyxrc.backupdir_path,
1606                                     subst(os::slashify_path(s),'/','!'));
1607
1608                 // Rename is the wrong way of making a backup,
1609                 // this is the correct way.
1610                 /* truss cp fil fil2:
1611                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1612                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1613                    open("LyXVC.lyx", O_RDONLY)                     = 3
1614                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1615                    fstat(4, 0xEFFFF508)                            = 0
1616                    fstat(3, 0xEFFFF508)                            = 0
1617                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1618                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1619                    read(3, 0xEFFFD4A0, 8192)                       = 0
1620                    close(4)                                        = 0
1621                    close(3)                                        = 0
1622                    chmod("LyXVC3.lyx", 0100644)                    = 0
1623                    lseek(0, 0, SEEK_CUR)                           = 46440
1624                    _exit(0)
1625                 */
1626
1627                 // Should probably have some more error checking here.
1628                 // Should be cleaned up in 0.13, at least a bit.
1629                 // Doing it this way, also makes the inodes stay the same.
1630                 // This is still not a very good solution, in particular we
1631                 // might loose the owner of the backup.
1632                 FileInfo finfo(fileName());
1633                 if (finfo.exist()) {
1634                         mode_t fmode = finfo.getMode();
1635                         struct utimbuf times = {
1636                                 finfo.getAccessTime(),
1637                                 finfo.getModificationTime() };
1638
1639                         ifstream ifs(fileName().c_str());
1640                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1641                         if (ifs && ofs) {
1642                                 ofs << ifs.rdbuf();
1643                                 ifs.close();
1644                                 ofs.close();
1645                                 ::chmod(s.c_str(), fmode);
1646                                 
1647                                 if (::utime(s.c_str(), &times)) {
1648                                         lyxerr << "utime error." << endl;
1649                                 }
1650                         } else {
1651                                 lyxerr << "LyX was not able to make "
1652                                         "backup copy. Beware." << endl;
1653                         }
1654                 }
1655         }
1656         
1657         if (writeFile(fileName(), false)) {
1658                 markLyxClean();
1659                 removeAutosaveFile(fileName());
1660         } else {
1661                 // Saving failed, so backup is not backup
1662                 if (lyxrc.make_backup) {
1663                         lyx::rename(s, fileName());
1664                 }
1665                 return false;
1666         }
1667         return true;
1668 }
1669
1670
1671 // Returns false if unsuccesful
1672 bool Buffer::writeFile(string const & fname, bool flag) const
1673 {
1674         // if flag is false writeFile will not create any GUI
1675         // warnings, only cerr.
1676         // Needed for autosave in background or panic save (Matthias 120496)
1677
1678         if (read_only && (fname == fileName())) {
1679                 // Here we should come with a question if we should
1680                 // perform the write anyway.
1681                 if (flag)
1682                         lyxerr << _("Error! Document is read-only: ")
1683                                << fname << endl;
1684                 else
1685                         Alert::alert(_("Error! Document is read-only: "),
1686                                    fname);
1687                 return false;
1688         }
1689
1690         FileInfo finfo(fname);
1691         if (finfo.exist() && !finfo.writable()) {
1692                 // Here we should come with a question if we should
1693                 // try to do the save anyway. (i.e. do a chmod first)
1694                 if (flag)
1695                         lyxerr << _("Error! Cannot write file: ")
1696                                << fname << endl;
1697                 else
1698                         Alert::err_alert(_("Error! Cannot write file: "),
1699                                      fname);
1700                 return false;
1701         }
1702
1703         ofstream ofs(fname.c_str());
1704         if (!ofs) {
1705                 if (flag)
1706                         lyxerr << _("Error! Cannot open file: ")
1707                                << fname << endl;
1708                 else
1709                         Alert::err_alert(_("Error! Cannot open file: "),
1710                                      fname);
1711                 return false;
1712         }
1713
1714 #ifdef HAVE_LOCALE
1715         // Use the standard "C" locale for file output.
1716         ofs.imbue(std::locale::classic());
1717 #endif
1718
1719         // The top of the file should not be written by params.
1720
1721         // write out a comment in the top of the file
1722         ofs << '#' << lyx_docversion 
1723             << " created this file. For more info see http://www.lyx.org/\n"
1724             << "\\lyxformat " << LYX_FORMAT << "\n";
1725
1726         // now write out the buffer paramters.
1727         params.writeFile(ofs);
1728
1729         Paragraph::depth_type depth = 0;
1730
1731         // this will write out all the paragraphs
1732         // using recursive descent.
1733         paragraph->writeFile(this, ofs, params, depth);
1734
1735         // Write marker that shows file is complete
1736         ofs << "\n\\the_end" << endl;
1737
1738         ofs.close();
1739
1740         // how to check if close went ok?
1741         // Following is an attempt... (BE 20001011)
1742         
1743         // good() returns false if any error occured, including some
1744         //        formatting error.
1745         // bad()  returns true if something bad happened in the buffer,
1746         //        which should include file system full errors.
1747
1748         bool status = true;
1749         if (!ofs.good()) {
1750                 status = false;
1751 #if 0
1752                 if (ofs.bad()) {
1753                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1754                 } else {
1755                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1756                                << endl;
1757                 }
1758 #endif
1759         }
1760         
1761         return status;
1762 }
1763
1764
1765 string const Buffer::asciiParagraph(Paragraph const * par,
1766                                     unsigned int linelen,
1767                                     bool noparbreak) const
1768 {
1769         ostringstream buffer;
1770         ostringstream word;
1771         Paragraph::depth_type depth = 0;
1772         int ltype = 0;
1773         Paragraph::depth_type ltype_depth = 0;
1774         string::size_type currlinelen = 0;
1775         bool ref_printed = false;
1776 //      if (!par->previous()) {
1777 #if 0
1778         // begins or ends a deeper area ?
1779         if (depth != par->params().depth()) {
1780                 if (par->params().depth() > depth) {
1781                         while (par->params().depth() > depth) {
1782                                 ++depth;
1783                         }
1784                 } else {
1785                         while (par->params().depth() < depth) {
1786                                 --depth;
1787                         }
1788                 }
1789         }
1790 #else
1791         depth = par->params().depth();
1792 #endif
1793                 
1794         // First write the layout
1795         string const & tmp = lowercase(par->layout());
1796         if (tmp == "itemize") {
1797                 ltype = 1;
1798                 ltype_depth = depth + 1;
1799         } else if (tmp == "enumerate") {
1800                 ltype = 2;
1801                 ltype_depth = depth + 1;
1802         } else if (contains(tmp, "ection")) {
1803                 ltype = 3;
1804                 ltype_depth = depth + 1;
1805         } else if (contains(tmp, "aragraph")) {
1806                 ltype = 4;
1807                 ltype_depth = depth + 1;
1808         } else if (tmp == "description") {
1809                 ltype = 5;
1810                 ltype_depth = depth + 1;
1811         } else if (tmp == "abstract") {
1812                 ltype = 6;
1813                 ltype_depth = 0;
1814         } else if (tmp == "bibliography") {
1815                 ltype = 7;
1816                 ltype_depth = 0;
1817         } else {
1818                 ltype = 0;
1819                 ltype_depth = 0;
1820         }
1821                 
1822         /* maybe some vertical spaces */ 
1823                 
1824         /* the labelwidthstring used in lists */ 
1825                 
1826         /* some lines? */ 
1827                 
1828         /* some pagebreaks? */ 
1829                 
1830         /* noindent ? */ 
1831                 
1832         /* what about the alignment */ 
1833 //      } else {
1834 //              lyxerr << "Should this ever happen?" << endl;
1835 //      }
1836
1837         // linelen <= 0 is special and means we don't have pargraph breaks
1838         if (!noparbreak) {
1839                 if (linelen > 0)
1840                         buffer << "\n\n";
1841                 for (Paragraph::depth_type j = 0; j < depth; ++j)
1842                         buffer << "  ";
1843                 currlinelen = depth * 2;
1844                 //--
1845                 // we should probably change to the paragraph language in the
1846                 // gettext here (if possible) so that strings are outputted in
1847                 // the correct language! (20012712 Jug)
1848                 //--    
1849                 switch (ltype) {
1850                 case 0: // Standard
1851                 case 4: // (Sub)Paragraph
1852                 case 5: // Description
1853                         break;
1854                 case 6: // Abstract
1855                         if (linelen > 0)
1856                                 buffer << _("Abstract") << "\n\n";
1857                         else
1858                                 buffer << _("Abstract: ");
1859                         break;
1860                 case 7: // Bibliography
1861                         if (!ref_printed) {
1862                                 if (linelen > 0)
1863                                         buffer << _("References") << "\n\n";
1864                                 else
1865                                         buffer << _("References: ");
1866                                 ref_printed = true;
1867                         }
1868                         break;
1869                 default:
1870                         buffer << par->params().labelString() << " ";
1871                         break;
1872                 }
1873         }
1874         string s = buffer.str();
1875         if (s.rfind('\n') != string::npos) {
1876                 string dummy;
1877                 s = rsplit(buffer.str().c_str(), dummy, '\n');
1878         }
1879         currlinelen = s.length();
1880         if (!currlinelen) {
1881                 for (Paragraph::depth_type j = 0; j < depth; ++j)
1882                         buffer << "  ";
1883                 currlinelen = depth * 2;
1884                 if (ltype_depth > depth) {
1885                         for (Paragraph::depth_type j = ltype_depth;
1886                                  j > depth; --j)
1887                         {
1888                                 buffer << "  ";
1889                         }
1890                         currlinelen += (ltype_depth-depth)*2;
1891                 }
1892         }
1893         // this is to change the linebreak to do it by word a bit more intelligent
1894         // hopefully! (only in the case where we have a max linelenght!) (Jug)
1895         for (pos_type i = 0; i < par->size(); ++i) {
1896                 char c = par->getUChar(params, i);
1897                 switch (c) {
1898                 case Paragraph::META_INSET:
1899                 {
1900                         Inset const * inset = par->getInset(i);
1901                         if (inset) {
1902                                 if (linelen > 0) {
1903                                         buffer << word.str();
1904                                         word.str("");
1905                                 }
1906                                 if (inset->ascii(this, buffer, linelen)) {
1907                                         // to be sure it breaks paragraph
1908                                         currlinelen += linelen;
1909                                 }
1910 #if 0
1911                                 else {
1912                                         string dummy;
1913                                         string const s =
1914                                                 rsplit(buffer.str().c_str(),
1915                                                        dummy, '\n');
1916                                         currlinelen = s.length();
1917                                 }
1918 #endif
1919                         }
1920                 }
1921                 break;
1922                 
1923                 case Paragraph::META_NEWLINE:
1924                         if (linelen > 0) {
1925                                 buffer << word.str() << "\n";
1926                                 word.str("");
1927                                 for (Paragraph::depth_type j = 0; 
1928                                      j < depth; ++j)
1929                                         buffer << "  ";
1930                                 currlinelen = depth * 2;
1931                                 if (ltype_depth > depth) {
1932                                         for (Paragraph::depth_type j = ltype_depth;
1933                                                  j > depth; --j)
1934                                                 buffer << "  ";
1935                                         currlinelen += (ltype_depth - depth) * 2;
1936                                 }
1937                         }
1938                         break;
1939                         
1940                 case Paragraph::META_HFILL:
1941                         buffer << word.str() << "\t";
1942                         currlinelen += word.str().length() + 1;
1943                         word.str("");
1944                         break;
1945
1946                 default:
1947                         if (c == ' ') {
1948                                 buffer << word.str() << ' ';
1949                                 currlinelen += word.str().length() + 1;
1950                                 word.str("");
1951                         } else {
1952                                 if (c != '\0') {
1953                                         word << c;
1954                                 } else {
1955                                         lyxerr[Debug::INFO] <<
1956                                                 "writeAsciiFile: NULL char in structure." << endl;
1957                                 }
1958                                 if ((linelen > 0) &&
1959                                         (currlinelen+word.str().length()) > linelen)
1960                                 {
1961                                         buffer << "\n";
1962                                         for (Paragraph::depth_type j = 0; j < depth; ++j)
1963                                                 buffer << "  ";
1964                                         currlinelen = depth * 2;
1965                                         if (ltype_depth > depth) {
1966                                                 for (Paragraph::depth_type j = ltype_depth;
1967                                                          j > depth; --j)
1968                                                 {
1969                                                         buffer << "  ";
1970                                                 }
1971                                                 currlinelen += (ltype_depth-depth)*2;
1972                                         }
1973                                 }
1974                         }
1975                         break;
1976                 }
1977         }
1978         buffer << word.str();
1979         return buffer.str().c_str();
1980 }
1981
1982
1983 void Buffer::writeFileAscii(string const & fname, int linelen) 
1984 {
1985         ofstream ofs(fname.c_str());
1986         if (!ofs) {
1987                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1988                 return;
1989         }
1990         writeFileAscii(ofs, linelen);
1991 }
1992
1993
1994 void Buffer::writeFileAscii(ostream & ofs, int linelen) 
1995 {
1996         Paragraph * par = paragraph;
1997         while (par) {
1998                 ofs << asciiParagraph(par, linelen, par->previous() == 0);
1999                 par = par->next();
2000         }
2001         ofs << "\n";
2002 }
2003
2004
2005 bool use_babel;
2006
2007
2008 void Buffer::makeLaTeXFile(string const & fname, 
2009                            string const & original_path,
2010                            bool nice, bool only_body)
2011 {
2012         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
2013         
2014         niceFile = nice; // this will be used by Insetincludes.
2015
2016         tex_code_break_column = lyxrc.ascii_linelen;
2017
2018         LyXTextClass const & tclass =
2019                 textclasslist[params.textclass];
2020
2021         ofstream ofs(fname.c_str());
2022         if (!ofs) {
2023                 Alert::err_alert(_("Error: Cannot open file: "), fname);
2024                 return;
2025         }
2026         
2027         // validate the buffer.
2028         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
2029         LaTeXFeatures features(params, tclass.size());
2030         validate(features);
2031         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
2032         
2033         texrow.reset();
2034         // The starting paragraph of the coming rows is the 
2035         // first paragraph of the document. (Asger)
2036         texrow.start(paragraph, 0);
2037
2038         if (!only_body && nice) {
2039                 ofs << "%% " << lyx_docversion << " created this file.  "
2040                         "For more info, see http://www.lyx.org/.\n"
2041                         "%% Do not edit unless you really know what "
2042                         "you are doing.\n";
2043                 texrow.newline();
2044                 texrow.newline();
2045         }
2046         lyxerr[Debug::INFO] << "lyx header finished" << endl;
2047         // There are a few differences between nice LaTeX and usual files:
2048         // usual is \batchmode and has a 
2049         // special input@path to allow the including of figures
2050         // with either \input or \includegraphics (what figinsets do).
2051         // batchmode is not set if there is a tex_code_break_column.
2052         // In this case somebody is interested in the generated LaTeX,
2053         // so this is OK. input@path is set when the actual parameter
2054         // original_path is set. This is done for usual tex-file, but not
2055         // for nice-latex-file. (Matthias 250696)
2056         if (!only_body) {
2057                 if (!nice) {
2058                         // code for usual, NOT nice-latex-file
2059                         ofs << "\\batchmode\n"; // changed
2060                         // from \nonstopmode
2061                         texrow.newline();
2062                 }
2063                 if (!original_path.empty()) {
2064                         ofs << "\\makeatletter\n"
2065                             << "\\def\\input@path{{"
2066                             << os::external_path(original_path) << "/}}\n"
2067                             << "\\makeatother\n";
2068                         texrow.newline();
2069                         texrow.newline();
2070                         texrow.newline();
2071                 }
2072                 
2073                 ofs << "\\documentclass";
2074                 
2075                 ostringstream options; // the document class options.
2076                 
2077                 if (tokenPos(tclass.opt_fontsize(),
2078                              '|', params.fontsize) >= 0) {
2079                         // only write if existing in list (and not default)
2080                         options << params.fontsize << "pt,";
2081                 }
2082                 
2083                 
2084                 if (!params.use_geometry &&
2085                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
2086                         switch (params.papersize) {
2087                         case BufferParams::PAPER_A4PAPER:
2088                                 options << "a4paper,";
2089                                 break;
2090                         case BufferParams::PAPER_USLETTER:
2091                                 options << "letterpaper,";
2092                                 break;
2093                         case BufferParams::PAPER_A5PAPER:
2094                                 options << "a5paper,";
2095                                 break;
2096                         case BufferParams::PAPER_B5PAPER:
2097                                 options << "b5paper,";
2098                                 break;
2099                         case BufferParams::PAPER_EXECUTIVEPAPER:
2100                                 options << "executivepaper,";
2101                                 break;
2102                         case BufferParams::PAPER_LEGALPAPER:
2103                                 options << "legalpaper,";
2104                                 break;
2105                         }
2106                 }
2107
2108                 // if needed
2109                 if (params.sides != tclass.sides()) {
2110                         switch (params.sides) {
2111                         case LyXTextClass::OneSide:
2112                                 options << "oneside,";
2113                                 break;
2114                         case LyXTextClass::TwoSides:
2115                                 options << "twoside,";
2116                                 break;
2117                         }
2118                 }
2119
2120                 // if needed
2121                 if (params.columns != tclass.columns()) {
2122                         if (params.columns == 2)
2123                                 options << "twocolumn,";
2124                         else
2125                                 options << "onecolumn,";
2126                 }
2127
2128                 if (!params.use_geometry 
2129                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2130                         options << "landscape,";
2131                 
2132                 // language should be a parameter to \documentclass
2133                 use_babel = false;
2134                 ostringstream language_options;
2135                 if (params.language->babel() == "hebrew"
2136                     && default_language->babel() != "hebrew")
2137                          // This seems necessary
2138                         features.useLanguage(default_language);
2139
2140                 if (lyxrc.language_use_babel ||
2141                     params.language->lang() != lyxrc.default_language ||
2142                     !features.hasLanguages()) {
2143                         use_babel = true;
2144                         language_options << features.getLanguages();
2145                         language_options << params.language->babel();
2146                         if (lyxrc.language_global_options)
2147                                 options << language_options.str() << ',';
2148                 }
2149
2150                 // the user-defined options
2151                 if (!params.options.empty()) {
2152                         options << params.options << ',';
2153                 }
2154
2155                 string strOptions(options.str().c_str());
2156                 if (!strOptions.empty()) {
2157                         strOptions = strip(strOptions, ',');
2158                         ofs << '[' << strOptions << ']';
2159                 }
2160                 
2161                 ofs << '{'
2162                     << textclasslist[params.textclass].latexname()
2163                     << "}\n";
2164                 texrow.newline();
2165                 // end of \documentclass defs
2166                 
2167                 // font selection must be done before loading fontenc.sty
2168                 // The ae package is not needed when using OT1 font encoding.
2169                 if (params.fonts != "default" &&
2170                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
2171                         ofs << "\\usepackage{" << params.fonts << "}\n";
2172                         texrow.newline();
2173                         if (params.fonts == "ae") {
2174                                 ofs << "\\usepackage{aecompl}\n";
2175                                 texrow.newline();
2176                         }
2177                 }
2178                 // this one is not per buffer
2179                 if (lyxrc.fontenc != "default") {
2180                         ofs << "\\usepackage[" << lyxrc.fontenc
2181                             << "]{fontenc}\n";
2182                         texrow.newline();
2183                 }
2184
2185                 if (params.inputenc == "auto") {
2186                         string const doc_encoding =
2187                                 params.language->encoding()->LatexName();
2188
2189                         // Create a list with all the input encodings used 
2190                         // in the document
2191                         set<string> encodings = features.getEncodingSet(doc_encoding);
2192
2193                         ofs << "\\usepackage[";
2194                         std::copy(encodings.begin(), encodings.end(),
2195                                   std::ostream_iterator<string>(ofs, ","));
2196                         ofs << doc_encoding << "]{inputenc}\n";
2197                         texrow.newline();
2198                 } else if (params.inputenc != "default") {
2199                         ofs << "\\usepackage[" << params.inputenc
2200                             << "]{inputenc}\n";
2201                         texrow.newline();
2202                 }
2203
2204                 // At the very beginning the text parameters.
2205                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
2206                         switch (params.paperpackage) {
2207                         case BufferParams::PACKAGE_A4:
2208                                 ofs << "\\usepackage{a4}\n";
2209                                 texrow.newline();
2210                                 break;
2211                         case BufferParams::PACKAGE_A4WIDE:
2212                                 ofs << "\\usepackage{a4wide}\n";
2213                                 texrow.newline();
2214                                 break;
2215                         case BufferParams::PACKAGE_WIDEMARGINSA4:
2216                                 ofs << "\\usepackage[widemargins]{a4}\n";
2217                                 texrow.newline();
2218                                 break;
2219                         }
2220                 }
2221                 if (params.use_geometry) {
2222                         ofs << "\\usepackage{geometry}\n";
2223                         texrow.newline();
2224                         ofs << "\\geometry{verbose";
2225                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
2226                                 ofs << ",landscape";
2227                         switch (params.papersize2) {
2228                         case BufferParams::VM_PAPER_CUSTOM:
2229                                 if (!params.paperwidth.empty())
2230                                         ofs << ",paperwidth="
2231                                             << params.paperwidth;
2232                                 if (!params.paperheight.empty())
2233                                         ofs << ",paperheight="
2234                                             << params.paperheight;
2235                                 break;
2236                         case BufferParams::VM_PAPER_USLETTER:
2237                                 ofs << ",letterpaper";
2238                                 break;
2239                         case BufferParams::VM_PAPER_USLEGAL:
2240                                 ofs << ",legalpaper";
2241                                 break;
2242                         case BufferParams::VM_PAPER_USEXECUTIVE:
2243                                 ofs << ",executivepaper";
2244                                 break;
2245                         case BufferParams::VM_PAPER_A3:
2246                                 ofs << ",a3paper";
2247                                 break;
2248                         case BufferParams::VM_PAPER_A4:
2249                                 ofs << ",a4paper";
2250                                 break;
2251                         case BufferParams::VM_PAPER_A5:
2252                                 ofs << ",a5paper";
2253                                 break;
2254                         case BufferParams::VM_PAPER_B3:
2255                                 ofs << ",b3paper";
2256                                 break;
2257                         case BufferParams::VM_PAPER_B4:
2258                                 ofs << ",b4paper";
2259                                 break;
2260                         case BufferParams::VM_PAPER_B5:
2261                                 ofs << ",b5paper";
2262                                 break;
2263                         default:
2264                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
2265                                 switch (lyxrc.default_papersize) {
2266                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
2267                                 case BufferParams::PAPER_USLETTER:
2268                                         ofs << ",letterpaper";
2269                                         break;
2270                                 case BufferParams::PAPER_LEGALPAPER:
2271                                         ofs << ",legalpaper";
2272                                         break;
2273                                 case BufferParams::PAPER_EXECUTIVEPAPER:
2274                                         ofs << ",executivepaper";
2275                                         break;
2276                                 case BufferParams::PAPER_A3PAPER:
2277                                         ofs << ",a3paper";
2278                                         break;
2279                                 case BufferParams::PAPER_A4PAPER:
2280                                         ofs << ",a4paper";
2281                                         break;
2282                                 case BufferParams::PAPER_A5PAPER:
2283                                         ofs << ",a5paper";
2284                                         break;
2285                                 case BufferParams::PAPER_B5PAPER:
2286                                         ofs << ",b5paper";
2287                                         break;
2288                                 }
2289                         }
2290                         if (!params.topmargin.empty())
2291                                 ofs << ",tmargin=" << params.topmargin;
2292                         if (!params.bottommargin.empty())
2293                                 ofs << ",bmargin=" << params.bottommargin;
2294                         if (!params.leftmargin.empty())
2295                                 ofs << ",lmargin=" << params.leftmargin;
2296                         if (!params.rightmargin.empty())
2297                                 ofs << ",rmargin=" << params.rightmargin;
2298                         if (!params.headheight.empty())
2299                                 ofs << ",headheight=" << params.headheight;
2300                         if (!params.headsep.empty())
2301                                 ofs << ",headsep=" << params.headsep;
2302                         if (!params.footskip.empty())
2303                                 ofs << ",footskip=" << params.footskip;
2304                         ofs << "}\n";
2305                         texrow.newline();
2306                 }
2307
2308                 if (tokenPos(tclass.opt_pagestyle(),
2309                              '|', params.pagestyle) >= 0) {
2310                         if (params.pagestyle == "fancy") {
2311                                 ofs << "\\usepackage{fancyhdr}\n";
2312                                 texrow.newline();
2313                         }
2314                         ofs << "\\pagestyle{" << params.pagestyle << "}\n";
2315                         texrow.newline();
2316                 }
2317
2318                 if (params.secnumdepth != tclass.secnumdepth()) {
2319                         ofs << "\\setcounter{secnumdepth}{"
2320                             << params.secnumdepth
2321                             << "}\n";
2322                         texrow.newline();
2323                 }
2324                 if (params.tocdepth != tclass.tocdepth()) {
2325                         ofs << "\\setcounter{tocdepth}{"
2326                             << params.tocdepth
2327                             << "}\n";
2328                         texrow.newline();
2329                 }
2330                 
2331                 if (params.paragraph_separation) {
2332                         switch (params.defskip.kind()) {
2333                         case VSpace::SMALLSKIP: 
2334                                 ofs << "\\setlength\\parskip{\\smallskipamount}\n";
2335                                 break;
2336                         case VSpace::MEDSKIP:
2337                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2338                                 break;
2339                         case VSpace::BIGSKIP:
2340                                 ofs << "\\setlength\\parskip{\\bigskipamount}\n";
2341                                 break;
2342                         case VSpace::LENGTH:
2343                                 ofs << "\\setlength\\parskip{"
2344                                     << params.defskip.length().asLatexString()
2345                                     << "}\n";
2346                                 break;
2347                         default: // should never happen // Then delete it.
2348                                 ofs << "\\setlength\\parskip{\\medskipamount}\n";
2349                                 break;
2350                         }
2351                         texrow.newline();
2352                         
2353                         ofs << "\\setlength\\parindent{0pt}\n";
2354                         texrow.newline();
2355                 }
2356
2357                 // Now insert the LyX specific LaTeX commands...
2358
2359                 // The optional packages;
2360                 string preamble(features.getPackages());
2361
2362                 // this might be useful...
2363                 preamble += "\n\\makeatletter\n";
2364
2365                 // Some macros LyX will need
2366                 string tmppreamble(features.getMacros());
2367
2368                 if (!tmppreamble.empty()) {
2369                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2370                                 "LyX specific LaTeX commands.\n"
2371                                 + tmppreamble + '\n';
2372                 }
2373
2374                 // the text class specific preamble 
2375                 tmppreamble = features.getTClassPreamble();
2376                 if (!tmppreamble.empty()) {
2377                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2378                                 "Textclass specific LaTeX commands.\n"
2379                                 + tmppreamble + '\n';
2380                 }
2381
2382                 /* the user-defined preamble */
2383                 if (!params.preamble.empty()) {
2384                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2385                                 "User specified LaTeX commands.\n"
2386                                 + params.preamble + '\n';
2387                 }
2388
2389                 preamble += "\\makeatother\n";
2390
2391                 // Itemize bullet settings need to be last in case the user
2392                 // defines their own bullets that use a package included
2393                 // in the user-defined preamble -- ARRae
2394                 // Actually it has to be done much later than that
2395                 // since some packages like frenchb make modifications
2396                 // at \begin{document} time -- JMarc 
2397                 string bullets_def;
2398                 for (int i = 0; i < 4; ++i) {
2399                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2400                                 if (bullets_def.empty())
2401                                         bullets_def="\\AtBeginDocument{\n";
2402                                 bullets_def += "  \\renewcommand{\\labelitemi";
2403                                 switch (i) {
2404                                 // `i' is one less than the item to modify
2405                                 case 0:
2406                                         break;
2407                                 case 1:
2408                                         bullets_def += 'i';
2409                                         break;
2410                                 case 2:
2411                                         bullets_def += "ii";
2412                                         break;
2413                                 case 3:
2414                                         bullets_def += 'v';
2415                                         break;
2416                                 }
2417                                 bullets_def += "}{" + 
2418                                   params.user_defined_bullets[i].getText() 
2419                                   + "}\n";
2420                         }
2421                 }
2422
2423                 if (!bullets_def.empty())
2424                   preamble += bullets_def + "}\n\n";
2425
2426                 int const nlines =
2427                         int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2428                 for (int j = 0; j != nlines; ++j) {
2429                         texrow.newline();
2430                 }
2431
2432                 ofs << preamble;
2433
2434                 // We try to load babel late, in case it interferes
2435                 // with other packages.
2436                 if (use_babel) {
2437                         string tmp = lyxrc.language_package;
2438                         if (!lyxrc.language_global_options
2439                             && tmp == "\\usepackage{babel}")
2440                                 tmp = string("\\usepackage[") +
2441                                         language_options.str().c_str() +
2442                                         "]{babel}";
2443                         ofs << tmp << "\n";
2444                         texrow.newline();
2445                 }
2446
2447                 // make the body.
2448                 ofs << "\\begin{document}\n";
2449                 texrow.newline();
2450         } // only_body
2451         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2452
2453         if (!lyxrc.language_auto_begin) {
2454                 ofs << subst(lyxrc.language_command_begin, "$$lang",
2455                              params.language->babel())
2456                     << endl;
2457                 texrow.newline();
2458         }
2459         
2460         latexParagraphs(ofs, paragraph, 0, texrow);
2461
2462         // add this just in case after all the paragraphs
2463         ofs << endl;
2464         texrow.newline();
2465
2466         if (!lyxrc.language_auto_end) {
2467                 ofs << subst(lyxrc.language_command_end, "$$lang",
2468                              params.language->babel())
2469                     << endl;
2470                 texrow.newline();
2471         }
2472
2473         if (!only_body) {
2474                 ofs << "\\end{document}\n";
2475                 texrow.newline();
2476         
2477                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2478         } else {
2479                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2480                                      << endl;
2481         }
2482
2483         // Just to be sure. (Asger)
2484         texrow.newline();
2485
2486         // tex_code_break_column's value is used to decide
2487         // if we are in batchmode or not (within mathed_write()
2488         // in math_write.C) so we must set it to a non-zero
2489         // value when we leave otherwise we save incorrect .lyx files.
2490         tex_code_break_column = lyxrc.ascii_linelen;
2491
2492         ofs.close();
2493         if (ofs.fail()) {
2494                 lyxerr << "File was not closed properly." << endl;
2495         }
2496         
2497         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2498         lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2499 }
2500
2501
2502 //
2503 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2504 //
2505 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2506                              Paragraph * endpar, TexRow & texrow) const
2507 {
2508         bool was_title = false;
2509         bool already_title = false;
2510
2511         // if only_body
2512         while (par != endpar) {
2513                 Inset * in = par->inInset();
2514                 // well we have to check if we are in an inset with unlimited
2515                 // lenght (all in one row) if that is true then we don't allow
2516                 // any special options in the paragraph and also we don't allow
2517                 // any environment other then "Standard" to be valid!
2518                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2519                         LyXLayout const & layout =
2520                                 textclasslist[params.textclass][par->layout()];
2521                         
2522                         if (layout.intitle) {
2523                                 if (already_title) {
2524                                         lyxerr <<"Error in latexParagraphs: You"
2525                                                 " should not mix title layouts"
2526                                                 " with normal ones." << endl;
2527                                 } else
2528                                         was_title = true;
2529                         } else if (was_title && !already_title) {
2530                                 ofs << "\\maketitle\n";
2531                                 texrow.newline();
2532                                 already_title = true;
2533                                 was_title = false;                  
2534                         }
2535                         
2536                         if (layout.isEnvironment()) {
2537                                 par = par->TeXEnvironment(this, params, ofs, texrow);
2538                         } else {
2539                                 par = par->TeXOnePar(this, params, ofs, texrow, false);
2540                         }
2541                 } else {
2542                         par = par->TeXOnePar(this, params, ofs, texrow, false);
2543                 }
2544         }
2545         // It might be that we only have a title in this document
2546         if (was_title && !already_title) {
2547                 ofs << "\\maketitle\n";
2548                 texrow.newline();
2549         }
2550 }
2551
2552
2553 bool Buffer::isLatex() const
2554 {
2555         return textclasslist[params.textclass].outputType() == LATEX;
2556 }
2557
2558
2559 bool Buffer::isLinuxDoc() const
2560 {
2561         return textclasslist[params.textclass].outputType() == LINUXDOC;
2562 }
2563
2564
2565 bool Buffer::isLiterate() const
2566 {
2567         return textclasslist[params.textclass].outputType() == LITERATE;
2568 }
2569
2570
2571 bool Buffer::isDocBook() const
2572 {
2573         return textclasslist[params.textclass].outputType() == DOCBOOK;
2574 }
2575
2576
2577 bool Buffer::isSGML() const
2578 {
2579         LyXTextClass const & tclass = textclasslist[params.textclass];
2580         
2581         return tclass.outputType() == LINUXDOC ||
2582                tclass.outputType() == DOCBOOK;
2583 }
2584
2585
2586 void Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth,
2587                          string const & latexname) const
2588 {
2589         if (!latexname.empty() && latexname != "!-- --")
2590                 //os << "<!-- " << depth << " -->" << "<" << latexname << ">";
2591                 os << string(depth, ' ') << "<" << latexname << ">\n";
2592 }
2593
2594
2595 void Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth,
2596                           string const & latexname) const
2597 {
2598         if (!latexname.empty() && latexname != "!-- --")
2599                 //os << "<!-- " << depth << " -->" << "</" << latexname << ">\n";
2600                 os << string(depth, ' ') << "</" << latexname << ">\n";
2601 }
2602
2603
2604 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2605 {
2606         ofstream ofs(fname.c_str());
2607
2608         if (!ofs) {
2609                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2610                 return;
2611         }
2612
2613         niceFile = nice; // this will be used by included files.
2614
2615         LyXTextClass const & tclass = textclasslist[params.textclass];
2616
2617         LaTeXFeatures features(params, tclass.size());
2618         
2619         validate(features);
2620
2621         texrow.reset();
2622
2623         string top_element = textclasslist[params.textclass].latexname();
2624
2625         if (!body_only) {
2626                 ofs << "<!doctype linuxdoc system";
2627
2628                 string preamble = params.preamble;
2629                 preamble += features.getIncludedFiles(fname);
2630                 preamble += features.getLyXSGMLEntities();
2631
2632                 if (!preamble.empty()) {
2633                         ofs << " [ " << preamble << " ]";
2634                 }
2635                 ofs << ">\n\n";
2636
2637                 if (params.options.empty())
2638                         sgmlOpenTag(ofs, 0, top_element);
2639                 else {
2640                         string top = top_element;
2641                         top += " ";
2642                         top += params.options;
2643                         sgmlOpenTag(ofs, 0, top);
2644                 }
2645         }
2646
2647         ofs << "<!-- "  << lyx_docversion
2648             << " created this file. For more info see http://www.lyx.org/"
2649             << " -->\n";
2650
2651         Paragraph::depth_type depth = 0; // paragraph depth
2652         Paragraph * par = paragraph;
2653         string item_name;
2654         vector<string> environment_stack(5);
2655
2656         while (par) {
2657                 LyXLayout const & style =
2658                         textclasslist[params.textclass][par->layout()];
2659
2660                 // treat <toc> as a special case for compatibility with old code
2661                 if (par->isInset(0)) {
2662                         Inset * inset = par->getInset(0);
2663                         Inset::Code lyx_code = inset->lyxCode();
2664                         if (lyx_code == Inset::TOC_CODE) {
2665                                 string const temp = "toc";
2666                                 sgmlOpenTag(ofs, depth, temp);
2667
2668                                 par = par->next();
2669                                 continue;
2670                         }
2671                 }
2672
2673                 // environment tag closing
2674                 for (; depth > par->params().depth(); --depth) {
2675                         sgmlCloseTag(ofs, depth, environment_stack[depth]);
2676                         environment_stack[depth].erase();
2677                 }
2678
2679                 // write opening SGML tags
2680                 switch (style.latextype) {
2681                 case LATEX_PARAGRAPH:
2682                         if (depth == par->params().depth() 
2683                            && !environment_stack[depth].empty()) {
2684                                 sgmlCloseTag(ofs, depth, environment_stack[depth]);
2685                                 environment_stack[depth].erase();
2686                                 if (depth) 
2687                                         --depth;
2688                                 else
2689                                         ofs << "</p>";
2690                         }
2691                         sgmlOpenTag(ofs, depth, style.latexname());
2692                         break;
2693
2694                 case LATEX_COMMAND:
2695                         if (depth!= 0)
2696                                 sgmlError(par, 0,
2697                                           _("Error : Wrong depth for"
2698                                             " LatexType Command.\n"));
2699
2700                         if (!environment_stack[depth].empty()) {
2701                                 sgmlCloseTag(ofs, depth,
2702                                              environment_stack[depth]);
2703                                 ofs << "</p>";
2704                         }
2705
2706                         environment_stack[depth].erase();
2707                         sgmlOpenTag(ofs, depth, style.latexname());
2708                         break;
2709
2710                 case LATEX_ENVIRONMENT:
2711                 case LATEX_ITEM_ENVIRONMENT:
2712                         if (depth == par->params().depth() 
2713                             && environment_stack[depth] != style.latexname()) {
2714                                 sgmlCloseTag(ofs, depth,
2715                                              environment_stack[depth]);
2716                                 environment_stack[depth].erase();
2717                         }
2718                         if (depth < par->params().depth()) {
2719                                depth = par->params().depth();
2720                                environment_stack[depth].erase();
2721                         }
2722                         if (environment_stack[depth] != style.latexname()) {
2723                                 if (depth == 0) {
2724                                         sgmlOpenTag(ofs, depth, "p");
2725                                 }
2726                                 sgmlOpenTag(ofs, depth, style.latexname());
2727
2728                                 if (environment_stack.size() == depth + 1)
2729                                         environment_stack.push_back("!-- --");
2730                                 environment_stack[depth] = style.latexname();
2731                         }
2732
2733                         if (style.latexparam() == "CDATA")
2734                                 ofs << "<![CDATA[";
2735
2736                         if (style.latextype == LATEX_ENVIRONMENT) break;
2737
2738                         if (style.labeltype == LABEL_MANUAL)
2739                                 item_name = "tag";
2740                         else
2741                                 item_name = "item";
2742
2743                         sgmlOpenTag(ofs, depth + 1, item_name);
2744                         break;
2745                 default:
2746                         sgmlOpenTag(ofs, depth, style.latexname());
2747                         break;
2748                 }
2749
2750                 simpleLinuxDocOnePar(ofs, par, depth);
2751
2752                 par = par->next();
2753
2754                 ofs << "\n";
2755                 // write closing SGML tags
2756                 switch (style.latextype) {
2757                 case LATEX_COMMAND:
2758                         break;
2759                 case LATEX_ENVIRONMENT:
2760                 case LATEX_ITEM_ENVIRONMENT:
2761                         if (style.latexparam() == "CDATA")
2762                                 ofs << "]]>";
2763                         break;
2764                 default:
2765                         sgmlCloseTag(ofs, depth, style.latexname());
2766                         break;
2767                 }
2768         }
2769    
2770         // Close open tags
2771         for (int i=depth; i >= 0; --i)
2772                 sgmlCloseTag(ofs, depth, environment_stack[i]);
2773
2774         if (!body_only) {
2775                 ofs << "\n\n";
2776                 sgmlCloseTag(ofs, 0, top_element);
2777         }
2778
2779         ofs.close();
2780         // How to check for successful close
2781 }
2782
2783
2784 // checks, if newcol chars should be put into this line
2785 // writes newline, if necessary.
2786 namespace {
2787
2788 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2789                           string::size_type newcol)
2790 {
2791         colcount += newcol;
2792         if (colcount > lyxrc.ascii_linelen) {
2793                 os << "\n";
2794                 colcount = newcol; // assume write after this call
2795         }
2796 }
2797
2798 enum PAR_TAG {
2799         NONE=0,
2800         TT = 1,
2801         SF = 2,
2802         BF = 4,
2803         IT = 8,
2804         SL = 16,
2805         EM = 32
2806 };
2807
2808
2809 string tag_name(PAR_TAG const & pt) {
2810         switch (pt) {
2811         case NONE: return "!-- --";
2812         case TT: return "tt";
2813         case SF: return "sf";
2814         case BF: return "bf";
2815         case IT: return "it";
2816         case SL: return "sl";
2817         case EM: return "em";
2818         }
2819         return "";
2820 }
2821
2822
2823 inline
2824 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2825 {
2826         p1 = static_cast<PAR_TAG>(p1 | p2);
2827 }
2828
2829
2830 inline
2831 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2832 {
2833         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2834 }
2835
2836 } // namespace anon
2837
2838
2839 // Handle internal paragraph parsing -- layout already processed.
2840 void Buffer::simpleLinuxDocOnePar(ostream & os,
2841                                   Paragraph * par, 
2842                                   Paragraph::depth_type /*depth*/)
2843 {
2844         LyXLayout const & style =
2845                 textclasslist[params.textclass][par->layout()];
2846         string::size_type char_line_count = 5;     // Heuristic choice ;-) 
2847
2848         // gets paragraph main font
2849         LyXFont font_old;
2850         bool desc_on;
2851         if (style.labeltype == LABEL_MANUAL) {
2852                 font_old = style.labelfont;
2853                 desc_on = true;
2854         } else {
2855                 font_old = style.font;
2856                 desc_on = false;
2857         }
2858
2859         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2860         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2861         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2862         bool is_em = false;
2863
2864         stack<PAR_TAG> tag_state;
2865         // parsing main loop
2866         for (pos_type i = 0; i < par->size(); ++i) {
2867
2868                 PAR_TAG tag_close = NONE;
2869                 list < PAR_TAG > tag_open;
2870
2871                 LyXFont const font = par->getFont(params, i);
2872
2873                 if (font_old.family() != font.family()) {
2874                         switch (family_type) {
2875                         case LyXFont::SANS_FAMILY:
2876                                 tag_close |= SF;
2877                                 break;
2878                         case LyXFont::TYPEWRITER_FAMILY:
2879                                 tag_close |= TT;
2880                                 break;
2881                         default:
2882                                 break;
2883                         }
2884
2885                         family_type = font.family();
2886
2887                         switch (family_type) {
2888                         case LyXFont::SANS_FAMILY:
2889                                 tag_open.push_back(SF);
2890                                 break;
2891                         case LyXFont::TYPEWRITER_FAMILY:
2892                                 tag_open.push_back(TT);
2893                                 break;
2894                         default:
2895                                 break;
2896                         }
2897                 }
2898
2899                 if (font_old.series() != font.series()) {
2900                         switch (series_type) {
2901                         case LyXFont::BOLD_SERIES:
2902                                 tag_close |= BF;
2903                                 break;
2904                         default:
2905                                 break;
2906                         }
2907
2908                         series_type = font.series();
2909
2910                         switch (series_type) {
2911                         case LyXFont::BOLD_SERIES:
2912                                 tag_open.push_back(BF);
2913                                 break;
2914                         default:
2915                                 break;
2916                         }
2917
2918                 }
2919
2920                 if (font_old.shape() != font.shape()) {
2921                         switch (shape_type) {
2922                         case LyXFont::ITALIC_SHAPE:
2923                                 tag_close |= IT;
2924                                 break;
2925                         case LyXFont::SLANTED_SHAPE:
2926                                 tag_close |= SL;
2927                                 break;
2928                         default:
2929                                 break;
2930                         }
2931
2932                         shape_type = font.shape();
2933
2934                         switch (shape_type) {
2935                         case LyXFont::ITALIC_SHAPE:
2936                                 tag_open.push_back(IT);
2937                                 break;
2938                         case LyXFont::SLANTED_SHAPE:
2939                                 tag_open.push_back(SL);
2940                                 break;
2941                         default:
2942                                 break;
2943                         }
2944                 }
2945                 // handle <em> tag
2946                 if (font_old.emph() != font.emph()) {
2947                         if (font.emph() == LyXFont::ON) {
2948                                 tag_open.push_back(EM);
2949                                 is_em = true;
2950                         }
2951                         else if (is_em) {
2952                                 tag_close |= EM;
2953                                 is_em = false;
2954                         }
2955                 }
2956
2957                 list < PAR_TAG > temp;
2958                 while (!tag_state.empty() && tag_close) {
2959                         PAR_TAG k =  tag_state.top();
2960                         tag_state.pop();
2961                         os << "</" << tag_name(k) << ">";
2962                         if (tag_close & k)
2963                                 reset(tag_close,k);
2964                         else
2965                                 temp.push_back(k);
2966                 }
2967
2968                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2969                     j != temp.end(); ++j) {
2970                         tag_state.push(*j);
2971                         os << "<" << tag_name(*j) << ">";
2972                 }
2973
2974                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2975                     j != tag_open.end(); ++j) {
2976                         tag_state.push(*j);
2977                         os << "<" << tag_name(*j) << ">";
2978                 }
2979
2980                 char c = par->getChar(i);
2981
2982                 if (c == Paragraph::META_INSET) {
2983                         Inset * inset = par->getInset(i);
2984                         inset->linuxdoc(this, os);
2985                         font_old = font;
2986                         continue;
2987                 }
2988
2989                 if (style.latexparam() == "CDATA") {
2990                         // "TeX"-Mode on == > SGML-Mode on.
2991                         if (c != '\0')
2992                                 os << c;
2993                         ++char_line_count;
2994                 } else {
2995                         string sgml_string;
2996                         if (par->sgmlConvertChar(c, sgml_string)
2997                             && !style.free_spacing && !par->isFreeSpacing())
2998                         { 
2999                                 // in freespacing mode, spaces are
3000                                 // non-breaking characters
3001                                 if (desc_on) {// if char is ' ' then...
3002
3003                                         ++char_line_count;
3004                                         sgmlLineBreak(os, char_line_count, 6);
3005                                         os << "</tag>";
3006                                         desc_on = false;
3007                                 } else  {
3008                                         sgmlLineBreak(os, char_line_count, 1);
3009                                         os << c;
3010                                 }
3011                         } else {
3012                                 os << sgml_string;
3013                                 char_line_count += sgml_string.length();
3014                         }
3015                 }
3016                 font_old = font;
3017         }
3018
3019         while (!tag_state.empty()) {
3020                 os << "</" << tag_name(tag_state.top()) << ">";
3021                 tag_state.pop();
3022         }
3023
3024         // resets description flag correctly
3025         if (desc_on) {
3026                 // <tag> not closed...
3027                 sgmlLineBreak(os, char_line_count, 6);
3028                 os << "</tag>";
3029         }
3030 }
3031
3032
3033 // Print an error message.
3034 void Buffer::sgmlError(Paragraph * par, int pos,
3035                        string const & message) const
3036 {
3037         // insert an error marker in text
3038         InsetError * new_inset = new InsetError(message);
3039         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT, 
3040                                                  params.language));
3041 }
3042
3043
3044 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
3045 {
3046         ofstream ofs(fname.c_str());
3047         if (!ofs) {
3048                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
3049                 return;
3050         }
3051
3052         Paragraph * par = paragraph;
3053
3054         niceFile = nice; // this will be used by Insetincludes.
3055
3056         LyXTextClass const & tclass =
3057                 textclasslist[params.textclass];
3058
3059         LaTeXFeatures features(params, tclass.size());
3060         validate(features);
3061    
3062         texrow.reset();
3063
3064         string top_element = textclasslist[params.textclass].latexname();
3065
3066         if (!only_body) {
3067                 ofs << "<!DOCTYPE " << top_element
3068                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
3069
3070                 string preamble = params.preamble;
3071                 preamble += features.getIncludedFiles(fname);
3072                 preamble += features.getLyXSGMLEntities();
3073
3074                 if (!preamble.empty()) {
3075                         ofs << "\n [ " << preamble << " ]";
3076                 }
3077                 ofs << ">\n\n";
3078         }
3079
3080         string top = top_element;       
3081         top += " lang=\"";
3082         top += params.language->code();
3083         top += "\"";
3084
3085         if (!params.options.empty()) {
3086                 top += " ";
3087                 top += params.options;
3088         }
3089         sgmlOpenTag(ofs, 0, top);
3090
3091         ofs << "<!-- DocBook file was created by " << lyx_docversion
3092             << "\n  See http://www.lyx.org/ for more information -->\n";
3093
3094         vector<string> environment_stack(10);
3095         vector<string> environment_inner(10);
3096         vector<string> command_stack(10);
3097
3098         bool command_flag = false;
3099         Paragraph::depth_type command_depth = 0;
3100         Paragraph::depth_type command_base = 0;
3101         Paragraph::depth_type cmd_depth = 0;
3102         Paragraph::depth_type depth = 0; // paragraph depth
3103
3104         string item_name;
3105         string command_name;
3106
3107         while (par) {
3108                 string sgmlparam;
3109                 string c_depth;
3110                 string c_params;
3111                 int desc_on = 0; // description mode
3112
3113                 LyXLayout const & style =
3114                         textclasslist[params.textclass][par->layout()];
3115
3116                 // environment tag closing
3117                 for (; depth > par->params().depth(); --depth) {
3118                         if (environment_inner[depth] != "!-- --") {
3119                                 item_name = "listitem";
3120                                 sgmlCloseTag(ofs, command_depth + depth,
3121                                              item_name);
3122                                 if (environment_inner[depth] == "varlistentry")
3123                                         sgmlCloseTag(ofs, depth+command_depth,
3124                                                      environment_inner[depth]);
3125                         }
3126                         sgmlCloseTag(ofs, depth + command_depth,
3127                                      environment_stack[depth]);
3128                         environment_stack[depth].erase();
3129                         environment_inner[depth].erase();
3130                 }
3131
3132                 if (depth == par->params().depth()
3133                    && environment_stack[depth] != style.latexname()
3134                    && !environment_stack[depth].empty()) {
3135                         if (environment_inner[depth] != "!-- --") {
3136                                 item_name= "listitem";
3137                                 sgmlCloseTag(ofs, command_depth+depth,
3138                                              item_name);
3139                                 if (environment_inner[depth] == "varlistentry")
3140                                         sgmlCloseTag(ofs,
3141                                                      depth + command_depth,
3142                                                      environment_inner[depth]);
3143                         }
3144                         
3145                         sgmlCloseTag(ofs, depth + command_depth,
3146                                      environment_stack[depth]);
3147                         
3148                         environment_stack[depth].erase();
3149                         environment_inner[depth].erase();
3150                 }
3151
3152                 // Write opening SGML tags.
3153                 switch (style.latextype) {
3154                 case LATEX_PARAGRAPH:
3155                         sgmlOpenTag(ofs, depth + command_depth,
3156                                     style.latexname());
3157                         break;
3158
3159                 case LATEX_COMMAND:
3160                         if (depth != 0)
3161                                 sgmlError(par, 0,
3162                                           _("Error : Wrong depth for "
3163                                             "LatexType Command.\n"));
3164                         
3165                         command_name = style.latexname();
3166                         
3167                         sgmlparam = style.latexparam();
3168                         c_params = split(sgmlparam, c_depth,'|');
3169                         
3170                         cmd_depth = lyx::atoi(c_depth);
3171                         
3172                         if (command_flag) {
3173                                 if (cmd_depth < command_base) {
3174                                         for (Paragraph::depth_type j = command_depth; j >= command_base; --j)
3175                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3176                                         command_depth = command_base = cmd_depth;
3177                                 } else if (cmd_depth <= command_depth) {
3178                                         for (int j = command_depth; j >= int(cmd_depth); --j)
3179                                                 sgmlCloseTag(ofs, j, command_stack[j]);
3180                                         command_depth = cmd_depth;
3181                                 } else
3182                                         command_depth = cmd_depth;
3183                         } else {
3184                                 command_depth = command_base = cmd_depth;
3185                                 command_flag = true;
3186                         }
3187                         if (command_stack.size() == command_depth + 1)
3188                                 command_stack.push_back(string());
3189                         command_stack[command_depth] = command_name;
3190
3191                         // treat label as a special case for
3192                         // more WYSIWYM handling.
3193                         // This is a hack while paragraphs can't have
3194                         // attributes, like id in this case.
3195                         if (par->isInset(0)) {
3196                                 Inset * inset = par->getInset(0);
3197                                 Inset::Code lyx_code = inset->lyxCode();
3198                                 if (lyx_code == Inset::LABEL_CODE) {
3199                                         command_name += " id=\"";
3200                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
3201                                         command_name += "\"";
3202                                         desc_on = 3;
3203                                 }
3204                         }
3205
3206                         sgmlOpenTag(ofs, depth + command_depth, command_name);
3207                         if (c_params.empty())
3208                                 item_name = "title";
3209                         else
3210                                 item_name = c_params;
3211                         sgmlOpenTag(ofs, depth + 1 + command_depth, item_name);
3212                         break;
3213
3214                 case LATEX_ENVIRONMENT:
3215                 case LATEX_ITEM_ENVIRONMENT:
3216                         if (depth < par->params().depth()) {
3217                                 depth = par->params().depth();
3218                                 environment_stack[depth].erase();
3219                         }
3220
3221                         if (environment_stack[depth] != style.latexname()) {
3222                                 if (environment_stack.size() == depth + 1) {
3223                                         environment_stack.push_back("!-- --");
3224                                         environment_inner.push_back("!-- --");
3225                                 }
3226                                 environment_stack[depth] = style.latexname();
3227                                 environment_inner[depth] = "!-- --";
3228                                 sgmlOpenTag(ofs, depth + command_depth,
3229                                             environment_stack[depth]);
3230                         } else {
3231                                 if (environment_inner[depth] != "!-- --") {
3232                                         item_name= "listitem";
3233                                         sgmlCloseTag(ofs,
3234                                                      command_depth + depth,
3235                                                      item_name);
3236                                         if (environment_inner[depth] == "varlistentry")
3237                                                 sgmlCloseTag(ofs,
3238                                                              depth + command_depth,
3239                                                              environment_inner[depth]);
3240                                 }
3241                         }
3242                         
3243                         if (style.latextype == LATEX_ENVIRONMENT) {
3244                                 if (!style.latexparam().empty()) {
3245                                         if (style.latexparam() == "CDATA")
3246                                                 ofs << "<![CDATA[";
3247                                         else
3248                                                 sgmlOpenTag(ofs, depth + command_depth,
3249                                                             style.latexparam());
3250                                 }
3251                                 break;
3252                         }
3253
3254                         desc_on = (style.labeltype == LABEL_MANUAL);
3255
3256                         if (desc_on)
3257                                 environment_inner[depth]= "varlistentry";
3258                         else
3259                                 environment_inner[depth]= "listitem";
3260
3261                         sgmlOpenTag(ofs, depth + 1 + command_depth,
3262                                     environment_inner[depth]);
3263
3264                         if (desc_on) {
3265                                 item_name= "term";
3266                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3267                                             item_name);
3268                         } else {
3269                                 item_name= "para";
3270                                 sgmlOpenTag(ofs, depth + 1 + command_depth,
3271                                             item_name);
3272                         }
3273                         break;
3274                 default:
3275                         sgmlOpenTag(ofs, depth + command_depth,
3276                                     style.latexname());
3277                         break;
3278                 }
3279
3280                 simpleDocBookOnePar(ofs, par, desc_on, depth+1+command_depth);
3281                 par = par->next();
3282
3283                 string end_tag;
3284                 // write closing SGML tags
3285                 switch (style.latextype) {
3286                 case LATEX_COMMAND:
3287                         if (c_params.empty())
3288                                 end_tag = "title";
3289                         else
3290                                 end_tag = c_params;
3291                         sgmlCloseTag(ofs, depth + command_depth, end_tag);
3292                         break;
3293                 case LATEX_ENVIRONMENT:
3294                         if (!style.latexparam().empty()) {
3295                                 if (style.latexparam() == "CDATA")
3296                                         ofs << "]]>";
3297                                 else
3298                                         sgmlCloseTag(ofs, depth + command_depth,
3299                                                      style.latexparam());
3300                         }
3301                         break;
3302                 case LATEX_ITEM_ENVIRONMENT:
3303                         if (desc_on == 1) break;
3304                         end_tag= "para";
3305                         sgmlCloseTag(ofs, depth + 1 + command_depth, end_tag);
3306                         break;
3307                 case LATEX_PARAGRAPH:
3308                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3309                         break;
3310                 default:
3311                         sgmlCloseTag(ofs, depth + command_depth, style.latexname());
3312                         break;
3313                 }
3314         }
3315
3316         // Close open tags
3317         for (int d = depth; d >= 0; --d) {
3318                 if (!environment_stack[depth].empty()) {
3319                         if (environment_inner[depth] != "!-- --") {
3320                                 item_name = "listitem";
3321                                 sgmlCloseTag(ofs, command_depth + depth,
3322                                              item_name);
3323                                if (environment_inner[depth] == "varlistentry")
3324                                        sgmlCloseTag(ofs, depth + command_depth,
3325                                                     environment_inner[depth]);
3326                         }
3327                         
3328                         sgmlCloseTag(ofs, depth + command_depth,
3329                                      environment_stack[depth]);
3330                 }
3331         }
3332         
3333         for (int j = command_depth; j >= 0 ; --j)
3334                 if (!command_stack[j].empty())
3335                         sgmlCloseTag(ofs, j, command_stack[j]);
3336
3337         ofs << "\n\n";
3338         sgmlCloseTag(ofs, 0, top_element);
3339
3340         ofs.close();
3341         // How to check for successful close
3342 }
3343
3344
3345 void Buffer::simpleDocBookOnePar(ostream & os,
3346                                  Paragraph * par, int & desc_on,
3347                                  Paragraph::depth_type depth) const
3348 {
3349         bool emph_flag = false;
3350
3351         LyXLayout const & style =
3352                 textclasslist[params.textclass][par->layout()];
3353
3354         LyXFont font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3355
3356         int char_line_count = depth;
3357         //if (!style.free_spacing)
3358         //      os << string(depth,' ');
3359
3360         // parsing main loop
3361         for (pos_type i = 0; i < par->size(); ++i) {
3362                 LyXFont font = par->getFont(params, i);
3363
3364                 // handle <emphasis> tag
3365                 if (font_old.emph() != font.emph()) {
3366                         if (font.emph() == LyXFont::ON) {
3367                                 os << "<emphasis>";
3368                                 emph_flag = true;
3369                         } else if (i) {
3370                                 os << "</emphasis>";
3371                                 emph_flag = false;
3372                         }
3373                 }
3374       
3375
3376                 if (par->isInset(i)) {
3377                         Inset * inset = par->getInset(i);
3378                         // don't print the inset in position 0 if desc_on == 3 (label)
3379                         if ( i || desc_on != 3) {
3380                                 if(style.latexparam() == "CDATA")
3381                                         os << "]]>";
3382                                 inset->docbook(this, os);
3383                                 if(style.latexparam() == "CDATA")
3384                                         os << "<![CDATA[";
3385                         }
3386                 } else {
3387                         char c = par->getChar(i);
3388                         string sgml_string;
3389                         par->sgmlConvertChar(c, sgml_string);
3390
3391                         if (style.pass_thru) {
3392                                 os << c;
3393                         } else if (style.free_spacing || par->isFreeSpacing() || c != ' ') {
3394                                         os << sgml_string;
3395                         } else if (desc_on ==1) {
3396                                 ++char_line_count;
3397                                 os << "\n</term><listitem><para>";
3398                                 desc_on = 2;
3399                         } else {
3400                                 os << ' ';
3401                         }
3402                 }
3403                 font_old = font;
3404         }
3405
3406         if (emph_flag) {
3407                 os << "</emphasis>";
3408         }
3409         
3410         // resets description flag correctly
3411         if (desc_on == 1) {
3412                 // <term> not closed...
3413                 os << "</term>";
3414         }
3415         if (style.free_spacing) os << '\n';
3416 }
3417
3418
3419 // This should be enabled when the Chktex class is implemented. (Asger)
3420 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3421 // Other flags: -wall -v0 -x
3422 int Buffer::runChktex()
3423 {
3424         if (!users->text) return 0;
3425
3426         users->owner()->prohibitInput();
3427
3428         // get LaTeX-Filename
3429         string const name = getLatexName();
3430         string path = filePath();
3431
3432         string const org_path = path;
3433         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3434                 path = tmppath;  
3435         }
3436
3437         Path p(path); // path to LaTeX file
3438         users->owner()->message(_("Running chktex..."));
3439
3440         // Remove all error insets
3441         bool const removedErrorInsets = users->removeAutoInsets();
3442
3443         // Generate the LaTeX file if neccessary
3444         makeLaTeXFile(name, org_path, false);
3445
3446         TeXErrors terr;
3447         Chktex chktex(lyxrc.chktex_command, name, filePath());
3448         int res = chktex.run(terr); // run chktex
3449
3450         if (res == -1) {
3451                 Alert::alert(_("chktex did not work!"),
3452                            _("Could not run with file:"), name);
3453         } else if (res > 0) {
3454                 // Insert all errors as errors boxes
3455                 users->insertErrors(terr);
3456         }
3457
3458         // if we removed error insets before we ran chktex or if we inserted
3459         // error insets after we ran chktex, this must be run:
3460         if (removedErrorInsets || res) {
3461                 users->redraw();
3462                 users->fitCursor();
3463         }
3464         users->owner()->allowInput();
3465
3466         return res;
3467 }
3468
3469
3470 void Buffer::validate(LaTeXFeatures & features) const
3471 {
3472         Paragraph * par = paragraph;
3473         LyXTextClass const & tclass = textclasslist[params.textclass];
3474     
3475         // AMS Style is at document level
3476         if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3477                 features.require("amsmath");
3478     
3479         while (par) {
3480                 // We don't use "lyxerr.debug" because of speed. (Asger)
3481                 if (lyxerr.debugging(Debug::LATEX))
3482                         lyxerr << "Paragraph: " <<  par << endl;
3483
3484                 // Now just follow the list of paragraphs and run
3485                 // validate on each of them.
3486                 par->validate(features);
3487
3488                 // and then the next paragraph
3489                 par = par->next();
3490         }
3491
3492         // the bullet shapes are buffer level not paragraph level
3493         // so they are tested here
3494         for (int i = 0; i < 4; ++i) {
3495                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3496                         int const font = params.user_defined_bullets[i].getFont();
3497                         if (font == 0) {
3498                                 int const c = params
3499                                         .user_defined_bullets[i]
3500                                         .getCharacter();
3501                                 if (c == 16
3502                                    || c == 17
3503                                    || c == 25
3504                                    || c == 26
3505                                    || c == 31) {
3506                                         features.require("latexsym");
3507                                 }
3508                         } else if (font == 1) {
3509                                 features.require("amssymb");
3510                         } else if ((font >= 2 && font <= 5)) {
3511                                 features.require("pifont");
3512                         }
3513                 }
3514         }
3515         
3516         if (lyxerr.debugging(Debug::LATEX)) {
3517                 features.showStruct();
3518         }
3519 }
3520
3521
3522 // This function should be in Buffer because it's a buffer's property (ale)
3523 string const Buffer::getIncludeonlyList(char delim)
3524 {
3525         string lst;
3526         for (inset_iterator it = inset_iterator_begin();
3527             it != inset_iterator_end(); ++it) {
3528                 if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3529                         InsetInclude * insetinc = 
3530                                 static_cast<InsetInclude *>(*it);
3531                         if (insetinc->isIncludeOnly()) {
3532                                 if (!lst.empty())
3533                                         lst += delim;
3534                                 lst += insetinc->getRelFileBaseName();
3535                         }
3536                 }
3537         }
3538         lyxerr[Debug::INFO] << "Includeonly(" << lst << ')' << endl;
3539         return lst;
3540 }
3541
3542
3543 vector<string> const Buffer::getLabelList()
3544 {
3545         /// if this is a child document and the parent is already loaded
3546         /// Use the parent's list instead  [ale990407]
3547         if (!params.parentname.empty()
3548             && bufferlist.exists(params.parentname)) {
3549                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3550                 if (tmp)
3551                         return tmp->getLabelList();
3552         }
3553
3554         vector<string> label_list;
3555         for (inset_iterator it = inset_iterator_begin();
3556              it != inset_iterator_end(); ++it) {
3557                 vector<string> const l = (*it)->getLabelList();
3558                 label_list.insert(label_list.end(), l.begin(), l.end());
3559         }
3560         return label_list;
3561 }
3562
3563
3564 Buffer::Lists const Buffer::getLists() const
3565 {
3566         Lists l;
3567         Paragraph * par = paragraph;
3568
3569         LyXTextClass const & textclass = textclasslist[params.textclass];
3570         bool found = textclass.hasLayout("caption");
3571         string const layout("caption");
3572
3573         while (par) {
3574                 char const labeltype = textclass[par->layout()].labeltype;
3575                 
3576                 if (labeltype >= LABEL_COUNTER_CHAPTER
3577                     && labeltype <= LABEL_COUNTER_CHAPTER + params.tocdepth) {
3578                                 // insert this into the table of contents
3579                         SingleList & item = l["TOC"];
3580                         int depth = max(0,
3581                                         labeltype - 
3582                                         textclass.maxcounter());
3583                         item.push_back(TocItem(par, depth, par->asString(this, true)));
3584                 }
3585                 // For each paragrph, traverse its insets and look for
3586                 // FLOAT_CODE
3587                 
3588                 if (found) {
3589                         Paragraph::inset_iterator it =
3590                                 par->inset_iterator_begin();
3591                         Paragraph::inset_iterator end =
3592                                 par->inset_iterator_end();
3593                         
3594                         for (; it != end; ++it) {
3595                                 if ((*it)->lyxCode() == Inset::FLOAT_CODE) {
3596                                         InsetFloat * il =
3597                                                 static_cast<InsetFloat*>(*it);
3598                                         
3599                                         string const type = il->type();
3600                                         
3601                                         // Now find the caption in the float...
3602                                         // We now tranverse the paragraphs of
3603                                         // the inset...
3604                                         Paragraph * tmp = il->inset.paragraph();
3605                                         while (tmp) {
3606                                                 if (tmp->layout() == layout) {
3607                                                         SingleList & item = l[type];
3608                                                         string const str =
3609                                                                 tostr(item.size()+1) + ". " + tmp->asString(this, false);
3610                                                         item.push_back(TocItem(tmp, 0 , str));
3611                                                 }
3612                                                 tmp = tmp->next();
3613                                         }
3614                                 }
3615                         }
3616                 } else {
3617                         lyxerr << "caption not found" << endl;
3618                 }
3619                 
3620                 par = par->next();
3621         }
3622         return l;
3623 }
3624
3625
3626 // This is also a buffer property (ale)
3627 vector<pair<string, string> > const Buffer::getBibkeyList()
3628 {
3629         /// if this is a child document and the parent is already loaded
3630         /// Use the parent's list instead  [ale990412]
3631         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3632                 Buffer * tmp = bufferlist.getBuffer(params.parentname);
3633                 if (tmp)
3634                         return tmp->getBibkeyList();
3635         }
3636
3637         vector<pair<string, string> > keys;
3638         Paragraph * par = paragraph;
3639         while (par) {
3640                 if (par->bibkey)
3641                         keys.push_back(pair<string, string>(par->bibkey->getContents(),
3642                                                            par->asString(this, false)));
3643                 par = par->next();
3644         }
3645
3646         // Might be either using bibtex or a child has bibliography
3647         if (keys.empty()) {
3648                 for (inset_iterator it = inset_iterator_begin();
3649                         it != inset_iterator_end(); ++it) {
3650                         // Search for Bibtex or Include inset
3651                         if ((*it)->lyxCode() == Inset::BIBTEX_CODE) {
3652                                 vector<pair<string,string> > tmp =
3653                                         static_cast<InsetBibtex*>(*it)->getKeys(this);
3654                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3655                         } else if ((*it)->lyxCode() == Inset::INCLUDE_CODE) {
3656                                 vector<pair<string,string> > const tmp =
3657                                         static_cast<InsetInclude*>(*it)->getKeys();
3658                                 keys.insert(keys.end(), tmp.begin(), tmp.end());
3659                         }
3660                 }
3661         }
3662  
3663         return keys;
3664 }
3665
3666
3667 bool Buffer::isDepClean(string const & name) const
3668 {
3669         DEPCLEAN * item = dep_clean;
3670         while (item && item->master != name)
3671                 item = item->next;
3672         if (!item) return true;
3673         return item->clean;
3674 }
3675
3676
3677 void Buffer::markDepClean(string const & name)
3678 {
3679         if (!dep_clean) {
3680                 dep_clean = new DEPCLEAN;
3681                 dep_clean->clean = true;
3682                 dep_clean->master = name;
3683                 dep_clean->next = 0;
3684         } else {
3685                 DEPCLEAN * item = dep_clean;
3686                 while (item && item->master != name)
3687                         item = item->next;
3688                 if (item) {
3689                         item->clean = true;
3690                 } else {
3691                         item = new DEPCLEAN;
3692                         item->clean = true;
3693                         item->master = name;
3694                         item->next = 0;
3695                 }
3696         }
3697 }
3698
3699
3700 bool Buffer::dispatch(string const & command)
3701 {
3702         // Split command string into command and argument
3703         string cmd;
3704         string line = frontStrip(command);
3705         string const arg = strip(frontStrip(split(line, cmd, ' ')));
3706
3707         return dispatch(lyxaction.LookupFunc(cmd), arg);
3708 }
3709
3710
3711 bool Buffer::dispatch(int action, string const & argument)
3712 {
3713         bool dispatched = true;
3714         switch (action) {
3715                 case LFUN_EXPORT: 
3716                         Exporter::Export(this, argument, false);
3717                         break;
3718
3719                 default:
3720                         dispatched = false;
3721         }
3722         return dispatched;
3723 }
3724
3725
3726 void Buffer::resizeInsets(BufferView * bv)
3727 {
3728         /// then remove all LyXText in text-insets
3729         Paragraph * par = paragraph;
3730         for (; par; par = par->next()) {
3731             par->resizeInsetsLyXText(bv);
3732         }
3733 }
3734
3735
3736 void Buffer::redraw()
3737 {
3738         users->redraw(); 
3739         users->fitCursor(); 
3740 }
3741
3742
3743 void Buffer::changeLanguage(Language const * from, Language const * to)
3744 {
3745
3746         ParIterator end = par_iterator_end();
3747         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3748                 (*it)->changeLanguage(params, from, to);
3749 }
3750
3751
3752 bool Buffer::isMultiLingual()
3753 {
3754         ParIterator end = par_iterator_end();
3755         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3756                 if ((*it)->isMultiLingual(params))
3757                         return true;
3758
3759         return false;
3760 }
3761
3762
3763 Buffer::inset_iterator::inset_iterator(Paragraph * paragraph, pos_type pos)
3764         : par(paragraph)
3765 {
3766         it = par->InsetIterator(pos);
3767         if (it == par->inset_iterator_end()) {
3768                 par = par->next();
3769                 setParagraph();
3770         }
3771 }
3772
3773
3774 void Buffer::inset_iterator::setParagraph()
3775 {
3776         while (par) {
3777                 it = par->inset_iterator_begin();
3778                 if (it != par->inset_iterator_end())
3779                         return;
3780                 par = par->next();
3781         }
3782         //it = 0;
3783         // We maintain an invariant that whenever par = 0 then it = 0
3784 }
3785
3786
3787 Inset * Buffer::getInsetFromID(int id_arg) const
3788 {
3789         for (inset_iterator it = inset_const_iterator_begin();
3790                  it != inset_const_iterator_end(); ++it)
3791         {
3792                 if ((*it)->id() == id_arg)
3793                         return *it;
3794                 Inset * in = (*it)->getInsetFromID(id_arg);
3795                 if (in)
3796                         return in;
3797         }
3798         return 0;
3799 }
3800
3801
3802 Paragraph * Buffer::getParFromID(int id) const
3803 {
3804         if (id < 0) return 0;
3805         Paragraph * par = paragraph;
3806         while (par) {
3807                 if (par->id() == id) {
3808                         return par;
3809                 }
3810                 Paragraph * tmp = par->getParFromID(id);
3811                 if (tmp) {
3812                         return tmp;
3813                 }
3814                 par = par->next();
3815         }
3816         return 0;
3817 }
3818
3819
3820 ParIterator Buffer::par_iterator_begin()
3821 {
3822         return ParIterator(paragraph);
3823 }
3824
3825
3826 ParIterator Buffer::par_iterator_end()
3827 {
3828         return ParIterator();
3829 }