]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Routines for calculating numerical labels for BibTeX citations.
[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         checkBibInfoCache();
1461         d->bibinfo_.collectCitedEntries(*this);
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         checkBibInfoCache();
1644         return d->bibinfo_;
1645 }
1646
1647
1648 void Buffer::checkBibInfoCache() const 
1649 {
1650         support::FileNameList const & bibfilesCache = getBibfilesCache();
1651         // compare the cached timestamps with the actual ones.
1652         support::FileNameList::const_iterator ei = bibfilesCache.begin();
1653         support::FileNameList::const_iterator en = bibfilesCache.end();
1654         for (; ei != en; ++ ei) {
1655                 time_t lastw = ei->lastModified();
1656                 time_t prevw = d->bibfileStatus_[*ei];
1657                 if (lastw != prevw) {
1658                         d->bibinfoCacheValid_ = false;
1659                         d->bibfileStatus_[*ei] = lastw;
1660                 }
1661         }
1662
1663         if (!d->bibinfoCacheValid_) {
1664                 d->bibinfo_.clear();
1665                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1666                         it->fillWithBibKeys(d->bibinfo_, it);
1667                 d->bibinfoCacheValid_ = true;
1668         }       
1669 }
1670
1671
1672 bool Buffer::isDepClean(string const & name) const
1673 {
1674         DepClean::const_iterator const it = d->dep_clean.find(name);
1675         if (it == d->dep_clean.end())
1676                 return true;
1677         return it->second;
1678 }
1679
1680
1681 void Buffer::markDepClean(string const & name)
1682 {
1683         d->dep_clean[name] = true;
1684 }
1685
1686
1687 bool Buffer::isExportableFormat(string const & format) const
1688 {
1689                 typedef vector<Format const *> Formats;
1690                 Formats formats;
1691                 formats = exportableFormats(true);
1692                 Formats::const_iterator fit = formats.begin();
1693                 Formats::const_iterator end = formats.end();
1694                 for (; fit != end ; ++fit) {
1695                         if ((*fit)->name() == format)
1696                                 return true;
1697                 }
1698                 return false;
1699 }
1700
1701
1702 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
1703 {
1704         if (isInternal()) {
1705                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1706                 // if internal, put a switch '(cmd.action)' here.
1707                 return false;
1708         }
1709
1710         bool enable = true;
1711
1712         switch (cmd.action) {
1713
1714                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
1715                         flag.setOnOff(isReadonly());
1716                         break;
1717
1718                 // FIXME: There is need for a command-line import.
1719                 //case LFUN_BUFFER_IMPORT:
1720
1721                 case LFUN_BUFFER_AUTO_SAVE:
1722                         break;
1723
1724                 case LFUN_BUFFER_EXPORT_CUSTOM:
1725                         // FIXME: Nothing to check here?
1726                         break;
1727
1728                 case LFUN_BUFFER_EXPORT: {
1729                         docstring const arg = cmd.argument();
1730                         enable = arg == "custom" || isExportable(to_utf8(arg));
1731                         if (!enable)
1732                                 flag.message(bformat(
1733                                         _("Don't know how to export to format: %1$s"), arg));
1734                         break;
1735                 }
1736
1737                 case LFUN_BUFFER_CHKTEX:
1738                         enable = isLatex() && !lyxrc.chktex_command.empty();
1739                         break;
1740
1741                 case LFUN_BUILD_PROGRAM:
1742                         enable = isExportable("program");
1743                         break;
1744
1745                 case LFUN_BRANCH_ACTIVATE: 
1746                 case LFUN_BRANCH_DEACTIVATE: {
1747                         BranchList const & branchList = params().branchlist();
1748                         docstring const branchName = cmd.argument();
1749                         enable = !branchName.empty() && branchList.find(branchName);
1750                         break;
1751                 }
1752
1753                 case LFUN_BRANCH_ADD:
1754                 case LFUN_BRANCHES_RENAME:
1755                 case LFUN_BUFFER_PRINT:
1756                         // if no Buffer is present, then of course we won't be called!
1757                         break;
1758
1759                 case LFUN_BUFFER_LANGUAGE:
1760                         enable = !isReadonly();
1761                         break;
1762
1763                 default:
1764                         return false;
1765         }
1766         flag.setEnabled(enable);
1767         return true;
1768 }
1769
1770
1771 void Buffer::dispatch(string const & command, DispatchResult & result)
1772 {
1773         return dispatch(lyxaction.lookupFunc(command), result);
1774 }
1775
1776
1777 // NOTE We can end up here even if we have no GUI, because we are called
1778 // by LyX::exec to handled command-line requests. So we may need to check 
1779 // whether we have a GUI or not. The boolean use_gui holds this information.
1780 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
1781 {
1782         if (isInternal()) {
1783                 // FIXME? if there is an Buffer LFUN that can be dispatched even
1784                 // if internal, put a switch '(cmd.action)' here.
1785                 dr.dispatched(false);
1786                 return;
1787         }
1788         string const argument = to_utf8(func.argument());
1789         // We'll set this back to false if need be.
1790         bool dispatched = true;
1791         undo().beginUndoGroup();
1792
1793         switch (func.action) {
1794         case LFUN_BUFFER_TOGGLE_READ_ONLY:
1795                 if (lyxvc().inUse())
1796                         lyxvc().toggleReadOnly();
1797                 else
1798                         setReadonly(!isReadonly());
1799                 break;
1800
1801         case LFUN_BUFFER_EXPORT: {
1802                 bool success = doExport(argument, false);
1803                 dr.setError(success);
1804                 if (!success)
1805                         dr.setMessage(bformat(_("Error exporting to format: %1$s."), 
1806                                               func.argument()));
1807                 break;
1808         }
1809
1810         case LFUN_BUILD_PROGRAM:
1811                 doExport("program", true);
1812                 break;
1813
1814         case LFUN_BUFFER_CHKTEX:
1815                 runChktex();
1816                 break;
1817
1818         case LFUN_BUFFER_EXPORT_CUSTOM: {
1819                 string format_name;
1820                 string command = split(argument, format_name, ' ');
1821                 Format const * format = formats.getFormat(format_name);
1822                 if (!format) {
1823                         lyxerr << "Format \"" << format_name
1824                                 << "\" not recognized!"
1825                                 << endl;
1826                         break;
1827                 }
1828
1829                 // The name of the file created by the conversion process
1830                 string filename;
1831
1832                 // Output to filename
1833                 if (format->name() == "lyx") {
1834                         string const latexname = latexName(false);
1835                         filename = changeExtension(latexname,
1836                                 format->extension());
1837                         filename = addName(temppath(), filename);
1838
1839                         if (!writeFile(FileName(filename)))
1840                                 break;
1841
1842                 } else {
1843                         doExport(format_name, true, filename);
1844                 }
1845
1846                 // Substitute $$FName for filename
1847                 if (!contains(command, "$$FName"))
1848                         command = "( " + command + " ) < $$FName";
1849                 command = subst(command, "$$FName", filename);
1850
1851                 // Execute the command in the background
1852                 Systemcall call;
1853                 call.startscript(Systemcall::DontWait, command);
1854                 break;
1855         }
1856
1857         // FIXME: There is need for a command-line import.
1858         /*
1859         case LFUN_BUFFER_IMPORT:
1860                 doImport(argument);
1861                 break;
1862         */
1863
1864         case LFUN_BUFFER_AUTO_SAVE:
1865                 autoSave();
1866                 break;
1867
1868         case LFUN_BRANCH_ADD: {
1869                 docstring const branch_name = func.argument();
1870                 if (branch_name.empty()) {
1871                         dispatched = false;
1872                         break;
1873                 }
1874                 BranchList & branch_list = params().branchlist();
1875                 Branch * branch = branch_list.find(branch_name);
1876                 if (branch) {
1877                         LYXERR0("Branch " << branch_name << " already exists.");
1878                         dr.setError(true);
1879                         docstring const msg = 
1880                                 bformat(_("Branch \"%1$s\" already exists."), branch_name);
1881                         dr.setMessage(msg);
1882                 } else {
1883                         branch_list.add(branch_name);
1884                         branch = branch_list.find(branch_name);
1885                         string const x11hexname = X11hexname(branch->color());
1886                         docstring const str = branch_name + ' ' + from_ascii(x11hexname);
1887                         lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));        
1888                         dr.setError(false);
1889                         dr.update(Update::Force);
1890                 }
1891                 break;
1892         }
1893
1894         case LFUN_BRANCH_ACTIVATE:
1895         case LFUN_BRANCH_DEACTIVATE: {
1896                 BranchList & branchList = params().branchlist();
1897                 docstring const branchName = func.argument();
1898                 // the case without a branch name is handled elsewhere
1899                 if (branchName.empty()) {
1900                         dispatched = false;
1901                         break;
1902                 }
1903                 Branch * branch = branchList.find(branchName);
1904                 if (!branch) {
1905                         LYXERR0("Branch " << branchName << " does not exist.");
1906                         dr.setError(true);
1907                         docstring const msg = 
1908                                 bformat(_("Branch \"%1$s\" does not exist."), branchName);
1909                         dr.setMessage(msg);
1910                 } else {
1911                         branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1912                         dr.setError(false);
1913                         dr.update(Update::Force);
1914                 }
1915                 break;
1916         }
1917
1918         case LFUN_BRANCHES_RENAME: {
1919                 if (func.argument().empty())
1920                         break;
1921
1922                 docstring const oldname = from_utf8(func.getArg(0));
1923                 docstring const newname = from_utf8(func.getArg(1));
1924                 InsetIterator it  = inset_iterator_begin(inset());
1925                 InsetIterator const end = inset_iterator_end(inset());
1926                 bool success = false;
1927                 for (; it != end; ++it) {
1928                         if (it->lyxCode() == BRANCH_CODE) {
1929                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
1930                                 if (ins.branch() == oldname) {
1931                                         undo().recordUndo(it);
1932                                         ins.rename(newname);
1933                                         success = true;
1934                                         continue;
1935                                 }
1936                         }
1937                         if (it->lyxCode() == INCLUDE_CODE) {
1938                                 // get buffer of external file
1939                                 InsetInclude const & ins =
1940                                         static_cast<InsetInclude const &>(*it);
1941                                 Buffer * child = ins.getChildBuffer();
1942                                 if (!child)
1943                                         continue;
1944                                 child->dispatch(func, dr);
1945                         }
1946                 }
1947
1948                 if (success)
1949                         dr.update(Update::Force);
1950                 break;
1951         }
1952
1953         case LFUN_BUFFER_PRINT: {
1954                 // we'll assume there's a problem until we succeed
1955                 dr.setError(true); 
1956                 string target = func.getArg(0);
1957                 string target_name = func.getArg(1);
1958                 string command = func.getArg(2);
1959
1960                 if (target.empty()
1961                     || target_name.empty()
1962                     || command.empty()) {
1963                         LYXERR0("Unable to parse " << func.argument());
1964                         docstring const msg = 
1965                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
1966                         dr.setMessage(msg);
1967                         break;
1968                 }
1969                 if (target != "printer" && target != "file") {
1970                         LYXERR0("Unrecognized target \"" << target << '"');
1971                         docstring const msg = 
1972                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
1973                         dr.setMessage(msg);
1974                         break;
1975                 }
1976
1977                 if (!doExport("dvi", true)) {
1978                         showPrintError(absFileName());
1979                         dr.setMessage(_("Error exporting to DVI."));
1980                         break;
1981                 }
1982
1983                 // Push directory path.
1984                 string const path = temppath();
1985                 // Prevent the compiler from optimizing away p
1986                 FileName pp(path);
1987                 PathChanger p(pp);
1988
1989                 // there are three cases here:
1990                 // 1. we print to a file
1991                 // 2. we print directly to a printer
1992                 // 3. we print using a spool command (print to file first)
1993                 Systemcall one;
1994                 int res = 0;
1995                 string const dviname = changeExtension(latexName(true), "dvi");
1996
1997                 if (target == "printer") {
1998                         if (!lyxrc.print_spool_command.empty()) {
1999                                 // case 3: print using a spool
2000                                 string const psname = changeExtension(dviname,".ps");
2001                                 command += ' ' + lyxrc.print_to_file
2002                                         + quoteName(psname)
2003                                         + ' '
2004                                         + quoteName(dviname);
2005
2006                                 string command2 = lyxrc.print_spool_command + ' ';
2007                                 if (target_name != "default") {
2008                                         command2 += lyxrc.print_spool_printerprefix
2009                                                 + target_name
2010                                                 + ' ';
2011                                 }
2012                                 command2 += quoteName(psname);
2013                                 // First run dvips.
2014                                 // If successful, then spool command
2015                                 res = one.startscript(Systemcall::Wait, command);
2016
2017                                 if (res == 0) {
2018                                         // If there's no GUI, we have to wait on this command. Otherwise,
2019                                         // LyX deletes the temporary directory, and with it the spooled
2020                                         // file, before it can be printed!!
2021                                         Systemcall::Starttype stype = use_gui ?
2022                                                 Systemcall::DontWait : Systemcall::Wait;
2023                                         res = one.startscript(stype, command2);
2024                                 }
2025                         } else {
2026                                 // case 2: print directly to a printer
2027                                 if (target_name != "default")
2028                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2029                                 // as above....
2030                                 Systemcall::Starttype stype = use_gui ?
2031                                         Systemcall::DontWait : Systemcall::Wait;
2032                                 res = one.startscript(stype, command + quoteName(dviname));
2033                         }
2034
2035                 } else {
2036                         // case 1: print to a file
2037                         FileName const filename(makeAbsPath(target_name, filePath()));
2038                         FileName const dvifile(makeAbsPath(dviname, path));
2039                         if (filename.exists()) {
2040                                 docstring text = bformat(
2041                                         _("The file %1$s already exists.\n\n"
2042                                           "Do you want to overwrite that file?"),
2043                                         makeDisplayPath(filename.absFilename()));
2044                                 if (Alert::prompt(_("Overwrite file?"),
2045                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2046                                         break;
2047                         }
2048                         command += ' ' + lyxrc.print_to_file
2049                                 + quoteName(filename.toFilesystemEncoding())
2050                                 + ' '
2051                                 + quoteName(dvifile.toFilesystemEncoding());
2052                         // as above....
2053                         Systemcall::Starttype stype = use_gui ?
2054                                 Systemcall::DontWait : Systemcall::Wait;
2055                         res = one.startscript(stype, command);
2056                 }
2057
2058                 if (res == 0) 
2059                         dr.setError(false);
2060                 else {
2061                         dr.setMessage(_("Error running external commands."));
2062                         showPrintError(absFileName());
2063                 }
2064                 break;
2065         }
2066
2067         case LFUN_BUFFER_LANGUAGE: {
2068                 Language const * oldL = params().language;
2069                 Language const * newL = languages.getLanguage(argument);
2070                 if (!newL || oldL == newL)
2071                         break;
2072                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2073                         changeLanguage(oldL, newL);
2074                 break;
2075         }
2076
2077         default:
2078                 dispatched = false;
2079                 break;
2080         }
2081         dr.dispatched(dispatched);
2082         undo().endUndoGroup();
2083 }
2084
2085
2086 void Buffer::changeLanguage(Language const * from, Language const * to)
2087 {
2088         LASSERT(from, /**/);
2089         LASSERT(to, /**/);
2090
2091         for_each(par_iterator_begin(),
2092                  par_iterator_end(),
2093                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2094 }
2095
2096
2097 bool Buffer::isMultiLingual() const
2098 {
2099         ParConstIterator end = par_iterator_end();
2100         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2101                 if (it->isMultiLingual(params()))
2102                         return true;
2103
2104         return false;
2105 }
2106
2107
2108 DocIterator Buffer::getParFromID(int const id) const
2109 {
2110         Buffer * buf = const_cast<Buffer *>(this);
2111         if (id < 0) {
2112                 // John says this is called with id == -1 from undo
2113                 lyxerr << "getParFromID(), id: " << id << endl;
2114                 return doc_iterator_end(buf);
2115         }
2116
2117         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2118                 if (it.paragraph().id() == id)
2119                         return it;
2120
2121         return doc_iterator_end(buf);
2122 }
2123
2124
2125 bool Buffer::hasParWithID(int const id) const
2126 {
2127         return !getParFromID(id).atEnd();
2128 }
2129
2130
2131 ParIterator Buffer::par_iterator_begin()
2132 {
2133         return ParIterator(doc_iterator_begin(this));
2134 }
2135
2136
2137 ParIterator Buffer::par_iterator_end()
2138 {
2139         return ParIterator(doc_iterator_end(this));
2140 }
2141
2142
2143 ParConstIterator Buffer::par_iterator_begin() const
2144 {
2145         return ParConstIterator(doc_iterator_begin(this));
2146 }
2147
2148
2149 ParConstIterator Buffer::par_iterator_end() const
2150 {
2151         return ParConstIterator(doc_iterator_end(this));
2152 }
2153
2154
2155 Language const * Buffer::language() const
2156 {
2157         return params().language;
2158 }
2159
2160
2161 docstring const Buffer::B_(string const & l10n) const
2162 {
2163         return params().B_(l10n);
2164 }
2165
2166
2167 bool Buffer::isClean() const
2168 {
2169         return d->lyx_clean;
2170 }
2171
2172
2173 bool Buffer::isBakClean() const
2174 {
2175         return d->bak_clean;
2176 }
2177
2178
2179 bool Buffer::isExternallyModified(CheckMethod method) const
2180 {
2181         LASSERT(d->filename.exists(), /**/);
2182         // if method == timestamp, check timestamp before checksum
2183         return (method == checksum_method
2184                 || d->timestamp_ != d->filename.lastModified())
2185                 && d->checksum_ != d->filename.checksum();
2186 }
2187
2188
2189 void Buffer::saveCheckSum(FileName const & file) const
2190 {
2191         if (file.exists()) {
2192                 d->timestamp_ = file.lastModified();
2193                 d->checksum_ = file.checksum();
2194         } else {
2195                 // in the case of save to a new file.
2196                 d->timestamp_ = 0;
2197                 d->checksum_ = 0;
2198         }
2199 }
2200
2201
2202 void Buffer::markClean() const
2203 {
2204         if (!d->lyx_clean) {
2205                 d->lyx_clean = true;
2206                 updateTitles();
2207         }
2208         // if the .lyx file has been saved, we don't need an
2209         // autosave
2210         d->bak_clean = true;
2211 }
2212
2213
2214 void Buffer::markBakClean() const
2215 {
2216         d->bak_clean = true;
2217 }
2218
2219
2220 void Buffer::setUnnamed(bool flag)
2221 {
2222         d->unnamed = flag;
2223 }
2224
2225
2226 bool Buffer::isUnnamed() const
2227 {
2228         return d->unnamed;
2229 }
2230
2231
2232 /// \note
2233 /// Don't check unnamed, here: isInternal() is used in
2234 /// newBuffer(), where the unnamed flag has not been set by anyone
2235 /// yet. Also, for an internal buffer, there should be no need for
2236 /// retrieving fileName() nor for checking if it is unnamed or not.
2237 bool Buffer::isInternal() const
2238 {
2239         return fileName().extension() == "internal";
2240 }
2241
2242
2243 void Buffer::markDirty()
2244 {
2245         if (d->lyx_clean) {
2246                 d->lyx_clean = false;
2247                 updateTitles();
2248         }
2249         d->bak_clean = false;
2250
2251         DepClean::iterator it = d->dep_clean.begin();
2252         DepClean::const_iterator const end = d->dep_clean.end();
2253
2254         for (; it != end; ++it)
2255                 it->second = false;
2256 }
2257
2258
2259 FileName Buffer::fileName() const
2260 {
2261         return d->filename;
2262 }
2263
2264
2265 string Buffer::absFileName() const
2266 {
2267         return d->filename.absFilename();
2268 }
2269
2270
2271 string Buffer::filePath() const
2272 {
2273         return d->filename.onlyPath().absFilename() + "/";
2274 }
2275
2276
2277 bool Buffer::isReadonly() const
2278 {
2279         return d->read_only;
2280 }
2281
2282
2283 void Buffer::setParent(Buffer const * buffer)
2284 {
2285         // Avoids recursive include.
2286         d->setParent(buffer == this ? 0 : buffer);
2287         updateMacros();
2288 }
2289
2290
2291 Buffer const * Buffer::parent() const
2292 {
2293         return d->parent();
2294 }
2295
2296
2297 void Buffer::collectRelatives(BufferSet & bufs) const
2298 {
2299         bufs.insert(this);
2300         if (parent())
2301                 parent()->collectRelatives(bufs);
2302
2303         // loop over children
2304         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2305         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2306         for (; it != end; ++it)
2307                 bufs.insert(const_cast<Buffer *>(it->first));
2308 }
2309
2310
2311 std::vector<Buffer const *> Buffer::allRelatives() const
2312 {
2313         BufferSet bufs;
2314         collectRelatives(bufs);
2315         BufferSet::iterator it = bufs.begin();
2316         std::vector<Buffer const *> ret;
2317         for (; it != bufs.end(); ++it)
2318                 ret.push_back(*it);
2319         return ret;
2320 }
2321
2322
2323 Buffer const * Buffer::masterBuffer() const
2324 {
2325         Buffer const * const pbuf = d->parent();
2326         if (!pbuf)
2327                 return this;
2328
2329         return pbuf->masterBuffer();
2330 }
2331
2332
2333 bool Buffer::isChild(Buffer * child) const
2334 {
2335         return d->children_positions.find(child) != d->children_positions.end();
2336 }
2337
2338
2339 DocIterator Buffer::firstChildPosition(Buffer const * child)
2340 {
2341         Impl::BufferPositionMap::iterator it;
2342         it = d->children_positions.find(child);
2343         if (it == d->children_positions.end())
2344                 return DocIterator(this);
2345         return it->second;
2346 }
2347
2348
2349 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2350 {
2351         // loop over children
2352         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2353         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2354         for (; it != end; ++it) {
2355                 Buffer * child = const_cast<Buffer *>(it->first);
2356                 clist.push_back(child);
2357                 if (grand_children) {
2358                         // there might be grandchildren
2359                         std::vector<Buffer *> glist = child->getChildren();
2360                         for (vector<Buffer *>::const_iterator git = glist.begin();
2361                                  git != glist.end(); ++git)
2362                                 clist.push_back(*git);
2363                 }
2364         }
2365 }
2366
2367
2368 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2369 {
2370         std::vector<Buffer *> v;
2371         getChildren(v, grand_children);
2372         return v;
2373 }
2374
2375
2376 template<typename M>
2377 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2378 {
2379         if (m.empty())
2380                 return m.end();
2381
2382         typename M::iterator it = m.lower_bound(x);
2383         if (it == m.begin())
2384                 return m.end();
2385
2386         it--;
2387         return it;
2388 }
2389
2390
2391 MacroData const * Buffer::getBufferMacro(docstring const & name,
2392                                          DocIterator const & pos) const
2393 {
2394         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2395
2396         // if paragraphs have no macro context set, pos will be empty
2397         if (pos.empty())
2398                 return 0;
2399
2400         // we haven't found anything yet
2401         DocIterator bestPos = par_iterator_begin();
2402         MacroData const * bestData = 0;
2403
2404         // find macro definitions for name
2405         Impl::NamePositionScopeMacroMap::iterator nameIt
2406                 = d->macros.find(name);
2407         if (nameIt != d->macros.end()) {
2408                 // find last definition in front of pos or at pos itself
2409                 Impl::PositionScopeMacroMap::const_iterator it
2410                         = greatest_below(nameIt->second, pos);
2411                 if (it != nameIt->second.end()) {
2412                         while (true) {
2413                                 // scope ends behind pos?
2414                                 if (pos < it->second.first) {
2415                                         // Looks good, remember this. If there
2416                                         // is no external macro behind this,
2417                                         // we found the right one already.
2418                                         bestPos = it->first;
2419                                         bestData = &it->second.second;
2420                                         break;
2421                                 }
2422
2423                                 // try previous macro if there is one
2424                                 if (it == nameIt->second.begin())
2425                                         break;
2426                                 it--;
2427                         }
2428                 }
2429         }
2430
2431         // find macros in included files
2432         Impl::PositionScopeBufferMap::const_iterator it
2433                 = greatest_below(d->position_to_children, pos);
2434         if (it == d->position_to_children.end())
2435                 // no children before
2436                 return bestData;
2437
2438         while (true) {
2439                 // do we know something better (i.e. later) already?
2440                 if (it->first < bestPos )
2441                         break;
2442
2443                 // scope ends behind pos?
2444                 if (pos < it->second.first) {
2445                         // look for macro in external file
2446                         d->macro_lock = true;
2447                         MacroData const * data
2448                         = it->second.second->getMacro(name, false);
2449                         d->macro_lock = false;
2450                         if (data) {
2451                                 bestPos = it->first;
2452                                 bestData = data;
2453                                 break;
2454                         }
2455                 }
2456
2457                 // try previous file if there is one
2458                 if (it == d->position_to_children.begin())
2459                         break;
2460                 --it;
2461         }
2462
2463         // return the best macro we have found
2464         return bestData;
2465 }
2466
2467
2468 MacroData const * Buffer::getMacro(docstring const & name,
2469         DocIterator const & pos, bool global) const
2470 {
2471         if (d->macro_lock)
2472                 return 0;
2473
2474         // query buffer macros
2475         MacroData const * data = getBufferMacro(name, pos);
2476         if (data != 0)
2477                 return data;
2478
2479         // If there is a master buffer, query that
2480         Buffer const * const pbuf = d->parent();
2481         if (pbuf) {
2482                 d->macro_lock = true;
2483                 MacroData const * macro = pbuf->getMacro(
2484                         name, *this, false);
2485                 d->macro_lock = false;
2486                 if (macro)
2487                         return macro;
2488         }
2489
2490         if (global) {
2491                 data = MacroTable::globalMacros().get(name);
2492                 if (data != 0)
2493                         return data;
2494         }
2495
2496         return 0;
2497 }
2498
2499
2500 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2501 {
2502         // set scope end behind the last paragraph
2503         DocIterator scope = par_iterator_begin();
2504         scope.pit() = scope.lastpit() + 1;
2505
2506         return getMacro(name, scope, global);
2507 }
2508
2509
2510 MacroData const * Buffer::getMacro(docstring const & name,
2511         Buffer const & child, bool global) const
2512 {
2513         // look where the child buffer is included first
2514         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2515         if (it == d->children_positions.end())
2516                 return 0;
2517
2518         // check for macros at the inclusion position
2519         return getMacro(name, it->second, global);
2520 }
2521
2522
2523 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2524 {
2525         pit_type lastpit = it.lastpit();
2526
2527         // look for macros in each paragraph
2528         while (it.pit() <= lastpit) {
2529                 Paragraph & par = it.paragraph();
2530
2531                 // iterate over the insets of the current paragraph
2532                 InsetList const & insets = par.insetList();
2533                 InsetList::const_iterator iit = insets.begin();
2534                 InsetList::const_iterator end = insets.end();
2535                 for (; iit != end; ++iit) {
2536                         it.pos() = iit->pos;
2537
2538                         // is it a nested text inset?
2539                         if (iit->inset->asInsetText()) {
2540                                 // Inset needs its own scope?
2541                                 InsetText const * itext = iit->inset->asInsetText();
2542                                 bool newScope = itext->isMacroScope();
2543
2544                                 // scope which ends just behind the inset
2545                                 DocIterator insetScope = it;
2546                                 ++insetScope.pos();
2547
2548                                 // collect macros in inset
2549                                 it.push_back(CursorSlice(*iit->inset));
2550                                 updateMacros(it, newScope ? insetScope : scope);
2551                                 it.pop_back();
2552                                 continue;
2553                         }
2554
2555                         // is it an external file?
2556                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2557                                 // get buffer of external file
2558                                 InsetInclude const & inset =
2559                                         static_cast<InsetInclude const &>(*iit->inset);
2560                                 d->macro_lock = true;
2561                                 Buffer * child = inset.getChildBuffer();
2562                                 d->macro_lock = false;
2563                                 if (!child)
2564                                         continue;
2565
2566                                 // register its position, but only when it is
2567                                 // included first in the buffer
2568                                 if (d->children_positions.find(child) ==
2569                                         d->children_positions.end())
2570                                                 d->children_positions[child] = it;
2571
2572                                 // register child with its scope
2573                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2574                                 continue;
2575                         }
2576
2577                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2578                                 continue;
2579
2580                         // get macro data
2581                         MathMacroTemplate & macroTemplate =
2582                                 static_cast<MathMacroTemplate &>(*iit->inset);
2583                         MacroContext mc(this, it);
2584                         macroTemplate.updateToContext(mc);
2585
2586                         // valid?
2587                         bool valid = macroTemplate.validMacro();
2588                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2589                         // then the BufferView's cursor will be invalid in
2590                         // some cases which leads to crashes.
2591                         if (!valid)
2592                                 continue;
2593
2594                         // register macro
2595                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2596                         // instead of 'macroTemplate' defined above... is this correct?
2597                         d->macros[macroTemplate.name()][it] =
2598                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2599                 }
2600
2601                 // next paragraph
2602                 it.pit()++;
2603                 it.pos() = 0;
2604         }
2605 }
2606
2607
2608 void Buffer::updateMacros() const
2609 {
2610         if (d->macro_lock)
2611                 return;
2612
2613         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2614
2615         // start with empty table
2616         d->macros.clear();
2617         d->children_positions.clear();
2618         d->position_to_children.clear();
2619
2620         // Iterate over buffer, starting with first paragraph
2621         // The scope must be bigger than any lookup DocIterator
2622         // later. For the global lookup, lastpit+1 is used, hence
2623         // we use lastpit+2 here.
2624         DocIterator it = par_iterator_begin();
2625         DocIterator outerScope = it;
2626         outerScope.pit() = outerScope.lastpit() + 2;
2627         updateMacros(it, outerScope);
2628 }
2629
2630
2631 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2632 {
2633         InsetIterator it  = inset_iterator_begin(inset());
2634         InsetIterator const end = inset_iterator_end(inset());
2635         for (; it != end; ++it) {
2636                 if (it->lyxCode() == BRANCH_CODE) {
2637                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2638                         docstring const name = br.branch();
2639                         if (!from_master && !params().branchlist().find(name))
2640                                 result.push_back(name);
2641                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2642                                 result.push_back(name);
2643                         continue;
2644                 }
2645                 if (it->lyxCode() == INCLUDE_CODE) {
2646                         // get buffer of external file
2647                         InsetInclude const & ins =
2648                                 static_cast<InsetInclude const &>(*it);
2649                         Buffer * child = ins.getChildBuffer();
2650                         if (!child)
2651                                 continue;
2652                         child->getUsedBranches(result, true);
2653                 }
2654         }
2655         // remove duplicates
2656         result.unique();
2657 }
2658
2659
2660 void Buffer::updateMacroInstances() const
2661 {
2662         LYXERR(Debug::MACROS, "updateMacroInstances for "
2663                 << d->filename.onlyFileName());
2664         DocIterator it = doc_iterator_begin(this);
2665         it.forwardInset();
2666         DocIterator const end = doc_iterator_end(this);
2667         for (; it != end; it.forwardInset()) {
2668                 // look for MathData cells in InsetMathNest insets
2669                 InsetMath * minset = it.nextInset()->asInsetMath();
2670                 if (!minset)
2671                         continue;
2672
2673                 // update macro in all cells of the InsetMathNest
2674                 DocIterator::idx_type n = minset->nargs();
2675                 MacroContext mc = MacroContext(this, it);
2676                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2677                         MathData & data = minset->cell(i);
2678                         data.updateMacros(0, mc);
2679                 }
2680         }
2681 }
2682
2683
2684 void Buffer::listMacroNames(MacroNameSet & macros) const
2685 {
2686         if (d->macro_lock)
2687                 return;
2688
2689         d->macro_lock = true;
2690
2691         // loop over macro names
2692         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2693         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2694         for (; nameIt != nameEnd; ++nameIt)
2695                 macros.insert(nameIt->first);
2696
2697         // loop over children
2698         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2699         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2700         for (; it != end; ++it)
2701                 it->first->listMacroNames(macros);
2702
2703         // call parent
2704         Buffer const * const pbuf = d->parent();
2705         if (pbuf)
2706                 pbuf->listMacroNames(macros);
2707
2708         d->macro_lock = false;
2709 }
2710
2711
2712 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2713 {
2714         Buffer const * const pbuf = d->parent();
2715         if (!pbuf)
2716                 return;
2717
2718         MacroNameSet names;
2719         pbuf->listMacroNames(names);
2720
2721         // resolve macros
2722         MacroNameSet::iterator it = names.begin();
2723         MacroNameSet::iterator end = names.end();
2724         for (; it != end; ++it) {
2725                 // defined?
2726                 MacroData const * data =
2727                 pbuf->getMacro(*it, *this, false);
2728                 if (data) {
2729                         macros.insert(data);
2730
2731                         // we cannot access the original MathMacroTemplate anymore
2732                         // here to calls validate method. So we do its work here manually.
2733                         // FIXME: somehow make the template accessible here.
2734                         if (data->optionals() > 0)
2735                                 features.require("xargs");
2736                 }
2737         }
2738 }
2739
2740
2741 Buffer::References & Buffer::references(docstring const & label)
2742 {
2743         if (d->parent())
2744                 return const_cast<Buffer *>(masterBuffer())->references(label);
2745
2746         RefCache::iterator it = d->ref_cache_.find(label);
2747         if (it != d->ref_cache_.end())
2748                 return it->second.second;
2749
2750         static InsetLabel const * dummy_il = 0;
2751         static References const dummy_refs;
2752         it = d->ref_cache_.insert(
2753                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2754         return it->second.second;
2755 }
2756
2757
2758 Buffer::References const & Buffer::references(docstring const & label) const
2759 {
2760         return const_cast<Buffer *>(this)->references(label);
2761 }
2762
2763
2764 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2765 {
2766         masterBuffer()->d->ref_cache_[label].first = il;
2767 }
2768
2769
2770 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2771 {
2772         return masterBuffer()->d->ref_cache_[label].first;
2773 }
2774
2775
2776 void Buffer::clearReferenceCache() const
2777 {
2778         if (!d->parent())
2779                 d->ref_cache_.clear();
2780 }
2781
2782
2783 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2784         InsetCode code)
2785 {
2786         //FIXME: This does not work for child documents yet.
2787         LASSERT(code == CITE_CODE, /**/);
2788         // Check if the label 'from' appears more than once
2789         vector<docstring> labels;
2790         string paramName;
2791         BiblioInfo const & keys = masterBibInfo();
2792         BiblioInfo::const_iterator bit  = keys.begin();
2793         BiblioInfo::const_iterator bend = keys.end();
2794
2795         for (; bit != bend; ++bit)
2796                 // FIXME UNICODE
2797                 labels.push_back(bit->first);
2798         paramName = "key";
2799
2800         if (count(labels.begin(), labels.end(), from) > 1)
2801                 return;
2802
2803         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2804                 if (it->lyxCode() == code) {
2805                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2806                         docstring const oldValue = inset.getParam(paramName);
2807                         if (oldValue == from)
2808                                 inset.setParam(paramName, to);
2809                 }
2810         }
2811 }
2812
2813
2814 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2815         pit_type par_end, bool full_source) const
2816 {
2817         OutputParams runparams(&params().encoding());
2818         runparams.nice = true;
2819         runparams.flavor = params().useXetex ? 
2820                 OutputParams::XETEX : OutputParams::LATEX;
2821         runparams.linelen = lyxrc.plaintext_linelen;
2822         // No side effect of file copying and image conversion
2823         runparams.dryrun = true;
2824
2825         if (full_source) {
2826                 os << "% " << _("Preview source code") << "\n\n";
2827                 d->texrow.reset();
2828                 d->texrow.newline();
2829                 d->texrow.newline();
2830                 if (isDocBook())
2831                         writeDocBookSource(os, absFileName(), runparams, false);
2832                 else
2833                         // latex or literate
2834                         writeLaTeXSource(os, string(), runparams, true, true);
2835         } else {
2836                 runparams.par_begin = par_begin;
2837                 runparams.par_end = par_end;
2838                 if (par_begin + 1 == par_end) {
2839                         os << "% "
2840                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2841                            << "\n\n";
2842                 } else {
2843                         os << "% "
2844                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2845                                         convert<docstring>(par_begin),
2846                                         convert<docstring>(par_end - 1))
2847                            << "\n\n";
2848                 }
2849                 TexRow texrow;
2850                 texrow.reset();
2851                 texrow.newline();
2852                 texrow.newline();
2853                 // output paragraphs
2854                 if (isDocBook())
2855                         docbookParagraphs(text(), *this, os, runparams);
2856                 else 
2857                         // latex or literate
2858                         latexParagraphs(*this, text(), os, texrow, runparams);
2859         }
2860 }
2861
2862
2863 ErrorList & Buffer::errorList(string const & type) const
2864 {
2865         static ErrorList emptyErrorList;
2866         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2867         if (I == d->errorLists.end())
2868                 return emptyErrorList;
2869
2870         return I->second;
2871 }
2872
2873
2874 void Buffer::updateTocItem(std::string const & type,
2875         DocIterator const & dit) const
2876 {
2877         if (gui_)
2878                 gui_->updateTocItem(type, dit);
2879 }
2880
2881
2882 void Buffer::structureChanged() const
2883 {
2884         if (gui_)
2885                 gui_->structureChanged();
2886 }
2887
2888
2889 void Buffer::errors(string const & err, bool from_master) const
2890 {
2891         if (gui_)
2892                 gui_->errors(err, from_master);
2893 }
2894
2895
2896 void Buffer::message(docstring const & msg) const
2897 {
2898         if (gui_)
2899                 gui_->message(msg);
2900 }
2901
2902
2903 void Buffer::setBusy(bool on) const
2904 {
2905         if (gui_)
2906                 gui_->setBusy(on);
2907 }
2908
2909
2910 void Buffer::setReadOnly(bool on) const
2911 {
2912         if (d->wa_)
2913                 d->wa_->setReadOnly(on);
2914 }
2915
2916
2917 void Buffer::updateTitles() const
2918 {
2919         if (d->wa_)
2920                 d->wa_->updateTitles();
2921 }
2922
2923
2924 void Buffer::resetAutosaveTimers() const
2925 {
2926         if (gui_)
2927                 gui_->resetAutosaveTimers();
2928 }
2929
2930
2931 bool Buffer::hasGuiDelegate() const
2932 {
2933         return gui_;
2934 }
2935
2936
2937 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2938 {
2939         gui_ = gui;
2940 }
2941
2942
2943
2944 namespace {
2945
2946 class AutoSaveBuffer : public ForkedProcess {
2947 public:
2948         ///
2949         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2950                 : buffer_(buffer), fname_(fname) {}
2951         ///
2952         virtual boost::shared_ptr<ForkedProcess> clone() const
2953         {
2954                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2955         }
2956         ///
2957         int start()
2958         {
2959                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2960                                                  from_utf8(fname_.absFilename())));
2961                 return run(DontWait);
2962         }
2963 private:
2964         ///
2965         virtual int generateChild();
2966         ///
2967         Buffer const & buffer_;
2968         FileName fname_;
2969 };
2970
2971
2972 int AutoSaveBuffer::generateChild()
2973 {
2974 #if defined(__APPLE__)
2975         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
2976          *   We should use something else like threads.
2977          *
2978          * Since I do not know how to determine at run time what is the OS X
2979          * version, I just disable forking altogether for now (JMarc)
2980          */
2981         pid_t const pid = -1;
2982 #else
2983         // tmp_ret will be located (usually) in /tmp
2984         // will that be a problem?
2985         // Note that this calls ForkedCalls::fork(), so it's
2986         // ok cross-platform.
2987         pid_t const pid = fork();
2988         // If you want to debug the autosave
2989         // you should set pid to -1, and comment out the fork.
2990         if (pid != 0 && pid != -1)
2991                 return pid;
2992 #endif
2993
2994         // pid = -1 signifies that lyx was unable
2995         // to fork. But we will do the save
2996         // anyway.
2997         bool failed = false;
2998         FileName const tmp_ret = FileName::tempName("lyxauto");
2999         if (!tmp_ret.empty()) {
3000                 buffer_.writeFile(tmp_ret);
3001                 // assume successful write of tmp_ret
3002                 if (!tmp_ret.moveTo(fname_))
3003                         failed = true;
3004         } else
3005                 failed = true;
3006
3007         if (failed) {
3008                 // failed to write/rename tmp_ret so try writing direct
3009                 if (!buffer_.writeFile(fname_)) {
3010                         // It is dangerous to do this in the child,
3011                         // but safe in the parent, so...
3012                         if (pid == -1) // emit message signal.
3013                                 buffer_.message(_("Autosave failed!"));
3014                 }
3015         }
3016
3017         if (pid == 0) // we are the child so...
3018                 _exit(0);
3019
3020         return pid;
3021 }
3022
3023 } // namespace anon
3024
3025
3026 FileName Buffer::getAutosaveFilename() const
3027 {
3028         // if the document is unnamed try to save in the backup dir, else
3029         // in the default document path, and as a last try in the filePath, 
3030         // which will most often be the temporary directory
3031         string fpath;
3032         if (isUnnamed())
3033                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3034                         : lyxrc.backupdir_path;
3035         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3036                 fpath = filePath();
3037
3038         string const fname = "#" + d->filename.onlyFileName() + "#";
3039         return makeAbsPath(fname, fpath);
3040 }
3041
3042
3043 void Buffer::removeAutosaveFile() const
3044 {
3045         FileName const f = getAutosaveFilename();
3046         if (f.exists())
3047                 f.removeFile();
3048 }
3049
3050
3051 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3052 {
3053         FileName const newauto = getAutosaveFilename();
3054         if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3055                 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3056 }
3057
3058
3059 // Perfect target for a thread...
3060 void Buffer::autoSave() const
3061 {
3062         if (isBakClean() || isReadonly()) {
3063                 // We don't save now, but we'll try again later
3064                 resetAutosaveTimers();
3065                 return;
3066         }
3067
3068         // emit message signal.
3069         message(_("Autosaving current document..."));
3070         AutoSaveBuffer autosave(*this, getAutosaveFilename());
3071         autosave.start();
3072
3073         markBakClean();
3074         resetAutosaveTimers();
3075 }
3076
3077
3078 string Buffer::bufferFormat() const
3079 {
3080         string format = params().documentClass().outputFormat();
3081         if (format == "latex") {
3082                 if (params().useXetex)
3083                         return "xetex";
3084                 if (params().encoding().package() == Encoding::japanese)
3085                         return "platex";
3086         }
3087         return format;
3088 }
3089
3090
3091 string Buffer::getDefaultOutputFormat() const
3092 {
3093         if (!params().defaultOutputFormat.empty()
3094             && params().defaultOutputFormat != "default")
3095                 return params().defaultOutputFormat;
3096         typedef vector<Format const *> Formats;
3097         Formats formats = exportableFormats(true);
3098         if (isDocBook()
3099             || isLiterate()
3100             || params().useXetex
3101             || params().encoding().package() == Encoding::japanese) {
3102                 if (formats.empty())
3103                         return string();
3104                 // return the first we find
3105                 return formats.front()->name();
3106         }
3107         return lyxrc.default_view_format;
3108 }
3109
3110
3111
3112 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3113         string & result_file) const
3114 {
3115         string backend_format;
3116         OutputParams runparams(&params().encoding());
3117         runparams.flavor = OutputParams::LATEX;
3118         runparams.linelen = lyxrc.plaintext_linelen;
3119         vector<string> backs = backends();
3120         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3121                 // Get shortest path to format
3122                 Graph::EdgePath path;
3123                 for (vector<string>::const_iterator it = backs.begin();
3124                      it != backs.end(); ++it) {
3125                         Graph::EdgePath p = theConverters().getPath(*it, format);
3126                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3127                                 backend_format = *it;
3128                                 path = p;
3129                         }
3130                 }
3131                 if (path.empty()) {
3132                         if (!put_in_tempdir) {
3133                                 // Only show this alert if this is an export to a non-temporary
3134                                 // file (not for previewing).
3135                                 Alert::error(_("Couldn't export file"), bformat(
3136                                         _("No information for exporting the format %1$s."),
3137                                         formats.prettyName(format)));
3138                         }
3139                         return false;
3140                 }
3141                 runparams.flavor = theConverters().getFlavor(path);
3142
3143         } else {
3144                 backend_format = format;
3145                 // FIXME: Don't hardcode format names here, but use a flag
3146                 if (backend_format == "pdflatex")
3147                         runparams.flavor = OutputParams::PDFLATEX;
3148         }
3149
3150         string filename = latexName(false);
3151         filename = addName(temppath(), filename);
3152         filename = changeExtension(filename,
3153                                    formats.extension(backend_format));
3154
3155         // fix macros
3156         updateMacroInstances();
3157
3158         // Plain text backend
3159         if (backend_format == "text") {
3160                 runparams.flavor = OutputParams::TEXT;
3161                 writePlaintextFile(*this, FileName(filename), runparams);
3162         }
3163         // HTML backend
3164         else if (backend_format == "xhtml") {
3165                 runparams.flavor = OutputParams::HTML;
3166                 makeLyXHTMLFile(FileName(filename), runparams);
3167         }       else if (backend_format == "lyx")
3168                 writeFile(FileName(filename));
3169         // Docbook backend
3170         else if (isDocBook()) {
3171                 runparams.nice = !put_in_tempdir;
3172                 makeDocBookFile(FileName(filename), runparams);
3173         }
3174         // LaTeX backend
3175         else if (backend_format == format) {
3176                 runparams.nice = true;
3177                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3178                         return false;
3179         } else if (!lyxrc.tex_allows_spaces
3180                    && contains(filePath(), ' ')) {
3181                 Alert::error(_("File name error"),
3182                            _("The directory path to the document cannot contain spaces."));
3183                 return false;
3184         } else {
3185                 runparams.nice = false;
3186                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3187                         return false;
3188         }
3189
3190         string const error_type = (format == "program")
3191                 ? "Build" : bufferFormat();
3192         ErrorList & error_list = d->errorLists[error_type];
3193         string const ext = formats.extension(format);
3194         FileName const tmp_result_file(changeExtension(filename, ext));
3195         bool const success = theConverters().convert(this, FileName(filename),
3196                 tmp_result_file, FileName(absFileName()), backend_format, format,
3197                 error_list);
3198         // Emit the signal to show the error list.
3199         if (format != backend_format) {
3200                 errors(error_type);
3201                 // also to the children, in case of master-buffer-view
3202                 std::vector<Buffer *> clist = getChildren();
3203                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3204                      cit != clist.end(); ++cit)
3205                         (*cit)->errors(error_type, true);
3206         }
3207         if (!success)
3208                 return false;
3209
3210         if (d->cloned_buffer_) {
3211                 // Enable reverse dvi or pdf to work by copying back the texrow
3212                 // object to the cloned buffer.
3213                 // FIXME: There is a possibility of concurrent access to texrow
3214                 // here from the main GUI thread that should be securized.
3215                 d->cloned_buffer_->d->texrow = d->texrow;
3216         }
3217
3218         if (put_in_tempdir) {
3219                 result_file = tmp_result_file.absFilename();
3220                 return true;
3221         }
3222
3223         result_file = changeExtension(exportFileName().absFilename(), ext);
3224         // We need to copy referenced files (e. g. included graphics
3225         // if format == "dvi") to the result dir.
3226         vector<ExportedFile> const files =
3227                 runparams.exportdata->externalFiles(format);
3228         string const dest = onlyPath(result_file);
3229         CopyStatus status = SUCCESS;
3230         for (vector<ExportedFile>::const_iterator it = files.begin();
3231                 it != files.end() && status != CANCEL; ++it) {
3232                 string const fmt = formats.getFormatFromFile(it->sourceName);
3233                 status = copyFile(fmt, it->sourceName,
3234                         makeAbsPath(it->exportName, dest),
3235                         it->exportName, status == FORCE);
3236         }
3237         if (status == CANCEL) {
3238                 message(_("Document export cancelled."));
3239         } else if (tmp_result_file.exists()) {
3240                 // Finally copy the main file
3241                 status = copyFile(format, tmp_result_file,
3242                         FileName(result_file), result_file,
3243                         status == FORCE);
3244                 message(bformat(_("Document exported as %1$s "
3245                         "to file `%2$s'"),
3246                         formats.prettyName(format),
3247                         makeDisplayPath(result_file)));
3248         } else {
3249                 // This must be a dummy converter like fax (bug 1888)
3250                 message(bformat(_("Document exported as %1$s"),
3251                         formats.prettyName(format)));
3252         }
3253
3254         return true;
3255 }
3256
3257
3258 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
3259 {
3260         string result_file;
3261         return doExport(format, put_in_tempdir, result_file);
3262 }
3263
3264
3265 bool Buffer::preview(string const & format) const
3266 {
3267         string result_file;
3268         if (!doExport(format, true, result_file))
3269                 return false;
3270         return formats.view(*this, FileName(result_file), format);
3271 }
3272
3273
3274 bool Buffer::isExportable(string const & format) const
3275 {
3276         vector<string> backs = backends();
3277         for (vector<string>::const_iterator it = backs.begin();
3278              it != backs.end(); ++it)
3279                 if (theConverters().isReachable(*it, format))
3280                         return true;
3281         return false;
3282 }
3283
3284
3285 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3286 {
3287         vector<string> const backs = backends();
3288         vector<Format const *> result =
3289                 theConverters().getReachable(backs[0], only_viewable, true);
3290         for (vector<string>::const_iterator it = backs.begin() + 1;
3291              it != backs.end(); ++it) {
3292                 vector<Format const *>  r =
3293                         theConverters().getReachable(*it, only_viewable, false);
3294                 result.insert(result.end(), r.begin(), r.end());
3295         }
3296         return result;
3297 }
3298
3299
3300 vector<string> Buffer::backends() const
3301 {
3302         vector<string> v;
3303         v.push_back(bufferFormat());
3304         // FIXME: Don't hardcode format names here, but use a flag
3305         if (v.back() == "latex")
3306                 v.push_back("pdflatex");
3307         v.push_back("xhtml");
3308         v.push_back("text");
3309         v.push_back("lyx");
3310         return v;
3311 }
3312
3313
3314 bool Buffer::readFileHelper(FileName const & s)
3315 {
3316         // File information about normal file
3317         if (!s.exists()) {
3318                 docstring const file = makeDisplayPath(s.absFilename(), 50);
3319                 docstring text = bformat(_("The specified document\n%1$s"
3320                                                      "\ncould not be read."), file);
3321                 Alert::error(_("Could not read document"), text);
3322                 return false;
3323         }
3324
3325         // Check if emergency save file exists and is newer.
3326         FileName const e(s.absFilename() + ".emergency");
3327
3328         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3329                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3330                 docstring const text =
3331                         bformat(_("An emergency save of the document "
3332                                   "%1$s exists.\n\n"
3333                                                "Recover emergency save?"), file);
3334                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3335                                       _("&Recover"),  _("&Load Original"),
3336                                       _("&Cancel")))
3337                 {
3338                 case 0: {
3339                         // the file is not saved if we load the emergency file.
3340                         markDirty();
3341                         docstring str;
3342                         bool res;
3343
3344                         if ((res = readFile(e)) == success)
3345                                 str = _("Document was successfully recovered.");
3346                         else
3347                                 str = _("Document was NOT successfully recovered.");
3348                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3349                                                 from_utf8(e.absFilename()));
3350
3351                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3352                                         _("&Remove"), _("&Keep it"))) {
3353                                 e.removeFile();
3354                                 if (res == success)
3355                                         Alert::warning(_("Emergency file deleted"),
3356                                                 _("Do not forget to save your file now!"), true);
3357                                 }
3358                         return res;
3359                 }
3360                 case 1:
3361                         if (!Alert::prompt(_("Delete emergency file?"),
3362                                         _("Remove emergency file now?"), 1, 1,
3363                                         _("&Remove"), _("&Keep it")))
3364                                 e.removeFile();
3365                         break;
3366                 default:
3367                         return false;
3368                 }
3369         }
3370
3371         // Now check if autosave file is newer.
3372         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3373
3374         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3375                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3376                 docstring const text =
3377                         bformat(_("The backup of the document "
3378                                   "%1$s is newer.\n\nLoad the "
3379                                                "backup instead?"), file);
3380                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3381                                       _("&Load backup"), _("Load &original"),
3382                                       _("&Cancel") ))
3383                 {
3384                 case 0:
3385                         // the file is not saved if we load the autosave file.
3386                         markDirty();
3387                         return readFile(a);
3388                 case 1:
3389                         // Here we delete the autosave
3390                         a.removeFile();
3391                         break;
3392                 default:
3393                         return false;
3394                 }
3395         }
3396         return readFile(s);
3397 }
3398
3399
3400 bool Buffer::loadLyXFile(FileName const & s)
3401 {
3402         if (s.isReadableFile()) {
3403                 if (readFileHelper(s)) {
3404                         lyxvc().file_found_hook(s);
3405                         if (!s.isWritable())
3406                                 setReadonly(true);
3407                         return true;
3408                 }
3409         } else {
3410                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3411                 // Here we probably should run
3412                 if (LyXVC::file_not_found_hook(s)) {
3413                         docstring const text =
3414                                 bformat(_("Do you want to retrieve the document"
3415                                                        " %1$s from version control?"), file);
3416                         int const ret = Alert::prompt(_("Retrieve from version control?"),
3417                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
3418
3419                         if (ret == 0) {
3420                                 // How can we know _how_ to do the checkout?
3421                                 // With the current VC support it has to be,
3422                                 // a RCS file since CVS do not have special ,v files.
3423                                 RCS::retrieve(s);
3424                                 return loadLyXFile(s);
3425                         }
3426                 }
3427         }
3428         return false;
3429 }
3430
3431
3432 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3433 {
3434         TeXErrors::Errors::const_iterator cit = terr.begin();
3435         TeXErrors::Errors::const_iterator end = terr.end();
3436
3437         for (; cit != end; ++cit) {
3438                 int id_start = -1;
3439                 int pos_start = -1;
3440                 int errorRow = cit->error_in_line;
3441                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3442                                                        pos_start);
3443                 int id_end = -1;
3444                 int pos_end = -1;
3445                 do {
3446                         ++errorRow;
3447                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3448                 } while (found && id_start == id_end && pos_start == pos_end);
3449
3450                 errorList.push_back(ErrorItem(cit->error_desc,
3451                         cit->error_text, id_start, pos_start, pos_end));
3452         }
3453 }
3454
3455
3456 void Buffer::setBuffersForInsets() const
3457 {
3458         inset().setBuffer(const_cast<Buffer &>(*this)); 
3459 }
3460
3461
3462 void Buffer::updateLabels(UpdateScope scope, bool out) const
3463 {
3464         // Use the master text class also for child documents
3465         Buffer const * const master = masterBuffer();
3466         DocumentClass const & textclass = master->params().documentClass();
3467
3468         // keep the buffers to be children in this set. If the call from the
3469         // master comes back we can see which of them were actually seen (i.e.
3470         // via an InsetInclude). The remaining ones in the set need still be updated.
3471         static std::set<Buffer const *> bufToUpdate;
3472         if (scope == UpdateMaster) {
3473                 // If this is a child document start with the master
3474                 if (master != this) {
3475                         bufToUpdate.insert(this);
3476                         master->updateLabels(UpdateMaster, out);
3477                         // Do this here in case the master has no gui associated with it. Then, 
3478                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3479                         if (!master->gui_)
3480                                 structureChanged();
3481
3482                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3483                         if (bufToUpdate.find(this) == bufToUpdate.end())
3484                                 return;
3485                 }
3486
3487                 // start over the counters in the master
3488                 textclass.counters().reset();
3489         }
3490
3491         // update will be done below for this buffer
3492         bufToUpdate.erase(this);
3493
3494         // update all caches
3495         clearReferenceCache();
3496         updateMacros();
3497
3498         Buffer & cbuf = const_cast<Buffer &>(*this);
3499
3500         LASSERT(!text().paragraphs().empty(), /**/);
3501
3502         // do the real work
3503         ParIterator parit = cbuf.par_iterator_begin();
3504         updateLabels(parit, out);
3505
3506         if (master != this)
3507                 // TocBackend update will be done later.
3508                 return;
3509
3510         cbuf.tocBackend().update();
3511         if (scope == UpdateMaster)
3512                 cbuf.structureChanged();
3513 }
3514
3515
3516 static depth_type getDepth(DocIterator const & it)
3517 {
3518         depth_type depth = 0;
3519         for (size_t i = 0 ; i < it.depth() ; ++i)
3520                 if (!it[i].inset().inMathed())
3521                         depth += it[i].paragraph().getDepth() + 1;
3522         // remove 1 since the outer inset does not count
3523         return depth - 1;
3524 }
3525
3526 static depth_type getItemDepth(ParIterator const & it)
3527 {
3528         Paragraph const & par = *it;
3529         LabelType const labeltype = par.layout().labeltype;
3530
3531         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3532                 return 0;
3533
3534         // this will hold the lowest depth encountered up to now.
3535         depth_type min_depth = getDepth(it);
3536         ParIterator prev_it = it;
3537         while (true) {
3538                 if (prev_it.pit())
3539                         --prev_it.top().pit();
3540                 else {
3541                         // start of nested inset: go to outer par
3542                         prev_it.pop_back();
3543                         if (prev_it.empty()) {
3544                                 // start of document: nothing to do
3545                                 return 0;
3546                         }
3547                 }
3548
3549                 // We search for the first paragraph with same label
3550                 // that is not more deeply nested.
3551                 Paragraph & prev_par = *prev_it;
3552                 depth_type const prev_depth = getDepth(prev_it);
3553                 if (labeltype == prev_par.layout().labeltype) {
3554                         if (prev_depth < min_depth)
3555                                 return prev_par.itemdepth + 1;
3556                         if (prev_depth == min_depth)
3557                                 return prev_par.itemdepth;
3558                 }
3559                 min_depth = min(min_depth, prev_depth);
3560                 // small optimization: if we are at depth 0, we won't
3561                 // find anything else
3562                 if (prev_depth == 0)
3563                         return 0;
3564         }
3565 }
3566
3567
3568 static bool needEnumCounterReset(ParIterator const & it)
3569 {
3570         Paragraph const & par = *it;
3571         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3572         depth_type const cur_depth = par.getDepth();
3573         ParIterator prev_it = it;
3574         while (prev_it.pit()) {
3575                 --prev_it.top().pit();
3576                 Paragraph const & prev_par = *prev_it;
3577                 if (prev_par.getDepth() <= cur_depth)
3578                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3579         }
3580         // start of nested inset: reset
3581         return true;
3582 }
3583
3584
3585 // set the label of a paragraph. This includes the counters.
3586 void Buffer::setLabel(ParIterator & it) const
3587 {
3588         BufferParams const & bp = this->masterBuffer()->params();
3589         DocumentClass const & textclass = bp.documentClass();
3590         Paragraph & par = it.paragraph();
3591         Layout const & layout = par.layout();
3592         Counters & counters = textclass.counters();
3593
3594         if (par.params().startOfAppendix()) {
3595                 // FIXME: only the counter corresponding to toplevel
3596                 // sectioning should be reset
3597                 counters.reset();
3598                 counters.appendix(true);
3599         }
3600         par.params().appendix(counters.appendix());
3601
3602         // Compute the item depth of the paragraph
3603         par.itemdepth = getItemDepth(it);
3604
3605         if (layout.margintype == MARGIN_MANUAL
3606             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3607                 if (par.params().labelWidthString().empty())
3608                         par.params().labelWidthString(par.expandLabel(layout, bp));
3609         } else {
3610                 par.params().labelWidthString(docstring());
3611         }
3612
3613         switch(layout.labeltype) {
3614         case LABEL_COUNTER:
3615                 if (layout.toclevel <= bp.secnumdepth
3616                     && (layout.latextype != LATEX_ENVIRONMENT
3617                         || it.text()->isFirstInSequence(it.pit()))) {
3618                         counters.step(layout.counter);
3619                         par.params().labelString(
3620                                 par.expandLabel(layout, bp));
3621                 } else
3622                         par.params().labelString(docstring());
3623                 break;
3624
3625         case LABEL_ITEMIZE: {
3626                 // At some point of time we should do something more
3627                 // clever here, like:
3628                 //   par.params().labelString(
3629                 //    bp.user_defined_bullet(par.itemdepth).getText());
3630                 // for now, use a simple hardcoded label
3631                 docstring itemlabel;
3632                 switch (par.itemdepth) {
3633                 case 0:
3634                         itemlabel = char_type(0x2022);
3635                         break;
3636                 case 1:
3637                         itemlabel = char_type(0x2013);
3638                         break;
3639                 case 2:
3640                         itemlabel = char_type(0x2217);
3641                         break;
3642                 case 3:
3643                         itemlabel = char_type(0x2219); // or 0x00b7
3644                         break;
3645                 }
3646                 par.params().labelString(itemlabel);
3647                 break;
3648         }
3649
3650         case LABEL_ENUMERATE: {
3651                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3652
3653                 switch (par.itemdepth) {
3654                 case 2:
3655                         enumcounter += 'i';
3656                 case 1:
3657                         enumcounter += 'i';
3658                 case 0:
3659                         enumcounter += 'i';
3660                         break;
3661                 case 3:
3662                         enumcounter += "iv";
3663                         break;
3664                 default:
3665                         // not a valid enumdepth...
3666                         break;
3667                 }
3668
3669                 // Maybe we have to reset the enumeration counter.
3670                 if (needEnumCounterReset(it))
3671                         counters.reset(enumcounter);
3672                 counters.step(enumcounter);
3673
3674                 string const & lang = par.getParLanguage(bp)->code();
3675                 par.params().labelString(counters.theCounter(enumcounter, lang));
3676
3677                 break;
3678         }
3679
3680         case LABEL_SENSITIVE: {
3681                 string const & type = counters.current_float();
3682                 docstring full_label;
3683                 if (type.empty())
3684                         full_label = this->B_("Senseless!!! ");
3685                 else {
3686                         docstring name = this->B_(textclass.floats().getType(type).name());
3687                         if (counters.hasCounter(from_utf8(type))) {
3688                                 string const & lang = par.getParLanguage(bp)->code();
3689                                 counters.step(from_utf8(type));
3690                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3691                                                      name, 
3692                                                      counters.theCounter(from_utf8(type), lang));
3693                         } else
3694                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3695                 }
3696                 par.params().labelString(full_label);   
3697                 break;
3698         }
3699
3700         case LABEL_NO_LABEL:
3701                 par.params().labelString(docstring());
3702                 break;
3703
3704         case LABEL_MANUAL:
3705         case LABEL_TOP_ENVIRONMENT:
3706         case LABEL_CENTERED_TOP_ENVIRONMENT:
3707         case LABEL_STATIC:      
3708         case LABEL_BIBLIO:
3709                 par.params().labelString(par.expandLabel(layout, bp));
3710                 break;
3711         }
3712 }
3713
3714
3715 void Buffer::updateLabels(ParIterator & parit, bool out) const
3716 {
3717         LASSERT(parit.pit() == 0, /**/);
3718
3719         // set the position of the text in the buffer to be able
3720         // to resolve macros in it. This has nothing to do with
3721         // labels, but by putting it here we avoid implementing
3722         // a whole bunch of traversal routines just for this call.
3723         parit.text()->setMacrocontextPosition(parit);
3724
3725         depth_type maxdepth = 0;
3726         pit_type const lastpit = parit.lastpit();
3727         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3728                 // reduce depth if necessary
3729                 parit->params().depth(min(parit->params().depth(), maxdepth));
3730                 maxdepth = parit->getMaxDepthAfter();
3731
3732                 // set the counter for this paragraph
3733                 setLabel(parit);
3734
3735                 // Now the insets
3736                 InsetList::const_iterator iit = parit->insetList().begin();
3737                 InsetList::const_iterator end = parit->insetList().end();
3738                 for (; iit != end; ++iit) {
3739                         parit.pos() = iit->pos;
3740                         iit->inset->updateLabels(parit, out);
3741                 }
3742         }
3743 }
3744
3745
3746 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3747         WordLangTuple & word_lang, docstring_list & suggestions) const
3748 {
3749         int progress = 0;
3750         WordLangTuple wl;
3751         suggestions.clear();
3752         word_lang = WordLangTuple();
3753         // OK, we start from here.
3754         DocIterator const end = doc_iterator_end(this);
3755         for (; from != end; from.forwardPos()) {
3756                 // We are only interested in text so remove the math CursorSlice.
3757                 while (from.inMathed()) {
3758                         from.pop_back();
3759                         from.pos()++;
3760                 }
3761                 // If from is at the end of the document (which is possible
3762                 // when leaving the mathed) LyX will crash later.
3763                 if (from == end)
3764                         break;
3765                 to = from;
3766                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3767                         word_lang = wl;
3768                         break;
3769                 }
3770
3771                 // Do not increase progress when from == to, otherwise the word
3772                 // count will be wrong.
3773                 if (from != to) {
3774                         from = to;
3775                         ++progress;
3776                 }
3777         }
3778         return progress;
3779 }
3780
3781
3782 bool Buffer::reload()
3783 {
3784         setBusy(true);
3785         // e.g., read-only status could have changed due to version control
3786         d->filename.refresh();
3787         docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3788
3789         bool const success = loadLyXFile(d->filename);
3790         if (success) {
3791                 updateLabels();
3792                 changed(true);
3793                 errors("Parse");
3794                 message(bformat(_("Document %1$s reloaded."), disp_fn));
3795         } else {
3796                 message(bformat(_("Could not reload document %1$s."), disp_fn));
3797         }       
3798         setBusy(false);
3799         return success;
3800 }
3801
3802
3803 } // namespace lyx