]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Rob's latest and greatest dialog tweaking.
[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 "LyXAction.h"
24 #include "lyxrc.h"
25 #include "lyxlex.h"
26 #include "tex-strings.h"
27 #include "layout.h"
28 #include "bufferview_funcs.h"
29 #include "lyxfont.h"
30 #include "version.h"
31 #include "LaTeX.h"
32 #include "Chktex.h"
33 #include "debug.h"
34 #include "LaTeXFeatures.h"
35 #include "lyxtext.h"
36 #include "gettext.h"
37 #include "language.h"
38 #include "encoding.h"
39 #include "exporter.h"
40 #include "Lsstream.h"
41 #include "converter.h"
42 #include "BufferView.h"
43 #include "ParagraphParameters.h"
44 #include "iterators.h"
45 #include "lyxtextclasslist.h"
46 #include "sgml.h"
47 #include "paragraph_funcs.h"
48
49 #include "frontends/LyXView.h"
50
51 #include "mathed/formulamacro.h"
52 #include "mathed/formula.h"
53
54 #include "insets/inset.h"
55 #include "insets/inseterror.h"
56 #include "insets/insetlabel.h"
57 #include "insets/insetref.h"
58 #include "insets/inseturl.h"
59 #include "insets/insetnote.h"
60 #include "insets/insetquotes.h"
61 #include "insets/insetlatexaccent.h"
62 #include "insets/insetbib.h"
63 #include "insets/insetcite.h"
64 #include "insets/insetexternal.h"
65 #include "insets/insetindex.h"
66 #include "insets/insetinclude.h"
67 #include "insets/insettoc.h"
68 #include "insets/insetparent.h"
69 #include "insets/insetspecialchar.h"
70 #include "insets/insettext.h"
71 #include "insets/insetert.h"
72 #include "insets/insetgraphics.h"
73 #include "insets/insetfoot.h"
74 #include "insets/insetmarginal.h"
75 #include "insets/insetoptarg.h"
76 #include "insets/insetminipage.h"
77 #include "insets/insetfloat.h"
78 #include "insets/insetwrap.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 = 221;
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)
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                 } else if (tmptok == "Wrap") {
1121                         lex.next();
1122                         string tmptok = lex.getString();
1123                         inset = new InsetWrap(params, tmptok);
1124 #if 0
1125                 } else if (tmptok == "List") {
1126                         inset = new InsetList;
1127                 } else if (tmptok == "Theorem") {
1128                         inset = new InsetList;
1129 #endif
1130                 } else if (tmptok == "Caption") {
1131                         inset = new InsetCaption(params);
1132                 } else if (tmptok == "FloatList") {
1133                         inset = new InsetFloatList;
1134                 }
1135
1136                 if (inset && !alreadyread) inset->read(this, lex);
1137         }
1138
1139         if (inset) {
1140                 par->insertInset(pos, inset, font);
1141                 ++pos;
1142         }
1143 }
1144
1145
1146 bool Buffer::readFile(LyXLex & lex, Paragraph * par)
1147 {
1148         if (lex.isOK()) {
1149                 lex.next();
1150                 string const token(lex.getString());
1151                 if (token == "\\lyxformat") { // the first token _must_ be...
1152                         lex.eatLine();
1153                         string tmp_format = lex.getString();
1154                         //lyxerr << "LyX Format: `" << tmp_format << "'" << endl;
1155                         // if present remove ".," from string.
1156                         string::size_type dot = tmp_format.find_first_of(".,");
1157                         //lyxerr << "           dot found at " << dot << endl;
1158                         if (dot != string::npos)
1159                                 tmp_format.erase(dot, 1);
1160                         file_format = strToInt(tmp_format);
1161                         //lyxerr << "format: " << file_format << endl;
1162                         if (file_format == LYX_FORMAT) {
1163                                 // current format
1164                         } else if (file_format > LYX_FORMAT) {
1165                                 // future format
1166                                 Alert::alert(_("Warning!"),
1167                                         _("The file was created with a newer version of"
1168                                         "LyX. This is likely to cause problems."));
1169
1170                         } else if (file_format < LYX_FORMAT) {
1171                                 // old formats
1172                                 if (file_format < 200) {
1173                                         Alert::alert(_("ERROR!"),
1174                                                    _("Old LyX file format found. "
1175                                                      "Use LyX 0.10.x to read this!"));
1176                                         return false;
1177                                 } else {
1178                                         string command =
1179                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
1180                                         if (command.empty()) {
1181                                                 Alert::alert(_("ERROR!"),
1182                                                              _("Can't find conversion script."));
1183                                                 return false;
1184                                         }
1185                                         command += " -t"
1186                                                 +tostr(LYX_FORMAT)+" "
1187                                                 + QuoteName(filename_);
1188                                         cmd_ret const ret = RunCommand(command);
1189                                         if (ret.first) {
1190                                                 Alert::alert(_("ERROR!"),
1191                                                              _("An error occured while "
1192                                                                "running the conversion script."));
1193                                                 return false;
1194                                         }
1195                                         istringstream is(ret.second);
1196                                         LyXLex tmplex(0, 0);
1197                                         tmplex.setStream(is);
1198                                         return readFile(tmplex);
1199                                 }
1200                         }
1201                         bool the_end = readLyXformat2(lex, par);
1202                         params.setPaperStuff();
1203
1204 #if 0
1205                         // the_end was added in 213
1206                         if (file_format < 213)
1207                                 the_end = true;
1208 #endif
1209
1210                         if (!the_end) {
1211                                 Alert::alert(_("Warning!"),
1212                                            _("Reading of document is not complete"),
1213                                            _("Maybe the document is truncated"));
1214                         }
1215                         return true;
1216                 } else { // "\\lyxformat" not found
1217                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1218                 }
1219         } else
1220                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1221         return false;
1222 }
1223
1224
1225 // Should probably be moved to somewhere else: BufferView? LyXView?
1226 bool Buffer::save() const
1227 {
1228         // We don't need autosaves in the immediate future. (Asger)
1229         resetAutosaveTimers();
1230
1231         // make a backup
1232         string s;
1233         if (lyxrc.make_backup) {
1234                 s = fileName() + '~';
1235                 if (!lyxrc.backupdir_path.empty())
1236                         s = AddName(lyxrc.backupdir_path,
1237                                     subst(os::slashify_path(s),'/','!'));
1238
1239                 // Rename is the wrong way of making a backup,
1240                 // this is the correct way.
1241                 /* truss cp fil fil2:
1242                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1243                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1244                    open("LyXVC.lyx", O_RDONLY)                     = 3
1245                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1246                    fstat(4, 0xEFFFF508)                            = 0
1247                    fstat(3, 0xEFFFF508)                            = 0
1248                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1249                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1250                    read(3, 0xEFFFD4A0, 8192)                       = 0
1251                    close(4)                                        = 0
1252                    close(3)                                        = 0
1253                    chmod("LyXVC3.lyx", 0100644)                    = 0
1254                    lseek(0, 0, SEEK_CUR)                           = 46440
1255                    _exit(0)
1256                 */
1257
1258                 // Should probably have some more error checking here.
1259                 // Doing it this way, also makes the inodes stay the same.
1260                 // This is still not a very good solution, in particular we
1261                 // might loose the owner of the backup.
1262                 FileInfo finfo(fileName());
1263                 if (finfo.exist()) {
1264                         mode_t fmode = finfo.getMode();
1265                         struct utimbuf times = {
1266                                 finfo.getAccessTime(),
1267                                 finfo.getModificationTime() };
1268
1269                         ifstream ifs(fileName().c_str());
1270                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1271                         if (ifs && ofs) {
1272                                 ofs << ifs.rdbuf();
1273                                 ifs.close();
1274                                 ofs.close();
1275                                 ::chmod(s.c_str(), fmode);
1276
1277                                 if (::utime(s.c_str(), &times)) {
1278                                         lyxerr << "utime error." << endl;
1279                                 }
1280                         } else {
1281                                 lyxerr << "LyX was not able to make "
1282                                         "backup copy. Beware." << endl;
1283                         }
1284                 }
1285         }
1286
1287         if (writeFile(fileName())) {
1288                 markClean();
1289                 removeAutosaveFile(fileName());
1290         } else {
1291                 // Saving failed, so backup is not backup
1292                 if (lyxrc.make_backup) {
1293                         lyx::rename(s, fileName());
1294                 }
1295                 return false;
1296         }
1297         return true;
1298 }
1299
1300
1301 bool Buffer::writeFile(string const & fname) const
1302 {
1303         if (read_only && (fname == fileName())) {
1304                 return false;
1305         }
1306
1307         FileInfo finfo(fname);
1308         if (finfo.exist() && !finfo.writable()) {
1309                 return false;
1310         }
1311
1312         ofstream ofs(fname.c_str());
1313         if (!ofs) {
1314                 return false;
1315         }
1316
1317 #ifdef HAVE_LOCALE
1318         // Use the standard "C" locale for file output.
1319         ofs.imbue(std::locale::classic());
1320 #endif
1321
1322         // The top of the file should not be written by params.
1323
1324         // write out a comment in the top of the file
1325         ofs << '#' << lyx_docversion
1326             << " created this file. For more info see http://www.lyx.org/\n"
1327             << "\\lyxformat " << LYX_FORMAT << "\n";
1328
1329         // now write out the buffer paramters.
1330         params.writeFile(ofs);
1331
1332         Paragraph::depth_type depth = 0;
1333
1334         // this will write out all the paragraphs
1335         // using recursive descent.
1336         ParagraphList::iterator pit = paragraphs.begin();
1337         ParagraphList::iterator pend = paragraphs.end();
1338         for (; pit != pend; ++pit)
1339                 pit->write(this, ofs, params, depth);
1340
1341         // Write marker that shows file is complete
1342         ofs << "\n\\the_end" << endl;
1343
1344         ofs.close();
1345
1346         // how to check if close went ok?
1347         // Following is an attempt... (BE 20001011)
1348
1349         // good() returns false if any error occured, including some
1350         //        formatting error.
1351         // bad()  returns true if something bad happened in the buffer,
1352         //        which should include file system full errors.
1353
1354         bool status = true;
1355         if (!ofs.good()) {
1356                 status = false;
1357 #if 0
1358                 if (ofs.bad()) {
1359                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1360                 } else {
1361                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1362                                << endl;
1363                 }
1364 #endif
1365         }
1366
1367         return status;
1368 }
1369
1370
1371 namespace {
1372
1373 pair<int, string> const addDepth(int depth, int ldepth)
1374 {
1375         int d = depth * 2;
1376         if (ldepth > depth)
1377                 d += (ldepth - depth) * 2;
1378         return make_pair(d, string(d, ' '));
1379 }
1380
1381 }
1382
1383
1384 string const Buffer::asciiParagraph(Paragraph const & par,
1385                                     unsigned int linelen,
1386                                     bool noparbreak) const
1387 {
1388         ostringstream buffer;
1389         Paragraph::depth_type depth = 0;
1390         int ltype = 0;
1391         Paragraph::depth_type ltype_depth = 0;
1392         bool ref_printed = false;
1393 //      if (!par->previous()) {
1394 #if 0
1395         // begins or ends a deeper area ?
1396         if (depth != par->params().depth()) {
1397                 if (par->params().depth() > depth) {
1398                         while (par->params().depth() > depth) {
1399                                 ++depth;
1400                         }
1401                 } else {
1402                         while (par->params().depth() < depth) {
1403                                 --depth;
1404                         }
1405                 }
1406         }
1407 #else
1408         depth = par.params().depth();
1409 #endif
1410
1411         // First write the layout
1412         string const & tmp = par.layout()->name();
1413         if (compare_no_case(tmp, "itemize") == 0) {
1414                 ltype = 1;
1415                 ltype_depth = depth + 1;
1416         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1417                 ltype = 2;
1418                 ltype_depth = depth + 1;
1419         } else if (contains(ascii_lowercase(tmp), "ection")) {
1420                 ltype = 3;
1421                 ltype_depth = depth + 1;
1422         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1423                 ltype = 4;
1424                 ltype_depth = depth + 1;
1425         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1426                 ltype = 5;
1427                 ltype_depth = depth + 1;
1428         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1429                 ltype = 6;
1430                 ltype_depth = 0;
1431         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1432                 ltype = 7;
1433                 ltype_depth = 0;
1434         } else {
1435                 ltype = 0;
1436                 ltype_depth = 0;
1437         }
1438
1439         /* maybe some vertical spaces */
1440
1441         /* the labelwidthstring used in lists */
1442
1443         /* some lines? */
1444
1445         /* some pagebreaks? */
1446
1447         /* noindent ? */
1448
1449         /* what about the alignment */
1450 //      } else {
1451 //              lyxerr << "Should this ever happen?" << endl;
1452 //      }
1453
1454         // linelen <= 0 is special and means we don't have paragraph breaks
1455
1456         string::size_type currlinelen = 0;
1457
1458         if (!noparbreak) {
1459                 if (linelen > 0)
1460                         buffer << "\n\n";
1461
1462                 buffer << string(depth * 2, ' ');
1463                 currlinelen += depth * 2;
1464
1465                 //--
1466                 // we should probably change to the paragraph language in the
1467                 // gettext here (if possible) so that strings are outputted in
1468                 // the correct language! (20012712 Jug)
1469                 //--
1470                 switch (ltype) {
1471                 case 0: // Standard
1472                 case 4: // (Sub)Paragraph
1473                 case 5: // Description
1474                         break;
1475                 case 6: // Abstract
1476                         if (linelen > 0) {
1477                                 buffer << _("Abstract") << "\n\n";
1478                                 currlinelen = 0;
1479                         } else {
1480                                 string const abst = _("Abstract: ");
1481                                 buffer << abst;
1482                                 currlinelen += abst.length();
1483                         }
1484                         break;
1485                 case 7: // Bibliography
1486                         if (!ref_printed) {
1487                                 if (linelen > 0) {
1488                                         buffer << _("References") << "\n\n";
1489                                         currlinelen = 0;
1490                                 } else {
1491                                         string const refs = _("References: ");
1492                                         buffer << refs;
1493                                         currlinelen += refs.length();
1494                                 }
1495
1496                                 ref_printed = true;
1497                         }
1498                         break;
1499                 default:
1500                 {
1501                         string const parlab = par.params().labelString();
1502                         buffer << parlab << " ";
1503                         currlinelen += parlab.length() + 1;
1504                 }
1505                 break;
1506
1507                 }
1508         }
1509
1510         if (!currlinelen) {
1511                 pair<int, string> p = addDepth(depth, ltype_depth);
1512                 buffer << p.second;
1513                 currlinelen += p.first;
1514         }
1515
1516         // this is to change the linebreak to do it by word a bit more
1517         // intelligent hopefully! (only in the case where we have a
1518         // max linelenght!) (Jug)
1519
1520         string word;
1521
1522         for (pos_type i = 0; i < par.size(); ++i) {
1523                 char c = par.getUChar(params, i);
1524                 switch (c) {
1525                 case Paragraph::META_INSET:
1526                 {
1527                         Inset const * inset = par.getInset(i);
1528                         if (inset) {
1529                                 if (linelen > 0) {
1530                                         buffer << word;
1531                                         currlinelen += word.length();
1532                                         word.erase();
1533                                 }
1534                                 if (inset->ascii(this, buffer, linelen)) {
1535                                         // to be sure it breaks paragraph
1536                                         currlinelen += linelen;
1537                                 }
1538                         }
1539                 }
1540                 break;
1541
1542                 case Paragraph::META_NEWLINE:
1543                         if (linelen > 0) {
1544                                 buffer << word << "\n";
1545                                 word.erase();
1546
1547                                 pair<int, string> p = addDepth(depth,
1548                                                                ltype_depth);
1549                                 buffer << p.second;
1550                                 currlinelen = p.first;
1551                         }
1552                         break;
1553
1554                 case Paragraph::META_HFILL:
1555                         buffer << word << "\t";
1556                         currlinelen += word.length() + 1;
1557                         word.erase();
1558                         break;
1559
1560                 default:
1561                         if (c == ' ') {
1562                                 if (linelen > 0 &&
1563                                     currlinelen + word.length() > linelen - 10) {
1564                                         buffer << "\n";
1565                                         pair<int, string> p =
1566                                                 addDepth(depth, ltype_depth);
1567                                         buffer << p.second;
1568                                         currlinelen = p.first;
1569                                 }
1570
1571                                 buffer << word << ' ';
1572                                 currlinelen += word.length() + 1;
1573                                 word.erase();
1574
1575                         } else {
1576                                 if (c != '\0') {
1577                                         word += c;
1578                                 } else {
1579                                         lyxerr[Debug::INFO] <<
1580                                                 "writeAsciiFile: NULL char in structure." << endl;
1581                                 }
1582                                 if ((linelen > 0) &&
1583                                         (currlinelen + word.length()) > linelen)
1584                                 {
1585                                         buffer << "\n";
1586
1587                                         pair<int, string> p =
1588                                                 addDepth(depth, ltype_depth);
1589                                         buffer << p.second;
1590                                         currlinelen = p.first;
1591                                 }
1592                         }
1593                         break;
1594                 }
1595         }
1596         buffer << word;
1597         return buffer.str().c_str();
1598 }
1599
1600
1601 void Buffer::writeFileAscii(string const & fname, int linelen)
1602 {
1603         ofstream ofs(fname.c_str());
1604         if (!ofs) {
1605                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1606                 return;
1607         }
1608         writeFileAscii(ofs, linelen);
1609 }
1610
1611
1612 void Buffer::writeFileAscii(ostream & os, int linelen)
1613 {
1614         ParagraphList::iterator beg = paragraphs.begin();
1615         ParagraphList::iterator end = paragraphs.end();
1616         ParagraphList::iterator it = beg;
1617         for (; it != end; ++it) {
1618                 os << asciiParagraph(*it, linelen, it == beg);
1619         }
1620         os << "\n";
1621 }
1622
1623
1624 bool use_babel;
1625
1626
1627 void Buffer::makeLaTeXFile(string const & fname,
1628                            string const & original_path,
1629                            bool nice, bool only_body, bool only_preamble)
1630 {
1631         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1632
1633         ofstream ofs(fname.c_str());
1634         if (!ofs) {
1635                 Alert::err_alert(_("Error: Cannot open file: "), fname);
1636                 return;
1637         }
1638
1639         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1640
1641         ofs.close();
1642         if (ofs.fail()) {
1643                 lyxerr << "File was not closed properly." << endl;
1644         }
1645 }
1646
1647
1648 void Buffer::makeLaTeXFile(ostream & os,
1649                            string const & original_path,
1650                            bool nice, bool only_body, bool only_preamble)
1651 {
1652         niceFile = nice; // this will be used by Insetincludes.
1653
1654         // validate the buffer.
1655         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1656         LaTeXFeatures features(params);
1657         validate(features);
1658         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1659
1660         texrow.reset();
1661         // The starting paragraph of the coming rows is the
1662         // first paragraph of the document. (Asger)
1663         texrow.start(&*(paragraphs.begin()), 0);
1664
1665         if (!only_body && nice) {
1666                 os << "%% " << lyx_docversion << " created this file.  "
1667                         "For more info, see http://www.lyx.org/.\n"
1668                         "%% Do not edit unless you really know what "
1669                         "you are doing.\n";
1670                 texrow.newline();
1671                 texrow.newline();
1672         }
1673         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1674         // There are a few differences between nice LaTeX and usual files:
1675         // usual is \batchmode and has a
1676         // special input@path to allow the including of figures
1677         // with either \input or \includegraphics (what figinsets do).
1678         // input@path is set when the actual parameter
1679         // original_path is set. This is done for usual tex-file, but not
1680         // for nice-latex-file. (Matthias 250696)
1681         if (!only_body) {
1682                 if (!nice) {
1683                         // code for usual, NOT nice-latex-file
1684                         os << "\\batchmode\n"; // changed
1685                         // from \nonstopmode
1686                         texrow.newline();
1687                 }
1688                 if (!original_path.empty()) {
1689                         string inputpath = os::external_path(original_path);
1690                         subst(inputpath, "~", "\\string~");
1691                         os << "\\makeatletter\n"
1692                             << "\\def\\input@path{{"
1693                             << inputpath << "/}}\n"
1694                             << "\\makeatother\n";
1695                         texrow.newline();
1696                         texrow.newline();
1697                         texrow.newline();
1698                 }
1699
1700                 os << "\\documentclass";
1701
1702                 LyXTextClass const & tclass = params.getLyXTextClass();
1703
1704                 ostringstream options; // the document class options.
1705
1706                 if (tokenPos(tclass.opt_fontsize(),
1707                              '|', params.fontsize) >= 0) {
1708                         // only write if existing in list (and not default)
1709                         options << params.fontsize << "pt,";
1710                 }
1711
1712
1713                 if (!params.use_geometry &&
1714                     (params.paperpackage == BufferParams::PACKAGE_NONE)) {
1715                         switch (params.papersize) {
1716                         case BufferParams::PAPER_A4PAPER:
1717                                 options << "a4paper,";
1718                                 break;
1719                         case BufferParams::PAPER_USLETTER:
1720                                 options << "letterpaper,";
1721                                 break;
1722                         case BufferParams::PAPER_A5PAPER:
1723                                 options << "a5paper,";
1724                                 break;
1725                         case BufferParams::PAPER_B5PAPER:
1726                                 options << "b5paper,";
1727                                 break;
1728                         case BufferParams::PAPER_EXECUTIVEPAPER:
1729                                 options << "executivepaper,";
1730                                 break;
1731                         case BufferParams::PAPER_LEGALPAPER:
1732                                 options << "legalpaper,";
1733                                 break;
1734                         }
1735                 }
1736
1737                 // if needed
1738                 if (params.sides != tclass.sides()) {
1739                         switch (params.sides) {
1740                         case LyXTextClass::OneSide:
1741                                 options << "oneside,";
1742                                 break;
1743                         case LyXTextClass::TwoSides:
1744                                 options << "twoside,";
1745                                 break;
1746                         }
1747                 }
1748
1749                 // if needed
1750                 if (params.columns != tclass.columns()) {
1751                         if (params.columns == 2)
1752                                 options << "twocolumn,";
1753                         else
1754                                 options << "onecolumn,";
1755                 }
1756
1757                 if (!params.use_geometry
1758                     && params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1759                         options << "landscape,";
1760
1761                 // language should be a parameter to \documentclass
1762                 use_babel = false;
1763                 ostringstream language_options;
1764                 if (params.language->babel() == "hebrew"
1765                     && default_language->babel() != "hebrew")
1766                          // This seems necessary
1767                         features.useLanguage(default_language);
1768
1769                 if (lyxrc.language_use_babel ||
1770                     params.language->lang() != lyxrc.default_language ||
1771                     features.hasLanguages()) {
1772                         use_babel = true;
1773                         language_options << features.getLanguages();
1774                         language_options << params.language->babel();
1775                         if (lyxrc.language_global_options)
1776                                 options << language_options.str() << ',';
1777                 }
1778
1779                 // the user-defined options
1780                 if (!params.options.empty()) {
1781                         options << params.options << ',';
1782                 }
1783
1784                 string strOptions(options.str().c_str());
1785                 if (!strOptions.empty()) {
1786                         strOptions = rtrim(strOptions, ",");
1787                         os << '[' << strOptions << ']';
1788                 }
1789
1790                 os << '{' << tclass.latexname() << "}\n";
1791                 texrow.newline();
1792                 // end of \documentclass defs
1793
1794                 // font selection must be done before loading fontenc.sty
1795                 // The ae package is not needed when using OT1 font encoding.
1796                 if (params.fonts != "default" &&
1797                     (params.fonts != "ae" || lyxrc.fontenc != "default")) {
1798                         os << "\\usepackage{" << params.fonts << "}\n";
1799                         texrow.newline();
1800                         if (params.fonts == "ae") {
1801                                 os << "\\usepackage{aecompl}\n";
1802                                 texrow.newline();
1803                         }
1804                 }
1805                 // this one is not per buffer
1806                 if (lyxrc.fontenc != "default") {
1807                         os << "\\usepackage[" << lyxrc.fontenc
1808                             << "]{fontenc}\n";
1809                         texrow.newline();
1810                 }
1811
1812                 if (params.inputenc == "auto") {
1813                         string const doc_encoding =
1814                                 params.language->encoding()->LatexName();
1815
1816                         // Create a list with all the input encodings used
1817                         // in the document
1818                         set<string> encodings = features.getEncodingSet(doc_encoding);
1819
1820                         os << "\\usepackage[";
1821                         std::copy(encodings.begin(), encodings.end(),
1822                                   std::ostream_iterator<string>(os, ","));
1823                         os << doc_encoding << "]{inputenc}\n";
1824                         texrow.newline();
1825                 } else if (params.inputenc != "default") {
1826                         os << "\\usepackage[" << params.inputenc
1827                             << "]{inputenc}\n";
1828                         texrow.newline();
1829                 }
1830
1831                 // At the very beginning the text parameters.
1832                 if (params.paperpackage != BufferParams::PACKAGE_NONE) {
1833                         switch (params.paperpackage) {
1834                         case BufferParams::PACKAGE_A4:
1835                                 os << "\\usepackage{a4}\n";
1836                                 texrow.newline();
1837                                 break;
1838                         case BufferParams::PACKAGE_A4WIDE:
1839                                 os << "\\usepackage{a4wide}\n";
1840                                 texrow.newline();
1841                                 break;
1842                         case BufferParams::PACKAGE_WIDEMARGINSA4:
1843                                 os << "\\usepackage[widemargins]{a4}\n";
1844                                 texrow.newline();
1845                                 break;
1846                         }
1847                 }
1848                 if (params.use_geometry) {
1849                         os << "\\usepackage{geometry}\n";
1850                         texrow.newline();
1851                         os << "\\geometry{verbose";
1852                         if (params.orientation == BufferParams::ORIENTATION_LANDSCAPE)
1853                                 os << ",landscape";
1854                         switch (params.papersize2) {
1855                         case BufferParams::VM_PAPER_CUSTOM:
1856                                 if (!params.paperwidth.empty())
1857                                         os << ",paperwidth="
1858                                             << params.paperwidth;
1859                                 if (!params.paperheight.empty())
1860                                         os << ",paperheight="
1861                                             << params.paperheight;
1862                                 break;
1863                         case BufferParams::VM_PAPER_USLETTER:
1864                                 os << ",letterpaper";
1865                                 break;
1866                         case BufferParams::VM_PAPER_USLEGAL:
1867                                 os << ",legalpaper";
1868                                 break;
1869                         case BufferParams::VM_PAPER_USEXECUTIVE:
1870                                 os << ",executivepaper";
1871                                 break;
1872                         case BufferParams::VM_PAPER_A3:
1873                                 os << ",a3paper";
1874                                 break;
1875                         case BufferParams::VM_PAPER_A4:
1876                                 os << ",a4paper";
1877                                 break;
1878                         case BufferParams::VM_PAPER_A5:
1879                                 os << ",a5paper";
1880                                 break;
1881                         case BufferParams::VM_PAPER_B3:
1882                                 os << ",b3paper";
1883                                 break;
1884                         case BufferParams::VM_PAPER_B4:
1885                                 os << ",b4paper";
1886                                 break;
1887                         case BufferParams::VM_PAPER_B5:
1888                                 os << ",b5paper";
1889                                 break;
1890                         default:
1891                                 // default papersize ie BufferParams::VM_PAPER_DEFAULT
1892                                 switch (lyxrc.default_papersize) {
1893                                 case BufferParams::PAPER_DEFAULT: // keep compiler happy
1894                                 case BufferParams::PAPER_USLETTER:
1895                                         os << ",letterpaper";
1896                                         break;
1897                                 case BufferParams::PAPER_LEGALPAPER:
1898                                         os << ",legalpaper";
1899                                         break;
1900                                 case BufferParams::PAPER_EXECUTIVEPAPER:
1901                                         os << ",executivepaper";
1902                                         break;
1903                                 case BufferParams::PAPER_A3PAPER:
1904                                         os << ",a3paper";
1905                                         break;
1906                                 case BufferParams::PAPER_A4PAPER:
1907                                         os << ",a4paper";
1908                                         break;
1909                                 case BufferParams::PAPER_A5PAPER:
1910                                         os << ",a5paper";
1911                                         break;
1912                                 case BufferParams::PAPER_B5PAPER:
1913                                         os << ",b5paper";
1914                                         break;
1915                                 }
1916                         }
1917                         if (!params.topmargin.empty())
1918                                 os << ",tmargin=" << params.topmargin;
1919                         if (!params.bottommargin.empty())
1920                                 os << ",bmargin=" << params.bottommargin;
1921                         if (!params.leftmargin.empty())
1922                                 os << ",lmargin=" << params.leftmargin;
1923                         if (!params.rightmargin.empty())
1924                                 os << ",rmargin=" << params.rightmargin;
1925                         if (!params.headheight.empty())
1926                                 os << ",headheight=" << params.headheight;
1927                         if (!params.headsep.empty())
1928                                 os << ",headsep=" << params.headsep;
1929                         if (!params.footskip.empty())
1930                                 os << ",footskip=" << params.footskip;
1931                         os << "}\n";
1932                         texrow.newline();
1933                 }
1934
1935                 if (tokenPos(tclass.opt_pagestyle(),
1936                              '|', params.pagestyle) >= 0) {
1937                         if (params.pagestyle == "fancy") {
1938                                 os << "\\usepackage{fancyhdr}\n";
1939                                 texrow.newline();
1940                         }
1941                         os << "\\pagestyle{" << params.pagestyle << "}\n";
1942                         texrow.newline();
1943                 }
1944
1945                 if (params.secnumdepth != tclass.secnumdepth()) {
1946                         os << "\\setcounter{secnumdepth}{"
1947                             << params.secnumdepth
1948                             << "}\n";
1949                         texrow.newline();
1950                 }
1951                 if (params.tocdepth != tclass.tocdepth()) {
1952                         os << "\\setcounter{tocdepth}{"
1953                             << params.tocdepth
1954                             << "}\n";
1955                         texrow.newline();
1956                 }
1957
1958                 if (params.paragraph_separation) {
1959                         switch (params.defskip.kind()) {
1960                         case VSpace::SMALLSKIP:
1961                                 os << "\\setlength\\parskip{\\smallskipamount}\n";
1962                                 break;
1963                         case VSpace::MEDSKIP:
1964                                 os << "\\setlength\\parskip{\\medskipamount}\n";
1965                                 break;
1966                         case VSpace::BIGSKIP:
1967                                 os << "\\setlength\\parskip{\\bigskipamount}\n";
1968                                 break;
1969                         case VSpace::LENGTH:
1970                                 os << "\\setlength\\parskip{"
1971                                     << params.defskip.length().asLatexString()
1972                                     << "}\n";
1973                                 break;
1974                         default: // should never happen // Then delete it.
1975                                 os << "\\setlength\\parskip{\\medskipamount}\n";
1976                                 break;
1977                         }
1978                         texrow.newline();
1979
1980                         os << "\\setlength\\parindent{0pt}\n";
1981                         texrow.newline();
1982                 }
1983
1984                 // Now insert the LyX specific LaTeX commands...
1985
1986                 // The optional packages;
1987                 string preamble(features.getPackages());
1988
1989                 // this might be useful...
1990                 preamble += "\n\\makeatletter\n";
1991
1992                 // Some macros LyX will need
1993                 string tmppreamble(features.getMacros());
1994
1995                 if (!tmppreamble.empty()) {
1996                         preamble += "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
1997                                 "LyX specific LaTeX commands.\n"
1998                                 + tmppreamble + '\n';
1999                 }
2000
2001                 // the text class specific preamble
2002                 tmppreamble = features.getTClassPreamble();
2003                 if (!tmppreamble.empty()) {
2004                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2005                                 "Textclass specific LaTeX commands.\n"
2006                                 + tmppreamble + '\n';
2007                 }
2008
2009                 /* the user-defined preamble */
2010                 if (!params.preamble.empty()) {
2011                         preamble += "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% "
2012                                 "User specified LaTeX commands.\n"
2013                                 + params.preamble + '\n';
2014                 }
2015
2016                 // Itemize bullet settings need to be last in case the user
2017                 // defines their own bullets that use a package included
2018                 // in the user-defined preamble -- ARRae
2019                 // Actually it has to be done much later than that
2020                 // since some packages like frenchb make modifications
2021                 // at \begin{document} time -- JMarc
2022                 string bullets_def;
2023                 for (int i = 0; i < 4; ++i) {
2024                         if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2025                                 if (bullets_def.empty())
2026                                         bullets_def="\\AtBeginDocument{\n";
2027                                 bullets_def += "  \\renewcommand{\\labelitemi";
2028                                 switch (i) {
2029                                 // `i' is one less than the item to modify
2030                                 case 0:
2031                                         break;
2032                                 case 1:
2033                                         bullets_def += 'i';
2034                                         break;
2035                                 case 2:
2036                                         bullets_def += "ii";
2037                                         break;
2038                                 case 3:
2039                                         bullets_def += 'v';
2040                                         break;
2041                                 }
2042                                 bullets_def += "}{" +
2043                                   params.user_defined_bullets[i].getText()
2044                                   + "}\n";
2045                         }
2046                 }
2047
2048                 if (!bullets_def.empty())
2049                   preamble += bullets_def + "}\n\n";
2050
2051                 int const nlines =
2052                         int(lyx::count(preamble.begin(), preamble.end(), '\n'));
2053                 for (int j = 0; j != nlines; ++j) {
2054                         texrow.newline();
2055                 }
2056
2057                 // We try to load babel late, in case it interferes
2058                 // with other packages.
2059                 if (use_babel) {
2060                         string tmp = lyxrc.language_package;
2061                         if (!lyxrc.language_global_options
2062                             && tmp == "\\usepackage{babel}")
2063                                 tmp = string("\\usepackage[") +
2064                                         language_options.str().c_str() +
2065                                         "]{babel}";
2066                         preamble += tmp + "\n";
2067                         preamble += features.getBabelOptions();
2068                 }
2069
2070                 preamble += "\\makeatother\n";
2071
2072                 os << preamble;
2073
2074                 if (only_preamble)
2075                         return;
2076
2077                 // make the body.
2078                 os << "\\begin{document}\n";
2079                 texrow.newline();
2080         } // only_body
2081         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
2082
2083         if (!lyxrc.language_auto_begin) {
2084                 os << subst(lyxrc.language_command_begin, "$$lang",
2085                              params.language->babel())
2086                     << endl;
2087                 texrow.newline();
2088         }
2089
2090         latexParagraphs(os, &*(paragraphs.begin()), 0, texrow);
2091
2092         // add this just in case after all the paragraphs
2093         os << endl;
2094         texrow.newline();
2095
2096         if (!lyxrc.language_auto_end) {
2097                 os << subst(lyxrc.language_command_end, "$$lang",
2098                              params.language->babel())
2099                     << endl;
2100                 texrow.newline();
2101         }
2102
2103         if (!only_body) {
2104                 os << "\\end{document}\n";
2105                 texrow.newline();
2106
2107                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
2108         } else {
2109                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
2110                                      << endl;
2111         }
2112
2113         // Just to be sure. (Asger)
2114         texrow.newline();
2115
2116         lyxerr[Debug::INFO] << "Finished making latex file." << endl;
2117         lyxerr[Debug::INFO] << "Row count was " << texrow.rows()-1 << "." << endl;
2118
2119         // we want this to be true outside previews (for insetexternal)
2120         niceFile = true;
2121 }
2122
2123
2124 //
2125 // LaTeX all paragraphs from par to endpar, if endpar == 0 then to the end
2126 //
2127 void Buffer::latexParagraphs(ostream & ofs, Paragraph * par,
2128                              Paragraph * endpar, TexRow & texrow,
2129                              bool moving_arg) const
2130 {
2131         bool was_title = false;
2132         bool already_title = false;
2133
2134         // if only_body
2135         while (par != endpar) {
2136                 Inset * in = par->inInset();
2137                 // well we have to check if we are in an inset with unlimited
2138                 // length (all in one row) if that is true then we don't allow
2139                 // any special options in the paragraph and also we don't allow
2140                 // any environment other then "Standard" to be valid!
2141                 if ((in == 0) || !in->forceDefaultParagraphs(in)) {
2142                         LyXLayout_ptr const & layout = par->layout();
2143
2144                         if (layout->intitle) {
2145                                 if (already_title) {
2146                                         lyxerr <<"Error in latexParagraphs: You"
2147                                                 " should not mix title layouts"
2148                                                 " with normal ones." << endl;
2149                                 } else
2150                                         was_title = true;
2151                         } else if (was_title && !already_title) {
2152                                 ofs << "\\maketitle\n";
2153                                 texrow.newline();
2154                                 already_title = true;
2155                                 was_title = false;
2156                         }
2157
2158                         if (layout->isEnvironment() ||
2159                                 !par->params().leftIndent().zero())
2160                         {
2161                                 par = par->TeXEnvironment(this, params, ofs, texrow);
2162                         } else {
2163                                 par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2164                         }
2165                 } else {
2166                         par = par->TeXOnePar(this, params, ofs, texrow, moving_arg);
2167                 }
2168         }
2169         // It might be that we only have a title in this document
2170         if (was_title && !already_title) {
2171                 ofs << "\\maketitle\n";
2172                 texrow.newline();
2173         }
2174 }
2175
2176
2177 bool Buffer::isLatex() const
2178 {
2179         return params.getLyXTextClass().outputType() == LATEX;
2180 }
2181
2182
2183 bool Buffer::isLinuxDoc() const
2184 {
2185         return params.getLyXTextClass().outputType() == LINUXDOC;
2186 }
2187
2188
2189 bool Buffer::isLiterate() const
2190 {
2191         return params.getLyXTextClass().outputType() == LITERATE;
2192 }
2193
2194
2195 bool Buffer::isDocBook() const
2196 {
2197         return params.getLyXTextClass().outputType() == DOCBOOK;
2198 }
2199
2200
2201 bool Buffer::isSGML() const
2202 {
2203         LyXTextClass const & tclass = params.getLyXTextClass();
2204
2205         return tclass.outputType() == LINUXDOC ||
2206                tclass.outputType() == DOCBOOK;
2207 }
2208
2209
2210 int Buffer::sgmlOpenTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2211                          string const & latexname) const
2212 {
2213         if (!latexname.empty() && latexname != "!-- --") {
2214                 if (!mixcont)
2215                         os << string(" ",depth);
2216                 os << "<" << latexname << ">";
2217         }
2218
2219         if (!mixcont)
2220                 os << endl;
2221
2222         return mixcont?0:1;
2223 }
2224
2225
2226 int Buffer::sgmlCloseTag(ostream & os, Paragraph::depth_type depth, bool mixcont,
2227                           string const & latexname) const
2228 {
2229         if (!latexname.empty() && latexname != "!-- --") {
2230                 if (!mixcont)
2231                         os << endl << string(" ",depth);
2232                 os << "</" << latexname << ">";
2233         }
2234
2235         if (!mixcont)
2236                 os << endl;
2237
2238         return mixcont?0:1;
2239 }
2240
2241
2242 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
2243 {
2244         ofstream ofs(fname.c_str());
2245
2246         if (!ofs) {
2247                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2248                 return;
2249         }
2250
2251         niceFile = nice; // this will be used by included files.
2252
2253         LaTeXFeatures features(params);
2254
2255         validate(features);
2256
2257         texrow.reset();
2258
2259         LyXTextClass const & tclass = params.getLyXTextClass();
2260
2261         string top_element = tclass.latexname();
2262
2263         if (!body_only) {
2264                 ofs << "<!doctype linuxdoc system";
2265
2266                 string preamble = params.preamble;
2267                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2268                          : fname;
2269                 preamble += features.getIncludedFiles(name);
2270                 preamble += features.getLyXSGMLEntities();
2271
2272                 if (!preamble.empty()) {
2273                         ofs << " [ " << preamble << " ]";
2274                 }
2275                 ofs << ">\n\n";
2276
2277                 if (params.options.empty())
2278                         sgmlOpenTag(ofs, 0, false, top_element);
2279                 else {
2280                         string top = top_element;
2281                         top += " ";
2282                         top += params.options;
2283                         sgmlOpenTag(ofs, 0, false, top);
2284                 }
2285         }
2286
2287         ofs << "<!-- "  << lyx_docversion
2288             << " created this file. For more info see http://www.lyx.org/"
2289             << " -->\n";
2290
2291         Paragraph::depth_type depth = 0; // paragraph depth
2292         Paragraph * par = &*(paragraphs.begin());
2293         string item_name;
2294         vector<string> environment_stack(5);
2295
2296         while (par) {
2297                 LyXLayout_ptr const & style = par->layout();
2298                 // treat <toc> as a special case for compatibility with old code
2299                 if (par->isInset(0)) {
2300                         Inset * inset = par->getInset(0);
2301                         Inset::Code lyx_code = inset->lyxCode();
2302                         if (lyx_code == Inset::TOC_CODE) {
2303                                 string const temp = "toc";
2304                                 sgmlOpenTag(ofs, depth, false, temp);
2305
2306                                 par = par->next();
2307                                 continue;
2308                         }
2309                 }
2310
2311                 // environment tag closing
2312                 for (; depth > par->params().depth(); --depth) {
2313                         sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2314                         environment_stack[depth].erase();
2315                 }
2316
2317                 // write opening SGML tags
2318                 switch (style->latextype) {
2319                 case LATEX_PARAGRAPH:
2320                         if (depth == par->params().depth()
2321                            && !environment_stack[depth].empty()) {
2322                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2323                                 environment_stack[depth].erase();
2324                                 if (depth)
2325                                         --depth;
2326                                 else
2327                                         ofs << "</p>";
2328                         }
2329                         sgmlOpenTag(ofs, depth, false, style->latexname());
2330                         break;
2331
2332                 case LATEX_COMMAND:
2333                         if (depth!= 0)
2334                                 sgmlError(par, 0,
2335                                           _("Error : Wrong depth for"
2336                                             " LatexType Command.\n"));
2337
2338                         if (!environment_stack[depth].empty()) {
2339                                 sgmlCloseTag(ofs, depth, false, environment_stack[depth]);
2340                                 ofs << "</p>";
2341                         }
2342
2343                         environment_stack[depth].erase();
2344                         sgmlOpenTag(ofs, depth, false, style->latexname());
2345                         break;
2346
2347                 case LATEX_ENVIRONMENT:
2348                 case LATEX_ITEM_ENVIRONMENT:
2349                 {
2350                         string const & latexname = style->latexname();
2351
2352                         if (depth == par->params().depth()
2353                             && environment_stack[depth] != latexname) {
2354                                 sgmlCloseTag(ofs, depth, false,
2355                                              environment_stack[depth]);
2356                                 environment_stack[depth].erase();
2357                         }
2358                         if (depth < par->params().depth()) {
2359                                depth = par->params().depth();
2360                                environment_stack[depth].erase();
2361                         }
2362                         if (environment_stack[depth] != latexname) {
2363                                 if (depth == 0) {
2364                                         sgmlOpenTag(ofs, depth, false, "p");
2365                                 }
2366                                 sgmlOpenTag(ofs, depth, false, latexname);
2367
2368                                 if (environment_stack.size() == depth + 1)
2369                                         environment_stack.push_back("!-- --");
2370                                 environment_stack[depth] = latexname;
2371                         }
2372
2373                         if (style->latexparam() == "CDATA")
2374                                 ofs << "<![CDATA[";
2375
2376                         if (style->latextype == LATEX_ENVIRONMENT) break;
2377
2378                         if (style->labeltype == LABEL_MANUAL)
2379                                 item_name = "tag";
2380                         else
2381                                 item_name = "item";
2382
2383                         sgmlOpenTag(ofs, depth + 1, false, item_name);
2384                 }
2385                 break;
2386
2387                 default:
2388                         sgmlOpenTag(ofs, depth, false, style->latexname());
2389                         break;
2390                 }
2391
2392                 simpleLinuxDocOnePar(ofs, par, depth);
2393
2394                 par = par->next();
2395
2396                 ofs << "\n";
2397                 // write closing SGML tags
2398                 switch (style->latextype) {
2399                 case LATEX_COMMAND:
2400                         break;
2401                 case LATEX_ENVIRONMENT:
2402                 case LATEX_ITEM_ENVIRONMENT:
2403                         if (style->latexparam() == "CDATA")
2404                                 ofs << "]]>";
2405                         break;
2406                 default:
2407                         sgmlCloseTag(ofs, depth, false, style->latexname());
2408                         break;
2409                 }
2410         }
2411
2412         // Close open tags
2413         for (int i = depth; i >= 0; --i)
2414                 sgmlCloseTag(ofs, depth, false, environment_stack[i]);
2415
2416         if (!body_only) {
2417                 ofs << "\n\n";
2418                 sgmlCloseTag(ofs, 0, false, top_element);
2419         }
2420
2421         ofs.close();
2422         // How to check for successful close
2423
2424         // we want this to be true outside previews (for insetexternal)
2425         niceFile = true;
2426 }
2427
2428
2429 // checks, if newcol chars should be put into this line
2430 // writes newline, if necessary.
2431 namespace {
2432
2433 void sgmlLineBreak(ostream & os, string::size_type & colcount,
2434                           string::size_type newcol)
2435 {
2436         colcount += newcol;
2437         if (colcount > lyxrc.ascii_linelen) {
2438                 os << "\n";
2439                 colcount = newcol; // assume write after this call
2440         }
2441 }
2442
2443 enum PAR_TAG {
2444         NONE=0,
2445         TT = 1,
2446         SF = 2,
2447         BF = 4,
2448         IT = 8,
2449         SL = 16,
2450         EM = 32
2451 };
2452
2453
2454 string tag_name(PAR_TAG const & pt) {
2455         switch (pt) {
2456         case NONE: return "!-- --";
2457         case TT: return "tt";
2458         case SF: return "sf";
2459         case BF: return "bf";
2460         case IT: return "it";
2461         case SL: return "sl";
2462         case EM: return "em";
2463         }
2464         return "";
2465 }
2466
2467
2468 inline
2469 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2470 {
2471         p1 = static_cast<PAR_TAG>(p1 | p2);
2472 }
2473
2474
2475 inline
2476 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2477 {
2478         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2479 }
2480
2481 } // anon
2482
2483
2484 // Handle internal paragraph parsing -- layout already processed.
2485 void Buffer::simpleLinuxDocOnePar(ostream & os,
2486         Paragraph * par,
2487         Paragraph::depth_type /*depth*/)
2488 {
2489         LyXLayout_ptr const & style = par->layout();
2490
2491         string::size_type char_line_count = 5;     // Heuristic choice ;-)
2492
2493         // gets paragraph main font
2494         LyXFont font_old;
2495         bool desc_on;
2496         if (style->labeltype == LABEL_MANUAL) {
2497                 font_old = style->labelfont;
2498                 desc_on = true;
2499         } else {
2500                 font_old = style->font;
2501                 desc_on = false;
2502         }
2503
2504         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
2505         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
2506         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
2507         bool is_em = false;
2508
2509         stack<PAR_TAG> tag_state;
2510         // parsing main loop
2511         for (pos_type i = 0; i < par->size(); ++i) {
2512
2513                 PAR_TAG tag_close = NONE;
2514                 list < PAR_TAG > tag_open;
2515
2516                 LyXFont const font = par->getFont(params, i);
2517
2518                 if (font_old.family() != font.family()) {
2519                         switch (family_type) {
2520                         case LyXFont::SANS_FAMILY:
2521                                 tag_close |= SF;
2522                                 break;
2523                         case LyXFont::TYPEWRITER_FAMILY:
2524                                 tag_close |= TT;
2525                                 break;
2526                         default:
2527                                 break;
2528                         }
2529
2530                         family_type = font.family();
2531
2532                         switch (family_type) {
2533                         case LyXFont::SANS_FAMILY:
2534                                 tag_open.push_back(SF);
2535                                 break;
2536                         case LyXFont::TYPEWRITER_FAMILY:
2537                                 tag_open.push_back(TT);
2538                                 break;
2539                         default:
2540                                 break;
2541                         }
2542                 }
2543
2544                 if (font_old.series() != font.series()) {
2545                         switch (series_type) {
2546                         case LyXFont::BOLD_SERIES:
2547                                 tag_close |= BF;
2548                                 break;
2549                         default:
2550                                 break;
2551                         }
2552
2553                         series_type = font.series();
2554
2555                         switch (series_type) {
2556                         case LyXFont::BOLD_SERIES:
2557                                 tag_open.push_back(BF);
2558                                 break;
2559                         default:
2560                                 break;
2561                         }
2562
2563                 }
2564
2565                 if (font_old.shape() != font.shape()) {
2566                         switch (shape_type) {
2567                         case LyXFont::ITALIC_SHAPE:
2568                                 tag_close |= IT;
2569                                 break;
2570                         case LyXFont::SLANTED_SHAPE:
2571                                 tag_close |= SL;
2572                                 break;
2573                         default:
2574                                 break;
2575                         }
2576
2577                         shape_type = font.shape();
2578
2579                         switch (shape_type) {
2580                         case LyXFont::ITALIC_SHAPE:
2581                                 tag_open.push_back(IT);
2582                                 break;
2583                         case LyXFont::SLANTED_SHAPE:
2584                                 tag_open.push_back(SL);
2585                                 break;
2586                         default:
2587                                 break;
2588                         }
2589                 }
2590                 // handle <em> tag
2591                 if (font_old.emph() != font.emph()) {
2592                         if (font.emph() == LyXFont::ON) {
2593                                 tag_open.push_back(EM);
2594                                 is_em = true;
2595                         }
2596                         else if (is_em) {
2597                                 tag_close |= EM;
2598                                 is_em = false;
2599                         }
2600                 }
2601
2602                 list < PAR_TAG > temp;
2603                 while (!tag_state.empty() && tag_close) {
2604                         PAR_TAG k =  tag_state.top();
2605                         tag_state.pop();
2606                         os << "</" << tag_name(k) << ">";
2607                         if (tag_close & k)
2608                                 reset(tag_close,k);
2609                         else
2610                                 temp.push_back(k);
2611                 }
2612
2613                 for(list< PAR_TAG >::const_iterator j = temp.begin();
2614                     j != temp.end(); ++j) {
2615                         tag_state.push(*j);
2616                         os << "<" << tag_name(*j) << ">";
2617                 }
2618
2619                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
2620                     j != tag_open.end(); ++j) {
2621                         tag_state.push(*j);
2622                         os << "<" << tag_name(*j) << ">";
2623                 }
2624
2625                 char c = par->getChar(i);
2626
2627                 if (c == Paragraph::META_INSET) {
2628                         Inset * inset = par->getInset(i);
2629                         inset->linuxdoc(this, os);
2630                         font_old = font;
2631                         continue;
2632                 }
2633
2634                 if (style->latexparam() == "CDATA") {
2635                         // "TeX"-Mode on == > SGML-Mode on.
2636                         if (c != '\0')
2637                                 os << c;
2638                         ++char_line_count;
2639                 } else {
2640                         bool ws;
2641                         string str;
2642                         boost::tie(ws, str) = sgml::escapeChar(c);
2643                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2644                                 // in freespacing mode, spaces are
2645                                 // non-breaking characters
2646                                 if (desc_on) {// if char is ' ' then...
2647
2648                                         ++char_line_count;
2649                                         sgmlLineBreak(os, char_line_count, 6);
2650                                         os << "</tag>";
2651                                         desc_on = false;
2652                                 } else  {
2653                                         sgmlLineBreak(os, char_line_count, 1);
2654                                         os << c;
2655                                 }
2656                         } else {
2657                                 os << str;
2658                                 char_line_count += str.length();
2659                         }
2660                 }
2661                 font_old = font;
2662         }
2663
2664         while (!tag_state.empty()) {
2665                 os << "</" << tag_name(tag_state.top()) << ">";
2666                 tag_state.pop();
2667         }
2668
2669         // resets description flag correctly
2670         if (desc_on) {
2671                 // <tag> not closed...
2672                 sgmlLineBreak(os, char_line_count, 6);
2673                 os << "</tag>";
2674         }
2675 }
2676
2677
2678 // Print an error message.
2679 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2680         string const & /*message*/) const
2681 {
2682 #ifdef WITH_WARNINGS
2683 #warning This is wrong we cannot insert an inset like this!!!
2684         // I guess this was Jose' so I explain you more or less why this
2685         // is wrong. This way you insert something in the paragraph and
2686         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2687         // I deactivate this code, have a look at BufferView::insertErrors
2688         // how you should do this correctly! (Jug 20020315)
2689 #endif
2690 #if 0
2691         // insert an error marker in text
2692         InsetError * new_inset = new InsetError(message);
2693         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2694                          params.language));
2695 #endif
2696 }
2697
2698
2699 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2700 {
2701         ofstream ofs(fname.c_str());
2702         if (!ofs) {
2703                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2704                 return;
2705         }
2706
2707         Paragraph * par = &*(paragraphs.begin());
2708
2709         niceFile = nice; // this will be used by Insetincludes.
2710
2711         LaTeXFeatures features(params);
2712         validate(features);
2713
2714         texrow.reset();
2715
2716         LyXTextClass const & tclass = params.getLyXTextClass();
2717         string top_element = tclass.latexname();
2718
2719         if (!only_body) {
2720                 ofs << "<!DOCTYPE " << top_element
2721                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2722
2723                 string preamble = params.preamble;
2724                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2725                          : fname;
2726                 preamble += features.getIncludedFiles(name);
2727                 preamble += features.getLyXSGMLEntities();
2728
2729                 if (!preamble.empty()) {
2730                         ofs << "\n [ " << preamble << " ]";
2731                 }
2732                 ofs << ">\n\n";
2733         }
2734
2735         string top = top_element;
2736         top += " lang=\"";
2737         top += params.language->code();
2738         top += "\"";
2739
2740         if (!params.options.empty()) {
2741                 top += " ";
2742                 top += params.options;
2743         }
2744         sgmlOpenTag(ofs, 0, false, top);
2745
2746         ofs << "<!-- DocBook file was created by " << lyx_docversion
2747             << "\n  See http://www.lyx.org/ for more information -->\n";
2748
2749         vector<string> environment_stack(10);
2750         vector<string> environment_inner(10);
2751         vector<string> command_stack(10);
2752
2753         bool command_flag = false;
2754         Paragraph::depth_type command_depth = 0;
2755         Paragraph::depth_type command_base = 0;
2756         Paragraph::depth_type cmd_depth = 0;
2757         Paragraph::depth_type depth = 0; // paragraph depth
2758
2759         string item_name;
2760         string command_name;
2761
2762         while (par) {
2763                 string sgmlparam;
2764                 string c_depth;
2765                 string c_params;
2766                 int desc_on = 0; // description mode
2767
2768                 LyXLayout_ptr const & style = par->layout();
2769
2770                 // environment tag closing
2771                 for (; depth > par->params().depth(); --depth) {
2772                         if (environment_inner[depth] != "!-- --") {
2773                                 item_name = "listitem";
2774                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2775                                 if (environment_inner[depth] == "varlistentry")
2776                                         sgmlCloseTag(ofs, depth+command_depth, false, environment_inner[depth]);
2777                         }
2778                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2779                         environment_stack[depth].erase();
2780                         environment_inner[depth].erase();
2781                 }
2782
2783                 if (depth == par->params().depth()
2784                    && environment_stack[depth] != style->latexname()
2785                    && !environment_stack[depth].empty()) {
2786                         if (environment_inner[depth] != "!-- --") {
2787                                 item_name= "listitem";
2788                                 sgmlCloseTag(ofs, command_depth+depth, false, item_name);
2789                                 if (environment_inner[depth] == "varlistentry")
2790                                         sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2791                         }
2792
2793                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2794
2795                         environment_stack[depth].erase();
2796                         environment_inner[depth].erase();
2797                 }
2798
2799                 // Write opening SGML tags.
2800                 switch (style->latextype) {
2801                 case LATEX_PARAGRAPH:
2802                         sgmlOpenTag(ofs, depth + command_depth,
2803                                     false, style->latexname());
2804                         break;
2805
2806                 case LATEX_COMMAND:
2807                         if (depth != 0)
2808                                 sgmlError(par, 0,
2809                                           _("Error : Wrong depth for "
2810                                             "LatexType Command.\n"));
2811
2812                         command_name = style->latexname();
2813
2814                         sgmlparam = style->latexparam();
2815                         c_params = split(sgmlparam, c_depth,'|');
2816
2817                         cmd_depth = lyx::atoi(c_depth);
2818
2819                         if (command_flag) {
2820                                 if (cmd_depth < command_base) {
2821                                         for (Paragraph::depth_type j = command_depth;
2822                                              j >= command_base; --j) {
2823                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
2824                                                 ofs << endl;
2825                                         }
2826                                         command_depth = command_base = cmd_depth;
2827                                 } else if (cmd_depth <= command_depth) {
2828                                         for (int j = command_depth;
2829                                              j >= int(cmd_depth); --j) {
2830                                                 sgmlCloseTag(ofs, j, false, command_stack[j]);
2831                                                 ofs << endl;
2832                                         }
2833                                         command_depth = cmd_depth;
2834                                 } else
2835                                         command_depth = cmd_depth;
2836                         } else {
2837                                 command_depth = command_base = cmd_depth;
2838                                 command_flag = true;
2839                         }
2840                         if (command_stack.size() == command_depth + 1)
2841                                 command_stack.push_back(string());
2842                         command_stack[command_depth] = command_name;
2843
2844                         // treat label as a special case for
2845                         // more WYSIWYM handling.
2846                         // This is a hack while paragraphs can't have
2847                         // attributes, like id in this case.
2848                         if (par->isInset(0)) {
2849                                 Inset * inset = par->getInset(0);
2850                                 Inset::Code lyx_code = inset->lyxCode();
2851                                 if (lyx_code == Inset::LABEL_CODE) {
2852                                         command_name += " id=\"";
2853                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2854                                         command_name += "\"";
2855                                         desc_on = 3;
2856                                 }
2857                         }
2858
2859                         sgmlOpenTag(ofs, depth + command_depth, false, command_name);
2860
2861                         item_name = c_params.empty()?"title":c_params;
2862                         sgmlOpenTag(ofs, depth + 1 + command_depth, false, item_name);
2863                         break;
2864
2865                 case LATEX_ENVIRONMENT:
2866                 case LATEX_ITEM_ENVIRONMENT:
2867                         if (depth < par->params().depth()) {
2868                                 depth = par->params().depth();
2869                                 environment_stack[depth].erase();
2870                         }
2871
2872                         if (environment_stack[depth] != style->latexname()) {
2873                                 if (environment_stack.size() == depth + 1) {
2874                                         environment_stack.push_back("!-- --");
2875                                         environment_inner.push_back("!-- --");
2876                                 }
2877                                 environment_stack[depth] = style->latexname();
2878                                 environment_inner[depth] = "!-- --";
2879                                 sgmlOpenTag(ofs, depth + command_depth, false, environment_stack[depth]);
2880                         } else {
2881                                 if (environment_inner[depth] != "!-- --") {
2882                                         item_name= "listitem";
2883                                         sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2884                                         if (environment_inner[depth] == "varlistentry")
2885                                                 sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2886                                 }
2887                         }
2888
2889                         if (style->latextype == LATEX_ENVIRONMENT) {
2890                                 if (!style->latexparam().empty()) {
2891                                         if (style->latexparam() == "CDATA")
2892                                                 ofs << "<![CDATA[";
2893                                         else
2894                                                 sgmlOpenTag(ofs, depth + command_depth, false, style->latexparam());
2895                                 }
2896                                 break;
2897                         }
2898
2899                         desc_on = (style->labeltype == LABEL_MANUAL);
2900
2901                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2902                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2903                                     false, environment_inner[depth]);
2904
2905                         item_name = desc_on ? "term" : "para";
2906                         sgmlOpenTag(ofs, depth + 1 + command_depth,
2907                                     false, item_name);
2908                         break;
2909                 default:
2910                         sgmlOpenTag(ofs, depth + command_depth,
2911                                     false, style->latexname());
2912                         break;
2913                 }
2914
2915                 simpleDocBookOnePar(ofs, par, desc_on,
2916                                     depth + 1 + command_depth);
2917                 par = par->next();
2918
2919                 string end_tag;
2920                 // write closing SGML tags
2921                 switch (style->latextype) {
2922                 case LATEX_COMMAND:
2923                         end_tag = c_params.empty() ? "title" : c_params;
2924                         sgmlCloseTag(ofs, depth + command_depth,
2925                                      false, end_tag);
2926                         break;
2927                 case LATEX_ENVIRONMENT:
2928                         if (!style->latexparam().empty()) {
2929                                 if (style->latexparam() == "CDATA")
2930                                         ofs << "]]>";
2931                                 else
2932                                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexparam());
2933                         }
2934                         break;
2935                 case LATEX_ITEM_ENVIRONMENT:
2936                         if (desc_on == 1) break;
2937                         end_tag= "para";
2938                         sgmlCloseTag(ofs, depth + 1 + command_depth, false, end_tag);
2939                         break;
2940                 case LATEX_PARAGRAPH:
2941                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2942                         break;
2943                 default:
2944                         sgmlCloseTag(ofs, depth + command_depth, false, style->latexname());
2945                         break;
2946                 }
2947         }
2948
2949         // Close open tags
2950         for (int d = depth; d >= 0; --d) {
2951                 if (!environment_stack[depth].empty()) {
2952                         if (environment_inner[depth] != "!-- --") {
2953                                 item_name = "listitem";
2954                                 sgmlCloseTag(ofs, command_depth + depth, false, item_name);
2955                                if (environment_inner[depth] == "varlistentry")
2956                                        sgmlCloseTag(ofs, depth + command_depth, false, environment_inner[depth]);
2957                         }
2958
2959                         sgmlCloseTag(ofs, depth + command_depth, false, environment_stack[depth]);
2960                 }
2961         }
2962
2963         for (int j = command_depth; j >= 0 ; --j)
2964                 if (!command_stack[j].empty()) {
2965                         sgmlCloseTag(ofs, j, false, command_stack[j]);
2966                         ofs << endl;
2967                 }
2968
2969         ofs << "\n\n";
2970         sgmlCloseTag(ofs, 0, false, top_element);
2971
2972         ofs.close();
2973         // How to check for successful close
2974
2975         // we want this to be true outside previews (for insetexternal)
2976         niceFile = true;
2977 }
2978
2979
2980 void Buffer::simpleDocBookOnePar(ostream & os,
2981                                  Paragraph * par, int & desc_on,
2982                                  Paragraph::depth_type depth) const
2983 {
2984         bool emph_flag = false;
2985
2986         LyXLayout_ptr const & style = par->layout();
2987
2988         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2989
2990         int char_line_count = depth;
2991         //if (!style.free_spacing)
2992         //      os << string(depth,' ');
2993
2994         // parsing main loop
2995         for (pos_type i = 0; i < par->size(); ++i) {
2996                 LyXFont font = par->getFont(params, i);
2997
2998                 // handle <emphasis> tag
2999                 if (font_old.emph() != font.emph()) {
3000                         if (font.emph() == LyXFont::ON) {
3001                                 if (style->latexparam() == "CDATA")
3002                                         os << "]]>";
3003                                 os << "<emphasis>";
3004                                 if (style->latexparam() == "CDATA")
3005                                         os << "<![CDATA[";
3006                                 emph_flag = true;
3007                         } else if (i) {
3008                                 if (style->latexparam() == "CDATA")
3009                                         os << "]]>";
3010                                 os << "</emphasis>";
3011                                 if (style->latexparam() == "CDATA")
3012                                         os << "<![CDATA[";
3013                                 emph_flag = false;
3014                         }
3015                 }
3016
3017
3018                 if (par->isInset(i)) {
3019                         Inset * inset = par->getInset(i);
3020                         // don't print the inset in position 0 if desc_on == 3 (label)
3021                         if (i || desc_on != 3) {
3022                                 if (style->latexparam() == "CDATA")
3023                                         os << "]]>";
3024                                 inset->docbook(this, os, false);
3025                                 if (style->latexparam() == "CDATA")
3026                                         os << "<![CDATA[";
3027                         }
3028                 } else {
3029                         char c = par->getChar(i);
3030                         bool ws;
3031                         string str;
3032                         boost::tie(ws, str) = sgml::escapeChar(c);
3033
3034                         if (style->pass_thru) {
3035                                 os << c;
3036                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
3037                                         os << str;
3038                         } else if (desc_on ==1) {
3039                                 ++char_line_count;
3040                                 os << "\n</term><listitem><para>";
3041                                 desc_on = 2;
3042                         } else {
3043                                 os << ' ';
3044                         }
3045                 }
3046                 font_old = font;
3047         }
3048
3049         if (emph_flag) {
3050                 if (style->latexparam() == "CDATA")
3051                         os << "]]>";
3052                 os << "</emphasis>";
3053                 if (style->latexparam() == "CDATA")
3054                         os << "<![CDATA[";
3055         }
3056
3057         // resets description flag correctly
3058         if (desc_on == 1) {
3059                 // <term> not closed...
3060                 os << "</term>\n<listitem><para>&nbsp;</para>";
3061         }
3062         if (style->free_spacing)
3063                 os << '\n';
3064 }
3065
3066
3067 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
3068 // Other flags: -wall -v0 -x
3069 int Buffer::runChktex()
3070 {
3071         if (!users->text) return 0;
3072
3073         users->owner()->prohibitInput();
3074
3075         // get LaTeX-Filename
3076         string const name = getLatexName();
3077         string path = filePath();
3078
3079         string const org_path = path;
3080         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
3081                 path = tmppath;
3082         }
3083
3084         Path p(path); // path to LaTeX file
3085         users->owner()->message(_("Running chktex..."));
3086
3087         // Remove all error insets
3088         bool const removedErrorInsets = users->removeAutoInsets();
3089
3090         // Generate the LaTeX file if neccessary
3091         makeLaTeXFile(name, org_path, false);
3092
3093         TeXErrors terr;
3094         Chktex chktex(lyxrc.chktex_command, name, filePath());
3095         int res = chktex.run(terr); // run chktex
3096
3097         if (res == -1) {
3098                 Alert::alert(_("chktex did not work!"),
3099                            _("Could not run with file:"), name);
3100         } else if (res > 0) {
3101                 // Insert all errors as errors boxes
3102                 users->insertErrors(terr);
3103         }
3104
3105         // if we removed error insets before we ran chktex or if we inserted
3106         // error insets after we ran chktex, this must be run:
3107         if (removedErrorInsets || res) {
3108 #warning repaint needed here, or do you mean update() ?
3109                 users->repaint();
3110                 users->fitCursor();
3111         }
3112         users->owner()->allowInput();
3113
3114         return res;
3115 }
3116
3117
3118 void Buffer::validate(LaTeXFeatures & features) const
3119 {
3120         LyXTextClass const & tclass = params.getLyXTextClass();
3121
3122         // AMS Style is at document level
3123         if (params.use_amsmath || tclass.provides(LyXTextClass::amsmath))
3124                 features.require("amsmath");
3125
3126         for_each(paragraphs.begin(), paragraphs.end(),
3127                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
3128
3129         // the bullet shapes are buffer level not paragraph level
3130         // so they are tested here
3131         for (int i = 0; i < 4; ++i) {
3132                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
3133                         int const font = params.user_defined_bullets[i].getFont();
3134                         if (font == 0) {
3135                                 int const c = params
3136                                         .user_defined_bullets[i]
3137                                         .getCharacter();
3138                                 if (c == 16
3139                                    || c == 17
3140                                    || c == 25
3141                                    || c == 26
3142                                    || c == 31) {
3143                                         features.require("latexsym");
3144                                 }
3145                         } else if (font == 1) {
3146                                 features.require("amssymb");
3147                         } else if ((font >= 2 && font <= 5)) {
3148                                 features.require("pifont");
3149                         }
3150                 }
3151         }
3152
3153         if (lyxerr.debugging(Debug::LATEX)) {
3154                 features.showStruct();
3155         }
3156 }
3157
3158
3159 vector<string> const Buffer::getLabelList() const
3160 {
3161         /// if this is a child document and the parent is already loaded
3162         /// Use the parent's list instead  [ale990407]
3163         if (!params.parentname.empty()
3164             && bufferlist.exists(params.parentname)) {
3165                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3166                 if (tmp)
3167                         return tmp->getLabelList();
3168         }
3169
3170         vector<string> label_list;
3171         for (inset_iterator it = inset_const_iterator_begin();
3172              it != inset_const_iterator_end(); ++it) {
3173                 vector<string> const l = it->getLabelList();
3174                 label_list.insert(label_list.end(), l.begin(), l.end());
3175         }
3176         return label_list;
3177 }
3178
3179
3180 // This is also a buffer property (ale)
3181 vector<pair<string, string> > const Buffer::getBibkeyList() const
3182 {
3183         typedef pair<string, string> StringPair;
3184         /// if this is a child document and the parent is already loaded
3185         /// Use the parent's list instead  [ale990412]
3186         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
3187                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
3188                 if (tmp)
3189                         return tmp->getBibkeyList();
3190         }
3191
3192         vector<StringPair> keys;
3193         ParagraphList::iterator pit = paragraphs.begin();
3194         ParagraphList::iterator pend = paragraphs.end();
3195         for (; pit != pend; ++pit) {
3196                 if (pit->bibkey) {
3197                         string const key = pit->bibkey->getContents();
3198                         string const opt = pit->bibkey->getOptions();
3199                         string const ref = pit->asString(this, false);
3200                         string const info = opt + "TheBibliographyRef" + ref;
3201
3202                         keys.push_back(StringPair(key, info));
3203                 }
3204         }
3205
3206         if (!keys.empty())
3207                 return keys;
3208
3209         // Might be either using bibtex or a child has bibliography
3210         for (inset_iterator it = inset_const_iterator_begin();
3211                 it != inset_const_iterator_end(); ++it) {
3212                 // Search for Bibtex or Include inset
3213                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
3214                         vector<StringPair> tmp =
3215                                 static_cast<InsetBibtex &>(*it).getKeys(this);
3216                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3217                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
3218                         vector<StringPair> const tmp =
3219                                 static_cast<InsetInclude &>(*it).getKeys();
3220                         keys.insert(keys.end(), tmp.begin(), tmp.end());
3221                 }
3222         }
3223
3224         return keys;
3225 }
3226
3227
3228 bool Buffer::isDepClean(string const & name) const
3229 {
3230         DEPCLEAN * item = dep_clean;
3231         while (item && item->master != name)
3232                 item = item->next;
3233         if (!item) return true;
3234         return item->clean;
3235 }
3236
3237
3238 void Buffer::markDepClean(string const & name)
3239 {
3240         if (!dep_clean) {
3241                 dep_clean = new DEPCLEAN;
3242                 dep_clean->clean = true;
3243                 dep_clean->master = name;
3244                 dep_clean->next = 0;
3245         } else {
3246                 DEPCLEAN * item = dep_clean;
3247                 while (item && item->master != name)
3248                         item = item->next;
3249                 if (item) {
3250                         item->clean = true;
3251                 } else {
3252                         item = new DEPCLEAN;
3253                         item->clean = true;
3254                         item->master = name;
3255                         item->next = 0;
3256                 }
3257         }
3258 }
3259
3260
3261 bool Buffer::dispatch(string const & command, bool * result)
3262 {
3263         // Split command string into command and argument
3264         string cmd;
3265         string line = ltrim(command);
3266         string const arg = trim(split(line, cmd, ' '));
3267
3268         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
3269 }
3270
3271
3272 bool Buffer::dispatch(int action, string const & argument, bool * result)
3273 {
3274         bool dispatched = true;
3275
3276         switch (action) {
3277                 case LFUN_EXPORT: {
3278                         bool const tmp = Exporter::Export(this, argument, false);
3279                         if (result)
3280                                 *result = tmp;
3281                         break;
3282                 }
3283
3284                 default:
3285                         dispatched = false;
3286         }
3287         return dispatched;
3288 }
3289
3290
3291 void Buffer::resizeInsets(BufferView * bv)
3292 {
3293         /// then remove all LyXText in text-insets
3294         for_each(paragraphs.begin(), paragraphs.end(),
3295                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
3296 }
3297
3298
3299 void Buffer::redraw()
3300 {
3301 #warning repaint needed here, or do you mean update() ?
3302         users->repaint();
3303         users->fitCursor();
3304 }
3305
3306
3307 void Buffer::changeLanguage(Language const * from, Language const * to)
3308 {
3309
3310         ParIterator end = par_iterator_end();
3311         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3312                 (*it)->changeLanguage(params, from, to);
3313 }
3314
3315
3316 bool Buffer::isMultiLingual()
3317 {
3318         ParIterator end = par_iterator_end();
3319         for (ParIterator it = par_iterator_begin(); it != end; ++it)
3320                 if ((*it)->isMultiLingual(params))
3321                         return true;
3322
3323         return false;
3324 }
3325
3326
3327 void Buffer::inset_iterator::setParagraph()
3328 {
3329         while (pit != pend) {
3330                 it = pit->insetlist.begin();
3331                 if (it != pit->insetlist.end())
3332                         return;
3333                 ++pit;
3334         }
3335 }
3336
3337
3338 Inset * Buffer::getInsetFromID(int id_arg) const
3339 {
3340         for (inset_iterator it = inset_const_iterator_begin();
3341                  it != inset_const_iterator_end(); ++it)
3342         {
3343                 if (it->id() == id_arg)
3344                         return &(*it);
3345                 Inset * in = it->getInsetFromID(id_arg);
3346                 if (in)
3347                         return in;
3348         }
3349         return 0;
3350 }
3351
3352
3353 Paragraph * Buffer::getParFromID(int id) const
3354 {
3355         if (id < 0)
3356                 return 0;
3357
3358         ParagraphList::iterator it = paragraphs.begin();
3359         ParagraphList::iterator end = paragraphs.end();
3360         for (; it != end; ++it) {
3361                 if (it->id() == id) {
3362                         return &*it;
3363                 }
3364                 Paragraph * tmp = it->getParFromID(id);
3365                 if (tmp) {
3366                         return tmp;
3367                 }
3368         }
3369         return 0;
3370 }
3371
3372
3373 ParIterator Buffer::par_iterator_begin()
3374 {
3375         return ParIterator(&*(paragraphs.begin()));
3376 }
3377
3378
3379 ParIterator Buffer::par_iterator_end()
3380 {
3381         return ParIterator();
3382 }
3383
3384
3385 void Buffer::addUser(BufferView * u)
3386 {
3387         users = u;
3388 }
3389
3390
3391 void Buffer::delUser(BufferView *)
3392 {
3393         users = 0;
3394 }
3395
3396
3397 Language const * Buffer::getLanguage() const
3398 {
3399         return params.language;
3400 }
3401
3402
3403 bool Buffer::isClean() const
3404 {
3405         return lyx_clean;
3406 }
3407
3408
3409 bool Buffer::isBakClean() const
3410 {
3411         return bak_clean;
3412 }
3413
3414
3415 void Buffer::markClean() const
3416 {
3417         if (!lyx_clean) {
3418                 lyx_clean = true;
3419                 updateTitles();
3420         }
3421         // if the .lyx file has been saved, we don't need an
3422         // autosave
3423         bak_clean = true;
3424 }
3425
3426
3427 void Buffer::markBakClean()
3428 {
3429         bak_clean = true;
3430 }
3431
3432
3433 void Buffer::setUnnamed(bool flag)
3434 {
3435         unnamed = flag;
3436 }
3437
3438
3439 bool Buffer::isUnnamed()
3440 {
3441         return unnamed;
3442 }
3443
3444
3445 void Buffer::markDirty()
3446 {
3447         if (lyx_clean) {
3448                 lyx_clean = false;
3449                 updateTitles();
3450         }
3451         bak_clean = false;
3452         DEPCLEAN * tmp = dep_clean;
3453         while (tmp) {
3454                 tmp->clean = false;
3455                 tmp = tmp->next;
3456         }
3457 }
3458
3459
3460 string const & Buffer::fileName() const
3461 {
3462         return filename_;
3463 }
3464
3465
3466 string const & Buffer::filePath() const
3467 {
3468         return filepath_;
3469 }
3470
3471
3472 bool Buffer::isReadonly() const
3473 {
3474         return read_only;
3475 }
3476
3477
3478 BufferView * Buffer::getUser() const
3479 {
3480         return users;
3481 }
3482
3483
3484 void Buffer::setParentName(string const & name)
3485 {
3486         params.parentname = name;
3487 }
3488
3489
3490 Buffer::inset_iterator::inset_iterator()
3491         : pit(0), pend(0)
3492 {}
3493
3494
3495 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
3496         : pit(p), pend(e)
3497 {
3498         setParagraph();
3499 }
3500
3501
3502 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
3503 {
3504         if (pit != pend) {
3505                 ++it;
3506                 if (it == pit->insetlist.end()) {
3507                         ++pit;
3508                         setParagraph();
3509                 }
3510         }
3511         return *this;
3512 }
3513
3514
3515 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
3516 {
3517         inset_iterator tmp = *this;
3518         ++*this;
3519         return tmp;
3520 }
3521
3522
3523 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
3524 {
3525         return *it.getInset();
3526 }
3527
3528
3529 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
3530 {
3531         return it.getInset();
3532 }
3533
3534
3535 Paragraph * Buffer::inset_iterator::getPar()
3536 {
3537         return &(*pit);
3538 }
3539
3540
3541 lyx::pos_type Buffer::inset_iterator::getPos() const
3542 {
3543         return it.getPos();
3544 }
3545
3546
3547 bool operator==(Buffer::inset_iterator const & iter1,
3548                 Buffer::inset_iterator const & iter2)
3549 {
3550         return iter1.pit == iter2.pit
3551                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
3552 }
3553
3554
3555 bool operator!=(Buffer::inset_iterator const & iter1,
3556                 Buffer::inset_iterator const & iter2)
3557 {
3558         return !(iter1 == iter2);
3559 }