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