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