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