]> git.lyx.org Git - features.git/blob - src/buffer.C
Use ParList iterator to insert lyxfile and read the document.
[features.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 #include "buffer.h"
18 #include "bufferlist.h"
19 #include "LyXAction.h"
20 #include "lyxrc.h"
21 #include "lyxlex.h"
22 #include "tex-strings.h"
23 #include "layout.h"
24 #include "bufferview_funcs.h"
25 #include "lyxfont.h"
26 #include "version.h"
27 #include "LaTeX.h"
28 #include "Chktex.h"
29 #include "debug.h"
30 #include "LaTeXFeatures.h"
31 #include "lyxtext.h"
32 #include "gettext.h"
33 #include "language.h"
34 #include "exporter.h"
35 #include "Lsstream.h"
36 #include "format.h"
37 #include "BufferView.h"
38 #include "ParagraphParameters.h"
39 #include "iterators.h"
40 #include "lyxtextclasslist.h"
41 #include "sgml.h"
42 #include "paragraph_funcs.h"
43 #include "author.h"
44
45 #include "frontends/LyXView.h"
46
47 #include "mathed/formulamacro.h"
48 #include "mathed/formula.h"
49
50 #include "insets/inset.h"
51 #include "insets/inseterror.h"
52 #include "insets/insethfill.h"
53 #include "insets/insetlabel.h"
54 #include "insets/insetref.h"
55 #include "insets/inseturl.h"
56 #include "insets/insetnote.h"
57 #include "insets/insetquotes.h"
58 #include "insets/insetlatexaccent.h"
59 #include "insets/insetbibitem.h"
60 #include "insets/insetbibtex.h"
61 #include "insets/insetcite.h"
62 #include "insets/insetexternal.h"
63 #include "insets/insetindex.h"
64 #include "insets/insetinclude.h"
65 #include "insets/insettoc.h"
66 #include "insets/insetparent.h"
67 #include "insets/insetspecialchar.h"
68 #include "insets/insettext.h"
69 #include "insets/insetert.h"
70 #include "insets/insetgraphics.h"
71 #include "insets/insetfoot.h"
72 #include "insets/insetmarginal.h"
73 #include "insets/insetoptarg.h"
74 #include "insets/insetminipage.h"
75 #include "insets/insetfloat.h"
76 #include "insets/insetwrap.h"
77 #include "insets/insettabular.h"
78 #if 0
79 #include "insets/insettheorem.h"
80 #include "insets/insetlist.h"
81 #endif
82 #include "insets/insetcaption.h"
83 #include "insets/insetfloatlist.h"
84
85 #include "frontends/Dialogs.h"
86 #include "frontends/Alert.h"
87
88 #include "graphics/Previews.h"
89
90 #include "support/textutils.h"
91 #include "support/filetools.h"
92 #include "support/path.h"
93 #include "support/os.h"
94 #include "support/lyxlib.h"
95 #include "support/FileInfo.h"
96 #include "support/lyxmanip.h"
97 #include "support/lyxtime.h"
98
99 #include <boost/bind.hpp>
100 #include <boost/tuple/tuple.hpp>
101 #include "BoostFormat.h"
102
103 #include <fstream>
104 #include <iomanip>
105 #include <map>
106 #include <stack>
107 #include <list>
108 #include <algorithm>
109
110 #include <cstdlib>
111 #include <cmath>
112 #include <unistd.h>
113 #include <sys/types.h>
114 #include <utime.h>
115
116 #ifdef HAVE_LOCALE
117 #include <locale>
118 #endif
119
120 #ifndef CXX_GLOBAL_CSTD
121 using std::pow;
122 #endif
123
124 using std::ostream;
125 using std::ofstream;
126 using std::ifstream;
127 using std::fstream;
128 using std::ios;
129 using std::setw;
130 using std::endl;
131 using std::pair;
132 using std::make_pair;
133 using std::vector;
134 using std::map;
135 using std::stack;
136 using std::list;
137 using std::for_each;
138
139 using lyx::pos_type;
140 using lyx::textclass_type;
141
142 // all these externs should eventually be removed.
143 extern BufferList bufferlist;
144
145 namespace {
146
147 const int LYX_FORMAT = 222;
148
149 } // namespace anon
150
151 Buffer::Buffer(string const & file, bool ronly)
152         : niceFile(true), lyx_clean(true), bak_clean(true),
153           unnamed(false), read_only(ronly),
154           filename_(file), users(0)
155 {
156         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
157         filepath_ = OnlyPath(file);
158         lyxvc.buffer(this);
159         if (read_only || lyxrc.use_tempdir) {
160                 tmppath = CreateBufferTmpDir();
161         } else {
162                 tmppath.erase();
163         }
164
165         // set initial author
166         authors().record(Author(lyxrc.user_name, lyxrc.user_email));
167 }
168
169
170 Buffer::~Buffer()
171 {
172         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
173         // here the buffer should take care that it is
174         // saved properly, before it goes into the void.
175
176         // make sure that views using this buffer
177         // forgets it.
178         if (users)
179                 users->buffer(0);
180
181         if (!tmppath.empty()) {
182                 DestroyBufferTmpDir(tmppath);
183         }
184
185         paragraphs.clear();
186
187         // Remove any previewed LaTeX snippets assocoated with this buffer.
188         grfx::Previews::get().removeLoader(this);
189 }
190
191
192 string const Buffer::getLatexName(bool no_path) const
193 {
194         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
195         if (no_path)
196                 return OnlyFilename(name);
197         else
198                 return name;
199 }
200
201
202 pair<Buffer::LogType, string> const Buffer::getLogName() const
203 {
204         string const filename = getLatexName(false);
205
206         if (filename.empty())
207                 return make_pair(Buffer::latexlog, string());
208
209         string path = OnlyPath(filename);
210
211         if (lyxrc.use_tempdir || !IsDirWriteable(path))
212                 path = tmppath;
213
214         string const fname = AddName(path,
215                                      OnlyFilename(ChangeExtension(filename,
216                                                                   ".log")));
217         string const bname =
218                 AddName(path, OnlyFilename(
219                         ChangeExtension(filename,
220                                         formats.extension("literate") + ".out")));
221
222         // If no Latex log or Build log is newer, show Build log
223
224         FileInfo const f_fi(fname);
225         FileInfo const b_fi(bname);
226
227         if (b_fi.exist() &&
228             (!f_fi.exist() || f_fi.getModificationTime() < b_fi.getModificationTime())) {
229                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
230                 return make_pair(Buffer::buildlog, bname);
231         }
232         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
233         return make_pair(Buffer::latexlog, fname);
234 }
235
236
237 void Buffer::setReadonly(bool flag)
238 {
239         if (read_only != flag) {
240                 read_only = flag;
241                 updateTitles();
242                 users->owner()->getDialogs().updateBufferDependent(false);
243         }
244 }
245
246
247 AuthorList & Buffer::authors()
248 {
249         return params.authorlist;
250 }
251
252
253 /// Update window titles of all users
254 // Should work on a list
255 void Buffer::updateTitles() const
256 {
257         if (users)
258                 users->owner()->updateWindowTitle();
259 }
260
261
262 /// Reset autosave timer of all users
263 // Should work on a list
264 void Buffer::resetAutosaveTimers() const
265 {
266         if (users)
267                 users->owner()->resetAutosaveTimer();
268 }
269
270
271 void Buffer::setFileName(string const & newfile)
272 {
273         filename_ = MakeAbsPath(newfile);
274         filepath_ = OnlyPath(filename_);
275         setReadonly(IsFileWriteable(filename_) == 0);
276         updateTitles();
277 }
278
279
280 // We'll remove this later. (Lgb)
281 namespace {
282
283 #ifdef WITH_WARNINGS
284 #warning this is never set to != 0 !!! - remove ?
285 #endif
286 int unknown_layouts;
287
288 void unknownClass(string const & unknown)
289 {
290         string msg =
291 #if USE_BOOST_FORMAT
292                 boost::io::str(boost::format(
293                         _("The document uses an unknown textclass \"%1$s\".")) % unknown)
294                 + _("-- substituting default.");
295 #else
296                 _("The document uses an unknown textclass ")
297                 + unknown + _("-- substituting default.");
298 #endif
299         Alert::alert(_("Textclass error"), msg);
300 }
301
302 } // anon
303
304 int Buffer::readHeader(LyXLex & lex)
305 {
306         int unknown_tokens = 0;
307
308         while (lex.isOK()) {
309                 lex.nextToken();
310                 string const token = lex.getString();
311
312                 if (token.empty())
313                         continue;
314
315                 if (token == "\\end_header")
316                         break;
317
318                 lyxerr[Debug::PARSER] << "Handling header token: `"
319                                       << token << '\'' << endl;
320
321                 string unknown = params.readToken(lex, token);
322                 if (!unknown.empty()) {
323                         if (unknown[0] != '\\') {
324                                 unknownClass(unknown);
325                         } else {
326                         ++unknown_tokens;
327                         }
328                 }
329         }
330         return unknown_tokens;
331 }
332
333
334 // candidate for move to BufferView
335 // (at least some parts in the beginning of the func)
336 //
337 // Uwe C. Schroeder
338 // changed to be public and have one parameter
339 // if par = 0 normal behavior
340 // else insert behavior
341 // Returns false if "\the_end" is not read (Asger)
342 bool Buffer::readBody(LyXLex & lex, ParagraphList::iterator pit)
343 {
344         unknown_layouts = 0;
345         int unknown_tokens = 0;
346
347         int pos = 0;
348         Paragraph::depth_type depth = 0;
349         bool the_end_read = false;
350
351         LyXFont font(LyXFont::ALL_INHERIT, params.language);
352
353         if (paragraphs.empty()) {
354                 unknown_tokens += readHeader(lex);
355
356                 if (!params.getLyXTextClass().load()) {
357 #if USE_BOOST_FORMAT
358                         Alert::alert(_("Textclass Loading Error!"),
359                                    boost::io::str(boost::format(_("Can't load textclass %1$s")) %
360                                    params.getLyXTextClass().name()),
361                                    _("-- substituting default."));
362 #else
363                         Alert::alert(_("Textclass Loading Error!"),
364                                      _("Can't load textclass ")
365                                      + params.getLyXTextClass().name(),
366                                      _("-- substituting default."));
367 #endif
368                         params.textclass = 0;
369                 }
370         } else {
371                 // We are inserting into an existing document
372                 users->text->breakParagraph(users, paragraphs);
373                 pos = 0;
374                 markDirty();
375
376                 // We don't want to adopt the parameters from the
377                 // document we insert, so read them into a temporary buffer
378                 // and then discard it
379
380                 Buffer tmpbuf("", false);
381                 tmpbuf.readHeader(lex);
382         }
383
384         while (lex.isOK()) {
385                 lex.nextToken();
386                 string const token = lex.getString();
387
388                 if (token.empty())
389                         continue;
390
391                 lyxerr[Debug::PARSER] << "Handling token: `"
392                                       << token << '\'' << endl;
393
394                 if (token == "\\the_end") {
395                         the_end_read = true;
396                         continue;
397                 }
398
399                 unknown_tokens += readToken(lex, paragraphs, pit, token, pos, depth, font);
400         }
401
402         if (unknown_layouts > 0) {
403                 string s = _("Couldn't set the layout for ");
404                 if (unknown_layouts == 1) {
405                         s += _("one paragraph");
406                 } else {
407                         s += tostr(unknown_layouts);
408                         s += _(" paragraphs");
409                 }
410 #if USE_BOOST_FORMAT
411                 Alert::alert(_("Textclass Loading Error!"), s,
412                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
413 #else
414                 Alert::alert(_("Textclass Loading Error!"), s,
415                              _("When reading ") + fileName());
416 #endif
417         }
418
419         if (unknown_tokens > 0) {
420                 string s = _("Encountered ");
421                 if (unknown_tokens == 1) {
422                         s += _("one unknown token");
423                 } else {
424                         s += tostr(unknown_tokens);
425                         s += _(" unknown tokens");
426                 }
427 #if USE_BOOST_FORMAT
428                 Alert::alert(_("Textclass Loading Error!"), s,
429                            boost::io::str(boost::format(_("When reading %1$s")) % fileName()));
430 #else
431                 Alert::alert(_("Textclass Loading Error!"), s,
432                              _("When reading ") +  fileName());
433 #endif
434         }
435
436         return the_end_read;
437 }
438
439
440 int
441 Buffer::readToken(LyXLex & lex, ParagraphList & pars,
442                   ParagraphList::iterator & pit,
443                   string const & token, int & pos,
444                   Paragraph::depth_type & depth,
445                   LyXFont & font)
446 {
447         static Change current_change;
448         int unknown = 0;
449
450         // The order of the tags tested may seem unnatural, but this
451         // has been done in order to reduce the number of string
452         // comparisons needed to recognize a given token. This leads
453         // on large documents like UserGuide to a reduction of a
454         // factor 5! (JMarc)
455         if (token[0] != '\\') {
456                 for (string::const_iterator cit = token.begin();
457                      cit != token.end(); ++cit) {
458                         pit->insertChar(pos, (*cit), font, current_change);
459                         ++pos;
460                 }
461         } else if (token == "\\layout") {
462                 // reset the font as we start a new layout and if the font is
463                 // not ALL_INHERIT,document_language then it will be set to the
464                 // right values after this tag (Jug 20020420)
465                 font = LyXFont(LyXFont::ALL_INHERIT, params.language);
466
467                 lex.eatLine();
468                 string layoutname = lex.getString();
469
470                 LyXTextClass const & tclass = params.getLyXTextClass();
471
472                 if (layoutname.empty()) {
473                         layoutname = tclass.defaultLayoutName();
474                 }
475                 bool hasLayout = tclass.hasLayout(layoutname);
476                 if (!hasLayout) {
477                         lyxerr << "Layout '" << layoutname << "' does not"
478                                << " exist in textclass '" << tclass.name()
479                                << "'." << endl;
480                         lyxerr << "Trying to use default layout instead."
481                                << endl;
482                         layoutname = tclass.defaultLayoutName();
483                 }
484
485 #ifdef USE_CAPTION
486                 // The is the compability reading of layout caption.
487                 // It can be removed in LyX version 1.3.0. (Lgb)
488                 if (compare_ascii_no_case(layoutname, "caption") == 0) {
489                         // We expect that the par we are now working on is
490                         // really inside a InsetText inside a InsetFloat.
491                         // We also know that captions can only be
492                         // one paragraph. (Lgb)
493
494                         // We should now read until the next "\layout"
495                         // is reached.
496                         // This is probably not good enough, what if the
497                         // caption is the last par in the document (Lgb)
498                         istream & ist = lex.getStream();
499                         stringstream ss;
500                         string line;
501                         int begin = 0;
502                         while (true) {
503                                 getline(ist, line);
504                                 if (prefixIs(line, "\\layout")) {
505                                         lex.pushToken(line);
506                                         break;
507                                 }
508                                 if (prefixIs(line, "\\begin_inset"))
509                                         ++begin;
510                                 if (prefixIs(line, "\\end_inset")) {
511                                         if (begin)
512                                                 --begin;
513                                         else {
514                                                 lex.pushToken(line);
515                                                 break;
516                                         }
517                                 }
518
519                                 ss << line << '\n';
520                         }
521                         // Now we should have the whole layout in ss
522                         // we should now be able to give this to the
523                         // caption inset.
524                         ss << "\\end_inset\n";
525
526                         // This seems like a bug in stringstream.
527                         // We really should be able to use ss
528                         // directly. (Lgb)
529                         istringstream is(ss.str());
530                         LyXLex tmplex(0, 0);
531                         tmplex.setStream(is);
532                         Inset * inset = new InsetCaption;
533                         inset->Read(this, tmplex);
534                         pit->InsertInset(pos, inset, font);
535                         ++pos;
536                 } else {
537 #endif
538                         Paragraph * par = new Paragraph();
539                         par->layout(params.getLyXTextClass().defaultLayout());
540                         if (params.tracking_changes)
541                                 par->trackChanges();
542                         pos = 0;
543                         par->layout(params.getLyXTextClass()[layoutname]);
544                         // Test whether the layout is obsolete.
545                         LyXLayout_ptr const & layout = par->layout();
546                         if (!layout->obsoleted_by().empty())
547                                 par->layout(params.getLyXTextClass()[layout->obsoleted_by()]);
548                         par->params().depth(depth);
549                         // insert after
550                         if (pit != pars.end())
551                                 ++pit;
552                         pit = pars.insert(pit, par);
553 #if USE_CAPTION
554                 }
555 #endif
556
557         } else if (token == "\\end_inset") {
558                 lyxerr << "Solitary \\end_inset in line " << lex.getLineNo() << "\n"
559                        << "Missing \\begin_inset?.\n";
560                 // Simply ignore this. The insets do not have
561                 // to read this.
562                 // But insets should read it, it is a part of
563                 // the inset isn't it? Lgb.
564         } else if (token == "\\begin_inset") {
565                 readInset(lex, pit, pos, font, current_change);
566         } else if (token == "\\family") {
567                 lex.next();
568                 font.setLyXFamily(lex.getString());
569         } else if (token == "\\series") {
570                 lex.next();
571                 font.setLyXSeries(lex.getString());
572         } else if (token == "\\shape") {
573                 lex.next();
574                 font.setLyXShape(lex.getString());
575         } else if (token == "\\size") {
576                 lex.next();
577                 font.setLyXSize(lex.getString());
578         } else if (token == "\\lang") {
579                 lex.next();
580                 string const tok = lex.getString();
581                 Language const * lang = languages.getLanguage(tok);
582                 if (lang) {
583                         font.setLanguage(lang);
584                 } else {
585                         font.setLanguage(params.language);
586                         lex.printError("Unknown language `$$Token'");
587                 }
588         } else if (token == "\\numeric") {
589                 lex.next();
590                 font.setNumber(font.setLyXMisc(lex.getString()));
591         } else if (token == "\\emph") {
592                 lex.next();
593                 font.setEmph(font.setLyXMisc(lex.getString()));
594         } else if (token == "\\bar") {
595                 lex.next();
596                 string const tok = lex.getString();
597                 // This is dirty, but gone with LyX3. (Asger)
598                 if (tok == "under")
599                         font.setUnderbar(LyXFont::ON);
600                 else if (tok == "no")
601                         font.setUnderbar(LyXFont::OFF);
602                 else if (tok == "default")
603                         font.setUnderbar(LyXFont::INHERIT);
604                 else
605                         lex.printError("Unknown bar font flag "
606                                        "`$$Token'");
607         } else if (token == "\\noun") {
608                 lex.next();
609                 font.setNoun(font.setLyXMisc(lex.getString()));
610         } else if (token == "\\color") {
611                 lex.next();
612                 font.setLyXColor(lex.getString());
613         } else if (token == "\\SpecialChar") {
614                 LyXLayout_ptr const & layout = pit->layout();
615
616                 // Insets don't make sense in a free-spacing context! ---Kayvan
617                 if (layout->free_spacing || pit->isFreeSpacing()) {
618                         if (lex.isOK()) {
619                                 lex.next();
620                                 string const next_token = lex.getString();
621                                 if (next_token == "\\-") {
622                                         pit->insertChar(pos, '-', font, current_change);
623                                 } else if (next_token == "~") {
624                                         pit->insertChar(pos, ' ', font, current_change);
625                                 } else {
626                                         lex.printError("Token `$$Token' "
627                                                        "is in free space "
628                                                        "paragraph layout!");
629                                         --pos;
630                                 }
631                         }
632                 } else {
633                         Inset * inset = new InsetSpecialChar;
634                         inset->read(this, lex);
635                         pit->insertInset(pos, inset, font, current_change);
636                 }
637                 ++pos;
638         } else if (token == "\\i") {
639                 Inset * inset = new InsetLatexAccent;
640                 inset->read(this, lex);
641                 pit->insertInset(pos, inset, font, current_change);
642                 ++pos;
643         } else if (token == "\\backslash") {
644                 pit->insertChar(pos, '\\', font, current_change);
645                 ++pos;
646         } else if (token == "\\begin_deeper") {
647                 ++depth;
648         } else if (token == "\\end_deeper") {
649                 if (!depth) {
650                         lex.printError("\\end_deeper: "
651                                        "depth is already null");
652                 }
653                 else
654                         --depth;
655         } else if (token == "\\noindent") {
656                 pit->params().noindent(true);
657         } else if (token == "\\leftindent") {
658                 lex.nextToken();
659                 LyXLength value(lex.getString());
660                 pit->params().leftIndent(value);
661         } else if (token == "\\fill_top") {
662                 pit->params().spaceTop(VSpace(VSpace::VFILL));
663         } else if (token == "\\fill_bottom") {
664                 pit->params().spaceBottom(VSpace(VSpace::VFILL));
665         } else if (token == "\\line_top") {
666                 pit->params().lineTop(true);
667         } else if (token == "\\line_bottom") {
668                 pit->params().lineBottom(true);
669         } else if (token == "\\pagebreak_top") {
670                 pit->params().pagebreakTop(true);
671         } else if (token == "\\pagebreak_bottom") {
672                 pit->params().pagebreakBottom(true);
673         } else if (token == "\\start_of_appendix") {
674                 pit->params().startOfAppendix(true);
675         } else if (token == "\\paragraph_spacing") {
676                 lex.next();
677                 string const tmp = rtrim(lex.getString());
678                 if (tmp == "single") {
679                         pit->params().spacing(Spacing(Spacing::Single));
680                 } else if (tmp == "onehalf") {
681                         pit->params().spacing(Spacing(Spacing::Onehalf));
682                 } else if (tmp == "double") {
683                         pit->params().spacing(Spacing(Spacing::Double));
684                 } else if (tmp == "other") {
685                         lex.next();
686                         pit->params().spacing(Spacing(Spacing::Other,
687                                          lex.getFloat()));
688                 } else {
689                         lex.printError("Unknown spacing token: '$$Token'");
690                 }
691         } else if (token == "\\align") {
692                 int tmpret = lex.findToken(string_align);
693                 if (tmpret == -1)
694                         ++tmpret;
695                 int const tmpret2 = int(pow(2.0, tmpret));
696                 pit->params().align(LyXAlignment(tmpret2));
697         } else if (token == "\\added_space_top") {
698                 lex.nextToken();
699                 VSpace value = VSpace(lex.getString());
700                 // only add the length when value > 0 or
701                 // with option keep
702                 if ((value.length().len().value() != 0) ||
703                     value.keep() ||
704                     (value.kind() != VSpace::LENGTH))
705                         pit->params().spaceTop(value);
706         } else if (token == "\\added_space_bottom") {
707                 lex.nextToken();
708                 VSpace value = VSpace(lex.getString());
709                 // only add the length when value > 0 or
710                 // with option keep
711                 if ((value.length().len().value() != 0) ||
712                    value.keep() ||
713                     (value.kind() != VSpace::LENGTH))
714                         pit->params().spaceBottom(value);
715         } else if (token == "\\labelwidthstring") {
716                 lex.eatLine();
717                 pit->params().labelWidthString(lex.getString());
718                 // do not delete this token, it is still needed!
719         } else if (token == "\\newline") {
720                 pit->insertChar(pos, Paragraph::META_NEWLINE, font, current_change);
721                 ++pos;
722         } else if (token == "\\LyXTable") {
723                 Inset * inset = new InsetTabular(*this);
724                 inset->read(this, lex);
725                 pit->insertInset(pos, inset, font, current_change);
726                 ++pos;
727         } else if (token == "\\bibitem") {  // ale970302
728                 InsetCommandParams p("bibitem", "dummy");
729                 InsetBibitem * inset = new InsetBibitem(p);
730                 inset->read(this, lex);
731                 pit->insertInset(pos, inset, font, current_change);
732                 ++pos;
733         } else if (token == "\\hfill") {
734                 pit->insertInset(pos, new InsetHFill(),
735                         LyXFont(LyXFont::ALL_INHERIT, params.language));
736                 ++pos;
737         } else if (token == "\\change_unchanged") {
738                 // Hack ! Needed for empty paragraphs :/
739                 if (!pos)
740                         pit->cleanChanges();
741                 current_change = Change(Change::UNCHANGED);
742         } else if (token == "\\change_inserted") {
743                 lex.nextToken();
744                 istringstream istr(lex.getString());
745                 int aid;
746                 lyx::time_type ct;
747                 istr >> aid;
748                 istr >> ct;
749                 current_change = Change(Change::INSERTED, params.author_ids[aid], ct);
750         } else if (token == "\\change_deleted") {
751                 lex.nextToken();
752                 istringstream istr(lex.getString());
753                 int aid;
754                 lyx::time_type ct;
755                 istr >> aid;
756                 istr >> ct;
757                 current_change = Change(Change::DELETED, params.author_ids[aid], ct);
758         } else {
759                 // This should be insurance for the future: (Asger)
760                 ++unknown;
761                 lex.eatLine();
762 #if USE_BOOST_FORMAT
763                 boost::format fmt(_("Unknown token: %1$s %2$s\n"));
764                 fmt % token % lex.text();
765                 string const s = fmt.str();
766 #else
767                 string const s = _("Unknown token: ") + token
768                         + ' ' + lex.text() + '\n';
769 #endif
770                 // we can do this here this way because we're actually reading
771                 // the buffer and don't care about LyXText right now.
772                 InsetError * new_inset = new InsetError(s);
773                 pit->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
774                                  params.language));
775
776         }
777
778         return unknown;
779 }
780
781
782 // needed to insert the selection
783 void Buffer::insertStringAsLines(Paragraph *& par, pos_type & pos,
784                                  LyXFont const & fn,string const & str)
785 {
786         LyXLayout_ptr const & layout = par->layout();
787
788         LyXFont font = fn;
789
790         par->checkInsertChar(font);
791         // insert the string, don't insert doublespace
792         bool space_inserted = true;
793         bool autobreakrows = !par->inInset() ||
794                 static_cast<InsetText *>(par->inInset())->getAutoBreakRows();
795         for(string::const_iterator cit = str.begin();
796             cit != str.end(); ++cit) {
797                 if (*cit == '\n') {
798                         if (autobreakrows && (!par->empty() || layout->keepempty)) {
799                                 breakParagraph(params, paragraphs, par, pos,
800                                                layout->isEnvironment());
801                                 par = par->next();
802                                 pos = 0;
803                                 space_inserted = true;
804                         } else {
805                                 continue;
806                         }
807                         // do not insert consecutive spaces if !free_spacing
808                 } else if ((*cit == ' ' || *cit == '\t') &&
809                            space_inserted && !layout->free_spacing &&
810                                    !par->isFreeSpacing())
811                 {
812                         continue;
813                 } else if (*cit == '\t') {
814                         if (!layout->free_spacing && !par->isFreeSpacing()) {
815                                 // tabs are like spaces here
816                                 par->insertChar(pos, ' ', font);
817                                 ++pos;
818                                 space_inserted = true;
819                         } else {
820                                 const pos_type nb = 8 - pos % 8;
821                                 for (pos_type a = 0; a < nb ; ++a) {
822                                         par->insertChar(pos, ' ', font);
823                                         ++pos;
824                                 }
825                                 space_inserted = true;
826                         }
827                 } else if (!IsPrintable(*cit)) {
828                         // Ignore unprintables
829                         continue;
830                 } else {
831                         // just insert the character
832                         par->insertChar(pos, *cit, font);
833                         ++pos;
834                         space_inserted = (*cit == ' ');
835                 }
836
837         }
838 }
839
840
841 void Buffer::readInset(LyXLex & lex, ParagraphList::iterator pit,
842                        int & pos, LyXFont & font, Change current_change)
843 {
844         // consistency check
845         if (lex.getString() != "\\begin_inset") {
846                 lyxerr << "Buffer::readInset: Consistency check failed."
847                        << endl;
848         }
849
850         Inset * inset = 0;
851
852         lex.next();
853         string const tmptok = lex.getString();
854
855         // test the different insets
856         if (tmptok == "LatexCommand") {
857                 InsetCommandParams inscmd;
858                 inscmd.read(lex);
859
860                 string const cmdName = inscmd.getCmdName();
861
862                 // This strange command allows LyX to recognize "natbib" style
863                 // citations: citet, citep, Citet etc.
864                 if (compare_ascii_no_case(cmdName.substr(0,4), "cite") == 0) {
865                         inset = new InsetCitation(inscmd);
866                 } else if (cmdName == "bibitem") {
867                         lex.printError("Wrong place for bibitem");
868                         inset = new InsetBibitem(inscmd);
869                 } else if (cmdName == "BibTeX") {
870                         inset = new InsetBibtex(inscmd);
871                 } else if (cmdName == "index") {
872                         inset = new InsetIndex(inscmd);
873                 } else if (cmdName == "include") {
874                         inset = new InsetInclude(inscmd, *this);
875                 } else if (cmdName == "label") {
876                         inset = new InsetLabel(inscmd);
877                 } else if (cmdName == "url"
878                            || cmdName == "htmlurl") {
879                         inset = new InsetUrl(inscmd);
880                 } else if (cmdName == "ref"
881                            || cmdName == "pageref"
882                            || cmdName == "vref"
883                            || cmdName == "vpageref"
884                            || cmdName == "prettyref") {
885                         if (!inscmd.getOptions().empty()
886                             || !inscmd.getContents().empty()) {
887                                 inset = new InsetRef(inscmd, *this);
888                         }
889                 } else if (cmdName == "tableofcontents") {
890                         inset = new InsetTOC(inscmd);
891                 } else if (cmdName == "listofalgorithms") {
892                         inset = new InsetFloatList("algorithm");
893                 } else if (cmdName == "listoffigures") {
894                         inset = new InsetFloatList("figure");
895                 } else if (cmdName == "listoftables") {
896                         inset = new InsetFloatList("table");
897                 } else if (cmdName == "printindex") {
898                         inset = new InsetPrintIndex(inscmd);
899                 } else if (cmdName == "lyxparent") {
900                         inset = new InsetParent(inscmd, *this);
901                 }
902         } else {
903                 if (tmptok == "Quotes") {
904                         inset = new InsetQuotes;
905                 } else if (tmptok == "External") {
906                         inset = new InsetExternal;
907                 } else if (tmptok == "FormulaMacro") {
908                         inset = new InsetFormulaMacro;
909                 } else if (tmptok == "Formula") {
910                         inset = new InsetFormula;
911                 } else if (tmptok == "Graphics") {
912                         inset = new InsetGraphics;
913                 } else if (tmptok == "Note") {
914                         inset = new InsetNote(params);
915                 } else if (tmptok == "Include") {
916                         InsetCommandParams p("Include");
917                         inset = new InsetInclude(p, *this);
918                 } else if (tmptok == "ERT") {
919                         inset = new InsetERT(params);
920                 } else if (tmptok == "Tabular") {
921                         inset = new InsetTabular(*this);
922                 } else if (tmptok == "Text") {
923                         inset = new InsetText(params);
924                 } else if (tmptok == "Foot") {
925                         inset = new InsetFoot(params);
926                 } else if (tmptok == "Marginal") {
927                         inset = new InsetMarginal(params);
928                 } else if (tmptok == "OptArg") {
929                         inset = new InsetOptArg(params);
930                 } else if (tmptok == "Minipage") {
931                         inset = new InsetMinipage(params);
932                 } else if (tmptok == "Float") {
933                         lex.next();
934                         string tmptok = lex.getString();
935                         inset = new InsetFloat(params, tmptok);
936                 } else if (tmptok == "Wrap") {
937                         lex.next();
938                         string tmptok = lex.getString();
939                         inset = new InsetWrap(params, tmptok);
940 #if 0
941                 } else if (tmptok == "List") {
942                         inset = new InsetList;
943                 } else if (tmptok == "Theorem") {
944                         inset = new InsetList;
945 #endif
946                 } else if (tmptok == "Caption") {
947                         inset = new InsetCaption(params);
948                 } else if (tmptok == "FloatList") {
949                         inset = new InsetFloatList;
950                 }
951
952                 if (inset)
953                         inset->read(this, lex);
954         }
955
956         if (inset) {
957                 pit->insertInset(pos, inset, font, current_change);
958                 ++pos;
959         }
960 }
961
962
963 bool Buffer::readFile(LyXLex & lex, string const & filename)
964 {
965         return readFile(lex, filename, paragraphs.begin());
966 }
967
968
969 bool Buffer::readFile(LyXLex & lex, string const & filename, ParagraphList::iterator pit)
970 {
971         if (lex.isOK()) {
972                 lex.next();
973                 string const token(lex.getString());
974                 if (token == "\\lyxformat") { // the first token _must_ be...
975                         lex.eatLine();
976                         string tmp_format = lex.getString();
977                         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
978                         // if present remove ".," from string.
979                         string::size_type dot = tmp_format.find_first_of(".,");
980                         //lyxerr << "           dot found at " << dot << endl;
981                         if (dot != string::npos)
982                                 tmp_format.erase(dot, 1);
983                         file_format = strToInt(tmp_format);
984                         //lyxerr << "format: " << file_format << endl;
985                         if (file_format == LYX_FORMAT) {
986                                 // current format
987                         } else if (file_format > LYX_FORMAT) {
988                                 // future format
989                                 Alert::alert(_("Warning!"),
990                                         _("The file was created with a newer version of "
991                                         "LyX. This is likely to cause problems."));
992
993                         } else if (file_format < LYX_FORMAT) {
994                                 // old formats
995                                 if (file_format < 200) {
996                                         Alert::alert(_("ERROR!"),
997                                                    _("Old LyX file format found. "
998                                                      "Use LyX 0.10.x to read this!"));
999                                         return false;
1000                                 } else if (!filename.empty()) {
1001                                         string command =
1002                                                 LibFileSearch("lyx2lyx", "lyx2lyx");
1003                                         if (command.empty()) {
1004                                                 Alert::alert(_("ERROR!"),
1005                                                              _("Can't find conversion script."));
1006                                                 return false;
1007                                         }
1008                                         command += " -t"
1009                                                 +tostr(LYX_FORMAT) + ' '
1010                                                 + QuoteName(filename);
1011                                         lyxerr[Debug::INFO] << "Running '"
1012                                                             << command << '\''
1013                                                             << endl;
1014                                         cmd_ret const ret = RunCommand(command);
1015                                         if (ret.first) {
1016                                                 Alert::alert(_("ERROR!"),
1017                                                              _("An error occured while "
1018                                                                "running the conversion script."));
1019                                                 return false;
1020                                         }
1021                                         istringstream is(STRCONV(ret.second));
1022                                         LyXLex tmplex(0, 0);
1023                                         tmplex.setStream(is);
1024                                         return readFile(tmplex, string(), pit);
1025                                 } else {
1026                                         // This code is reached if lyx2lyx failed (for
1027                                         // some reason) to change the file format of
1028                                         // the file.
1029                                         lyx::Assert(false);
1030                                         return false;
1031                                 }
1032                         }
1033                         bool the_end = readBody(lex, pit);
1034                         params.setPaperStuff();
1035
1036                         if (!the_end) {
1037                                 Alert::alert(_("Warning!"),
1038                                            _("Reading of document is not complete"),
1039                                            _("Maybe the document is truncated"));
1040                         }
1041                         return true;
1042                 } else { // "\\lyxformat" not found
1043                         Alert::alert(_("ERROR!"), _("Not a LyX file!"));
1044                 }
1045         } else
1046                 Alert::alert(_("ERROR!"), _("Unable to read file!"));
1047         return false;
1048 }
1049
1050
1051 // Should probably be moved to somewhere else: BufferView? LyXView?
1052 bool Buffer::save() const
1053 {
1054         // We don't need autosaves in the immediate future. (Asger)
1055         resetAutosaveTimers();
1056
1057         // make a backup
1058         string s;
1059         if (lyxrc.make_backup) {
1060                 s = fileName() + '~';
1061                 if (!lyxrc.backupdir_path.empty())
1062                         s = AddName(lyxrc.backupdir_path,
1063                                     subst(os::slashify_path(s),'/','!'));
1064
1065                 // Rename is the wrong way of making a backup,
1066                 // this is the correct way.
1067                 /* truss cp fil fil2:
1068                    lstat("LyXVC3.lyx", 0xEFFFF898)                 Err#2 ENOENT
1069                    stat("LyXVC.lyx", 0xEFFFF688)                   = 0
1070                    open("LyXVC.lyx", O_RDONLY)                     = 3
1071                    open("LyXVC3.lyx", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 4
1072                    fstat(4, 0xEFFFF508)                            = 0
1073                    fstat(3, 0xEFFFF508)                            = 0
1074                    read(3, " # T h i s   f i l e   w".., 8192)     = 5579
1075                    write(4, " # T h i s   f i l e   w".., 5579)    = 5579
1076                    read(3, 0xEFFFD4A0, 8192)                       = 0
1077                    close(4)                                        = 0
1078                    close(3)                                        = 0
1079                    chmod("LyXVC3.lyx", 0100644)                    = 0
1080                    lseek(0, 0, SEEK_CUR)                           = 46440
1081                    _exit(0)
1082                 */
1083
1084                 // Should probably have some more error checking here.
1085                 // Doing it this way, also makes the inodes stay the same.
1086                 // This is still not a very good solution, in particular we
1087                 // might loose the owner of the backup.
1088                 FileInfo finfo(fileName());
1089                 if (finfo.exist()) {
1090                         mode_t fmode = finfo.getMode();
1091                         struct utimbuf times = {
1092                                 finfo.getAccessTime(),
1093                                 finfo.getModificationTime() };
1094
1095                         ifstream ifs(fileName().c_str());
1096                         ofstream ofs(s.c_str(), ios::out|ios::trunc);
1097                         if (ifs && ofs) {
1098                                 ofs << ifs.rdbuf();
1099                                 ifs.close();
1100                                 ofs.close();
1101                                 ::chmod(s.c_str(), fmode);
1102
1103                                 if (::utime(s.c_str(), &times)) {
1104                                         lyxerr << "utime error." << endl;
1105                                 }
1106                         } else {
1107                                 lyxerr << "LyX was not able to make "
1108                                         "backup copy. Beware." << endl;
1109                         }
1110                 }
1111         }
1112
1113         if (writeFile(fileName())) {
1114                 markClean();
1115                 removeAutosaveFile(fileName());
1116         } else {
1117                 // Saving failed, so backup is not backup
1118                 if (lyxrc.make_backup) {
1119                         lyx::rename(s, fileName());
1120                 }
1121                 return false;
1122         }
1123         return true;
1124 }
1125
1126
1127 bool Buffer::writeFile(string const & fname) const
1128 {
1129         if (read_only && (fname == fileName())) {
1130                 return false;
1131         }
1132
1133         FileInfo finfo(fname);
1134         if (finfo.exist() && !finfo.writable()) {
1135                 return false;
1136         }
1137
1138         ofstream ofs(fname.c_str());
1139         if (!ofs) {
1140                 return false;
1141         }
1142
1143 #ifdef HAVE_LOCALE
1144         // Use the standard "C" locale for file output.
1145         ofs.imbue(std::locale::classic());
1146 #endif
1147
1148         // The top of the file should not be written by params.
1149
1150         // write out a comment in the top of the file
1151         ofs << '#' << lyx_docversion
1152             << " created this file. For more info see http://www.lyx.org/\n"
1153             << "\\lyxformat " << LYX_FORMAT << "\n";
1154
1155         // now write out the buffer paramters.
1156         params.writeFile(ofs);
1157
1158         ofs << "\\end_header\n";
1159
1160         Paragraph::depth_type depth = 0;
1161
1162         // this will write out all the paragraphs
1163         // using recursive descent.
1164         ParagraphList::iterator pit = paragraphs.begin();
1165         ParagraphList::iterator pend = paragraphs.end();
1166         for (; pit != pend; ++pit)
1167                 pit->write(this, ofs, params, depth);
1168
1169         // Write marker that shows file is complete
1170         ofs << "\n\\the_end" << endl;
1171
1172         ofs.close();
1173
1174         // how to check if close went ok?
1175         // Following is an attempt... (BE 20001011)
1176
1177         // good() returns false if any error occured, including some
1178         //        formatting error.
1179         // bad()  returns true if something bad happened in the buffer,
1180         //        which should include file system full errors.
1181
1182         bool status = true;
1183         if (!ofs.good()) {
1184                 status = false;
1185 #if 0
1186                 if (ofs.bad()) {
1187                         lyxerr << "Buffer::writeFile: BAD ERROR!" << endl;
1188                 } else {
1189                         lyxerr << "Buffer::writeFile: NOT SO BAD ERROR!"
1190                                << endl;
1191                 }
1192 #endif
1193         }
1194
1195         return status;
1196 }
1197
1198
1199 namespace {
1200
1201 pair<int, string> const addDepth(int depth, int ldepth)
1202 {
1203         int d = depth * 2;
1204         if (ldepth > depth)
1205                 d += (ldepth - depth) * 2;
1206         return make_pair(d, string(d, ' '));
1207 }
1208
1209 }
1210
1211
1212 string const Buffer::asciiParagraph(Paragraph const & par,
1213                                     unsigned int linelen,
1214                                     bool noparbreak) const
1215 {
1216         ostringstream buffer;
1217         Paragraph::depth_type depth = 0;
1218         int ltype = 0;
1219         Paragraph::depth_type ltype_depth = 0;
1220         bool ref_printed = false;
1221 //      if (!par->previous()) {
1222 #if 0
1223         // begins or ends a deeper area ?
1224         if (depth != par->params().depth()) {
1225                 if (par->params().depth() > depth) {
1226                         while (par->params().depth() > depth) {
1227                                 ++depth;
1228                         }
1229                 } else {
1230                         while (par->params().depth() < depth) {
1231                                 --depth;
1232                         }
1233                 }
1234         }
1235 #else
1236         depth = par.params().depth();
1237 #endif
1238
1239         // First write the layout
1240         string const & tmp = par.layout()->name();
1241         if (compare_no_case(tmp, "itemize") == 0) {
1242                 ltype = 1;
1243                 ltype_depth = depth + 1;
1244         } else if (compare_ascii_no_case(tmp, "enumerate") == 0) {
1245                 ltype = 2;
1246                 ltype_depth = depth + 1;
1247         } else if (contains(ascii_lowercase(tmp), "ection")) {
1248                 ltype = 3;
1249                 ltype_depth = depth + 1;
1250         } else if (contains(ascii_lowercase(tmp), "aragraph")) {
1251                 ltype = 4;
1252                 ltype_depth = depth + 1;
1253         } else if (compare_ascii_no_case(tmp, "description") == 0) {
1254                 ltype = 5;
1255                 ltype_depth = depth + 1;
1256         } else if (compare_ascii_no_case(tmp, "abstract") == 0) {
1257                 ltype = 6;
1258                 ltype_depth = 0;
1259         } else if (compare_ascii_no_case(tmp, "bibliography") == 0) {
1260                 ltype = 7;
1261                 ltype_depth = 0;
1262         } else {
1263                 ltype = 0;
1264                 ltype_depth = 0;
1265         }
1266
1267         /* maybe some vertical spaces */
1268
1269         /* the labelwidthstring used in lists */
1270
1271         /* some lines? */
1272
1273         /* some pagebreaks? */
1274
1275         /* noindent ? */
1276
1277         /* what about the alignment */
1278 //      } else {
1279 //              lyxerr << "Should this ever happen?" << endl;
1280 //      }
1281
1282         // linelen <= 0 is special and means we don't have paragraph breaks
1283
1284         string::size_type currlinelen = 0;
1285
1286         if (!noparbreak) {
1287                 if (linelen > 0)
1288                         buffer << "\n\n";
1289
1290                 buffer << string(depth * 2, ' ');
1291                 currlinelen += depth * 2;
1292
1293                 //--
1294                 // we should probably change to the paragraph language in the
1295                 // gettext here (if possible) so that strings are outputted in
1296                 // the correct language! (20012712 Jug)
1297                 //--
1298                 switch (ltype) {
1299                 case 0: // Standard
1300                 case 4: // (Sub)Paragraph
1301                 case 5: // Description
1302                         break;
1303                 case 6: // Abstract
1304                         if (linelen > 0) {
1305                                 buffer << _("Abstract") << "\n\n";
1306                                 currlinelen = 0;
1307                         } else {
1308                                 string const abst = _("Abstract: ");
1309                                 buffer << abst;
1310                                 currlinelen += abst.length();
1311                         }
1312                         break;
1313                 case 7: // Bibliography
1314                         if (!ref_printed) {
1315                                 if (linelen > 0) {
1316                                         buffer << _("References") << "\n\n";
1317                                         currlinelen = 0;
1318                                 } else {
1319                                         string const refs = _("References: ");
1320                                         buffer << refs;
1321                                         currlinelen += refs.length();
1322                                 }
1323
1324                                 ref_printed = true;
1325                         }
1326                         break;
1327                 default:
1328                 {
1329                         string const parlab = par.params().labelString();
1330                         buffer << parlab << ' ';
1331                         currlinelen += parlab.length() + 1;
1332                 }
1333                 break;
1334
1335                 }
1336         }
1337
1338         if (!currlinelen) {
1339                 pair<int, string> p = addDepth(depth, ltype_depth);
1340                 buffer << p.second;
1341                 currlinelen += p.first;
1342         }
1343
1344         // this is to change the linebreak to do it by word a bit more
1345         // intelligent hopefully! (only in the case where we have a
1346         // max linelength!) (Jug)
1347
1348         string word;
1349
1350         for (pos_type i = 0; i < par.size(); ++i) {
1351                 char c = par.getUChar(params, i);
1352                 switch (c) {
1353                 case Paragraph::META_INSET:
1354                 {
1355                         Inset const * inset = par.getInset(i);
1356                         if (inset) {
1357                                 if (linelen > 0) {
1358                                         buffer << word;
1359                                         currlinelen += word.length();
1360                                         word.erase();
1361                                 }
1362                                 if (inset->ascii(this, buffer, linelen)) {
1363                                         // to be sure it breaks paragraph
1364                                         currlinelen += linelen;
1365                                 }
1366                         }
1367                 }
1368                 break;
1369
1370                 case Paragraph::META_NEWLINE:
1371                         if (linelen > 0) {
1372                                 buffer << word << "\n";
1373                                 word.erase();
1374
1375                                 pair<int, string> p = addDepth(depth,
1376                                                                ltype_depth);
1377                                 buffer << p.second;
1378                                 currlinelen = p.first;
1379                         }
1380                         break;
1381
1382                 default:
1383                         if (c == ' ') {
1384                                 if (linelen > 0 &&
1385                                     currlinelen + word.length() > linelen - 10) {
1386                                         buffer << "\n";
1387                                         pair<int, string> p = addDepth(depth, ltype_depth);
1388                                         buffer << p.second;
1389                                         currlinelen = p.first;
1390                                 }
1391
1392                                 buffer << word << ' ';
1393                                 currlinelen += word.length() + 1;
1394                                 word.erase();
1395
1396                         } else {
1397                                 if (c != '\0') {
1398                                         word += c;
1399                                 } else {
1400                                         lyxerr[Debug::INFO] <<
1401                                                 "writeAsciiFile: NULL char in structure." << endl;
1402                                 }
1403                                 if ((linelen > 0) &&
1404                                         (currlinelen + word.length()) > linelen)
1405                                 {
1406                                         buffer << "\n";
1407
1408                                         pair<int, string> p =
1409                                                 addDepth(depth, ltype_depth);
1410                                         buffer << p.second;
1411                                         currlinelen = p.first;
1412                                 }
1413                         }
1414                         break;
1415                 }
1416         }
1417         buffer << word;
1418         return STRCONV(buffer.str());
1419 }
1420
1421
1422 void Buffer::writeFileAscii(string const & fname, int linelen)
1423 {
1424         ofstream ofs(fname.c_str());
1425         if (!ofs) {
1426                 Alert::err_alert(_("Error: Cannot write file:"), fname);
1427                 return;
1428         }
1429         writeFileAscii(ofs, linelen);
1430 }
1431
1432
1433 void Buffer::writeFileAscii(ostream & os, int linelen)
1434 {
1435         ParagraphList::iterator beg = paragraphs.begin();
1436         ParagraphList::iterator end = paragraphs.end();
1437         ParagraphList::iterator it = beg;
1438         for (; it != end; ++it) {
1439                 os << asciiParagraph(*it, linelen, it == beg);
1440         }
1441         os << "\n";
1442 }
1443
1444
1445
1446 void Buffer::makeLaTeXFile(string const & fname,
1447                            string const & original_path,
1448                            bool nice, bool only_body, bool only_preamble)
1449 {
1450         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
1451
1452         ofstream ofs(fname.c_str());
1453         if (!ofs) {
1454                 Alert::err_alert(_("Error: Cannot open file: "), fname);
1455                 return;
1456         }
1457
1458         makeLaTeXFile(ofs, original_path, nice, only_body, only_preamble);
1459
1460         ofs.close();
1461         if (ofs.fail()) {
1462                 lyxerr << "File was not closed properly." << endl;
1463         }
1464 }
1465
1466
1467 void Buffer::makeLaTeXFile(ostream & os,
1468                            string const & original_path,
1469                            bool nice, bool only_body, bool only_preamble)
1470 {
1471         niceFile = nice; // this will be used by Insetincludes.
1472
1473         // validate the buffer.
1474         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
1475         LaTeXFeatures features(params);
1476         validate(features);
1477         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
1478
1479         texrow.reset();
1480         // The starting paragraph of the coming rows is the
1481         // first paragraph of the document. (Asger)
1482         texrow.start(&*(paragraphs.begin()), 0);
1483
1484         if (!only_body && nice) {
1485                 os << "%% " << lyx_docversion << " created this file.  "
1486                         "For more info, see http://www.lyx.org/.\n"
1487                         "%% Do not edit unless you really know what "
1488                         "you are doing.\n";
1489                 texrow.newline();
1490                 texrow.newline();
1491         }
1492         lyxerr[Debug::INFO] << "lyx header finished" << endl;
1493         // There are a few differences between nice LaTeX and usual files:
1494         // usual is \batchmode and has a
1495         // special input@path to allow the including of figures
1496         // with either \input or \includegraphics (what figinsets do).
1497         // input@path is set when the actual parameter
1498         // original_path is set. This is done for usual tex-file, but not
1499         // for nice-latex-file. (Matthias 250696)
1500         if (!only_body) {
1501                 if (!nice) {
1502                         // code for usual, NOT nice-latex-file
1503                         os << "\\batchmode\n"; // changed
1504                         // from \nonstopmode
1505                         texrow.newline();
1506                 }
1507                 if (!original_path.empty()) {
1508                         string inputpath = os::external_path(original_path);
1509                         subst(inputpath, "~", "\\string~");
1510                         os << "\\makeatletter\n"
1511                             << "\\def\\input@path{{"
1512                             << inputpath << "/}}\n"
1513                             << "\\makeatother\n";
1514                         texrow.newline();
1515                         texrow.newline();
1516                         texrow.newline();
1517                 }
1518
1519                 // Write the preamble
1520                 params.writeLaTeX(os, features, texrow);
1521
1522                 if (only_preamble)
1523                         return;
1524
1525                 // make the body.
1526                 os << "\\begin{document}\n";
1527                 texrow.newline();
1528         } // only_body
1529         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
1530
1531         if (!lyxrc.language_auto_begin) {
1532                 os << subst(lyxrc.language_command_begin, "$$lang",
1533                              params.language->babel())
1534                     << endl;
1535                 texrow.newline();
1536         }
1537
1538         latexParagraphs(this, paragraphs, paragraphs.begin(), paragraphs.end(), os, texrow);
1539
1540         // add this just in case after all the paragraphs
1541         os << endl;
1542         texrow.newline();
1543
1544         if (!lyxrc.language_auto_end) {
1545                 os << subst(lyxrc.language_command_end, "$$lang",
1546                              params.language->babel())
1547                     << endl;
1548                 texrow.newline();
1549         }
1550
1551         if (!only_body) {
1552                 os << "\\end{document}\n";
1553                 texrow.newline();
1554
1555                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1556         } else {
1557                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1558                                      << endl;
1559         }
1560
1561         // Just to be sure. (Asger)
1562         texrow.newline();
1563
1564         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1565         lyxerr[Debug::INFO] << "Row count was " << texrow.rows() - 1
1566                             << '.' << endl;
1567
1568         // we want this to be true outside previews (for insetexternal)
1569         niceFile = true;
1570 }
1571
1572
1573 bool Buffer::isLatex() const
1574 {
1575         return params.getLyXTextClass().outputType() == LATEX;
1576 }
1577
1578
1579 bool Buffer::isLinuxDoc() const
1580 {
1581         return params.getLyXTextClass().outputType() == LINUXDOC;
1582 }
1583
1584
1585 bool Buffer::isLiterate() const
1586 {
1587         return params.getLyXTextClass().outputType() == LITERATE;
1588 }
1589
1590
1591 bool Buffer::isDocBook() const
1592 {
1593         return params.getLyXTextClass().outputType() == DOCBOOK;
1594 }
1595
1596
1597 bool Buffer::isSGML() const
1598 {
1599         LyXTextClass const & tclass = params.getLyXTextClass();
1600
1601         return tclass.outputType() == LINUXDOC ||
1602                tclass.outputType() == DOCBOOK;
1603 }
1604
1605
1606 void Buffer::makeLinuxDocFile(string const & fname, bool nice, bool body_only)
1607 {
1608         ofstream ofs(fname.c_str());
1609
1610         if (!ofs) {
1611                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
1612                 return;
1613         }
1614
1615         niceFile = nice; // this will be used by included files.
1616
1617         LaTeXFeatures features(params);
1618
1619         validate(features);
1620
1621         texrow.reset();
1622
1623         LyXTextClass const & tclass = params.getLyXTextClass();
1624
1625         string top_element = tclass.latexname();
1626
1627         if (!body_only) {
1628                 ofs << "<!doctype linuxdoc system";
1629
1630                 string preamble = params.preamble;
1631                 const string name = nice ? ChangeExtension(filename_, ".sgml")
1632                          : fname;
1633                 preamble += features.getIncludedFiles(name);
1634                 preamble += features.getLyXSGMLEntities();
1635
1636                 if (!preamble.empty()) {
1637                         ofs << " [ " << preamble << " ]";
1638                 }
1639                 ofs << ">\n\n";
1640
1641                 if (params.options.empty())
1642                         sgml::openTag(ofs, 0, false, top_element);
1643                 else {
1644                         string top = top_element;
1645                         top += ' ';
1646                         top += params.options;
1647                         sgml::openTag(ofs, 0, false, top);
1648                 }
1649         }
1650
1651         ofs << "<!-- "  << lyx_docversion
1652             << " created this file. For more info see http://www.lyx.org/"
1653             << " -->\n";
1654
1655         Paragraph::depth_type depth = 0; // paragraph depth
1656         Paragraph * par = &*(paragraphs.begin());
1657         string item_name;
1658         vector<string> environment_stack(5);
1659
1660         while (par) {
1661                 LyXLayout_ptr const & style = par->layout();
1662                 // treat <toc> as a special case for compatibility with old code
1663                 if (par->isInset(0)) {
1664                         Inset * inset = par->getInset(0);
1665                         Inset::Code lyx_code = inset->lyxCode();
1666                         if (lyx_code == Inset::TOC_CODE) {
1667                                 string const temp = "toc";
1668                                 sgml::openTag(ofs, depth, false, temp);
1669
1670                                 par = par->next();
1671                                 continue;
1672                         }
1673                 }
1674
1675                 // environment tag closing
1676                 for (; depth > par->params().depth(); --depth) {
1677                         sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1678                         environment_stack[depth].erase();
1679                 }
1680
1681                 // write opening SGML tags
1682                 switch (style->latextype) {
1683                 case LATEX_PARAGRAPH:
1684                         if (depth == par->params().depth()
1685                            && !environment_stack[depth].empty()) {
1686                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1687                                 environment_stack[depth].erase();
1688                                 if (depth)
1689                                         --depth;
1690                                 else
1691                                         ofs << "</p>";
1692                         }
1693                         sgml::openTag(ofs, depth, false, style->latexname());
1694                         break;
1695
1696                 case LATEX_COMMAND:
1697                         if (depth!= 0)
1698                                 sgmlError(par, 0,
1699                                           _("Error: Wrong depth for LatexType Command.\n"));
1700
1701                         if (!environment_stack[depth].empty()) {
1702                                 sgml::closeTag(ofs, depth, false, environment_stack[depth]);
1703                                 ofs << "</p>";
1704                         }
1705
1706                         environment_stack[depth].erase();
1707                         sgml::openTag(ofs, depth, false, style->latexname());
1708                         break;
1709
1710                 case LATEX_ENVIRONMENT:
1711                 case LATEX_ITEM_ENVIRONMENT:
1712                 case LATEX_BIB_ENVIRONMENT:
1713                 {
1714                         string const & latexname = style->latexname();
1715
1716                         if (depth == par->params().depth()
1717                             && environment_stack[depth] != latexname) {
1718                                 sgml::closeTag(ofs, depth, false,
1719                                              environment_stack[depth]);
1720                                 environment_stack[depth].erase();
1721                         }
1722                         if (depth < par->params().depth()) {
1723                                depth = par->params().depth();
1724                                environment_stack[depth].erase();
1725                         }
1726                         if (environment_stack[depth] != latexname) {
1727                                 if (depth == 0) {
1728                                         sgml::openTag(ofs, depth, false, "p");
1729                                 }
1730                                 sgml::openTag(ofs, depth, false, latexname);
1731
1732                                 if (environment_stack.size() == depth + 1)
1733                                         environment_stack.push_back("!-- --");
1734                                 environment_stack[depth] = latexname;
1735                         }
1736
1737                         if (style->latexparam() == "CDATA")
1738                                 ofs << "<![CDATA[";
1739
1740                         if (style->latextype == LATEX_ENVIRONMENT) break;
1741
1742                         if (style->labeltype == LABEL_MANUAL)
1743                                 item_name = "tag";
1744                         else
1745                                 item_name = "item";
1746
1747                         sgml::openTag(ofs, depth + 1, false, item_name);
1748                 }
1749                 break;
1750
1751                 default:
1752                         sgml::openTag(ofs, depth, false, style->latexname());
1753                         break;
1754                 }
1755
1756                 simpleLinuxDocOnePar(ofs, par, depth);
1757
1758                 par = par->next();
1759
1760                 ofs << "\n";
1761                 // write closing SGML tags
1762                 switch (style->latextype) {
1763                 case LATEX_COMMAND:
1764                         break;
1765                 case LATEX_ENVIRONMENT:
1766                 case LATEX_ITEM_ENVIRONMENT:
1767                 case LATEX_BIB_ENVIRONMENT:
1768                         if (style->latexparam() == "CDATA")
1769                                 ofs << "]]>";
1770                         break;
1771                 default:
1772                         sgml::closeTag(ofs, depth, false, style->latexname());
1773                         break;
1774                 }
1775         }
1776
1777         // Close open tags
1778         for (int i = depth; i >= 0; --i)
1779                 sgml::closeTag(ofs, depth, false, environment_stack[i]);
1780
1781         if (!body_only) {
1782                 ofs << "\n\n";
1783                 sgml::closeTag(ofs, 0, false, top_element);
1784         }
1785
1786         ofs.close();
1787         // How to check for successful close
1788
1789         // we want this to be true outside previews (for insetexternal)
1790         niceFile = true;
1791 }
1792
1793
1794 // checks, if newcol chars should be put into this line
1795 // writes newline, if necessary.
1796 namespace {
1797
1798 void sgmlLineBreak(ostream & os, string::size_type & colcount,
1799                           string::size_type newcol)
1800 {
1801         colcount += newcol;
1802         if (colcount > lyxrc.ascii_linelen) {
1803                 os << "\n";
1804                 colcount = newcol; // assume write after this call
1805         }
1806 }
1807
1808 enum PAR_TAG {
1809         NONE=0,
1810         TT = 1,
1811         SF = 2,
1812         BF = 4,
1813         IT = 8,
1814         SL = 16,
1815         EM = 32
1816 };
1817
1818
1819 string tag_name(PAR_TAG const & pt) {
1820         switch (pt) {
1821         case NONE: return "!-- --";
1822         case TT: return "tt";
1823         case SF: return "sf";
1824         case BF: return "bf";
1825         case IT: return "it";
1826         case SL: return "sl";
1827         case EM: return "em";
1828         }
1829         return "";
1830 }
1831
1832
1833 inline
1834 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
1835 {
1836         p1 = static_cast<PAR_TAG>(p1 | p2);
1837 }
1838
1839
1840 inline
1841 void reset(PAR_TAG & p1, PAR_TAG const & p2)
1842 {
1843         p1 = static_cast<PAR_TAG>(p1 & ~p2);
1844 }
1845
1846 } // anon
1847
1848
1849 // Handle internal paragraph parsing -- layout already processed.
1850 void Buffer::simpleLinuxDocOnePar(ostream & os,
1851         Paragraph * par,
1852         Paragraph::depth_type /*depth*/)
1853 {
1854         LyXLayout_ptr const & style = par->layout();
1855
1856         string::size_type char_line_count = 5;     // Heuristic choice ;-)
1857
1858         // gets paragraph main font
1859         LyXFont font_old;
1860         bool desc_on;
1861         if (style->labeltype == LABEL_MANUAL) {
1862                 font_old = style->labelfont;
1863                 desc_on = true;
1864         } else {
1865                 font_old = style->font;
1866                 desc_on = false;
1867         }
1868
1869         LyXFont::FONT_FAMILY family_type = LyXFont::ROMAN_FAMILY;
1870         LyXFont::FONT_SERIES series_type = LyXFont::MEDIUM_SERIES;
1871         LyXFont::FONT_SHAPE  shape_type  = LyXFont::UP_SHAPE;
1872         bool is_em = false;
1873
1874         stack<PAR_TAG> tag_state;
1875         // parsing main loop
1876         for (pos_type i = 0; i < par->size(); ++i) {
1877
1878                 PAR_TAG tag_close = NONE;
1879                 list < PAR_TAG > tag_open;
1880
1881                 LyXFont const font = par->getFont(params, i);
1882
1883                 if (font_old.family() != font.family()) {
1884                         switch (family_type) {
1885                         case LyXFont::SANS_FAMILY:
1886                                 tag_close |= SF;
1887                                 break;
1888                         case LyXFont::TYPEWRITER_FAMILY:
1889                                 tag_close |= TT;
1890                                 break;
1891                         default:
1892                                 break;
1893                         }
1894
1895                         family_type = font.family();
1896
1897                         switch (family_type) {
1898                         case LyXFont::SANS_FAMILY:
1899                                 tag_open.push_back(SF);
1900                                 break;
1901                         case LyXFont::TYPEWRITER_FAMILY:
1902                                 tag_open.push_back(TT);
1903                                 break;
1904                         default:
1905                                 break;
1906                         }
1907                 }
1908
1909                 if (font_old.series() != font.series()) {
1910                         switch (series_type) {
1911                         case LyXFont::BOLD_SERIES:
1912                                 tag_close |= BF;
1913                                 break;
1914                         default:
1915                                 break;
1916                         }
1917
1918                         series_type = font.series();
1919
1920                         switch (series_type) {
1921                         case LyXFont::BOLD_SERIES:
1922                                 tag_open.push_back(BF);
1923                                 break;
1924                         default:
1925                                 break;
1926                         }
1927
1928                 }
1929
1930                 if (font_old.shape() != font.shape()) {
1931                         switch (shape_type) {
1932                         case LyXFont::ITALIC_SHAPE:
1933                                 tag_close |= IT;
1934                                 break;
1935                         case LyXFont::SLANTED_SHAPE:
1936                                 tag_close |= SL;
1937                                 break;
1938                         default:
1939                                 break;
1940                         }
1941
1942                         shape_type = font.shape();
1943
1944                         switch (shape_type) {
1945                         case LyXFont::ITALIC_SHAPE:
1946                                 tag_open.push_back(IT);
1947                                 break;
1948                         case LyXFont::SLANTED_SHAPE:
1949                                 tag_open.push_back(SL);
1950                                 break;
1951                         default:
1952                                 break;
1953                         }
1954                 }
1955                 // handle <em> tag
1956                 if (font_old.emph() != font.emph()) {
1957                         if (font.emph() == LyXFont::ON) {
1958                                 tag_open.push_back(EM);
1959                                 is_em = true;
1960                         }
1961                         else if (is_em) {
1962                                 tag_close |= EM;
1963                                 is_em = false;
1964                         }
1965                 }
1966
1967                 list < PAR_TAG > temp;
1968                 while (!tag_state.empty() && tag_close) {
1969                         PAR_TAG k =  tag_state.top();
1970                         tag_state.pop();
1971                         os << "</" << tag_name(k) << '>';
1972                         if (tag_close & k)
1973                                 reset(tag_close,k);
1974                         else
1975                                 temp.push_back(k);
1976                 }
1977
1978                 for(list< PAR_TAG >::const_iterator j = temp.begin();
1979                     j != temp.end(); ++j) {
1980                         tag_state.push(*j);
1981                         os << '<' << tag_name(*j) << '>';
1982                 }
1983
1984                 for(list< PAR_TAG >::const_iterator j = tag_open.begin();
1985                     j != tag_open.end(); ++j) {
1986                         tag_state.push(*j);
1987                         os << '<' << tag_name(*j) << '>';
1988                 }
1989
1990                 char c = par->getChar(i);
1991
1992                 if (c == Paragraph::META_INSET) {
1993                         Inset * inset = par->getInset(i);
1994                         inset->linuxdoc(this, os);
1995                         font_old = font;
1996                         continue;
1997                 }
1998
1999                 if (style->latexparam() == "CDATA") {
2000                         // "TeX"-Mode on == > SGML-Mode on.
2001                         if (c != '\0')
2002                                 os << c;
2003                         ++char_line_count;
2004                 } else {
2005                         bool ws;
2006                         string str;
2007                         boost::tie(ws, str) = sgml::escapeChar(c);
2008                         if (ws && !style->free_spacing && !par->isFreeSpacing()) {
2009                                 // in freespacing mode, spaces are
2010                                 // non-breaking characters
2011                                 if (desc_on) {// if char is ' ' then...
2012
2013                                         ++char_line_count;
2014                                         sgmlLineBreak(os, char_line_count, 6);
2015                                         os << "</tag>";
2016                                         desc_on = false;
2017                                 } else  {
2018                                         sgmlLineBreak(os, char_line_count, 1);
2019                                         os << c;
2020                                 }
2021                         } else {
2022                                 os << str;
2023                                 char_line_count += str.length();
2024                         }
2025                 }
2026                 font_old = font;
2027         }
2028
2029         while (!tag_state.empty()) {
2030                 os << "</" << tag_name(tag_state.top()) << '>';
2031                 tag_state.pop();
2032         }
2033
2034         // resets description flag correctly
2035         if (desc_on) {
2036                 // <tag> not closed...
2037                 sgmlLineBreak(os, char_line_count, 6);
2038                 os << "</tag>";
2039         }
2040 }
2041
2042
2043 // Print an error message.
2044 void Buffer::sgmlError(Paragraph * /*par*/, int /*pos*/,
2045         string const & /*message*/) const
2046 {
2047 #ifdef WITH_WARNINGS
2048 #warning This is wrong we cannot insert an inset like this!!!
2049         // I guess this was Jose' so I explain you more or less why this
2050         // is wrong. This way you insert something in the paragraph and
2051         // don't tell it to LyXText (row rebreaking and undo handling!!!)
2052         // I deactivate this code, have a look at BufferView::insertErrors
2053         // how you should do this correctly! (Jug 20020315)
2054 #endif
2055 #if 0
2056         // insert an error marker in text
2057         InsetError * new_inset = new InsetError(message);
2058         par->insertInset(pos, new_inset, LyXFont(LyXFont::ALL_INHERIT,
2059                          params.language));
2060 #endif
2061 }
2062
2063
2064 void Buffer::makeDocBookFile(string const & fname, bool nice, bool only_body)
2065 {
2066         ofstream ofs(fname.c_str());
2067         if (!ofs) {
2068                 Alert::alert(_("LYX_ERROR:"), _("Cannot write file"), fname);
2069                 return;
2070         }
2071
2072         Paragraph * par = &*(paragraphs.begin());
2073
2074         niceFile = nice; // this will be used by Insetincludes.
2075
2076         LaTeXFeatures features(params);
2077         validate(features);
2078
2079         texrow.reset();
2080
2081         LyXTextClass const & tclass = params.getLyXTextClass();
2082         string top_element = tclass.latexname();
2083
2084         if (!only_body) {
2085                 ofs << "<!DOCTYPE " << top_element
2086                     << "  PUBLIC \"-//OASIS//DTD DocBook V4.1//EN\"";
2087
2088                 string preamble = params.preamble;
2089                 const string name = nice ? ChangeExtension(filename_, ".sgml")
2090                          : fname;
2091                 preamble += features.getIncludedFiles(name);
2092                 preamble += features.getLyXSGMLEntities();
2093
2094                 if (!preamble.empty()) {
2095                         ofs << "\n [ " << preamble << " ]";
2096                 }
2097                 ofs << ">\n\n";
2098         }
2099
2100         string top = top_element;
2101         top += " lang=\"";
2102         top += params.language->code();
2103         top += '"';
2104
2105         if (!params.options.empty()) {
2106                 top += ' ';
2107                 top += params.options;
2108         }
2109         sgml::openTag(ofs, 0, false, top);
2110
2111         ofs << "<!-- DocBook file was created by " << lyx_docversion
2112             << "\n  See http://www.lyx.org/ for more information -->\n";
2113
2114         vector<string> environment_stack(10);
2115         vector<string> environment_inner(10);
2116         vector<string> command_stack(10);
2117
2118         bool command_flag = false;
2119         Paragraph::depth_type command_depth = 0;
2120         Paragraph::depth_type command_base = 0;
2121         Paragraph::depth_type cmd_depth = 0;
2122         Paragraph::depth_type depth = 0; // paragraph depth
2123
2124         string item_name;
2125         string command_name;
2126
2127         while (par) {
2128                 string sgmlparam;
2129                 string c_depth;
2130                 string c_params;
2131                 int desc_on = 0; // description mode
2132
2133                 LyXLayout_ptr const & style = par->layout();
2134
2135                 // environment tag closing
2136                 for (; depth > par->params().depth(); --depth) {
2137                         if (environment_inner[depth] != "!-- --") {
2138                                 item_name = "listitem";
2139                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2140                                 if (environment_inner[depth] == "varlistentry")
2141                                         sgml::closeTag(ofs, depth+command_depth, false, environment_inner[depth]);
2142                         }
2143                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2144                         environment_stack[depth].erase();
2145                         environment_inner[depth].erase();
2146                 }
2147
2148                 if (depth == par->params().depth()
2149                    && environment_stack[depth] != style->latexname()
2150                    && !environment_stack[depth].empty()) {
2151                         if (environment_inner[depth] != "!-- --") {
2152                                 item_name= "listitem";
2153                                 sgml::closeTag(ofs, command_depth+depth, false, item_name);
2154                                 if (environment_inner[depth] == "varlistentry")
2155                                         sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2156                         }
2157
2158                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2159
2160                         environment_stack[depth].erase();
2161                         environment_inner[depth].erase();
2162                 }
2163
2164                 // Write opening SGML tags.
2165                 switch (style->latextype) {
2166                 case LATEX_PARAGRAPH:
2167                         sgml::openTag(ofs, depth + command_depth,
2168                                     false, style->latexname());
2169                         break;
2170
2171                 case LATEX_COMMAND:
2172                         if (depth != 0)
2173                                 sgmlError(par, 0,
2174                                           _("Error: Wrong depth for LatexType Command.\n"));
2175
2176                         command_name = style->latexname();
2177
2178                         sgmlparam = style->latexparam();
2179                         c_params = split(sgmlparam, c_depth,'|');
2180
2181                         cmd_depth = lyx::atoi(c_depth);
2182
2183                         if (command_flag) {
2184                                 if (cmd_depth < command_base) {
2185                                         for (Paragraph::depth_type j = command_depth;
2186                                              j >= command_base; --j) {
2187                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2188                                                 ofs << endl;
2189                                         }
2190                                         command_depth = command_base = cmd_depth;
2191                                 } else if (cmd_depth <= command_depth) {
2192                                         for (int j = command_depth;
2193                                              j >= int(cmd_depth); --j) {
2194                                                 sgml::closeTag(ofs, j, false, command_stack[j]);
2195                                                 ofs << endl;
2196                                         }
2197                                         command_depth = cmd_depth;
2198                                 } else
2199                                         command_depth = cmd_depth;
2200                         } else {
2201                                 command_depth = command_base = cmd_depth;
2202                                 command_flag = true;
2203                         }
2204                         if (command_stack.size() == command_depth + 1)
2205                                 command_stack.push_back(string());
2206                         command_stack[command_depth] = command_name;
2207
2208                         // treat label as a special case for
2209                         // more WYSIWYM handling.
2210                         // This is a hack while paragraphs can't have
2211                         // attributes, like id in this case.
2212                         if (par->isInset(0)) {
2213                                 Inset * inset = par->getInset(0);
2214                                 Inset::Code lyx_code = inset->lyxCode();
2215                                 if (lyx_code == Inset::LABEL_CODE) {
2216                                         command_name += " id=\"";
2217                                         command_name += (static_cast<InsetCommand *>(inset))->getContents();
2218                                         command_name += '"';
2219                                         desc_on = 3;
2220                                 }
2221                         }
2222
2223                         sgml::openTag(ofs, depth + command_depth, false, command_name);
2224
2225                         item_name = c_params.empty() ? "title" : c_params;
2226                         sgml::openTag(ofs, depth + 1 + command_depth, false, item_name);
2227                         break;
2228
2229                 case LATEX_ENVIRONMENT:
2230                 case LATEX_ITEM_ENVIRONMENT:
2231                         if (depth < par->params().depth()) {
2232                                 depth = par->params().depth();
2233                                 environment_stack[depth].erase();
2234                         }
2235
2236                         if (environment_stack[depth] != style->latexname()) {
2237                                 if (environment_stack.size() == depth + 1) {
2238                                         environment_stack.push_back("!-- --");
2239                                         environment_inner.push_back("!-- --");
2240                                 }
2241                                 environment_stack[depth] = style->latexname();
2242                                 environment_inner[depth] = "!-- --";
2243                                 sgml::openTag(ofs, depth + command_depth, false, environment_stack[depth]);
2244                         } else {
2245                                 if (environment_inner[depth] != "!-- --") {
2246                                         item_name= "listitem";
2247                                         sgml::closeTag(ofs, command_depth + depth, false, item_name);
2248                                         if (environment_inner[depth] == "varlistentry")
2249                                                 sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2250                                 }
2251                         }
2252
2253                         if (style->latextype == LATEX_ENVIRONMENT) {
2254                                 if (!style->latexparam().empty()) {
2255                                         if (style->latexparam() == "CDATA")
2256                                                 ofs << "<![CDATA[";
2257                                         else
2258                                                 sgml::openTag(ofs, depth + command_depth, false, style->latexparam());
2259                                 }
2260                                 break;
2261                         }
2262
2263                         desc_on = (style->labeltype == LABEL_MANUAL);
2264
2265                         environment_inner[depth] = desc_on ? "varlistentry" : "listitem";
2266                         sgml::openTag(ofs, depth + 1 + command_depth,
2267                                     false, environment_inner[depth]);
2268
2269                         item_name = desc_on ? "term" : "para";
2270                         sgml::openTag(ofs, depth + 1 + command_depth,
2271                                     false, item_name);
2272                         break;
2273                 default:
2274                         sgml::openTag(ofs, depth + command_depth,
2275                                     false, style->latexname());
2276                         break;
2277                 }
2278
2279                 simpleDocBookOnePar(ofs, par, desc_on,
2280                                     depth + 1 + command_depth);
2281                 par = par->next();
2282
2283                 string end_tag;
2284                 // write closing SGML tags
2285                 switch (style->latextype) {
2286                 case LATEX_COMMAND:
2287                         end_tag = c_params.empty() ? "title" : c_params;
2288                         sgml::closeTag(ofs, depth + command_depth,
2289                                      false, end_tag);
2290                         break;
2291                 case LATEX_ENVIRONMENT:
2292                         if (!style->latexparam().empty()) {
2293                                 if (style->latexparam() == "CDATA")
2294                                         ofs << "]]>";
2295                                 else
2296                                         sgml::closeTag(ofs, depth + command_depth, false, style->latexparam());
2297                         }
2298                         break;
2299                 case LATEX_ITEM_ENVIRONMENT:
2300                         if (desc_on == 1) break;
2301                         end_tag = "para";
2302                         sgml::closeTag(ofs, depth + 1 + command_depth, false, end_tag);
2303                         break;
2304                 case LATEX_PARAGRAPH:
2305                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2306                         break;
2307                 default:
2308                         sgml::closeTag(ofs, depth + command_depth, false, style->latexname());
2309                         break;
2310                 }
2311         }
2312
2313         // Close open tags
2314         for (int d = depth; d >= 0; --d) {
2315                 if (!environment_stack[depth].empty()) {
2316                         if (environment_inner[depth] != "!-- --") {
2317                                 item_name = "listitem";
2318                                 sgml::closeTag(ofs, command_depth + depth, false, item_name);
2319                                if (environment_inner[depth] == "varlistentry")
2320                                        sgml::closeTag(ofs, depth + command_depth, false, environment_inner[depth]);
2321                         }
2322
2323                         sgml::closeTag(ofs, depth + command_depth, false, environment_stack[depth]);
2324                 }
2325         }
2326
2327         for (int j = command_depth; j >= 0 ; --j)
2328                 if (!command_stack[j].empty()) {
2329                         sgml::closeTag(ofs, j, false, command_stack[j]);
2330                         ofs << endl;
2331                 }
2332
2333         ofs << "\n\n";
2334         sgml::closeTag(ofs, 0, false, top_element);
2335
2336         ofs.close();
2337         // How to check for successful close
2338
2339         // we want this to be true outside previews (for insetexternal)
2340         niceFile = true;
2341 }
2342
2343
2344 void Buffer::simpleDocBookOnePar(ostream & os,
2345                                  Paragraph * par, int & desc_on,
2346                                  Paragraph::depth_type depth) const
2347 {
2348         bool emph_flag = false;
2349
2350         LyXLayout_ptr const & style = par->layout();
2351
2352         LyXFont font_old = (style->labeltype == LABEL_MANUAL ? style->labelfont : style->font);
2353
2354         int char_line_count = depth;
2355         //if (!style.free_spacing)
2356         //      os << string(depth,' ');
2357
2358         // parsing main loop
2359         for (pos_type i = 0; i < par->size(); ++i) {
2360                 LyXFont font = par->getFont(params, i);
2361
2362                 // handle <emphasis> tag
2363                 if (font_old.emph() != font.emph()) {
2364                         if (font.emph() == LyXFont::ON) {
2365                                 if (style->latexparam() == "CDATA")
2366                                         os << "]]>";
2367                                 os << "<emphasis>";
2368                                 if (style->latexparam() == "CDATA")
2369                                         os << "<![CDATA[";
2370                                 emph_flag = true;
2371                         } else if (i) {
2372                                 if (style->latexparam() == "CDATA")
2373                                         os << "]]>";
2374                                 os << "</emphasis>";
2375                                 if (style->latexparam() == "CDATA")
2376                                         os << "<![CDATA[";
2377                                 emph_flag = false;
2378                         }
2379                 }
2380
2381
2382                 if (par->isInset(i)) {
2383                         Inset * inset = par->getInset(i);
2384                         // don't print the inset in position 0 if desc_on == 3 (label)
2385                         if (i || desc_on != 3) {
2386                                 if (style->latexparam() == "CDATA")
2387                                         os << "]]>";
2388                                 inset->docbook(this, os, false);
2389                                 if (style->latexparam() == "CDATA")
2390                                         os << "<![CDATA[";
2391                         }
2392                 } else {
2393                         char c = par->getChar(i);
2394                         bool ws;
2395                         string str;
2396                         boost::tie(ws, str) = sgml::escapeChar(c);
2397
2398                         if (style->pass_thru) {
2399                                 os << c;
2400                         } else if (style->free_spacing || par->isFreeSpacing() || c != ' ') {
2401                                         os << str;
2402                         } else if (desc_on ==1) {
2403                                 ++char_line_count;
2404                                 os << "\n</term><listitem><para>";
2405                                 desc_on = 2;
2406                         } else {
2407                                 os << ' ';
2408                         }
2409                 }
2410                 font_old = font;
2411         }
2412
2413         if (emph_flag) {
2414                 if (style->latexparam() == "CDATA")
2415                         os << "]]>";
2416                 os << "</emphasis>";
2417                 if (style->latexparam() == "CDATA")
2418                         os << "<![CDATA[";
2419         }
2420
2421         // resets description flag correctly
2422         if (desc_on == 1) {
2423                 // <term> not closed...
2424                 os << "</term>\n<listitem><para>&nbsp;</para>";
2425         }
2426         if (style->free_spacing)
2427                 os << '\n';
2428 }
2429
2430
2431 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2432 // Other flags: -wall -v0 -x
2433 int Buffer::runChktex()
2434 {
2435         if (!users->text) return 0;
2436
2437         users->owner()->busy(true);
2438
2439         // get LaTeX-Filename
2440         string const name = getLatexName();
2441         string path = filePath();
2442
2443         string const org_path = path;
2444         if (lyxrc.use_tempdir || !IsDirWriteable(path)) {
2445                 path = tmppath;
2446         }
2447
2448         Path p(path); // path to LaTeX file
2449         users->owner()->message(_("Running chktex..."));
2450
2451         // Remove all error insets
2452         bool const removedErrorInsets = users->removeAutoInsets();
2453
2454         // Generate the LaTeX file if neccessary
2455         makeLaTeXFile(name, org_path, false);
2456
2457         TeXErrors terr;
2458         Chktex chktex(lyxrc.chktex_command, name, filePath());
2459         int res = chktex.run(terr); // run chktex
2460
2461         if (res == -1) {
2462                 Alert::alert(_("chktex did not work!"),
2463                            _("Could not run with file:"), name);
2464         } else if (res > 0) {
2465                 // Insert all errors as errors boxes
2466                 users->insertErrors(terr);
2467         }
2468
2469         // if we removed error insets before we ran chktex or if we inserted
2470         // error insets after we ran chktex, this must be run:
2471         if (removedErrorInsets || res) {
2472 #warning repaint needed here, or do you mean update() ?
2473                 users->repaint();
2474                 users->fitCursor();
2475         }
2476         users->owner()->busy(false);
2477
2478         return res;
2479 }
2480
2481
2482 void Buffer::validate(LaTeXFeatures & features) const
2483 {
2484         LyXTextClass const & tclass = params.getLyXTextClass();
2485
2486         if (params.tracking_changes) {
2487                 features.require("dvipost");
2488                 features.require("color");
2489         }
2490
2491         // AMS Style is at document level
2492         if (params.use_amsmath == BufferParams::AMS_ON
2493             || tclass.provides(LyXTextClass::amsmath))
2494                 features.require("amsmath");
2495
2496         for_each(paragraphs.begin(), paragraphs.end(),
2497                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
2498
2499         // the bullet shapes are buffer level not paragraph level
2500         // so they are tested here
2501         for (int i = 0; i < 4; ++i) {
2502                 if (params.user_defined_bullets[i] != ITEMIZE_DEFAULTS[i]) {
2503                         int const font = params.user_defined_bullets[i].getFont();
2504                         if (font == 0) {
2505                                 int const c = params
2506                                         .user_defined_bullets[i]
2507                                         .getCharacter();
2508                                 if (c == 16
2509                                    || c == 17
2510                                    || c == 25
2511                                    || c == 26
2512                                    || c == 31) {
2513                                         features.require("latexsym");
2514                                 }
2515                         } else if (font == 1) {
2516                                 features.require("amssymb");
2517                         } else if ((font >= 2 && font <= 5)) {
2518                                 features.require("pifont");
2519                         }
2520                 }
2521         }
2522
2523         if (lyxerr.debugging(Debug::LATEX)) {
2524                 features.showStruct();
2525         }
2526 }
2527
2528
2529 vector<string> const Buffer::getLabelList() const
2530 {
2531         /// if this is a child document and the parent is already loaded
2532         /// Use the parent's list instead  [ale990407]
2533         if (!params.parentname.empty()
2534             && bufferlist.exists(params.parentname)) {
2535                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2536                 if (tmp)
2537                         return tmp->getLabelList();
2538         }
2539
2540         vector<string> label_list;
2541         for (inset_iterator it = inset_const_iterator_begin();
2542              it != inset_const_iterator_end(); ++it) {
2543                 vector<string> const l = it->getLabelList();
2544                 label_list.insert(label_list.end(), l.begin(), l.end());
2545         }
2546         return label_list;
2547 }
2548
2549
2550 // This is also a buffer property (ale)
2551 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys) const
2552 {
2553         /// if this is a child document and the parent is already loaded
2554         /// use the parent's list instead  [ale990412]
2555         if (!params.parentname.empty() && bufferlist.exists(params.parentname)) {
2556                 Buffer const * tmp = bufferlist.getBuffer(params.parentname);
2557                 if (tmp) {
2558                         tmp->fillWithBibKeys(keys);
2559                         return;
2560                 }
2561         }
2562
2563         for (inset_iterator it = inset_const_iterator_begin();
2564                 it != inset_const_iterator_end(); ++it) {
2565                 if (it->lyxCode() == Inset::BIBTEX_CODE)
2566                         static_cast<InsetBibtex &>(*it).fillWithBibKeys(this, keys);
2567                 else if (it->lyxCode() == Inset::INCLUDE_CODE)
2568                         static_cast<InsetInclude &>(*it).fillWithBibKeys(keys);
2569                 else if (it->lyxCode() == Inset::BIBITEM_CODE) {
2570                         InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
2571                         string const key = bib.getContents();
2572                         string const opt = bib.getOptions();
2573                         string const ref; // = pit->asString(this, false);
2574                         string const info = opt + "TheBibliographyRef" + ref;
2575                         keys.push_back(pair<string, string>(key, info));
2576                 }
2577         }
2578 }
2579
2580
2581 bool Buffer::isDepClean(string const & name) const
2582 {
2583         DepClean::const_iterator it = dep_clean_.find(name);
2584         if (it == dep_clean_.end())
2585                 return true;
2586         return it->second;
2587 }
2588
2589
2590 void Buffer::markDepClean(string const & name)
2591 {
2592         dep_clean_[name] = true;
2593 }
2594
2595
2596 bool Buffer::dispatch(string const & command, bool * result)
2597 {
2598         // Split command string into command and argument
2599         string cmd;
2600         string line = ltrim(command);
2601         string const arg = trim(split(line, cmd, ' '));
2602
2603         return dispatch(lyxaction.LookupFunc(cmd), arg, result);
2604 }
2605
2606
2607 bool Buffer::dispatch(int action, string const & argument, bool * result)
2608 {
2609         bool dispatched = true;
2610
2611         switch (action) {
2612                 case LFUN_EXPORT: {
2613                         bool const tmp = Exporter::Export(this, argument, false);
2614                         if (result)
2615                                 *result = tmp;
2616                         break;
2617                 }
2618
2619                 default:
2620                         dispatched = false;
2621         }
2622         return dispatched;
2623 }
2624
2625
2626 void Buffer::resizeInsets(BufferView * bv)
2627 {
2628         /// then remove all LyXText in text-insets
2629         for_each(paragraphs.begin(), paragraphs.end(),
2630                  boost::bind(&Paragraph::resizeInsetsLyXText, _1, bv));
2631 }
2632
2633
2634 void Buffer::redraw()
2635 {
2636 #warning repaint needed here, or do you mean update() ?
2637         users->repaint();
2638         users->fitCursor();
2639 }
2640
2641
2642 void Buffer::changeLanguage(Language const * from, Language const * to)
2643 {
2644
2645         ParIterator end = par_iterator_end();
2646         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2647                 (*it)->changeLanguage(params, from, to);
2648 }
2649
2650
2651 bool Buffer::isMultiLingual()
2652 {
2653         ParIterator end = par_iterator_end();
2654         for (ParIterator it = par_iterator_begin(); it != end; ++it)
2655                 if ((*it)->isMultiLingual(params))
2656                         return true;
2657
2658         return false;
2659 }
2660
2661
2662 void Buffer::inset_iterator::setParagraph()
2663 {
2664         while (pit != pend) {
2665                 it = pit->insetlist.begin();
2666                 if (it != pit->insetlist.end())
2667                         return;
2668                 ++pit;
2669         }
2670 }
2671
2672
2673 Inset * Buffer::getInsetFromID(int id_arg) const
2674 {
2675         for (inset_iterator it = inset_const_iterator_begin();
2676                  it != inset_const_iterator_end(); ++it)
2677         {
2678                 if (it->id() == id_arg)
2679                         return &(*it);
2680                 Inset * in = it->getInsetFromID(id_arg);
2681                 if (in)
2682                         return in;
2683         }
2684         return 0;
2685 }
2686
2687
2688 Paragraph * Buffer::getParFromID(int id) const
2689 {
2690         if (id < 0)
2691                 return 0;
2692
2693         // why should we allow < 0 ??
2694         //lyx::Assert(id >= 0);
2695
2696         ParConstIterator it(par_iterator_begin());
2697         ParConstIterator end(par_iterator_end());
2698
2699         for (; it != end; ++it) {
2700                 // go on then, show me how to remove
2701                 // the cast
2702                 if ((*it)->id() == id) {
2703                         return const_cast<Paragraph*>(*it);
2704                 }
2705         }
2706
2707         return 0;
2708 }
2709
2710
2711 ParIterator Buffer::par_iterator_begin()
2712 {
2713         return ParIterator(&*(paragraphs.begin()));
2714 }
2715
2716
2717 ParIterator Buffer::par_iterator_end()
2718 {
2719         return ParIterator();
2720 }
2721
2722 ParConstIterator Buffer::par_iterator_begin() const
2723 {
2724         return ParConstIterator(&*(paragraphs.begin()));
2725 }
2726
2727
2728 ParConstIterator Buffer::par_iterator_end() const
2729 {
2730         return ParConstIterator();
2731 }
2732
2733
2734
2735 void Buffer::addUser(BufferView * u)
2736 {
2737         users = u;
2738 }
2739
2740
2741 void Buffer::delUser(BufferView *)
2742 {
2743         users = 0;
2744 }
2745
2746
2747 Language const * Buffer::getLanguage() const
2748 {
2749         return params.language;
2750 }
2751
2752
2753 bool Buffer::isClean() const
2754 {
2755         return lyx_clean;
2756 }
2757
2758
2759 bool Buffer::isBakClean() const
2760 {
2761         return bak_clean;
2762 }
2763
2764
2765 void Buffer::markClean() const
2766 {
2767         if (!lyx_clean) {
2768                 lyx_clean = true;
2769                 updateTitles();
2770         }
2771         // if the .lyx file has been saved, we don't need an
2772         // autosave
2773         bak_clean = true;
2774 }
2775
2776
2777 void Buffer::markBakClean()
2778 {
2779         bak_clean = true;
2780 }
2781
2782
2783 void Buffer::setUnnamed(bool flag)
2784 {
2785         unnamed = flag;
2786 }
2787
2788
2789 bool Buffer::isUnnamed()
2790 {
2791         return unnamed;
2792 }
2793
2794
2795 void Buffer::markDirty()
2796 {
2797         if (lyx_clean) {
2798                 lyx_clean = false;
2799                 updateTitles();
2800         }
2801         bak_clean = false;
2802
2803         DepClean::iterator it = dep_clean_.begin();
2804         DepClean::const_iterator const end = dep_clean_.end();
2805
2806         for (; it != end; ++it) {
2807                 it->second = false;
2808         }
2809 }
2810
2811
2812 string const & Buffer::fileName() const
2813 {
2814         return filename_;
2815 }
2816
2817
2818 string const & Buffer::filePath() const
2819 {
2820         return filepath_;
2821 }
2822
2823
2824 bool Buffer::isReadonly() const
2825 {
2826         return read_only;
2827 }
2828
2829
2830 BufferView * Buffer::getUser() const
2831 {
2832         return users;
2833 }
2834
2835
2836 void Buffer::setParentName(string const & name)
2837 {
2838         params.parentname = name;
2839 }
2840
2841
2842 Buffer::inset_iterator::inset_iterator()
2843         : pit(0), pend(0)
2844 {}
2845
2846
2847 Buffer::inset_iterator::inset_iterator(base_type p, base_type e)
2848         : pit(p), pend(e)
2849 {
2850         setParagraph();
2851 }
2852
2853
2854 Buffer::inset_iterator & Buffer::inset_iterator::operator++()
2855 {
2856         if (pit != pend) {
2857                 ++it;
2858                 if (it == pit->insetlist.end()) {
2859                         ++pit;
2860                         setParagraph();
2861                 }
2862         }
2863         return *this;
2864 }
2865
2866
2867 Buffer::inset_iterator Buffer::inset_iterator::operator++(int)
2868 {
2869         inset_iterator tmp = *this;
2870         ++*this;
2871         return tmp;
2872 }
2873
2874
2875 Buffer::inset_iterator::reference Buffer::inset_iterator::operator*()
2876 {
2877         return *it.getInset();
2878 }
2879
2880
2881 Buffer::inset_iterator::pointer Buffer::inset_iterator::operator->()
2882 {
2883         return it.getInset();
2884 }
2885
2886
2887 Paragraph * Buffer::inset_iterator::getPar()
2888 {
2889         return &(*pit);
2890 }
2891
2892
2893 lyx::pos_type Buffer::inset_iterator::getPos() const
2894 {
2895         return it.getPos();
2896 }
2897
2898
2899 bool operator==(Buffer::inset_iterator const & iter1,
2900                 Buffer::inset_iterator const & iter2)
2901 {
2902         return iter1.pit == iter2.pit
2903                 && (iter1.pit == iter1.pend || iter1.it == iter2.it);
2904 }
2905
2906
2907 bool operator!=(Buffer::inset_iterator const & iter1,
2908                 Buffer::inset_iterator const & iter2)
2909 {
2910         return !(iter1 == iter2);
2911 }