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