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