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