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