]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
cbe926bf4f2569448f194ea3a5b1041e0f3c2d36
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
29 #include "Encoding.h"
30 #include "ErrorList.h"
31 #include "Exporter.h"
32 #include "Format.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "LaTeXFeatures.h"
40 #include "LaTeX.h"
41 #include "Layout.h"
42 #include "Lexer.h"
43 #include "LyXAction.h"
44 #include "LyX.h"
45 #include "LyXFunc.h"
46 #include "LyXRC.h"
47 #include "LyXVC.h"
48 #include "output_docbook.h"
49 #include "output.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
58 #include "sgml.h"
59 #include "TexRow.h"
60 #include "TexStream.h"
61 #include "Text.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
64 #include "Undo.h"
65 #include "VCBackend.h"
66 #include "version.h"
67 #include "WordLangTuple.h"
68 #include "WordList.h"
69
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
75
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
79
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
83
84 #include "graphics/Previews.h"
85
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
105
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
108
109 #include <algorithm>
110 #include <fstream>
111 #include <iomanip>
112 #include <map>
113 #include <set>
114 #include <sstream>
115 #include <stack>
116 #include <vector>
117
118 using namespace std;
119 using namespace lyx::support;
120
121 namespace lyx {
122
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125
126 namespace {
127
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 374; // rgheck: HTML output options
131
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134
135 void showPrintError(string const & name)
136 {
137         docstring str = bformat(_("Could not print the document %1$s.\n"
138                                             "Check that your printer is set up correctly."),
139                              makeDisplayPath(name, 50));
140         Alert::error(_("Print document failed"), str);
141 }
142
143 } // namespace anon
144
145 class BufferSet : public std::set<Buffer const *> {};
146
147 class Buffer::Impl
148 {
149 public:
150         Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
151
152         ~Impl()
153         {
154                 if (wa_) {
155                         wa_->closeAll();
156                         delete wa_;
157                 }
158                 delete inset;
159         }
160
161         BufferParams params;
162         LyXVC lyxvc;
163         FileName temppath;
164         mutable TexRow texrow;
165
166         /// need to regenerate .tex?
167         DepClean dep_clean;
168
169         /// is save needed?
170         mutable bool lyx_clean;
171
172         /// is autosave needed?
173         mutable bool bak_clean;
174
175         /// is this a unnamed file (New...)?
176         bool unnamed;
177
178         /// buffer is r/o
179         bool read_only;
180
181         /// name of the file the buffer is associated with.
182         FileName filename;
183
184         /** Set to true only when the file is fully loaded.
185          *  Used to prevent the premature generation of previews
186          *  and by the citation inset.
187          */
188         bool file_fully_loaded;
189
190         ///
191         mutable TocBackend toc_backend;
192
193         /// macro tables
194         typedef pair<DocIterator, MacroData> ScopeMacro;
195         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197         /// map from the macro name to the position map,
198         /// which maps the macro definition position to the scope and the MacroData.
199         NamePositionScopeMacroMap macros;
200         bool macro_lock;
201
202         /// positions of child buffers in the buffer
203         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206         /// position of children buffers in this buffer
207         BufferPositionMap children_positions;
208         /// map from children inclusion positions to their scope and their buffer
209         PositionScopeBufferMap position_to_children;
210
211         /// Container for all sort of Buffer dependant errors.
212         map<string, ErrorList> errorLists;
213
214         /// timestamp and checksum used to test if the file has been externally
215         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216         time_t timestamp_;
217         unsigned long checksum_;
218
219         ///
220         frontend::WorkAreaManager * wa_;
221
222         ///
223         Undo undo_;
224
225         /// A cache for the bibfiles (including bibfiles of loaded child
226         /// documents), needed for appropriate update of natbib labels.
227         mutable support::FileNameList bibfilesCache_;
228
229         // FIXME The caching mechanism could be improved. At present, we have a
230         // cache for each Buffer, that caches all the bibliography info for that
231         // Buffer. A more efficient solution would be to have a global cache per
232         // file, and then to construct the Buffer's bibinfo from that.
233         /// A cache for bibliography info
234         mutable BiblioInfo bibinfo_;
235         /// whether the bibinfo cache is valid
236         bool bibinfoCacheValid_;
237         /// Cache of timestamps of .bib files
238         map<FileName, time_t> bibfileStatus_;
239
240         mutable RefCache ref_cache_;
241
242         /// our Text that should be wrapped in an InsetText
243         InsetText * inset;
244
245         /// This is here to force the test to be done whenever parent_buffer
246         /// is accessed.
247         Buffer const * parent() const { 
248                 // if parent_buffer is not loaded, then it has been unloaded,
249                 // which means that parent_buffer is an invalid pointer. So we
250                 // set it to null in that case.
251                 if (!theBufferList().isLoaded(parent_buffer))
252                         parent_buffer = 0;
253                 return parent_buffer; 
254         }
255         ///
256         void setParent(Buffer const * pb) {
257                 if (parent_buffer && pb && parent_buffer != pb)
258                         LYXERR0("Warning: a buffer should not have two parents!");
259                 parent_buffer = pb;
260         }
261
262         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263         /// This one is useful for preview detached in a thread.
264         Buffer const * cloned_buffer_;
265
266 private:
267         /// So we can force access via the accessors.
268         mutable Buffer const * parent_buffer;
269
270 };
271
272
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
275 {
276         static int count;
277         // We are in our own directory.  Why bother to mangle name?
278         // In fact I wrote this code to circumvent a problematic behaviour
279         // (bug?) of EMX mkstemp().
280         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281                 convert<string>(count++));
282
283         if (!tmpfl.createDirectory(0777)) {
284                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286                         from_utf8(tmpfl.absFilename())));
287         }
288         return tmpfl;
289 }
290
291
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293         Buffer const * cloned_buffer)
294         : lyx_clean(true), bak_clean(true), unnamed(false),
295           read_only(readonly_), filename(file), file_fully_loaded(false),
296           toc_backend(&parent), macro_lock(false), timestamp_(0),
297           checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false),
298           cloned_buffer_(cloned_buffer), parent_buffer(0)
299 {
300         if (!cloned_buffer_) {
301                 temppath = createBufferTmpDir();
302                 lyxvc.setBuffer(&parent);
303                 if (use_gui)
304                         wa_ = new frontend::WorkAreaManager;
305                 return;
306         }
307         temppath = cloned_buffer_->d->temppath;
308         file_fully_loaded = true;
309         params = cloned_buffer_->d->params;
310 }
311
312
313 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
314         : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
315 {
316         LYXERR(Debug::INFO, "Buffer::Buffer()");
317         if (cloned_buffer) {
318                 d->inset = new InsetText(*cloned_buffer->d->inset);
319                 d->inset->setBuffer(*this);
320                 // FIXME: optimize this loop somewhat, maybe by creating a new
321                 // general recursive Inset::setId().
322                 DocIterator it = doc_iterator_begin(this);
323                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
324                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
325                         it.paragraph().setId(cloned_it.paragraph().id());
326         } else
327                 d->inset = new InsetText(this);
328         d->inset->setAutoBreakRows(true);
329         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
330 }
331
332
333 Buffer::~Buffer()
334 {
335         LYXERR(Debug::INFO, "Buffer::~Buffer()");
336         // here the buffer should take care that it is
337         // saved properly, before it goes into the void.
338
339         // GuiView already destroyed
340         gui_ = 0;
341
342         if (isInternal()) {
343                 // No need to do additional cleanups for internal buffer.
344                 delete d;
345                 return;
346         }
347
348         // loop over children
349         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
350         Impl::BufferPositionMap::iterator end = d->children_positions.end();
351         for (; it != end; ++it) {
352                 Buffer * child = const_cast<Buffer *>(it->first);
353                 // The child buffer might have been closed already.
354                 if (theBufferList().isLoaded(child))
355                         theBufferList().releaseChild(this, child);
356         }
357
358         if (!isClean()) {
359                 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
360                 msg += emergencyWrite();
361                 Alert::warning(_("Attempting to close changed document!"), msg);
362         }
363                 
364         // clear references to children in macro tables
365         d->children_positions.clear();
366         d->position_to_children.clear();
367
368         if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
369                 Alert::warning(_("Could not remove temporary directory"),
370                         bformat(_("Could not remove the temporary directory %1$s"),
371                         from_utf8(d->temppath.absFilename())));
372         }
373
374         // Remove any previewed LaTeX snippets associated with this buffer.
375         thePreviews().removeLoader(*this);
376
377         delete d;
378 }
379
380
381 Buffer * Buffer::clone() const
382 {
383         return new Buffer(fileName().absFilename(), false, this);
384 }
385
386
387 bool Buffer::isClone() const
388 {
389         return d->cloned_buffer_;
390 }
391
392
393 void Buffer::changed() const
394 {
395         if (d->wa_)
396                 d->wa_->redrawAll();
397 }
398
399
400 frontend::WorkAreaManager & Buffer::workAreaManager() const
401 {
402         LASSERT(d->wa_, /**/);
403         return *d->wa_;
404 }
405
406
407 Text & Buffer::text() const
408 {
409         return d->inset->text();
410 }
411
412
413 Inset & Buffer::inset() const
414 {
415         return *d->inset;
416 }
417
418
419 BufferParams & Buffer::params()
420 {
421         return d->params;
422 }
423
424
425 BufferParams const & Buffer::params() const
426 {
427         return d->params;
428 }
429
430
431 ParagraphList & Buffer::paragraphs()
432 {
433         return text().paragraphs();
434 }
435
436
437 ParagraphList const & Buffer::paragraphs() const
438 {
439         return text().paragraphs();
440 }
441
442
443 LyXVC & Buffer::lyxvc()
444 {
445         return d->lyxvc;
446 }
447
448
449 LyXVC const & Buffer::lyxvc() const
450 {
451         return d->lyxvc;
452 }
453
454
455 string const Buffer::temppath() const
456 {
457         return d->temppath.absFilename();
458 }
459
460
461 TexRow & Buffer::texrow()
462 {
463         return d->texrow;
464 }
465
466
467 TexRow const & Buffer::texrow() const
468 {
469         return d->texrow;
470 }
471
472
473 TocBackend & Buffer::tocBackend() const
474 {
475         return d->toc_backend;
476 }
477
478
479 Undo & Buffer::undo()
480 {
481         return d->undo_;
482 }
483
484
485 string Buffer::latexName(bool const no_path) const
486 {
487         FileName latex_name =
488                 makeLatexName(exportFileName());
489         return no_path ? latex_name.onlyFileName()
490                 : latex_name.absFilename();
491 }
492
493
494 FileName Buffer::exportFileName() const
495 {
496         docstring const branch_suffix =
497                 params().branchlist().getFilenameSuffix();
498         if (branch_suffix.empty())
499                 return fileName();
500
501         string const name = fileName().onlyFileNameWithoutExt()
502                 + to_utf8(branch_suffix);
503         FileName res(fileName().onlyPath().absFilename() + "/" + name);
504         res.changeExtension(fileName().extension());
505
506         return res;
507 }
508
509
510 string Buffer::logName(LogType * type) const
511 {
512         string const filename = latexName(false);
513
514         if (filename.empty()) {
515                 if (type)
516                         *type = latexlog;
517                 return string();
518         }
519
520         string const path = temppath();
521
522         FileName const fname(addName(temppath(),
523                                      onlyFilename(changeExtension(filename,
524                                                                   ".log"))));
525
526         // FIXME: how do we know this is the name of the build log?
527         FileName const bname(
528                 addName(path, onlyFilename(
529                         changeExtension(filename,
530                                         formats.extension(bufferFormat()) + ".out"))));
531
532         // Also consider the master buffer log file
533         FileName masterfname = fname;
534         LogType mtype;
535         if (masterBuffer() != this) {
536                 string const mlogfile = masterBuffer()->logName(&mtype);
537                 masterfname = FileName(mlogfile);
538         }
539
540         // If no Latex log or Build log is newer, show Build log
541         if (bname.exists() &&
542             ((!fname.exists() && !masterfname.exists())
543              || (fname.lastModified() < bname.lastModified()
544                  && masterfname.lastModified() < bname.lastModified()))) {
545                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
546                 if (type)
547                         *type = buildlog;
548                 return bname.absFilename();
549         // If we have a newer master file log or only a master log, show this
550         } else if (fname != masterfname
551                    && (!fname.exists() && (masterfname.exists()
552                    || fname.lastModified() < masterfname.lastModified()))) {
553                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
554                 if (type)
555                         *type = mtype;
556                 return masterfname.absFilename();
557         }
558         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
559         if (type)
560                         *type = latexlog;
561         return fname.absFilename();
562 }
563
564
565 void Buffer::setReadonly(bool const flag)
566 {
567         if (d->read_only != flag) {
568                 d->read_only = flag;
569                 setReadOnly(flag);
570         }
571 }
572
573
574 void Buffer::setFileName(string const & newfile)
575 {
576         d->filename = makeAbsPath(newfile);
577         setReadonly(d->filename.isReadOnly());
578         updateTitles();
579 }
580
581
582 int Buffer::readHeader(Lexer & lex)
583 {
584         int unknown_tokens = 0;
585         int line = -1;
586         int begin_header_line = -1;
587
588         // Initialize parameters that may be/go lacking in header:
589         params().branchlist().clear();
590         params().preamble.erase();
591         params().options.erase();
592         params().master.erase();
593         params().float_placement.erase();
594         params().paperwidth.erase();
595         params().paperheight.erase();
596         params().leftmargin.erase();
597         params().rightmargin.erase();
598         params().topmargin.erase();
599         params().bottommargin.erase();
600         params().headheight.erase();
601         params().headsep.erase();
602         params().footskip.erase();
603         params().columnsep.erase();
604         params().fontsCJK.erase();
605         params().listings_params.clear();
606         params().clearLayoutModules();
607         params().clearRemovedModules();
608         params().pdfoptions().clear();
609         params().indiceslist().clear();
610         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
611
612         for (int i = 0; i < 4; ++i) {
613                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
614                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
615         }
616
617         ErrorList & errorList = d->errorLists["Parse"];
618
619         while (lex.isOK()) {
620                 string token;
621                 lex >> token;
622
623                 if (token.empty())
624                         continue;
625
626                 if (token == "\\end_header")
627                         break;
628
629                 ++line;
630                 if (token == "\\begin_header") {
631                         begin_header_line = line;
632                         continue;
633                 }
634
635                 LYXERR(Debug::PARSER, "Handling document header token: `"
636                                       << token << '\'');
637
638                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
639                 if (!unknown.empty()) {
640                         if (unknown[0] != '\\' && token == "\\textclass") {
641                                 Alert::warning(_("Unknown document class"),
642                        bformat(_("Using the default document class, because the "
643                                               "class %1$s is unknown."), from_utf8(unknown)));
644                         } else {
645                                 ++unknown_tokens;
646                                 docstring const s = bformat(_("Unknown token: "
647                                                                         "%1$s %2$s\n"),
648                                                          from_utf8(token),
649                                                          lex.getDocString());
650                                 errorList.push_back(ErrorItem(_("Document header error"),
651                                         s, -1, 0, 0));
652                         }
653                 }
654         }
655         if (begin_header_line) {
656                 docstring const s = _("\\begin_header is missing");
657                 errorList.push_back(ErrorItem(_("Document header error"),
658                         s, -1, 0, 0));
659         }
660
661         params().makeDocumentClass();
662
663         return unknown_tokens;
664 }
665
666
667 // Uwe C. Schroeder
668 // changed to be public and have one parameter
669 // Returns true if "\end_document" is not read (Asger)
670 bool Buffer::readDocument(Lexer & lex)
671 {
672         ErrorList & errorList = d->errorLists["Parse"];
673         errorList.clear();
674
675         if (!lex.checkFor("\\begin_document")) {
676                 docstring const s = _("\\begin_document is missing");
677                 errorList.push_back(ErrorItem(_("Document header error"),
678                         s, -1, 0, 0));
679         }
680
681         // we are reading in a brand new document
682         LASSERT(paragraphs().empty(), /**/);
683
684         readHeader(lex);
685
686         if (params().outputChanges) {
687                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
688                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
689                                   LaTeXFeatures::isAvailable("xcolor");
690
691                 if (!dvipost && !xcolorulem) {
692                         Alert::warning(_("Changes not shown in LaTeX output"),
693                                        _("Changes will not be highlighted in LaTeX output, "
694                                          "because neither dvipost nor xcolor/ulem are installed.\n"
695                                          "Please install these packages or redefine "
696                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
697                 } else if (!xcolorulem) {
698                         Alert::warning(_("Changes not shown in LaTeX output"),
699                                        _("Changes will not be highlighted in LaTeX output "
700                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
701                                          "Please install both packages or redefine "
702                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
703                 }
704         }
705
706         if (!params().master.empty()) {
707                 FileName const master_file = makeAbsPath(params().master,
708                            onlyPath(absFileName()));
709                 if (isLyXFilename(master_file.absFilename())) {
710                         Buffer * master = 
711                                 checkAndLoadLyXFile(master_file, true);
712                         if (master) {
713                                 // necessary e.g. after a reload
714                                 // to re-register the child (bug 5873)
715                                 // FIXME: clean up updateMacros (here, only
716                                 // child registering is needed).
717                                 master->updateMacros();
718                                 // set master as master buffer, but only
719                                 // if we are a real child
720                                 if (master->isChild(this))
721                                         setParent(master);
722                                 // if the master is not fully loaded
723                                 // it is probably just loading this
724                                 // child. No warning needed then.
725                                 else if (master->isFullyLoaded())
726                                         LYXERR0("The master '"
727                                                 << params().master
728                                                 << "' assigned to this document ("
729                                                 << absFileName()
730                                                 << ") does not include "
731                                                 "this document. Ignoring the master assignment.");
732                         }
733                 }
734         }
735         
736         // assure we have a default index
737         params().indiceslist().addDefault(B_("Index"));
738
739         // read main text
740         bool const res = text().read(lex, errorList, d->inset);
741
742         usermacros.clear();
743         updateMacros();
744         updateMacroInstances();
745         return res;
746 }
747
748
749 bool Buffer::readString(string const & s)
750 {
751         params().compressed = false;
752
753         // remove dummy empty par
754         paragraphs().clear();
755         Lexer lex;
756         istringstream is(s);
757         lex.setStream(is);
758         FileName const name = FileName::tempName("Buffer_readString");
759         switch (readFile(lex, name, true)) {
760         case failure:
761                 return false;
762         case wrongversion: {
763                 // We need to call lyx2lyx, so write the input to a file
764                 ofstream os(name.toFilesystemEncoding().c_str());
765                 os << s;
766                 os.close();
767                 return readFile(name);
768         }
769         case success:
770                 break;
771         }
772
773         return true;
774 }
775
776
777 bool Buffer::readFile(FileName const & filename)
778 {
779         FileName fname(filename);
780
781         params().compressed = fname.isZippedFile();
782
783         // remove dummy empty par
784         paragraphs().clear();
785         Lexer lex;
786         lex.setFile(fname);
787         if (readFile(lex, fname) != success)
788                 return false;
789
790         return true;
791 }
792
793
794 bool Buffer::isFullyLoaded() const
795 {
796         return d->file_fully_loaded;
797 }
798
799
800 void Buffer::setFullyLoaded(bool value)
801 {
802         d->file_fully_loaded = value;
803 }
804
805
806 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
807                 bool fromstring)
808 {
809         LASSERT(!filename.empty(), /**/);
810
811         // the first (non-comment) token _must_ be...
812         if (!lex.checkFor("\\lyxformat")) {
813                 Alert::error(_("Document format failure"),
814                              bformat(_("%1$s is not a readable LyX document."),
815                                        from_utf8(filename.absFilename())));
816                 return failure;
817         }
818
819         string tmp_format;
820         lex >> tmp_format;
821         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
822         // if present remove ".," from string.
823         size_t dot = tmp_format.find_first_of(".,");
824         //lyxerr << "           dot found at " << dot << endl;
825         if (dot != string::npos)
826                         tmp_format.erase(dot, 1);
827         int const file_format = convert<int>(tmp_format);
828         //lyxerr << "format: " << file_format << endl;
829
830         // save timestamp and checksum of the original disk file, making sure
831         // to not overwrite them with those of the file created in the tempdir
832         // when it has to be converted to the current format.
833         if (!d->checksum_) {
834                 // Save the timestamp and checksum of disk file. If filename is an
835                 // emergency file, save the timestamp and checksum of the original lyx file
836                 // because isExternallyModified will check for this file. (BUG4193)
837                 string diskfile = filename.absFilename();
838                 if (suffixIs(diskfile, ".emergency"))
839                         diskfile = diskfile.substr(0, diskfile.size() - 10);
840                 saveCheckSum(FileName(diskfile));
841         }
842
843         if (file_format != LYX_FORMAT) {
844
845                 if (fromstring)
846                         // lyx2lyx would fail
847                         return wrongversion;
848
849                 FileName const tmpfile = FileName::tempName("Buffer_readFile");
850                 if (tmpfile.empty()) {
851                         Alert::error(_("Conversion failed"),
852                                      bformat(_("%1$s is from a different"
853                                               " version of LyX, but a temporary"
854                                               " file for converting it could"
855                                               " not be created."),
856                                               from_utf8(filename.absFilename())));
857                         return failure;
858                 }
859                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
860                 if (lyx2lyx.empty()) {
861                         Alert::error(_("Conversion script not found"),
862                                      bformat(_("%1$s is from a different"
863                                                " version of LyX, but the"
864                                                " conversion script lyx2lyx"
865                                                " could not be found."),
866                                                from_utf8(filename.absFilename())));
867                         return failure;
868                 }
869                 ostringstream command;
870                 command << os::python()
871                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
872                         << " -t " << convert<string>(LYX_FORMAT)
873                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
874                         << ' ' << quoteName(filename.toFilesystemEncoding());
875                 string const command_str = command.str();
876
877                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
878
879                 cmd_ret const ret = runCommand(command_str);
880                 if (ret.first != 0) {
881                         Alert::error(_("Conversion script failed"),
882                                      bformat(_("%1$s is from a different version"
883                                               " of LyX, but the lyx2lyx script"
884                                               " failed to convert it."),
885                                               from_utf8(filename.absFilename())));
886                         return failure;
887                 } else {
888                         bool const ret = readFile(tmpfile);
889                         // Do stuff with tmpfile name and buffer name here.
890                         return ret ? success : failure;
891                 }
892
893         }
894
895         if (readDocument(lex)) {
896                 Alert::error(_("Document format failure"),
897                              bformat(_("%1$s ended unexpectedly, which means"
898                                                     " that it is probably corrupted."),
899                                        from_utf8(filename.absFilename())));
900         }
901
902         d->file_fully_loaded = true;
903         return success;
904 }
905
906
907 // Should probably be moved to somewhere else: BufferView? LyXView?
908 bool Buffer::save() const
909 {
910         // We don't need autosaves in the immediate future. (Asger)
911         resetAutosaveTimers();
912
913         string const encodedFilename = d->filename.toFilesystemEncoding();
914
915         FileName backupName;
916         bool madeBackup = false;
917
918         // make a backup if the file already exists
919         if (lyxrc.make_backup && fileName().exists()) {
920                 backupName = FileName(absFileName() + '~');
921                 if (!lyxrc.backupdir_path.empty()) {
922                         string const mangledName =
923                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
924                         backupName = FileName(addName(lyxrc.backupdir_path,
925                                                       mangledName));
926                 }
927                 if (fileName().copyTo(backupName)) {
928                         madeBackup = true;
929                 } else {
930                         Alert::error(_("Backup failure"),
931                                      bformat(_("Cannot create backup file %1$s.\n"
932                                                "Please check whether the directory exists and is writeable."),
933                                              from_utf8(backupName.absFilename())));
934                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
935                 }
936         }
937
938         // ask if the disk file has been externally modified (use checksum method)
939         if (fileName().exists() && isExternallyModified(checksum_method)) {
940                 docstring const file = makeDisplayPath(absFileName(), 20);
941                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
942                                                              "you want to overwrite this file?"), file);
943                 int const ret = Alert::prompt(_("Overwrite modified file?"),
944                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
945                 if (ret == 1)
946                         return false;
947         }
948
949         if (writeFile(d->filename)) {
950                 markClean();
951                 return true;
952         } else {
953                 // Saving failed, so backup is not backup
954                 if (madeBackup)
955                         backupName.moveTo(d->filename);
956                 return false;
957         }
958 }
959
960
961 bool Buffer::writeFile(FileName const & fname) const
962 {
963         if (d->read_only && fname == d->filename)
964                 return false;
965
966         bool retval = false;
967
968         docstring const str = bformat(_("Saving document %1$s..."),
969                 makeDisplayPath(fname.absFilename()));
970         message(str);
971
972         if (params().compressed) {
973                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
974                 retval = ofs && write(ofs);
975         } else {
976                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
977                 retval = ofs && write(ofs);
978         }
979
980         if (!retval) {
981                 message(str + _(" could not write file!"));
982                 return false;
983         }
984
985         removeAutosaveFile();
986
987         saveCheckSum(d->filename);
988         message(str + _(" done."));
989
990         return true;
991 }
992
993
994 docstring Buffer::emergencyWrite()
995 {
996         // No need to save if the buffer has not changed.
997         if (isClean())
998                 return docstring();
999
1000         string const doc = isUnnamed() ? onlyFilename(absFileName()) : absFileName();
1001
1002         docstring user_message = bformat(
1003                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1004
1005         // We try to save three places:
1006         // 1) Same place as document. Unless it is an unnamed doc.
1007         if (!isUnnamed()) {
1008                 string s = absFileName();
1009                 s += ".emergency";
1010                 LYXERR0("  " << s);
1011                 if (writeFile(FileName(s))) {
1012                         markClean();
1013                         user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1014                         return user_message;
1015                 } else {
1016                         user_message += _("  Save failed! Trying again...\n");
1017                 }
1018         }
1019
1020         // 2) In HOME directory.
1021         string s = addName(package().home_dir().absFilename(), absFileName());
1022         s += ".emergency";
1023         lyxerr << ' ' << s << endl;
1024         if (writeFile(FileName(s))) {
1025                 markClean();
1026                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1027                 return user_message;
1028         }
1029
1030         user_message += _("  Save failed! Trying yet again...\n");
1031
1032         // 3) In "/tmp" directory.
1033         // MakeAbsPath to prepend the current
1034         // drive letter on OS/2
1035         s = addName(package().temp_dir().absFilename(), absFileName());
1036         s += ".emergency";
1037         lyxerr << ' ' << s << endl;
1038         if (writeFile(FileName(s))) {
1039                 markClean();
1040                 user_message += bformat(_("  Saved to %1$s. Phew.\n"), from_utf8(s));
1041                 return user_message;
1042         }
1043
1044         user_message += _("  Save failed! Bummer. Document is lost.");
1045         // Don't try again.
1046         markClean();
1047         return user_message;
1048 }
1049
1050
1051 bool Buffer::write(ostream & ofs) const
1052 {
1053 #ifdef HAVE_LOCALE
1054         // Use the standard "C" locale for file output.
1055         ofs.imbue(locale::classic());
1056 #endif
1057
1058         // The top of the file should not be written by params().
1059
1060         // write out a comment in the top of the file
1061         ofs << "#LyX " << lyx_version
1062             << " created this file. For more info see http://www.lyx.org/\n"
1063             << "\\lyxformat " << LYX_FORMAT << "\n"
1064             << "\\begin_document\n";
1065
1066         /// For each author, set 'used' to true if there is a change
1067         /// by this author in the document; otherwise set it to 'false'.
1068         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1069         AuthorList::Authors::const_iterator a_end = params().authors().end();
1070         for (; a_it != a_end; ++a_it)
1071                 a_it->setUsed(false);
1072
1073         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1074         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1075         for ( ; it != end; ++it)
1076                 it->checkAuthors(params().authors());
1077
1078         // now write out the buffer parameters.
1079         ofs << "\\begin_header\n";
1080         params().writeFile(ofs);
1081         ofs << "\\end_header\n";
1082
1083         // write the text
1084         ofs << "\n\\begin_body\n";
1085         text().write(ofs);
1086         ofs << "\n\\end_body\n";
1087
1088         // Write marker that shows file is complete
1089         ofs << "\\end_document" << endl;
1090
1091         // Shouldn't really be needed....
1092         //ofs.close();
1093
1094         // how to check if close went ok?
1095         // Following is an attempt... (BE 20001011)
1096
1097         // good() returns false if any error occured, including some
1098         //        formatting error.
1099         // bad()  returns true if something bad happened in the buffer,
1100         //        which should include file system full errors.
1101
1102         bool status = true;
1103         if (!ofs) {
1104                 status = false;
1105                 lyxerr << "File was not closed properly." << endl;
1106         }
1107
1108         return status;
1109 }
1110
1111
1112 bool Buffer::makeLaTeXFile(FileName const & fname,
1113                            string const & original_path,
1114                            OutputParams const & runparams_in,
1115                            bool output_preamble, bool output_body) const
1116 {
1117         OutputParams runparams = runparams_in;
1118         if (params().useXetex)
1119                 runparams.flavor = OutputParams::XETEX;
1120
1121         string const encoding = runparams.encoding->iconvName();
1122         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
1123
1124         ofdocstream ofs;
1125         try { ofs.reset(encoding); }
1126         catch (iconv_codecvt_facet_exception & e) {
1127                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1128                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1129                         "verify that the support software for your encoding (%1$s) is "
1130                         "properly installed"), from_ascii(encoding)));
1131                 return false;
1132         }
1133         if (!openFileWrite(ofs, fname))
1134                 return false;
1135
1136         //TexStream ts(ofs.rdbuf(), &texrow());
1137         ErrorList & errorList = d->errorLists["Export"];
1138         errorList.clear();
1139         bool failed_export = false;
1140         try {
1141                 d->texrow.reset();
1142                 writeLaTeXSource(ofs, original_path,
1143                       runparams, output_preamble, output_body);
1144         }
1145         catch (EncodingException & e) {
1146                 odocstringstream ods;
1147                 ods.put(e.failed_char);
1148                 ostringstream oss;
1149                 oss << "0x" << hex << e.failed_char << dec;
1150                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1151                                           " (code point %2$s)"),
1152                                           ods.str(), from_utf8(oss.str()));
1153                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1154                                 "representable in the chosen encoding.\n"
1155                                 "Changing the document encoding to utf8 could help."),
1156                                 e.par_id, e.pos, e.pos + 1));
1157                 failed_export = true;
1158         }
1159         catch (iconv_codecvt_facet_exception & e) {
1160                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1161                         _(e.what()), -1, 0, 0));
1162                 failed_export = true;
1163         }
1164         catch (exception const & e) {
1165                 errorList.push_back(ErrorItem(_("conversion failed"),
1166                         _(e.what()), -1, 0, 0));
1167                 failed_export = true;
1168         }
1169         catch (...) {
1170                 lyxerr << "Caught some really weird exception..." << endl;
1171                 lyx_exit(1);
1172         }
1173
1174         ofs.close();
1175         if (ofs.fail()) {
1176                 failed_export = true;
1177                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1178         }
1179
1180         errors("Export");
1181         return !failed_export;
1182 }
1183
1184
1185 void Buffer::writeLaTeXSource(odocstream & os,
1186                            string const & original_path,
1187                            OutputParams const & runparams_in,
1188                            bool const output_preamble, bool const output_body) const
1189 {
1190         // The child documents, if any, shall be already loaded at this point.
1191
1192         OutputParams runparams = runparams_in;
1193
1194         // Classify the unicode characters appearing in math insets
1195         Encodings::initUnicodeMath(*this);
1196
1197         // validate the buffer.
1198         LYXERR(Debug::LATEX, "  Validating buffer...");
1199         LaTeXFeatures features(*this, params(), runparams);
1200         validate(features);
1201         LYXERR(Debug::LATEX, "  Buffer validation done.");
1202
1203         // The starting paragraph of the coming rows is the
1204         // first paragraph of the document. (Asger)
1205         if (output_preamble && runparams.nice) {
1206                 os << "%% LyX " << lyx_version << " created this file.  "
1207                         "For more info, see http://www.lyx.org/.\n"
1208                         "%% Do not edit unless you really know what "
1209                         "you are doing.\n";
1210                 d->texrow.newline();
1211                 d->texrow.newline();
1212         }
1213         LYXERR(Debug::INFO, "lyx document header finished");
1214
1215         // Don't move this behind the parent_buffer=0 code below,
1216         // because then the macros will not get the right "redefinition"
1217         // flag as they don't see the parent macros which are output before.
1218         updateMacros();
1219
1220         // fold macros if possible, still with parent buffer as the
1221         // macros will be put in the prefix anyway.
1222         updateMacroInstances();
1223
1224         // There are a few differences between nice LaTeX and usual files:
1225         // usual is \batchmode and has a
1226         // special input@path to allow the including of figures
1227         // with either \input or \includegraphics (what figinsets do).
1228         // input@path is set when the actual parameter
1229         // original_path is set. This is done for usual tex-file, but not
1230         // for nice-latex-file. (Matthias 250696)
1231         // Note that input@path is only needed for something the user does
1232         // in the preamble, included .tex files or ERT, files included by
1233         // LyX work without it.
1234         if (output_preamble) {
1235                 if (!runparams.nice) {
1236                         // code for usual, NOT nice-latex-file
1237                         os << "\\batchmode\n"; // changed
1238                         // from \nonstopmode
1239                         d->texrow.newline();
1240                 }
1241                 if (!original_path.empty()) {
1242                         // FIXME UNICODE
1243                         // We don't know the encoding of inputpath
1244                         docstring const inputpath = from_utf8(latex_path(original_path));
1245                         os << "\\makeatletter\n"
1246                            << "\\def\\input@path{{"
1247                            << inputpath << "/}}\n"
1248                            << "\\makeatother\n";
1249                         d->texrow.newline();
1250                         d->texrow.newline();
1251                         d->texrow.newline();
1252                 }
1253
1254                 // get parent macros (if this buffer has a parent) which will be
1255                 // written at the document begin further down.
1256                 MacroSet parentMacros;
1257                 listParentMacros(parentMacros, features);
1258
1259                 // Write the preamble
1260                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1261
1262                 runparams.use_japanese = features.isRequired("japanese");
1263
1264                 if (!output_body)
1265                         return;
1266
1267                 // make the body.
1268                 os << "\\begin{document}\n";
1269                 d->texrow.newline();
1270
1271                 // output the parent macros
1272                 MacroSet::iterator it = parentMacros.begin();
1273                 MacroSet::iterator end = parentMacros.end();
1274                 for (; it != end; ++it)
1275                         (*it)->write(os, true);
1276         } // output_preamble
1277
1278         d->texrow.start(paragraphs().begin()->id(), 0);
1279
1280         LYXERR(Debug::INFO, "preamble finished, now the body.");
1281
1282         // if we are doing a real file with body, even if this is the
1283         // child of some other buffer, let's cut the link here.
1284         // This happens for example if only a child document is printed.
1285         Buffer const * save_parent = 0;
1286         if (output_preamble) {
1287                 save_parent = d->parent();
1288                 d->setParent(0);
1289         }
1290
1291         // the real stuff
1292         latexParagraphs(*this, text(), os, d->texrow, runparams);
1293
1294         // Restore the parenthood if needed
1295         if (output_preamble)
1296                 d->setParent(save_parent);
1297
1298         // add this just in case after all the paragraphs
1299         os << endl;
1300         d->texrow.newline();
1301
1302         if (output_preamble) {
1303                 os << "\\end{document}\n";
1304                 d->texrow.newline();
1305                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1306         } else {
1307                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1308         }
1309         runparams_in.encoding = runparams.encoding;
1310
1311         // Just to be sure. (Asger)
1312         d->texrow.newline();
1313
1314         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1315         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1316 }
1317
1318
1319 bool Buffer::isLatex() const
1320 {
1321         return params().documentClass().outputType() == LATEX;
1322 }
1323
1324
1325 bool Buffer::isLiterate() const
1326 {
1327         return params().documentClass().outputType() == LITERATE;
1328 }
1329
1330
1331 bool Buffer::isDocBook() const
1332 {
1333         return params().documentClass().outputType() == DOCBOOK;
1334 }
1335
1336
1337 void Buffer::makeDocBookFile(FileName const & fname,
1338                               OutputParams const & runparams,
1339                               bool const body_only) const
1340 {
1341         LYXERR(Debug::LATEX, "makeDocBookFile...");
1342
1343         ofdocstream ofs;
1344         if (!openFileWrite(ofs, fname))
1345                 return;
1346
1347         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1348
1349         ofs.close();
1350         if (ofs.fail())
1351                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1352 }
1353
1354
1355 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1356                              OutputParams const & runparams,
1357                              bool const only_body) const
1358 {
1359         LaTeXFeatures features(*this, params(), runparams);
1360         validate(features);
1361
1362         d->texrow.reset();
1363
1364         DocumentClass const & tclass = params().documentClass();
1365         string const top_element = tclass.latexname();
1366
1367         if (!only_body) {
1368                 if (runparams.flavor == OutputParams::XML)
1369                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1370
1371                 // FIXME UNICODE
1372                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1373
1374                 // FIXME UNICODE
1375                 if (! tclass.class_header().empty())
1376                         os << from_ascii(tclass.class_header());
1377                 else if (runparams.flavor == OutputParams::XML)
1378                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1379                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1380                 else
1381                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1382
1383                 docstring preamble = from_utf8(params().preamble);
1384                 if (runparams.flavor != OutputParams::XML ) {
1385                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1386                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1387                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1388                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1389                 }
1390
1391                 string const name = runparams.nice
1392                         ? changeExtension(absFileName(), ".sgml") : fname;
1393                 preamble += features.getIncludedFiles(name);
1394                 preamble += features.getLyXSGMLEntities();
1395
1396                 if (!preamble.empty()) {
1397                         os << "\n [ " << preamble << " ]";
1398                 }
1399                 os << ">\n\n";
1400         }
1401
1402         string top = top_element;
1403         top += " lang=\"";
1404         if (runparams.flavor == OutputParams::XML)
1405                 top += params().language->code();
1406         else
1407                 top += params().language->code().substr(0, 2);
1408         top += '"';
1409
1410         if (!params().options.empty()) {
1411                 top += ' ';
1412                 top += params().options;
1413         }
1414
1415         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1416             << " file was created by LyX " << lyx_version
1417             << "\n  See http://www.lyx.org/ for more information -->\n";
1418
1419         params().documentClass().counters().reset();
1420
1421         updateMacros();
1422
1423         sgml::openTag(os, top);
1424         os << '\n';
1425         docbookParagraphs(text(), *this, os, runparams);
1426         sgml::closeTag(os, top_element);
1427 }
1428
1429
1430 void Buffer::makeLyXHTMLFile(FileName const & fname,
1431                               OutputParams const & runparams,
1432                               bool const body_only) const
1433 {
1434         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1435
1436         ofdocstream ofs;
1437         if (!openFileWrite(ofs, fname))
1438                 return;
1439
1440         writeLyXHTMLSource(ofs, runparams, body_only);
1441
1442         ofs.close();
1443         if (ofs.fail())
1444                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1445 }
1446
1447
1448 void Buffer::writeLyXHTMLSource(odocstream & os,
1449                              OutputParams const & runparams,
1450                              bool const only_body) const
1451 {
1452         LaTeXFeatures features(*this, params(), runparams);
1453         validate(features);
1454         updateLabels(UpdateMaster, true);
1455
1456         d->texrow.reset();
1457
1458         if (!only_body) {
1459                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1460                 os << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd\">\n";
1461                 // FIXME Language should be set properly.
1462                 os << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
1463                 // FIXME Header
1464                 os << "<head>\n";
1465                 // FIXME Presumably need to set this right
1466                 os << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1467                 // FIXME Get this during validation? What about other meta-data?
1468                 os << "<title>TBA</title>\n";
1469
1470                 os << "\n<!-- Text Class Preamble -->\n"
1471                         << features.getTClassHTMLPreamble()
1472                         << "\n<!-- Premable Snippets -->\n"
1473                         << from_utf8(features.getPreambleSnippets());
1474
1475                 os << "\n<!-- Layout-provided Styles -->\n";
1476                 docstring const styleinfo = features.getTClassHTMLStyles();
1477                 if (!styleinfo.empty()) {
1478                         os << "<style type='text/css'>\n"
1479                                 << styleinfo
1480                                 << "</style>\n";
1481                 }
1482                 os << "</head>\n<body>\n";
1483         }
1484
1485         XHTMLStream xs(os);
1486         params().documentClass().counters().reset();
1487         xhtmlParagraphs(text(), *this, xs, runparams);
1488         if (!only_body)
1489                 os << "</body>\n</html>\n";
1490 }
1491
1492
1493 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1494 // Other flags: -wall -v0 -x
1495 int Buffer::runChktex()
1496 {
1497         setBusy(true);
1498
1499         // get LaTeX-Filename
1500         FileName const path(temppath());
1501         string const name = addName(path.absFilename(), latexName());
1502         string const org_path = filePath();
1503
1504         PathChanger p(path); // path to LaTeX file
1505         message(_("Running chktex..."));
1506
1507         // Generate the LaTeX file if neccessary
1508         OutputParams runparams(&params().encoding());
1509         runparams.flavor = OutputParams::LATEX;
1510         runparams.nice = false;
1511         makeLaTeXFile(FileName(name), org_path, runparams);
1512
1513         TeXErrors terr;
1514         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1515         int const res = chktex.run(terr); // run chktex
1516
1517         if (res == -1) {
1518                 Alert::error(_("chktex failure"),
1519                              _("Could not run chktex successfully."));
1520         } else if (res > 0) {
1521                 ErrorList & errlist = d->errorLists["ChkTeX"];
1522                 errlist.clear();
1523                 bufferErrors(terr, errlist);
1524         }
1525
1526         setBusy(false);
1527
1528         errors("ChkTeX");
1529
1530         return res;
1531 }
1532
1533
1534 void Buffer::validate(LaTeXFeatures & features) const
1535 {
1536         params().validate(features);
1537
1538         updateMacros();
1539
1540         for_each(paragraphs().begin(), paragraphs().end(),
1541                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1542
1543         if (lyxerr.debugging(Debug::LATEX)) {
1544                 features.showStruct();
1545         }
1546 }
1547
1548
1549 void Buffer::getLabelList(vector<docstring> & list) const
1550 {
1551         // If this is a child document, use the parent's list instead.
1552         Buffer const * const pbuf = d->parent();
1553         if (pbuf) {
1554                 pbuf->getLabelList(list);
1555                 return;
1556         }
1557
1558         list.clear();
1559         Toc & toc = d->toc_backend.toc("label");
1560         TocIterator toc_it = toc.begin();
1561         TocIterator end = toc.end();
1562         for (; toc_it != end; ++toc_it) {
1563                 if (toc_it->depth() == 0)
1564                         list.push_back(toc_it->str());
1565         }
1566 }
1567
1568
1569 void Buffer::updateBibfilesCache(UpdateScope scope) const
1570 {
1571         // If this is a child document, use the parent's cache instead.
1572         Buffer const * const pbuf = d->parent();
1573         if (pbuf && scope != UpdateChildOnly) {
1574                 pbuf->updateBibfilesCache();
1575                 return;
1576         }
1577
1578         d->bibfilesCache_.clear();
1579         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1580                 if (it->lyxCode() == BIBTEX_CODE) {
1581                         InsetBibtex const & inset =
1582                                 static_cast<InsetBibtex const &>(*it);
1583                         support::FileNameList const bibfiles = inset.getBibFiles();
1584                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1585                                 bibfiles.begin(),
1586                                 bibfiles.end());
1587                 } else if (it->lyxCode() == INCLUDE_CODE) {
1588                         InsetInclude & inset =
1589                                 static_cast<InsetInclude &>(*it);
1590                         inset.updateBibfilesCache();
1591                         support::FileNameList const & bibfiles =
1592                                         inset.getBibfilesCache();
1593                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1594                                 bibfiles.begin(),
1595                                 bibfiles.end());
1596                 }
1597         }
1598         // the bibinfo cache is now invalid
1599         d->bibinfoCacheValid_ = false;
1600 }
1601
1602
1603 void Buffer::invalidateBibinfoCache()
1604 {
1605         d->bibinfoCacheValid_ = false;
1606 }
1607
1608
1609 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
1610 {
1611         // If this is a child document, use the parent's cache instead.
1612         Buffer const * const pbuf = d->parent();
1613         if (pbuf && scope != UpdateChildOnly)
1614                 return pbuf->getBibfilesCache();
1615
1616         // We update the cache when first used instead of at loading time.
1617         if (d->bibfilesCache_.empty())
1618                 const_cast<Buffer *>(this)->updateBibfilesCache(scope);
1619
1620         return d->bibfilesCache_;
1621 }
1622
1623
1624 BiblioInfo const & Buffer::masterBibInfo() const
1625 {
1626         // if this is a child document and the parent is already loaded
1627         // use the parent's list instead  [ale990412]
1628         Buffer const * const tmp = masterBuffer();
1629         LASSERT(tmp, /**/);
1630         if (tmp != this)
1631                 return tmp->masterBibInfo();
1632         return localBibInfo();
1633 }
1634
1635
1636 BiblioInfo const & Buffer::localBibInfo() const
1637 {
1638         if (d->bibinfoCacheValid_) {
1639                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1640                 // compare the cached timestamps with the actual ones.
1641                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1642                 support::FileNameList::const_iterator en = bibfilesCache.end();
1643                 for (; ei != en; ++ ei) {
1644                         time_t lastw = ei->lastModified();
1645                         if (lastw != d->bibfileStatus_[*ei]) {
1646                                 d->bibinfoCacheValid_ = false;
1647                                 d->bibfileStatus_[*ei] = lastw;
1648                                 break;
1649                         }
1650                 }
1651         }
1652
1653         if (!d->bibinfoCacheValid_) {
1654                 d->bibinfo_.clear();
1655                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1656                         it->fillWithBibKeys(d->bibinfo_, it);
1657                 d->bibinfoCacheValid_ = true;
1658         }
1659         return d->bibinfo_;
1660 }
1661
1662
1663 bool Buffer::isDepClean(string const & name) const
1664 {
1665         DepClean::const_iterator const it = d->dep_clean.find(name);
1666         if (it == d->dep_clean.end())
1667                 return true;
1668         return it->second;
1669 }
1670
1671
1672 void Buffer::markDepClean(string const & name)
1673 {
1674         d->dep_clean[name] = true;
1675 }
1676
1677
1678 bool Buffer::isExportableFormat(string const & format) const
1679 {
1680                 typedef vector<Format const *> Formats;
1681                 Formats formats;
1682                 formats = exportableFormats(true);
1683                 Formats::const_iterator fit = formats.begin();
1684                 Formats::const_iterator end = formats.end();
1685                 for (; fit != end ; ++fit) {
1686                         if ((*fit)->name() == format)
1687                                 return true;
1688                 }
1689                 return false;
1690 }
1691
1692
1693 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1694 {
1695         if (isInternal()) {
1696                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1697                 // if internal, put a switch '(cmd.action)' here.
1698                 return false;
1699         }
1700
1701         bool enable = true;
1702
1703         switch (cmd.action) {
1704
1705                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1706                         flag.setOnOff(isReadonly());
1707                         break;
1708
1709                 // FIXME: There is need for a command-line import.
1710                 //case LFUN_BUFFER_IMPORT:
1711
1712                 case LFUN_BUFFER_AUTO_SAVE:
1713                         break;
1714
1715                 case LFUN_BUFFER_EXPORT_CUSTOM:
1716                         // FIXME: Nothing to check here?
1717                         break;
1718
1719                 case LFUN_BUFFER_EXPORT: {
1720                         docstring const arg = cmd.argument();
1721                         enable = arg == "custom" || isExportable(to_utf8(arg));
1722                         if (!enable)
1723                                 flag.message(bformat(
1724                                         _("Don't know how to export to format: %1$s"), arg));
1725                         break;
1726                 }
1727
1728                 case LFUN_BUFFER_CHKTEX:
1729                         enable = isLatex() && !lyxrc.chktex_command.empty();
1730                         break;
1731
1732                 case LFUN_BUILD_PROGRAM:
1733                         enable = isExportable("program");
1734                         break;
1735
1736                 case LFUN_BRANCH_ACTIVATE: 
1737                 case LFUN_BRANCH_DEACTIVATE: {
1738                         BranchList const & branchList = params().branchlist();
1739                         docstring const branchName = cmd.argument();
1740                         enable = !branchName.empty() && branchList.find(branchName);
1741                         break;
1742                 }
1743
1744                 case LFUN_BRANCH_ADD:
1745                 case LFUN_BRANCHES_RENAME:
1746                 case LFUN_BUFFER_PRINT:
1747                         // if no Buffer is present, then of course we won't be called!
1748                         break;
1749
1750                 case LFUN_BUFFER_LANGUAGE:
1751                         enable = !isReadonly();
1752                         break;
1753
1754                 default:
1755                         return false;
1756         }
1757         flag.setEnabled(enable);
1758         return true;
1759 }
1760
1761
1762 void Buffer::dispatch(string const & command, DispatchResult & result)
1763 {
1764         return dispatch(lyxaction.lookupFunc(command), result);
1765 }
1766
1767
1768 // NOTE We can end up here even if we have no GUI, because we are called
1769 // by LyX::exec to handled command-line requests. So we may need to check 
1770 // whether we have a GUI or not. The boolean use_gui holds this information.
1771 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1772 {
1773         if (isInternal()) {
1774                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1775                 // if internal, put a switch '(cmd.action)' here.
1776                 dr.dispatched(false);
1777                 return;
1778         }
1779         string const argument = to_utf8(func.argument());
1780         // We'll set this back to false if need be.
1781         bool dispatched = true;
1782         undo().beginUndoGroup();
1783
1784         switch (func.action) {
1785         case LFUN_BUFFER_TOGGLE_READ_ONLY:
1786                 if (lyxvc().inUse())
1787                         lyxvc().toggleReadOnly();
1788                 else
1789                         setReadonly(!isReadonly());
1790                 break;
1791
1792         case LFUN_BUFFER_EXPORT: {
1793                 bool success = doExport(argument, false);
1794                 dr.setError(success);
1795                 if (!success)
1796                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1797                                               func.argument()));
1798                 break;
1799         }
1800
1801         case LFUN_BUILD_PROGRAM:
1802                 doExport("program", true);
1803                 break;
1804
1805         case LFUN_BUFFER_CHKTEX:
1806                 runChktex();
1807                 break;
1808
1809         case LFUN_BUFFER_EXPORT_CUSTOM: {
1810                 string format_name;
1811                 string command = split(argument, format_name, ' ');
1812                 Format const * format = formats.getFormat(format_name);
1813                 if (!format) {
1814                         lyxerr << "Format \"" << format_name
1815                                 << "\" not recognized!"
1816                                 << endl;
1817                         break;
1818                 }
1819
1820                 // The name of the file created by the conversion process
1821                 string filename;
1822
1823                 // Output to filename
1824                 if (format->name() == "lyx") {
1825                         string const latexname = latexName(false);
1826                         filename = changeExtension(latexname,
1827                                 format->extension());
1828                         filename = addName(temppath(), filename);
1829
1830                         if (!writeFile(FileName(filename)))
1831                                 break;
1832
1833                 } else {
1834                         doExport(format_name, true, filename);
1835                 }
1836
1837                 // Substitute $$FName for filename
1838                 if (!contains(command, "$$FName"))
1839                         command = "( " + command + " ) < $$FName";
1840                 command = subst(command, "$$FName", filename);
1841
1842                 // Execute the command in the background
1843                 Systemcall call;
1844                 call.startscript(Systemcall::DontWait, command);
1845                 break;
1846         }
1847
1848         // FIXME: There is need for a command-line import.
1849         /*
1850         case LFUN_BUFFER_IMPORT:
1851                 doImport(argument);
1852                 break;
1853         */
1854
1855         case LFUN_BUFFER_AUTO_SAVE:
1856                 autoSave();
1857                 break;
1858
1859         case LFUN_BRANCH_ADD: {
1860                 docstring const branch_name = func.argument();
1861                 if (branch_name.empty()) {
1862                         dispatched = false;
1863                         break;
1864                 }
1865                 BranchList & branch_list = params().branchlist();
1866                 Branch * branch = branch_list.find(branch_name);
1867                 if (branch) {
1868                         LYXERR0("Branch " << branch_name << " already exists.");
1869                         dr.setError(true);
1870                         docstring const msg = 
1871                                 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1872                         dr.setMessage(msg);
1873                 } else {
1874                         branch_list.add(branch_name);
1875                         branch = branch_list.find(branch_name);
1876                         string const x11hexname = X11hexname(branch->color());
1877                         docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1878                         lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));        
1879                         dr.setError(false);
1880                         dr.update(Update::Force);
1881                 }
1882                 break;
1883         }
1884
1885         case LFUN_BRANCH_ACTIVATE:
1886         case LFUN_BRANCH_DEACTIVATE: {
1887                 BranchList & branchList = params().branchlist();
1888                 docstring const branchName = func.argument();
1889                 // the case without a branch name is handled elsewhere
1890                 if (branchName.empty()) {
1891                         dispatched = false;
1892                         break;
1893                 }
1894                 Branch * branch = branchList.find(branchName);
1895                 if (!branch) {
1896                         LYXERR0("Branch " << branchName << " does not exist.");
1897                         dr.setError(true);
1898                         docstring const msg = 
1899                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1900                         dr.setMessage(msg);
1901                 } else {
1902                         branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1903                         dr.setError(false);
1904                         dr.update(Update::Force);
1905                 }
1906                 break;
1907         }
1908
1909         case LFUN_BRANCHES_RENAME: {
1910                 if (func.argument().empty())
1911                         break;
1912
1913                 docstring const oldname = from_utf8(func.getArg(0));
1914                 docstring const newname = from_utf8(func.getArg(1));
1915                 InsetIterator it  = inset_iterator_begin(inset());
1916                 InsetIterator const end = inset_iterator_end(inset());
1917                 bool success = false;
1918                 for (; it != end; ++it) {
1919                         if (it->lyxCode() == BRANCH_CODE) {
1920                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1921                                 if (ins.branch() == oldname) {
1922                                         undo().recordUndo(it);
1923                                         ins.rename(newname);
1924                                         success = true;
1925                                         continue;
1926                                 }
1927                         }
1928                         if (it->lyxCode() == INCLUDE_CODE) {
1929                                 // get buffer of external file
1930                                 InsetInclude const & ins =
1931                                         static_cast<InsetInclude const &>(*it);
1932                                 Buffer * child = ins.getChildBuffer();
1933                                 if (!child)
1934                                         continue;
1935                                 child->dispatch(func, dr);
1936                         }
1937                 }
1938
1939                 if (success)
1940                         dr.update(Update::Force);
1941                 break;
1942         }
1943
1944         case LFUN_BUFFER_PRINT: {
1945                 // we'll assume there's a problem until we succeed
1946                 dr.setError(true); 
1947                 string target = func.getArg(0);
1948                 string target_name = func.getArg(1);
1949                 string command = func.getArg(2);
1950
1951                 if (target.empty()
1952                     || target_name.empty()
1953                     || command.empty()) {
1954                         LYXERR0("Unable to parse " << func.argument());
1955                         docstring const msg = 
1956                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
1957                         dr.setMessage(msg);
1958                         break;
1959                 }
1960                 if (target != "printer" && target != "file") {
1961                         LYXERR0("Unrecognized target \"" << target << '"');
1962                         docstring const msg = 
1963                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1964                         dr.setMessage(msg);
1965                         break;
1966                 }
1967
1968                 if (!doExport("dvi", true)) {
1969                         showPrintError(absFileName());
1970                         dr.setMessage(_("Error exporting to DVI."));
1971                         break;
1972                 }
1973
1974                 // Push directory path.
1975                 string const path = temppath();
1976                 // Prevent the compiler from optimizing away p
1977                 FileName pp(path);
1978                 PathChanger p(pp);
1979
1980                 // there are three cases here:
1981                 // 1. we print to a file
1982                 // 2. we print directly to a printer
1983                 // 3. we print using a spool command (print to file first)
1984                 Systemcall one;
1985                 int res = 0;
1986                 string const dviname = changeExtension(latexName(true), "dvi");
1987
1988                 if (target == "printer") {
1989                         if (!lyxrc.print_spool_command.empty()) {
1990                                 // case 3: print using a spool
1991                                 string const psname = changeExtension(dviname,".ps");
1992                                 command += ' ' + lyxrc.print_to_file
1993                                         + quoteName(psname)
1994                                         + ' '
1995                                         + quoteName(dviname);
1996
1997                                 string command2 = lyxrc.print_spool_command + ' ';
1998                                 if (target_name != "default") {
1999                                         command2 += lyxrc.print_spool_printerprefix
2000                                                 + target_name
2001                                                 + ' ';
2002                                 }
2003                                 command2 += quoteName(psname);
2004                                 // First run dvips.
2005                                 // If successful, then spool command
2006                                 res = one.startscript(Systemcall::Wait, command);
2007
2008                                 if (res == 0) {
2009                                         // If there's no GUI, we have to wait on this command. Otherwise,
2010                                         // LyX deletes the temporary directory, and with it the spooled
2011                                         // file, before it can be printed!!
2012                                         Systemcall::Starttype stype = use_gui ?
2013                                                 Systemcall::DontWait : Systemcall::Wait;
2014                                         res = one.startscript(stype, command2);
2015                                 }
2016                         } else {
2017                                 // case 2: print directly to a printer
2018                                 if (target_name != "default")
2019                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2020                                 // as above....
2021                                 Systemcall::Starttype stype = use_gui ?
2022                                         Systemcall::DontWait : Systemcall::Wait;
2023                                 res = one.startscript(stype, command + quoteName(dviname));
2024                         }
2025
2026                 } else {
2027                         // case 1: print to a file
2028                         FileName const filename(makeAbsPath(target_name, filePath()));
2029                         FileName const dvifile(makeAbsPath(dviname, path));
2030                         if (filename.exists()) {
2031                                 docstring text = bformat(
2032                                         _("The file %1$s already exists.\n\n"
2033                                           "Do you want to overwrite that file?"),
2034                                         makeDisplayPath(filename.absFilename()));
2035                                 if (Alert::prompt(_("Overwrite file?"),
2036                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2037                                         break;
2038                         }
2039                         command += ' ' + lyxrc.print_to_file
2040                                 + quoteName(filename.toFilesystemEncoding())
2041                                 + ' '
2042                                 + quoteName(dvifile.toFilesystemEncoding());
2043                         // as above....
2044                         Systemcall::Starttype stype = use_gui ?
2045                                 Systemcall::DontWait : Systemcall::Wait;
2046                         res = one.startscript(stype, command);
2047                 }
2048
2049                 if (res == 0) 
2050                         dr.setError(false);
2051                 else {
2052                         dr.setMessage(_("Error running external commands."));
2053                         showPrintError(absFileName());
2054                 }
2055                 break;
2056         }
2057
2058         case LFUN_BUFFER_LANGUAGE: {
2059                 Language const * oldL = params().language;
2060                 Language const * newL = languages.getLanguage(argument);
2061                 if (!newL || oldL == newL)
2062                         break;
2063                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2064                         changeLanguage(oldL, newL);
2065                 break;
2066         }
2067
2068         default:
2069                 dispatched = false;
2070                 break;
2071         }
2072         dr.dispatched(dispatched);
2073         undo().endUndoGroup();
2074 }
2075
2076
2077 void Buffer::changeLanguage(Language const * from, Language const * to)
2078 {
2079         LASSERT(from, /**/);
2080         LASSERT(to, /**/);
2081
2082         for_each(par_iterator_begin(),
2083                  par_iterator_end(),
2084                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2085 }
2086
2087
2088 bool Buffer::isMultiLingual() const
2089 {
2090         ParConstIterator end = par_iterator_end();
2091         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2092                 if (it->isMultiLingual(params()))
2093                         return true;
2094
2095         return false;
2096 }
2097
2098
2099 DocIterator Buffer::getParFromID(int const id) const
2100 {
2101         Buffer * buf = const_cast<Buffer *>(this);
2102         if (id < 0) {
2103                 // John says this is called with id == -1 from undo
2104                 lyxerr << "getParFromID(), id: " << id << endl;
2105                 return doc_iterator_end(buf);
2106         }
2107
2108         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2109                 if (it.paragraph().id() == id)
2110                         return it;
2111
2112         return doc_iterator_end(buf);
2113 }
2114
2115
2116 bool Buffer::hasParWithID(int const id) const
2117 {
2118         return !getParFromID(id).atEnd();
2119 }
2120
2121
2122 ParIterator Buffer::par_iterator_begin()
2123 {
2124         return ParIterator(doc_iterator_begin(this));
2125 }
2126
2127
2128 ParIterator Buffer::par_iterator_end()
2129 {
2130         return ParIterator(doc_iterator_end(this));
2131 }
2132
2133
2134 ParConstIterator Buffer::par_iterator_begin() const
2135 {
2136         return ParConstIterator(doc_iterator_begin(this));
2137 }
2138
2139
2140 ParConstIterator Buffer::par_iterator_end() const
2141 {
2142         return ParConstIterator(doc_iterator_end(this));
2143 }
2144
2145
2146 Language const * Buffer::language() const
2147 {
2148         return params().language;
2149 }
2150
2151
2152 docstring const Buffer::B_(string const & l10n) const
2153 {
2154         return params().B_(l10n);
2155 }
2156
2157
2158 bool Buffer::isClean() const
2159 {
2160         return d->lyx_clean;
2161 }
2162
2163
2164 bool Buffer::isBakClean() const
2165 {
2166         return d->bak_clean;
2167 }
2168
2169
2170 bool Buffer::isExternallyModified(CheckMethod method) const
2171 {
2172         LASSERT(d->filename.exists(), /**/);
2173         // if method == timestamp, check timestamp before checksum
2174         return (method == checksum_method
2175                 || d->timestamp_ != d->filename.lastModified())
2176                 && d->checksum_ != d->filename.checksum();
2177 }
2178
2179
2180 void Buffer::saveCheckSum(FileName const & file) const
2181 {
2182         if (file.exists()) {
2183                 d->timestamp_ = file.lastModified();
2184                 d->checksum_ = file.checksum();
2185         } else {
2186                 // in the case of save to a new file.
2187                 d->timestamp_ = 0;
2188                 d->checksum_ = 0;
2189         }
2190 }
2191
2192
2193 void Buffer::markClean() const
2194 {
2195         if (!d->lyx_clean) {
2196                 d->lyx_clean = true;
2197                 updateTitles();
2198         }
2199         // if the .lyx file has been saved, we don't need an
2200         // autosave
2201         d->bak_clean = true;
2202 }
2203
2204
2205 void Buffer::markBakClean() const
2206 {
2207         d->bak_clean = true;
2208 }
2209
2210
2211 void Buffer::setUnnamed(bool flag)
2212 {
2213         d->unnamed = flag;
2214 }
2215
2216
2217 bool Buffer::isUnnamed() const
2218 {
2219         return d->unnamed;
2220 }
2221
2222
2223 /// \note
2224 /// Don't check unnamed, here: isInternal() is used in
2225 /// newBuffer(), where the unnamed flag has not been set by anyone
2226 /// yet. Also, for an internal buffer, there should be no need for
2227 /// retrieving fileName() nor for checking if it is unnamed or not.
2228 bool Buffer::isInternal() const
2229 {
2230         return fileName().extension() == "internal";
2231 }
2232
2233
2234 void Buffer::markDirty()
2235 {
2236         if (d->lyx_clean) {
2237                 d->lyx_clean = false;
2238                 updateTitles();
2239         }
2240         d->bak_clean = false;
2241
2242         DepClean::iterator it = d->dep_clean.begin();
2243         DepClean::const_iterator const end = d->dep_clean.end();
2244
2245         for (; it != end; ++it)
2246                 it->second = false;
2247 }
2248
2249
2250 FileName Buffer::fileName() const
2251 {
2252         return d->filename;
2253 }
2254
2255
2256 string Buffer::absFileName() const
2257 {
2258         return d->filename.absFilename();
2259 }
2260
2261
2262 string Buffer::filePath() const
2263 {
2264         return d->filename.onlyPath().absFilename() + "/";
2265 }
2266
2267
2268 bool Buffer::isReadonly() const
2269 {
2270         return d->read_only;
2271 }
2272
2273
2274 void Buffer::setParent(Buffer const * buffer)
2275 {
2276         // Avoids recursive include.
2277         d->setParent(buffer == this ? 0 : buffer);
2278         updateMacros();
2279 }
2280
2281
2282 Buffer const * Buffer::parent() const
2283 {
2284         return d->parent();
2285 }
2286
2287
2288 void Buffer::collectRelatives(BufferSet & bufs) const
2289 {
2290         bufs.insert(this);
2291         if (parent())
2292                 parent()->collectRelatives(bufs);
2293
2294         // loop over children
2295         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2296         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2297         for (; it != end; ++it)
2298                 bufs.insert(const_cast<Buffer *>(it->first));
2299 }
2300
2301
2302 std::vector<Buffer const *> Buffer::allRelatives() const
2303 {
2304         BufferSet bufs;
2305         collectRelatives(bufs);
2306         BufferSet::iterator it = bufs.begin();
2307         std::vector<Buffer const *> ret;
2308         for (; it != bufs.end(); ++it)
2309                 ret.push_back(*it);
2310         return ret;
2311 }
2312
2313
2314 Buffer const * Buffer::masterBuffer() const
2315 {
2316         Buffer const * const pbuf = d->parent();
2317         if (!pbuf)
2318                 return this;
2319
2320         return pbuf->masterBuffer();
2321 }
2322
2323
2324 bool Buffer::isChild(Buffer * child) const
2325 {
2326         return d->children_positions.find(child) != d->children_positions.end();
2327 }
2328
2329
2330 DocIterator Buffer::firstChildPosition(Buffer const * child)
2331 {
2332         Impl::BufferPositionMap::iterator it;
2333         it = d->children_positions.find(child);
2334         if (it == d->children_positions.end())
2335                 return DocIterator(this);
2336         return it->second;
2337 }
2338
2339
2340 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2341 {
2342         // loop over children
2343         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2344         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2345         for (; it != end; ++it) {
2346                 Buffer * child = const_cast<Buffer *>(it->first);
2347                 clist.push_back(child);
2348                 if (grand_children) {
2349                         // there might be grandchildren
2350                         std::vector<Buffer *> glist = child->getChildren();
2351                         for (vector<Buffer *>::const_iterator git = glist.begin();
2352                                  git != glist.end(); ++git)
2353                                 clist.push_back(*git);
2354                 }
2355         }
2356 }
2357
2358
2359 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2360 {
2361         std::vector<Buffer *> v;
2362         getChildren(v, grand_children);
2363         return v;
2364 }
2365
2366
2367 template<typename M>
2368 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2369 {
2370         if (m.empty())
2371                 return m.end();
2372
2373         typename M::iterator it = m.lower_bound(x);
2374         if (it == m.begin())
2375                 return m.end();
2376
2377         it--;
2378         return it;
2379 }
2380
2381
2382 MacroData const * Buffer::getBufferMacro(docstring const & name,
2383                                          DocIterator const & pos) const
2384 {
2385         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2386
2387         // if paragraphs have no macro context set, pos will be empty
2388         if (pos.empty())
2389                 return 0;
2390
2391         // we haven't found anything yet
2392         DocIterator bestPos = par_iterator_begin();
2393         MacroData const * bestData = 0;
2394
2395         // find macro definitions for name
2396         Impl::NamePositionScopeMacroMap::iterator nameIt
2397                 = d->macros.find(name);
2398         if (nameIt != d->macros.end()) {
2399                 // find last definition in front of pos or at pos itself
2400                 Impl::PositionScopeMacroMap::const_iterator it
2401                         = greatest_below(nameIt->second, pos);
2402                 if (it != nameIt->second.end()) {
2403                         while (true) {
2404                                 // scope ends behind pos?
2405                                 if (pos < it->second.first) {
2406                                         // Looks good, remember this. If there
2407                                         // is no external macro behind this,
2408                                         // we found the right one already.
2409                                         bestPos = it->first;
2410                                         bestData = &it->second.second;
2411                                         break;
2412                                 }
2413
2414                                 // try previous macro if there is one
2415                                 if (it == nameIt->second.begin())
2416                                         break;
2417                                 it--;
2418                         }
2419                 }
2420         }
2421
2422         // find macros in included files
2423         Impl::PositionScopeBufferMap::const_iterator it
2424                 = greatest_below(d->position_to_children, pos);
2425         if (it == d->position_to_children.end())
2426                 // no children before
2427                 return bestData;
2428
2429         while (true) {
2430                 // do we know something better (i.e. later) already?
2431                 if (it->first < bestPos )
2432                         break;
2433
2434                 // scope ends behind pos?
2435                 if (pos < it->second.first) {
2436                         // look for macro in external file
2437                         d->macro_lock = true;
2438                         MacroData const * data
2439                         = it->second.second->getMacro(name, false);
2440                         d->macro_lock = false;
2441                         if (data) {
2442                                 bestPos = it->first;
2443                                 bestData = data;
2444                                 break;
2445                         }
2446                 }
2447
2448                 // try previous file if there is one
2449                 if (it == d->position_to_children.begin())
2450                         break;
2451                 --it;
2452         }
2453
2454         // return the best macro we have found
2455         return bestData;
2456 }
2457
2458
2459 MacroData const * Buffer::getMacro(docstring const & name,
2460         DocIterator const & pos, bool global) const
2461 {
2462         if (d->macro_lock)
2463                 return 0;
2464
2465         // query buffer macros
2466         MacroData const * data = getBufferMacro(name, pos);
2467         if (data != 0)
2468                 return data;
2469
2470         // If there is a master buffer, query that
2471         Buffer const * const pbuf = d->parent();
2472         if (pbuf) {
2473                 d->macro_lock = true;
2474                 MacroData const * macro = pbuf->getMacro(
2475                         name, *this, false);
2476                 d->macro_lock = false;
2477                 if (macro)
2478                         return macro;
2479         }
2480
2481         if (global) {
2482                 data = MacroTable::globalMacros().get(name);
2483                 if (data != 0)
2484                         return data;
2485         }
2486
2487         return 0;
2488 }
2489
2490
2491 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2492 {
2493         // set scope end behind the last paragraph
2494         DocIterator scope = par_iterator_begin();
2495         scope.pit() = scope.lastpit() + 1;
2496
2497         return getMacro(name, scope, global);
2498 }
2499
2500
2501 MacroData const * Buffer::getMacro(docstring const & name,
2502         Buffer const & child, bool global) const
2503 {
2504         // look where the child buffer is included first
2505         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2506         if (it == d->children_positions.end())
2507                 return 0;
2508
2509         // check for macros at the inclusion position
2510         return getMacro(name, it->second, global);
2511 }
2512
2513
2514 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2515 {
2516         pit_type lastpit = it.lastpit();
2517
2518         // look for macros in each paragraph
2519         while (it.pit() <= lastpit) {
2520                 Paragraph & par = it.paragraph();
2521
2522                 // iterate over the insets of the current paragraph
2523                 InsetList const & insets = par.insetList();
2524                 InsetList::const_iterator iit = insets.begin();
2525                 InsetList::const_iterator end = insets.end();
2526                 for (; iit != end; ++iit) {
2527                         it.pos() = iit->pos;
2528
2529                         // is it a nested text inset?
2530                         if (iit->inset->asInsetText()) {
2531                                 // Inset needs its own scope?
2532                                 InsetText const * itext = iit->inset->asInsetText();
2533                                 bool newScope = itext->isMacroScope();
2534
2535                                 // scope which ends just behind the inset
2536                                 DocIterator insetScope = it;
2537                                 ++insetScope.pos();
2538
2539                                 // collect macros in inset
2540                                 it.push_back(CursorSlice(*iit->inset));
2541                                 updateMacros(it, newScope ? insetScope : scope);
2542                                 it.pop_back();
2543                                 continue;
2544                         }
2545
2546                         // is it an external file?
2547                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2548                                 // get buffer of external file
2549                                 InsetInclude const & inset =
2550                                         static_cast<InsetInclude const &>(*iit->inset);
2551                                 d->macro_lock = true;
2552                                 Buffer * child = inset.getChildBuffer();
2553                                 d->macro_lock = false;
2554                                 if (!child)
2555                                         continue;
2556
2557                                 // register its position, but only when it is
2558                                 // included first in the buffer
2559                                 if (d->children_positions.find(child) ==
2560                                         d->children_positions.end())
2561                                                 d->children_positions[child] = it;
2562
2563                                 // register child with its scope
2564                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2565                                 continue;
2566                         }
2567
2568                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2569                                 continue;
2570
2571                         // get macro data
2572                         MathMacroTemplate & macroTemplate =
2573                                 static_cast<MathMacroTemplate &>(*iit->inset);
2574                         MacroContext mc(this, it);
2575                         macroTemplate.updateToContext(mc);
2576
2577                         // valid?
2578                         bool valid = macroTemplate.validMacro();
2579                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2580                         // then the BufferView's cursor will be invalid in
2581                         // some cases which leads to crashes.
2582                         if (!valid)
2583                                 continue;
2584
2585                         // register macro
2586                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2587                         // instead of 'macroTemplate' defined above... is this correct?
2588                         d->macros[macroTemplate.name()][it] =
2589                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2590                 }
2591
2592                 // next paragraph
2593                 it.pit()++;
2594                 it.pos() = 0;
2595         }
2596 }
2597
2598
2599 void Buffer::updateMacros() const
2600 {
2601         if (d->macro_lock)
2602                 return;
2603
2604         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2605
2606         // start with empty table
2607         d->macros.clear();
2608         d->children_positions.clear();
2609         d->position_to_children.clear();
2610
2611         // Iterate over buffer, starting with first paragraph
2612         // The scope must be bigger than any lookup DocIterator
2613         // later. For the global lookup, lastpit+1 is used, hence
2614         // we use lastpit+2 here.
2615         DocIterator it = par_iterator_begin();
2616         DocIterator outerScope = it;
2617         outerScope.pit() = outerScope.lastpit() + 2;
2618         updateMacros(it, outerScope);
2619 }
2620
2621
2622 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2623 {
2624         InsetIterator it  = inset_iterator_begin(inset());
2625         InsetIterator const end = inset_iterator_end(inset());
2626         for (; it != end; ++it) {
2627                 if (it->lyxCode() == BRANCH_CODE) {
2628                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2629                         docstring const name = br.branch();
2630                         if (!from_master && !params().branchlist().find(name))
2631                                 result.push_back(name);
2632                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2633                                 result.push_back(name);
2634                         continue;
2635                 }
2636                 if (it->lyxCode() == INCLUDE_CODE) {
2637                         // get buffer of external file
2638                         InsetInclude const & ins =
2639                                 static_cast<InsetInclude const &>(*it);
2640                         Buffer * child = ins.getChildBuffer();
2641                         if (!child)
2642                                 continue;
2643                         child->getUsedBranches(result, true);
2644                 }
2645         }
2646         // remove duplicates
2647         result.unique();
2648 }
2649
2650
2651 void Buffer::updateMacroInstances() const
2652 {
2653         LYXERR(Debug::MACROS, "updateMacroInstances for "
2654                 << d->filename.onlyFileName());
2655         DocIterator it = doc_iterator_begin(this);
2656         it.forwardInset();
2657         DocIterator const end = doc_iterator_end(this);
2658         for (; it != end; it.forwardInset()) {
2659                 // look for MathData cells in InsetMathNest insets
2660                 InsetMath * minset = it.nextInset()->asInsetMath();
2661                 if (!minset)
2662                         continue;
2663
2664                 // update macro in all cells of the InsetMathNest
2665                 DocIterator::idx_type n = minset->nargs();
2666                 MacroContext mc = MacroContext(this, it);
2667                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2668                         MathData & data = minset->cell(i);
2669                         data.updateMacros(0, mc);
2670                 }
2671         }
2672 }
2673
2674
2675 void Buffer::listMacroNames(MacroNameSet & macros) const
2676 {
2677         if (d->macro_lock)
2678                 return;
2679
2680         d->macro_lock = true;
2681
2682         // loop over macro names
2683         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2684         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2685         for (; nameIt != nameEnd; ++nameIt)
2686                 macros.insert(nameIt->first);
2687
2688         // loop over children
2689         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2690         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2691         for (; it != end; ++it)
2692                 it->first->listMacroNames(macros);
2693
2694         // call parent
2695         Buffer const * const pbuf = d->parent();
2696         if (pbuf)
2697                 pbuf->listMacroNames(macros);
2698
2699         d->macro_lock = false;
2700 }
2701
2702
2703 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2704 {
2705         Buffer const * const pbuf = d->parent();
2706         if (!pbuf)
2707                 return;
2708
2709         MacroNameSet names;
2710         pbuf->listMacroNames(names);
2711
2712         // resolve macros
2713         MacroNameSet::iterator it = names.begin();
2714         MacroNameSet::iterator end = names.end();
2715         for (; it != end; ++it) {
2716                 // defined?
2717                 MacroData const * data =
2718                 pbuf->getMacro(*it, *this, false);
2719                 if (data) {
2720                         macros.insert(data);
2721
2722                         // we cannot access the original MathMacroTemplate anymore
2723                         // here to calls validate method. So we do its work here manually.
2724                         // FIXME: somehow make the template accessible here.
2725                         if (data->optionals() > 0)
2726                                 features.require("xargs");
2727                 }
2728         }
2729 }
2730
2731
2732 Buffer::References & Buffer::references(docstring const & label)
2733 {
2734         if (d->parent())
2735                 return const_cast<Buffer *>(masterBuffer())->references(label);
2736
2737         RefCache::iterator it = d->ref_cache_.find(label);
2738         if (it != d->ref_cache_.end())
2739                 return it->second.second;
2740
2741         static InsetLabel const * dummy_il = 0;
2742         static References const dummy_refs;
2743         it = d->ref_cache_.insert(
2744                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2745         return it->second.second;
2746 }
2747
2748
2749 Buffer::References const & Buffer::references(docstring const & label) const
2750 {
2751         return const_cast<Buffer *>(this)->references(label);
2752 }
2753
2754
2755 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2756 {
2757         masterBuffer()->d->ref_cache_[label].first = il;
2758 }
2759
2760
2761 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2762 {
2763         return masterBuffer()->d->ref_cache_[label].first;
2764 }
2765
2766
2767 void Buffer::clearReferenceCache() const
2768 {
2769         if (!d->parent())
2770                 d->ref_cache_.clear();
2771 }
2772
2773
2774 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2775         InsetCode code)
2776 {
2777         //FIXME: This does not work for child documents yet.
2778         LASSERT(code == CITE_CODE, /**/);
2779         // Check if the label 'from' appears more than once
2780         vector<docstring> labels;
2781         string paramName;
2782         BiblioInfo const & keys = masterBibInfo();
2783         BiblioInfo::const_iterator bit  = keys.begin();
2784         BiblioInfo::const_iterator bend = keys.end();
2785
2786         for (; bit != bend; ++bit)
2787                 // FIXME UNICODE
2788                 labels.push_back(bit->first);
2789         paramName = "key";
2790
2791         if (count(labels.begin(), labels.end(), from) > 1)
2792                 return;
2793
2794         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2795                 if (it->lyxCode() == code) {
2796                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2797                         docstring const oldValue = inset.getParam(paramName);
2798                         if (oldValue == from)
2799                                 inset.setParam(paramName, to);
2800                 }
2801         }
2802 }
2803
2804
2805 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2806         pit_type par_end, bool full_source) const
2807 {
2808         OutputParams runparams(&params().encoding());
2809         runparams.nice = true;
2810         runparams.flavor = params().useXetex ? 
2811                 OutputParams::XETEX : OutputParams::LATEX;
2812         runparams.linelen = lyxrc.plaintext_linelen;
2813         // No side effect of file copying and image conversion
2814         runparams.dryrun = true;
2815
2816         if (full_source) {
2817                 os << "% " << _("Preview source code") << "\n\n";
2818                 d->texrow.reset();
2819                 d->texrow.newline();
2820                 d->texrow.newline();
2821                 if (isDocBook())
2822                         writeDocBookSource(os, absFileName(), runparams, false);
2823                 else
2824                         // latex or literate
2825                         writeLaTeXSource(os, string(), runparams, true, true);
2826         } else {
2827                 runparams.par_begin = par_begin;
2828                 runparams.par_end = par_end;
2829                 if (par_begin + 1 == par_end) {
2830                         os << "% "
2831                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2832                            << "\n\n";
2833                 } else {
2834                         os << "% "
2835                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2836                                         convert<docstring>(par_begin),
2837                                         convert<docstring>(par_end - 1))
2838                            << "\n\n";
2839                 }
2840                 TexRow texrow;
2841                 texrow.reset();
2842                 texrow.newline();
2843                 texrow.newline();
2844                 // output paragraphs
2845                 if (isDocBook())
2846                         docbookParagraphs(text(), *this, os, runparams);
2847                 else 
2848                         // latex or literate
2849                         latexParagraphs(*this, text(), os, texrow, runparams);
2850         }
2851 }
2852
2853
2854 ErrorList & Buffer::errorList(string const & type) const
2855 {
2856         static ErrorList emptyErrorList;
2857         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2858         if (I == d->errorLists.end())
2859                 return emptyErrorList;
2860
2861         return I->second;
2862 }
2863
2864
2865 void Buffer::updateTocItem(std::string const & type,
2866         DocIterator const & dit) const
2867 {
2868         if (gui_)
2869                 gui_->updateTocItem(type, dit);
2870 }
2871
2872
2873 void Buffer::structureChanged() const
2874 {
2875         if (gui_)
2876                 gui_->structureChanged();
2877 }
2878
2879
2880 void Buffer::errors(string const & err, bool from_master) const
2881 {
2882         if (gui_)
2883                 gui_->errors(err, from_master);
2884 }
2885
2886
2887 void Buffer::message(docstring const & msg) const
2888 {
2889         if (gui_)
2890                 gui_->message(msg);
2891 }
2892
2893
2894 void Buffer::setBusy(bool on) const
2895 {
2896         if (gui_)
2897                 gui_->setBusy(on);
2898 }
2899
2900
2901 void Buffer::setReadOnly(bool on) const
2902 {
2903         if (d->wa_)
2904                 d->wa_->setReadOnly(on);
2905 }
2906
2907
2908 void Buffer::updateTitles() const
2909 {
2910         if (d->wa_)
2911                 d->wa_->updateTitles();
2912 }
2913
2914
2915 void Buffer::resetAutosaveTimers() const
2916 {
2917         if (gui_)
2918                 gui_->resetAutosaveTimers();
2919 }
2920
2921
2922 bool Buffer::hasGuiDelegate() const
2923 {
2924         return gui_;
2925 }
2926
2927
2928 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2929 {
2930         gui_ = gui;
2931 }
2932
2933
2934
2935 namespace {
2936
2937 class AutoSaveBuffer : public ForkedProcess {
2938 public:
2939         ///
2940         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2941                 : buffer_(buffer), fname_(fname) {}
2942         ///
2943         virtual boost::shared_ptr<ForkedProcess> clone() const
2944         {
2945                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2946         }
2947         ///
2948         int start()
2949         {
2950                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2951                                                  from_utf8(fname_.absFilename())));
2952                 return run(DontWait);
2953         }
2954 private:
2955         ///
2956         virtual int generateChild();
2957         ///
2958         Buffer const & buffer_;
2959         FileName fname_;
2960 };
2961
2962
2963 int AutoSaveBuffer::generateChild()
2964 {
2965 #if defined(__APPLE__)
2966         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
2967          *   We should use something else like threads.
2968          *
2969          * Since I do not know how to determine at run time what is the OS X
2970          * version, I just disable forking altogether for now (JMarc)
2971          */
2972         pid_t const pid = -1;
2973 #else
2974         // tmp_ret will be located (usually) in /tmp
2975         // will that be a problem?
2976         // Note that this calls ForkedCalls::fork(), so it's
2977         // ok cross-platform.
2978         pid_t const pid = fork();
2979         // If you want to debug the autosave
2980         // you should set pid to -1, and comment out the fork.
2981         if (pid != 0 && pid != -1)
2982                 return pid;
2983 #endif
2984
2985         // pid = -1 signifies that lyx was unable
2986         // to fork. But we will do the save
2987         // anyway.
2988         bool failed = false;
2989         FileName const tmp_ret = FileName::tempName("lyxauto");
2990         if (!tmp_ret.empty()) {
2991                 buffer_.writeFile(tmp_ret);
2992                 // assume successful write of tmp_ret
2993                 if (!tmp_ret.moveTo(fname_))
2994                         failed = true;
2995         } else
2996                 failed = true;
2997
2998         if (failed) {
2999                 // failed to write/rename tmp_ret so try writing direct
3000                 if (!buffer_.writeFile(fname_)) {
3001                         // It is dangerous to do this in the child,
3002                         // but safe in the parent, so...
3003                         if (pid == -1) // emit message signal.
3004                                 buffer_.message(_("Autosave failed!"));
3005                 }
3006         }
3007
3008         if (pid == 0) // we are the child so...
3009                 _exit(0);
3010
3011         return pid;
3012 }
3013
3014 } // namespace anon
3015
3016
3017 FileName Buffer::getAutosaveFilename() const
3018 {
3019         // if the document is unnamed try to save in the backup dir, else
3020         // in the default document path, and as a last try in the filePath, 
3021         // which will most often be the temporary directory
3022         string fpath;
3023         if (isUnnamed())
3024                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3025                         : lyxrc.backupdir_path;
3026         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3027                 fpath = filePath();
3028
3029         string const fname = "#" + d->filename.onlyFileName() + "#";
3030         return makeAbsPath(fname, fpath);
3031 }
3032
3033
3034 void Buffer::removeAutosaveFile() const
3035 {
3036         FileName const f = getAutosaveFilename();
3037         if (f.exists())
3038                 f.removeFile();
3039 }
3040
3041
3042 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3043 {
3044         FileName const newauto = getAutosaveFilename();
3045         if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3046                 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3047 }
3048
3049
3050 // Perfect target for a thread...
3051 void Buffer::autoSave() const
3052 {
3053         if (isBakClean() || isReadonly()) {
3054                 // We don't save now, but we'll try again later
3055                 resetAutosaveTimers();
3056                 return;
3057         }
3058
3059         // emit message signal.
3060         message(_("Autosaving current document..."));
3061         AutoSaveBuffer autosave(*this, getAutosaveFilename());
3062         autosave.start();
3063
3064         markBakClean();
3065         resetAutosaveTimers();
3066 }
3067
3068
3069 string Buffer::bufferFormat() const
3070 {
3071         string format = params().documentClass().outputFormat();
3072         if (format == "latex") {
3073                 if (params().useXetex)
3074                         return "xetex";
3075                 if (params().encoding().package() == Encoding::japanese)
3076                         return "platex";
3077         }
3078         return format;
3079 }
3080
3081
3082 string Buffer::getDefaultOutputFormat() const
3083 {
3084         if (!params().defaultOutputFormat.empty()
3085             && params().defaultOutputFormat != "default")
3086                 return params().defaultOutputFormat;
3087         typedef vector<Format const *> Formats;
3088         Formats formats = exportableFormats(true);
3089         if (isDocBook()
3090             || isLiterate()
3091             || params().useXetex
3092             || params().encoding().package() == Encoding::japanese) {
3093                 if (formats.empty())
3094                         return string();
3095                 // return the first we find
3096                 return formats.front()->name();
3097         }
3098         return lyxrc.default_view_format;
3099 }
3100
3101
3102
3103 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3104         string & result_file) const
3105 {
3106         string backend_format;
3107         OutputParams runparams(&params().encoding());
3108         runparams.flavor = OutputParams::LATEX;
3109         runparams.linelen = lyxrc.plaintext_linelen;
3110         vector<string> backs = backends();
3111         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3112                 // Get shortest path to format
3113                 Graph::EdgePath path;
3114                 for (vector<string>::const_iterator it = backs.begin();
3115                      it != backs.end(); ++it) {
3116                         Graph::EdgePath p = theConverters().getPath(*it, format);
3117                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3118                                 backend_format = *it;
3119                                 path = p;
3120                         }
3121                 }
3122                 if (path.empty()) {
3123                         if (!put_in_tempdir) {
3124                                 // Only show this alert if this is an export to a non-temporary
3125                                 // file (not for previewing).
3126                                 Alert::error(_("Couldn't export file"), bformat(
3127                                         _("No information for exporting the format %1$s."),
3128                                         formats.prettyName(format)));
3129                         }
3130                         return false;
3131                 }
3132                 runparams.flavor = theConverters().getFlavor(path);
3133
3134         } else {
3135                 backend_format = format;
3136                 // FIXME: Don't hardcode format names here, but use a flag
3137                 if (backend_format == "pdflatex")
3138                         runparams.flavor = OutputParams::PDFLATEX;
3139         }
3140
3141         string filename = latexName(false);
3142         filename = addName(temppath(), filename);
3143         filename = changeExtension(filename,
3144                                    formats.extension(backend_format));
3145
3146         // fix macros
3147         updateMacroInstances();
3148
3149         // Plain text backend
3150         if (backend_format == "text") {
3151                 runparams.flavor = OutputParams::TEXT;
3152                 writePlaintextFile(*this, FileName(filename), runparams);
3153         }
3154         // HTML backend
3155         else if (backend_format == "xhtml") {
3156                 runparams.flavor = OutputParams::HTML;
3157                 makeLyXHTMLFile(FileName(filename), runparams);
3158         }       else if (backend_format == "lyx")
3159                 writeFile(FileName(filename));
3160         // Docbook backend
3161         else if (isDocBook()) {
3162                 runparams.nice = !put_in_tempdir;
3163                 makeDocBookFile(FileName(filename), runparams);
3164         }
3165         // LaTeX backend
3166         else if (backend_format == format) {
3167                 runparams.nice = true;
3168                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3169                         return false;
3170         } else if (!lyxrc.tex_allows_spaces
3171                    && contains(filePath(), ' ')) {
3172                 Alert::error(_("File name error"),
3173                            _("The directory path to the document cannot contain spaces."));
3174                 return false;
3175         } else {
3176                 runparams.nice = false;
3177                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3178                         return false;
3179         }
3180
3181         string const error_type = (format == "program")
3182                 ? "Build" : bufferFormat();
3183         ErrorList & error_list = d->errorLists[error_type];
3184         string const ext = formats.extension(format);
3185         FileName const tmp_result_file(changeExtension(filename, ext));
3186         bool const success = theConverters().convert(this, FileName(filename),
3187                 tmp_result_file, FileName(absFileName()), backend_format, format,
3188                 error_list);
3189         // Emit the signal to show the error list.
3190         if (format != backend_format) {
3191                 errors(error_type);
3192                 // also to the children, in case of master-buffer-view
3193                 std::vector<Buffer *> clist = getChildren();
3194                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3195                      cit != clist.end(); ++cit)
3196                         (*cit)->errors(error_type, true);
3197         }
3198         if (!success)
3199                 return false;
3200
3201         if (put_in_tempdir) {
3202                 result_file = tmp_result_file.absFilename();
3203                 return true;
3204         }
3205
3206         result_file = changeExtension(exportFileName().absFilename(), ext);
3207         // We need to copy referenced files (e. g. included graphics
3208         // if format == "dvi") to the result dir.
3209         vector<ExportedFile> const files =
3210                 runparams.exportdata->externalFiles(format);
3211         string const dest = onlyPath(result_file);
3212         CopyStatus status = SUCCESS;
3213         for (vector<ExportedFile>::const_iterator it = files.begin();
3214                 it != files.end() && status != CANCEL; ++it) {
3215                 string const fmt = formats.getFormatFromFile(it->sourceName);
3216                 status = copyFile(fmt, it->sourceName,
3217                         makeAbsPath(it->exportName, dest),
3218                         it->exportName, status == FORCE);
3219         }
3220         if (status == CANCEL) {
3221                 message(_("Document export cancelled."));
3222         } else if (tmp_result_file.exists()) {
3223                 // Finally copy the main file
3224                 status = copyFile(format, tmp_result_file,
3225                         FileName(result_file), result_file,
3226                         status == FORCE);
3227                 message(bformat(_("Document exported as %1$s "
3228                         "to file `%2$s'"),
3229                         formats.prettyName(format),
3230                         makeDisplayPath(result_file)));
3231         } else {
3232                 // This must be a dummy converter like fax (bug 1888)
3233                 message(bformat(_("Document exported as %1$s"),
3234                         formats.prettyName(format)));
3235         }
3236
3237         return true;
3238 }
3239
3240
3241 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3242 {
3243         string result_file;
3244         return doExport(format, put_in_tempdir, result_file);
3245 }
3246
3247
3248 bool Buffer::preview(string const & format) const
3249 {
3250         string result_file;
3251         if (!doExport(format, true, result_file))
3252                 return false;
3253         return formats.view(*this, FileName(result_file), format);
3254 }
3255
3256
3257 bool Buffer::isExportable(string const & format) const
3258 {
3259         vector<string> backs = backends();
3260         for (vector<string>::const_iterator it = backs.begin();
3261              it != backs.end(); ++it)
3262                 if (theConverters().isReachable(*it, format))
3263                         return true;
3264         return false;
3265 }
3266
3267
3268 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3269 {
3270         vector<string> const backs = backends();
3271         vector<Format const *> result =
3272                 theConverters().getReachable(backs[0], only_viewable, true);
3273         for (vector<string>::const_iterator it = backs.begin() + 1;
3274              it != backs.end(); ++it) {
3275                 vector<Format const *>  r =
3276                         theConverters().getReachable(*it, only_viewable, false);
3277                 result.insert(result.end(), r.begin(), r.end());
3278         }
3279         return result;
3280 }
3281
3282
3283 vector<string> Buffer::backends() const
3284 {
3285         vector<string> v;
3286         v.push_back(bufferFormat());
3287         // FIXME: Don't hardcode format names here, but use a flag
3288         if (v.back() == "latex")
3289                 v.push_back("pdflatex");
3290         v.push_back("xhtml");
3291         v.push_back("text");
3292         v.push_back("lyx");
3293         return v;
3294 }
3295
3296
3297 bool Buffer::readFileHelper(FileName const & s)
3298 {
3299         // File information about normal file
3300         if (!s.exists()) {
3301                 docstring const file = makeDisplayPath(s.absFilename(), 50);
3302                 docstring text = bformat(_("The specified document\n%1$s"
3303                                                      "\ncould not be read."), file);
3304                 Alert::error(_("Could not read document"), text);
3305                 return false;
3306         }
3307
3308         // Check if emergency save file exists and is newer.
3309         FileName const e(s.absFilename() + ".emergency");
3310
3311         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3312                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3313                 docstring const text =
3314                         bformat(_("An emergency save of the document "
3315                                   "%1$s exists.\n\n"
3316                                                "Recover emergency save?"), file);
3317                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3318                                       _("&Recover"),  _("&Load Original"),
3319                                       _("&Cancel")))
3320                 {
3321                 case 0: {
3322                         // the file is not saved if we load the emergency file.
3323                         markDirty();
3324                         docstring str;
3325                         bool res;
3326
3327                         if ((res = readFile(e)) == success)
3328                                 str = _("Document was successfully recovered.");
3329                         else
3330                                 str = _("Document was NOT successfully recovered.");
3331                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3332                                                 from_utf8(e.absFilename()));
3333
3334                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3335                                         _("&Remove"), _("&Keep it"))) {
3336                                 e.removeFile();
3337                                 if (res == success)
3338                                         Alert::warning(_("Emergency file deleted"),
3339                                                 _("Do not forget to save your file now!"), true);
3340                                 }
3341                         return res;
3342                 }
3343                 case 1:
3344                         if (!Alert::prompt(_("Delete emergency file?"),
3345                                         _("Remove emergency file now?"), 1, 1,
3346                                         _("&Remove"), _("&Keep it")))
3347                                 e.removeFile();
3348                         break;
3349                 default:
3350                         return false;
3351                 }
3352         }
3353
3354         // Now check if autosave file is newer.
3355         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3356
3357         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3358                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3359                 docstring const text =
3360                         bformat(_("The backup of the document "
3361                                   "%1$s is newer.\n\nLoad the "
3362                                                "backup instead?"), file);
3363                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3364                                       _("&Load backup"), _("Load &original"),
3365                                       _("&Cancel") ))
3366                 {
3367                 case 0:
3368                         // the file is not saved if we load the autosave file.
3369                         markDirty();
3370                         return readFile(a);
3371                 case 1:
3372                         // Here we delete the autosave
3373                         a.removeFile();
3374                         break;
3375                 default:
3376                         return false;
3377                 }
3378         }
3379         return readFile(s);
3380 }
3381
3382
3383 bool Buffer::loadLyXFile(FileName const & s)
3384 {
3385         if (s.isReadableFile()) {
3386                 if (readFileHelper(s)) {
3387                         lyxvc().file_found_hook(s);
3388                         if (!s.isWritable())
3389                                 setReadonly(true);
3390                         return true;
3391                 }
3392         } else {
3393                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3394                 // Here we probably should run
3395                 if (LyXVC::file_not_found_hook(s)) {
3396                         docstring const text =
3397                                 bformat(_("Do you want to retrieve the document"
3398                                                        " %1$s from version control?"), file);
3399                         int const ret = Alert::prompt(_("Retrieve from version control?"),
3400                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3401
3402                         if (ret == 0) {
3403                                 // How can we know _how_ to do the checkout?
3404                                 // With the current VC support it has to be,
3405                                 // a RCS file since CVS do not have special ,v files.
3406                                 RCS::retrieve(s);
3407                                 return loadLyXFile(s);
3408                         }
3409                 }
3410         }
3411         return false;
3412 }
3413
3414
3415 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3416 {
3417         TeXErrors::Errors::const_iterator cit = terr.begin();
3418         TeXErrors::Errors::const_iterator end = terr.end();
3419
3420         for (; cit != end; ++cit) {
3421                 int id_start = -1;
3422                 int pos_start = -1;
3423                 int errorRow = cit->error_in_line;
3424                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3425                                                        pos_start);
3426                 int id_end = -1;
3427                 int pos_end = -1;
3428                 do {
3429                         ++errorRow;
3430                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3431                 } while (found && id_start == id_end && pos_start == pos_end);
3432
3433                 errorList.push_back(ErrorItem(cit->error_desc,
3434                         cit->error_text, id_start, pos_start, pos_end));
3435         }
3436 }
3437
3438
3439 void Buffer::setBuffersForInsets() const
3440 {
3441         inset().setBuffer(const_cast<Buffer &>(*this)); 
3442 }
3443
3444
3445 void Buffer::updateLabels(UpdateScope scope, bool out) const
3446 {
3447         // Use the master text class also for child documents
3448         Buffer const * const master = masterBuffer();
3449         DocumentClass const & textclass = master->params().documentClass();
3450
3451         // keep the buffers to be children in this set. If the call from the
3452         // master comes back we can see which of them were actually seen (i.e.
3453         // via an InsetInclude). The remaining ones in the set need still be updated.
3454         static std::set<Buffer const *> bufToUpdate;
3455         if (scope == UpdateMaster) {
3456                 // If this is a child document start with the master
3457                 if (master != this) {
3458                         bufToUpdate.insert(this);
3459                         master->updateLabels(UpdateMaster, out);
3460                         // Do this here in case the master has no gui associated with it. Then, 
3461                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3462                         if (!master->gui_)
3463                                 structureChanged();
3464
3465                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3466                         if (bufToUpdate.find(this) == bufToUpdate.end())
3467                                 return;
3468                 }
3469
3470                 // start over the counters in the master
3471                 textclass.counters().reset();
3472         }
3473
3474         // update will be done below for this buffer
3475         bufToUpdate.erase(this);
3476
3477         // update all caches
3478         clearReferenceCache();
3479         updateMacros();
3480
3481         Buffer & cbuf = const_cast<Buffer &>(*this);
3482
3483         LASSERT(!text().paragraphs().empty(), /**/);
3484
3485         // do the real work
3486         ParIterator parit = cbuf.par_iterator_begin();
3487         updateLabels(parit, out);
3488
3489         if (master != this)
3490                 // TocBackend update will be done later.
3491                 return;
3492
3493         cbuf.tocBackend().update();
3494         if (scope == UpdateMaster)
3495                 cbuf.structureChanged();
3496 }
3497
3498
3499 static depth_type getDepth(DocIterator const & it)
3500 {
3501         depth_type depth = 0;
3502         for (size_t i = 0 ; i < it.depth() ; ++i)
3503                 if (!it[i].inset().inMathed())
3504                         depth += it[i].paragraph().getDepth() + 1;
3505         // remove 1 since the outer inset does not count
3506         return depth - 1;
3507 }
3508
3509 static depth_type getItemDepth(ParIterator const & it)
3510 {
3511         Paragraph const & par = *it;
3512         LabelType const labeltype = par.layout().labeltype;
3513
3514         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3515                 return 0;
3516
3517         // this will hold the lowest depth encountered up to now.
3518         depth_type min_depth = getDepth(it);
3519         ParIterator prev_it = it;
3520         while (true) {
3521                 if (prev_it.pit())
3522                         --prev_it.top().pit();
3523                 else {
3524                         // start of nested inset: go to outer par
3525                         prev_it.pop_back();
3526                         if (prev_it.empty()) {
3527                                 // start of document: nothing to do
3528                                 return 0;
3529                         }
3530                 }
3531
3532                 // We search for the first paragraph with same label
3533                 // that is not more deeply nested.
3534                 Paragraph & prev_par = *prev_it;
3535                 depth_type const prev_depth = getDepth(prev_it);
3536                 if (labeltype == prev_par.layout().labeltype) {
3537                         if (prev_depth < min_depth)
3538                                 return prev_par.itemdepth + 1;
3539                         if (prev_depth == min_depth)
3540                                 return prev_par.itemdepth;
3541                 }
3542                 min_depth = min(min_depth, prev_depth);
3543                 // small optimization: if we are at depth 0, we won't
3544                 // find anything else
3545                 if (prev_depth == 0)
3546                         return 0;
3547         }
3548 }
3549
3550
3551 static bool needEnumCounterReset(ParIterator const & it)
3552 {
3553         Paragraph const & par = *it;
3554         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3555         depth_type const cur_depth = par.getDepth();
3556         ParIterator prev_it = it;
3557         while (prev_it.pit()) {
3558                 --prev_it.top().pit();
3559                 Paragraph const & prev_par = *prev_it;
3560                 if (prev_par.getDepth() <= cur_depth)
3561                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3562         }
3563         // start of nested inset: reset
3564         return true;
3565 }
3566
3567
3568 // set the label of a paragraph. This includes the counters.
3569 void Buffer::setLabel(ParIterator & it) const
3570 {
3571         BufferParams const & bp = this->masterBuffer()->params();
3572         DocumentClass const & textclass = bp.documentClass();
3573         Paragraph & par = it.paragraph();
3574         Layout const & layout = par.layout();
3575         Counters & counters = textclass.counters();
3576
3577         if (par.params().startOfAppendix()) {
3578                 // FIXME: only the counter corresponding to toplevel
3579                 // sectioning should be reset
3580                 counters.reset();
3581                 counters.appendix(true);
3582         }
3583         par.params().appendix(counters.appendix());
3584
3585         // Compute the item depth of the paragraph
3586         par.itemdepth = getItemDepth(it);
3587
3588         if (layout.margintype == MARGIN_MANUAL
3589             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3590                 if (par.params().labelWidthString().empty())
3591                         par.params().labelWidthString(par.expandLabel(layout, bp));
3592         } else {
3593                 par.params().labelWidthString(docstring());
3594         }
3595
3596         switch(layout.labeltype) {
3597         case LABEL_COUNTER:
3598                 if (layout.toclevel <= bp.secnumdepth
3599                     && (layout.latextype != LATEX_ENVIRONMENT
3600                         || it.text()->isFirstInSequence(it.pit()))) {
3601                         counters.step(layout.counter);
3602                         par.params().labelString(
3603                                 par.expandLabel(layout, bp));
3604                 } else
3605                         par.params().labelString(docstring());
3606                 break;
3607
3608         case LABEL_ITEMIZE: {
3609                 // At some point of time we should do something more
3610                 // clever here, like:
3611                 //   par.params().labelString(
3612                 //    bp.user_defined_bullet(par.itemdepth).getText());
3613                 // for now, use a simple hardcoded label
3614                 docstring itemlabel;
3615                 switch (par.itemdepth) {
3616                 case 0:
3617                         itemlabel = char_type(0x2022);
3618                         break;
3619                 case 1:
3620                         itemlabel = char_type(0x2013);
3621                         break;
3622                 case 2:
3623                         itemlabel = char_type(0x2217);
3624                         break;
3625                 case 3:
3626                         itemlabel = char_type(0x2219); // or 0x00b7
3627                         break;
3628                 }
3629                 par.params().labelString(itemlabel);
3630                 break;
3631         }
3632
3633         case LABEL_ENUMERATE: {
3634                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3635
3636                 switch (par.itemdepth) {
3637                 case 2:
3638                         enumcounter += 'i';
3639                 case 1:
3640                         enumcounter += 'i';
3641                 case 0:
3642                         enumcounter += 'i';
3643                         break;
3644                 case 3:
3645                         enumcounter += "iv";
3646                         break;
3647                 default:
3648                         // not a valid enumdepth...
3649                         break;
3650                 }
3651
3652                 // Maybe we have to reset the enumeration counter.
3653                 if (needEnumCounterReset(it))
3654                         counters.reset(enumcounter);
3655                 counters.step(enumcounter);
3656
3657                 string const & lang = par.getParLanguage(bp)->code();
3658                 par.params().labelString(counters.theCounter(enumcounter, lang));
3659
3660                 break;
3661         }
3662
3663         case LABEL_SENSITIVE: {
3664                 string const & type = counters.current_float();
3665                 docstring full_label;
3666                 if (type.empty())
3667                         full_label = this->B_("Senseless!!! ");
3668                 else {
3669                         docstring name = this->B_(textclass.floats().getType(type).name());
3670                         if (counters.hasCounter(from_utf8(type))) {
3671                                 string const & lang = par.getParLanguage(bp)->code();
3672                                 counters.step(from_utf8(type));
3673                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3674                                                      name, 
3675                                                      counters.theCounter(from_utf8(type), lang));
3676                         } else
3677                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3678                 }
3679                 par.params().labelString(full_label);   
3680                 break;
3681         }
3682
3683         case LABEL_NO_LABEL:
3684                 par.params().labelString(docstring());
3685                 break;
3686
3687         case LABEL_MANUAL:
3688         case LABEL_TOP_ENVIRONMENT:
3689         case LABEL_CENTERED_TOP_ENVIRONMENT:
3690         case LABEL_STATIC:      
3691         case LABEL_BIBLIO:
3692                 par.params().labelString(par.expandLabel(layout, bp));
3693                 break;
3694         }
3695 }
3696
3697
3698 void Buffer::updateLabels(ParIterator & parit, bool out) const
3699 {
3700         LASSERT(parit.pit() == 0, /**/);
3701
3702         // set the position of the text in the buffer to be able
3703         // to resolve macros in it. This has nothing to do with
3704         // labels, but by putting it here we avoid implementing
3705         // a whole bunch of traversal routines just for this call.
3706         parit.text()->setMacrocontextPosition(parit);
3707
3708         depth_type maxdepth = 0;
3709         pit_type const lastpit = parit.lastpit();
3710         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3711                 // reduce depth if necessary
3712                 parit->params().depth(min(parit->params().depth(), maxdepth));
3713                 maxdepth = parit->getMaxDepthAfter();
3714
3715                 // set the counter for this paragraph
3716                 setLabel(parit);
3717
3718                 // Now the insets
3719                 InsetList::const_iterator iit = parit->insetList().begin();
3720                 InsetList::const_iterator end = parit->insetList().end();
3721                 for (; iit != end; ++iit) {
3722                         parit.pos() = iit->pos;
3723                         iit->inset->updateLabels(parit, out);
3724                 }
3725         }
3726 }
3727
3728
3729 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3730         WordLangTuple & word_lang, docstring_list & suggestions) const
3731 {
3732         int progress = 0;
3733         WordLangTuple wl;
3734         suggestions.clear();
3735         word_lang = WordLangTuple();
3736         // OK, we start from here.
3737         DocIterator const end = doc_iterator_end(this);
3738         for (; from != end; from.forwardPos()) {
3739                 // We are only interested in text so remove the math CursorSlice.
3740                 while (from.inMathed()) {
3741                         from.pop_back();
3742                         from.pos()++;
3743                 }
3744                 // If from is at the end of the document (which is possible
3745                 // when leaving the mathed) LyX will crash later.
3746                 if (from == end)
3747                         break;
3748                 to = from;
3749                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3750                         word_lang = wl;
3751                         break;
3752                 }
3753
3754                 // Do not increase progress when from == to, otherwise the word
3755                 // count will be wrong.
3756                 if (from != to) {
3757                         from = to;
3758                         ++progress;
3759                 }
3760         }
3761         return progress;
3762 }
3763
3764 } // namespace lyx