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