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