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