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