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