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