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