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