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