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