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