]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Get rid of Buffer::setReadOnly() pseudo signal.
[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::isBakClean() const
2218 {
2219         return d->bak_clean;
2220 }
2221
2222
2223 bool Buffer::isExternallyModified(CheckMethod method) const
2224 {
2225         LASSERT(d->filename.exists(), /**/);
2226         // if method == timestamp, check timestamp before checksum
2227         return (method == checksum_method
2228                 || d->timestamp_ != d->filename.lastModified())
2229                 && d->checksum_ != d->filename.checksum();
2230 }
2231
2232
2233 void Buffer::saveCheckSum(FileName const & file) const
2234 {
2235         if (file.exists()) {
2236                 d->timestamp_ = file.lastModified();
2237                 d->checksum_ = file.checksum();
2238         } else {
2239                 // in the case of save to a new file.
2240                 d->timestamp_ = 0;
2241                 d->checksum_ = 0;
2242         }
2243 }
2244
2245
2246 void Buffer::markClean() const
2247 {
2248         if (!d->lyx_clean) {
2249                 d->lyx_clean = true;
2250                 updateTitles();
2251         }
2252         // if the .lyx file has been saved, we don't need an
2253         // autosave
2254         d->bak_clean = true;
2255 }
2256
2257
2258 void Buffer::markBakClean() const
2259 {
2260         d->bak_clean = true;
2261 }
2262
2263
2264 void Buffer::setUnnamed(bool flag)
2265 {
2266         d->unnamed = flag;
2267 }
2268
2269
2270 bool Buffer::isUnnamed() const
2271 {
2272         return d->unnamed;
2273 }
2274
2275
2276 /// \note
2277 /// Don't check unnamed, here: isInternal() is used in
2278 /// newBuffer(), where the unnamed flag has not been set by anyone
2279 /// yet. Also, for an internal buffer, there should be no need for
2280 /// retrieving fileName() nor for checking if it is unnamed or not.
2281 bool Buffer::isInternal() const
2282 {
2283         return fileName().extension() == "internal";
2284 }
2285
2286
2287 void Buffer::markDirty()
2288 {
2289         if (d->lyx_clean) {
2290                 d->lyx_clean = false;
2291                 updateTitles();
2292         }
2293         d->bak_clean = false;
2294
2295         DepClean::iterator it = d->dep_clean.begin();
2296         DepClean::const_iterator const end = d->dep_clean.end();
2297
2298         for (; it != end; ++it)
2299                 it->second = false;
2300 }
2301
2302
2303 FileName Buffer::fileName() const
2304 {
2305         return d->filename;
2306 }
2307
2308
2309 string Buffer::absFileName() const
2310 {
2311         return d->filename.absFilename();
2312 }
2313
2314
2315 string Buffer::filePath() const
2316 {
2317         return d->filename.onlyPath().absFilename() + "/";
2318 }
2319
2320
2321 bool Buffer::isReadonly() const
2322 {
2323         return d->read_only;
2324 }
2325
2326
2327 void Buffer::setParent(Buffer const * buffer)
2328 {
2329         // Avoids recursive include.
2330         d->setParent(buffer == this ? 0 : buffer);
2331         updateMacros();
2332 }
2333
2334
2335 Buffer const * Buffer::parent() const
2336 {
2337         return d->parent();
2338 }
2339
2340
2341 void Buffer::collectRelatives(BufferSet & bufs) const
2342 {
2343         bufs.insert(this);
2344         if (parent())
2345                 parent()->collectRelatives(bufs);
2346
2347         // loop over children
2348         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2349         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2350         for (; it != end; ++it)
2351                 bufs.insert(const_cast<Buffer *>(it->first));
2352 }
2353
2354
2355 std::vector<Buffer const *> Buffer::allRelatives() const
2356 {
2357         BufferSet bufs;
2358         collectRelatives(bufs);
2359         BufferSet::iterator it = bufs.begin();
2360         std::vector<Buffer const *> ret;
2361         for (; it != bufs.end(); ++it)
2362                 ret.push_back(*it);
2363         return ret;
2364 }
2365
2366
2367 Buffer const * Buffer::masterBuffer() const
2368 {
2369         Buffer const * const pbuf = d->parent();
2370         if (!pbuf)
2371                 return this;
2372
2373         return pbuf->masterBuffer();
2374 }
2375
2376
2377 bool Buffer::isChild(Buffer * child) const
2378 {
2379         return d->children_positions.find(child) != d->children_positions.end();
2380 }
2381
2382
2383 DocIterator Buffer::firstChildPosition(Buffer const * child)
2384 {
2385         Impl::BufferPositionMap::iterator it;
2386         it = d->children_positions.find(child);
2387         if (it == d->children_positions.end())
2388                 return DocIterator(this);
2389         return it->second;
2390 }
2391
2392
2393 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2394 {
2395         // loop over children
2396         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2397         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2398         for (; it != end; ++it) {
2399                 Buffer * child = const_cast<Buffer *>(it->first);
2400                 clist.push_back(child);
2401                 if (grand_children) {
2402                         // there might be grandchildren
2403                         std::vector<Buffer *> glist = child->getChildren();
2404                         for (vector<Buffer *>::const_iterator git = glist.begin();
2405                                  git != glist.end(); ++git)
2406                                 clist.push_back(*git);
2407                 }
2408         }
2409 }
2410
2411
2412 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2413 {
2414         std::vector<Buffer *> v;
2415         getChildren(v, grand_children);
2416         return v;
2417 }
2418
2419
2420 template<typename M>
2421 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2422 {
2423         if (m.empty())
2424                 return m.end();
2425
2426         typename M::iterator it = m.lower_bound(x);
2427         if (it == m.begin())
2428                 return m.end();
2429
2430         it--;
2431         return it;
2432 }
2433
2434
2435 MacroData const * Buffer::getBufferMacro(docstring const & name,
2436                                          DocIterator const & pos) const
2437 {
2438         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2439
2440         // if paragraphs have no macro context set, pos will be empty
2441         if (pos.empty())
2442                 return 0;
2443
2444         // we haven't found anything yet
2445         DocIterator bestPos = par_iterator_begin();
2446         MacroData const * bestData = 0;
2447
2448         // find macro definitions for name
2449         Impl::NamePositionScopeMacroMap::iterator nameIt
2450                 = d->macros.find(name);
2451         if (nameIt != d->macros.end()) {
2452                 // find last definition in front of pos or at pos itself
2453                 Impl::PositionScopeMacroMap::const_iterator it
2454                         = greatest_below(nameIt->second, pos);
2455                 if (it != nameIt->second.end()) {
2456                         while (true) {
2457                                 // scope ends behind pos?
2458                                 if (pos < it->second.first) {
2459                                         // Looks good, remember this. If there
2460                                         // is no external macro behind this,
2461                                         // we found the right one already.
2462                                         bestPos = it->first;
2463                                         bestData = &it->second.second;
2464                                         break;
2465                                 }
2466
2467                                 // try previous macro if there is one
2468                                 if (it == nameIt->second.begin())
2469                                         break;
2470                                 it--;
2471                         }
2472                 }
2473         }
2474
2475         // find macros in included files
2476         Impl::PositionScopeBufferMap::const_iterator it
2477                 = greatest_below(d->position_to_children, pos);
2478         if (it == d->position_to_children.end())
2479                 // no children before
2480                 return bestData;
2481
2482         while (true) {
2483                 // do we know something better (i.e. later) already?
2484                 if (it->first < bestPos )
2485                         break;
2486
2487                 // scope ends behind pos?
2488                 if (pos < it->second.first) {
2489                         // look for macro in external file
2490                         d->macro_lock = true;
2491                         MacroData const * data
2492                         = it->second.second->getMacro(name, false);
2493                         d->macro_lock = false;
2494                         if (data) {
2495                                 bestPos = it->first;
2496                                 bestData = data;
2497                                 break;
2498                         }
2499                 }
2500
2501                 // try previous file if there is one
2502                 if (it == d->position_to_children.begin())
2503                         break;
2504                 --it;
2505         }
2506
2507         // return the best macro we have found
2508         return bestData;
2509 }
2510
2511
2512 MacroData const * Buffer::getMacro(docstring const & name,
2513         DocIterator const & pos, bool global) const
2514 {
2515         if (d->macro_lock)
2516                 return 0;
2517
2518         // query buffer macros
2519         MacroData const * data = getBufferMacro(name, pos);
2520         if (data != 0)
2521                 return data;
2522
2523         // If there is a master buffer, query that
2524         Buffer const * const pbuf = d->parent();
2525         if (pbuf) {
2526                 d->macro_lock = true;
2527                 MacroData const * macro = pbuf->getMacro(
2528                         name, *this, false);
2529                 d->macro_lock = false;
2530                 if (macro)
2531                         return macro;
2532         }
2533
2534         if (global) {
2535                 data = MacroTable::globalMacros().get(name);
2536                 if (data != 0)
2537                         return data;
2538         }
2539
2540         return 0;
2541 }
2542
2543
2544 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2545 {
2546         // set scope end behind the last paragraph
2547         DocIterator scope = par_iterator_begin();
2548         scope.pit() = scope.lastpit() + 1;
2549
2550         return getMacro(name, scope, global);
2551 }
2552
2553
2554 MacroData const * Buffer::getMacro(docstring const & name,
2555         Buffer const & child, bool global) const
2556 {
2557         // look where the child buffer is included first
2558         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2559         if (it == d->children_positions.end())
2560                 return 0;
2561
2562         // check for macros at the inclusion position
2563         return getMacro(name, it->second, global);
2564 }
2565
2566
2567 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2568 {
2569         pit_type const lastpit = it.lastpit();
2570
2571         // look for macros in each paragraph
2572         while (it.pit() <= lastpit) {
2573                 Paragraph & par = it.paragraph();
2574
2575                 // iterate over the insets of the current paragraph
2576                 InsetList const & insets = par.insetList();
2577                 InsetList::const_iterator iit = insets.begin();
2578                 InsetList::const_iterator end = insets.end();
2579                 for (; iit != end; ++iit) {
2580                         it.pos() = iit->pos;
2581
2582                         // is it a nested text inset?
2583                         if (iit->inset->asInsetText()) {
2584                                 // Inset needs its own scope?
2585                                 InsetText const * itext = iit->inset->asInsetText();
2586                                 bool newScope = itext->isMacroScope();
2587
2588                                 // scope which ends just behind the inset
2589                                 DocIterator insetScope = it;
2590                                 ++insetScope.pos();
2591
2592                                 // collect macros in inset
2593                                 it.push_back(CursorSlice(*iit->inset));
2594                                 updateMacros(it, newScope ? insetScope : scope);
2595                                 it.pop_back();
2596                                 continue;
2597                         }
2598
2599                         // is it an external file?
2600                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2601                                 // get buffer of external file
2602                                 InsetInclude const & inset =
2603                                         static_cast<InsetInclude const &>(*iit->inset);
2604                                 d->macro_lock = true;
2605                                 Buffer * child = inset.getChildBuffer();
2606                                 d->macro_lock = false;
2607                                 if (!child)
2608                                         continue;
2609
2610                                 // register its position, but only when it is
2611                                 // included first in the buffer
2612                                 if (d->children_positions.find(child) ==
2613                                         d->children_positions.end())
2614                                                 d->children_positions[child] = it;
2615
2616                                 // register child with its scope
2617                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2618                                 continue;
2619                         }
2620
2621                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2622                                 continue;
2623
2624                         // get macro data
2625                         MathMacroTemplate & macroTemplate =
2626                                 static_cast<MathMacroTemplate &>(*iit->inset);
2627                         MacroContext mc(this, it);
2628                         macroTemplate.updateToContext(mc);
2629
2630                         // valid?
2631                         bool valid = macroTemplate.validMacro();
2632                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2633                         // then the BufferView's cursor will be invalid in
2634                         // some cases which leads to crashes.
2635                         if (!valid)
2636                                 continue;
2637
2638                         // register macro
2639                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2640                         // instead of 'macroTemplate' defined above... is this correct?
2641                         d->macros[macroTemplate.name()][it] =
2642                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2643                 }
2644
2645                 // next paragraph
2646                 it.pit()++;
2647                 it.pos() = 0;
2648         }
2649 }
2650
2651
2652 void Buffer::updateMacros() const
2653 {
2654         if (d->macro_lock)
2655                 return;
2656
2657         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2658
2659         // start with empty table
2660         d->macros.clear();
2661         d->children_positions.clear();
2662         d->position_to_children.clear();
2663
2664         // Iterate over buffer, starting with first paragraph
2665         // The scope must be bigger than any lookup DocIterator
2666         // later. For the global lookup, lastpit+1 is used, hence
2667         // we use lastpit+2 here.
2668         DocIterator it = par_iterator_begin();
2669         DocIterator outerScope = it;
2670         outerScope.pit() = outerScope.lastpit() + 2;
2671         updateMacros(it, outerScope);
2672 }
2673
2674
2675 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2676 {
2677         InsetIterator it  = inset_iterator_begin(inset());
2678         InsetIterator const end = inset_iterator_end(inset());
2679         for (; it != end; ++it) {
2680                 if (it->lyxCode() == BRANCH_CODE) {
2681                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2682                         docstring const name = br.branch();
2683                         if (!from_master && !params().branchlist().find(name))
2684                                 result.push_back(name);
2685                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2686                                 result.push_back(name);
2687                         continue;
2688                 }
2689                 if (it->lyxCode() == INCLUDE_CODE) {
2690                         // get buffer of external file
2691                         InsetInclude const & ins =
2692                                 static_cast<InsetInclude const &>(*it);
2693                         Buffer * child = ins.getChildBuffer();
2694                         if (!child)
2695                                 continue;
2696                         child->getUsedBranches(result, true);
2697                 }
2698         }
2699         // remove duplicates
2700         result.unique();
2701 }
2702
2703
2704 void Buffer::updateMacroInstances() const
2705 {
2706         LYXERR(Debug::MACROS, "updateMacroInstances for "
2707                 << d->filename.onlyFileName());
2708         DocIterator it = doc_iterator_begin(this);
2709         it.forwardInset();
2710         DocIterator const end = doc_iterator_end(this);
2711         for (; it != end; it.forwardInset()) {
2712                 // look for MathData cells in InsetMathNest insets
2713                 InsetMath * minset = it.nextInset()->asInsetMath();
2714                 if (!minset)
2715                         continue;
2716
2717                 // update macro in all cells of the InsetMathNest
2718                 DocIterator::idx_type n = minset->nargs();
2719                 MacroContext mc = MacroContext(this, it);
2720                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2721                         MathData & data = minset->cell(i);
2722                         data.updateMacros(0, mc);
2723                 }
2724         }
2725 }
2726
2727
2728 void Buffer::listMacroNames(MacroNameSet & macros) const
2729 {
2730         if (d->macro_lock)
2731                 return;
2732
2733         d->macro_lock = true;
2734
2735         // loop over macro names
2736         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2737         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2738         for (; nameIt != nameEnd; ++nameIt)
2739                 macros.insert(nameIt->first);
2740
2741         // loop over children
2742         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2743         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2744         for (; it != end; ++it)
2745                 it->first->listMacroNames(macros);
2746
2747         // call parent
2748         Buffer const * const pbuf = d->parent();
2749         if (pbuf)
2750                 pbuf->listMacroNames(macros);
2751
2752         d->macro_lock = false;
2753 }
2754
2755
2756 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2757 {
2758         Buffer const * const pbuf = d->parent();
2759         if (!pbuf)
2760                 return;
2761
2762         MacroNameSet names;
2763         pbuf->listMacroNames(names);
2764
2765         // resolve macros
2766         MacroNameSet::iterator it = names.begin();
2767         MacroNameSet::iterator end = names.end();
2768         for (; it != end; ++it) {
2769                 // defined?
2770                 MacroData const * data =
2771                 pbuf->getMacro(*it, *this, false);
2772                 if (data) {
2773                         macros.insert(data);
2774
2775                         // we cannot access the original MathMacroTemplate anymore
2776                         // here to calls validate method. So we do its work here manually.
2777                         // FIXME: somehow make the template accessible here.
2778                         if (data->optionals() > 0)
2779                                 features.require("xargs");
2780                 }
2781         }
2782 }
2783
2784
2785 Buffer::References & Buffer::references(docstring const & label)
2786 {
2787         if (d->parent())
2788                 return const_cast<Buffer *>(masterBuffer())->references(label);
2789
2790         RefCache::iterator it = d->ref_cache_.find(label);
2791         if (it != d->ref_cache_.end())
2792                 return it->second.second;
2793
2794         static InsetLabel const * dummy_il = 0;
2795         static References const dummy_refs;
2796         it = d->ref_cache_.insert(
2797                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2798         return it->second.second;
2799 }
2800
2801
2802 Buffer::References const & Buffer::references(docstring const & label) const
2803 {
2804         return const_cast<Buffer *>(this)->references(label);
2805 }
2806
2807
2808 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2809 {
2810         masterBuffer()->d->ref_cache_[label].first = il;
2811 }
2812
2813
2814 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2815 {
2816         return masterBuffer()->d->ref_cache_[label].first;
2817 }
2818
2819
2820 void Buffer::clearReferenceCache() const
2821 {
2822         if (!d->parent())
2823                 d->ref_cache_.clear();
2824 }
2825
2826
2827 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2828         InsetCode code)
2829 {
2830         //FIXME: This does not work for child documents yet.
2831         LASSERT(code == CITE_CODE, /**/);
2832         // Check if the label 'from' appears more than once
2833         vector<docstring> labels;
2834         string paramName;
2835         checkBibInfoCache();
2836         BiblioInfo const & keys = masterBibInfo();
2837         BiblioInfo::const_iterator bit  = keys.begin();
2838         BiblioInfo::const_iterator bend = keys.end();
2839
2840         for (; bit != bend; ++bit)
2841                 // FIXME UNICODE
2842                 labels.push_back(bit->first);
2843         paramName = "key";
2844
2845         if (count(labels.begin(), labels.end(), from) > 1)
2846                 return;
2847
2848         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2849                 if (it->lyxCode() == code) {
2850                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2851                         docstring const oldValue = inset.getParam(paramName);
2852                         if (oldValue == from)
2853                                 inset.setParam(paramName, to);
2854                 }
2855         }
2856 }
2857
2858
2859 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2860         pit_type par_end, bool full_source) const
2861 {
2862         OutputParams runparams(&params().encoding());
2863         runparams.nice = true;
2864         runparams.flavor = params().useXetex ? 
2865                 OutputParams::XETEX : OutputParams::LATEX;
2866         runparams.linelen = lyxrc.plaintext_linelen;
2867         // No side effect of file copying and image conversion
2868         runparams.dryrun = true;
2869
2870         if (full_source) {
2871                 os << "% " << _("Preview source code") << "\n\n";
2872                 d->texrow.reset();
2873                 d->texrow.newline();
2874                 d->texrow.newline();
2875                 if (isDocBook())
2876                         writeDocBookSource(os, absFileName(), runparams, false);
2877                 else
2878                         // latex or literate
2879                         writeLaTeXSource(os, string(), runparams, true, true);
2880         } else {
2881                 runparams.par_begin = par_begin;
2882                 runparams.par_end = par_end;
2883                 if (par_begin + 1 == par_end) {
2884                         os << "% "
2885                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2886                            << "\n\n";
2887                 } else {
2888                         os << "% "
2889                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2890                                         convert<docstring>(par_begin),
2891                                         convert<docstring>(par_end - 1))
2892                            << "\n\n";
2893                 }
2894                 TexRow texrow;
2895                 texrow.reset();
2896                 texrow.newline();
2897                 texrow.newline();
2898                 // output paragraphs
2899                 if (isDocBook())
2900                         docbookParagraphs(text(), *this, os, runparams);
2901                 else 
2902                         // latex or literate
2903                         latexParagraphs(*this, text(), os, texrow, runparams);
2904         }
2905 }
2906
2907
2908 ErrorList & Buffer::errorList(string const & type) const
2909 {
2910         static ErrorList emptyErrorList;
2911         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2912         if (I == d->errorLists.end())
2913                 return emptyErrorList;
2914
2915         return I->second;
2916 }
2917
2918
2919 void Buffer::updateTocItem(std::string const & type,
2920         DocIterator const & dit) const
2921 {
2922         if (gui_)
2923                 gui_->updateTocItem(type, dit);
2924 }
2925
2926
2927 void Buffer::structureChanged() const
2928 {
2929         if (gui_)
2930                 gui_->structureChanged();
2931 }
2932
2933
2934 void Buffer::errors(string const & err, bool from_master) const
2935 {
2936         if (gui_)
2937                 gui_->errors(err, from_master);
2938 }
2939
2940
2941 void Buffer::message(docstring const & msg) const
2942 {
2943         if (gui_)
2944                 gui_->message(msg);
2945 }
2946
2947
2948 void Buffer::setBusy(bool on) const
2949 {
2950         if (gui_)
2951                 gui_->setBusy(on);
2952 }
2953
2954
2955 void Buffer::updateTitles() const
2956 {
2957         if (d->wa_)
2958                 d->wa_->updateTitles();
2959 }
2960
2961
2962 void Buffer::resetAutosaveTimers() const
2963 {
2964         if (gui_)
2965                 gui_->resetAutosaveTimers();
2966 }
2967
2968
2969 bool Buffer::hasGuiDelegate() const
2970 {
2971         return gui_;
2972 }
2973
2974
2975 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2976 {
2977         gui_ = gui;
2978 }
2979
2980
2981
2982 namespace {
2983
2984 class AutoSaveBuffer : public ForkedProcess {
2985 public:
2986         ///
2987         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2988                 : buffer_(buffer), fname_(fname) {}
2989         ///
2990         virtual boost::shared_ptr<ForkedProcess> clone() const
2991         {
2992                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2993         }
2994         ///
2995         int start()
2996         {
2997                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2998                                                  from_utf8(fname_.absFilename())));
2999                 return run(DontWait);
3000         }
3001 private:
3002         ///
3003         virtual int generateChild();
3004         ///
3005         Buffer const & buffer_;
3006         FileName fname_;
3007 };
3008
3009
3010 int AutoSaveBuffer::generateChild()
3011 {
3012 #if defined(__APPLE__)
3013         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3014          *   We should use something else like threads.
3015          *
3016          * Since I do not know how to determine at run time what is the OS X
3017          * version, I just disable forking altogether for now (JMarc)
3018          */
3019         pid_t const pid = -1;
3020 #else
3021         // tmp_ret will be located (usually) in /tmp
3022         // will that be a problem?
3023         // Note that this calls ForkedCalls::fork(), so it's
3024         // ok cross-platform.
3025         pid_t const pid = fork();
3026         // If you want to debug the autosave
3027         // you should set pid to -1, and comment out the fork.
3028         if (pid != 0 && pid != -1)
3029                 return pid;
3030 #endif
3031
3032         // pid = -1 signifies that lyx was unable
3033         // to fork. But we will do the save
3034         // anyway.
3035         bool failed = false;
3036         FileName const tmp_ret = FileName::tempName("lyxauto");
3037         if (!tmp_ret.empty()) {
3038                 buffer_.writeFile(tmp_ret);
3039                 // assume successful write of tmp_ret
3040                 if (!tmp_ret.moveTo(fname_))
3041                         failed = true;
3042         } else
3043                 failed = true;
3044
3045         if (failed) {
3046                 // failed to write/rename tmp_ret so try writing direct
3047                 if (!buffer_.writeFile(fname_)) {
3048                         // It is dangerous to do this in the child,
3049                         // but safe in the parent, so...
3050                         if (pid == -1) // emit message signal.
3051                                 buffer_.message(_("Autosave failed!"));
3052                 }
3053         }
3054
3055         if (pid == 0) // we are the child so...
3056                 _exit(0);
3057
3058         return pid;
3059 }
3060
3061 } // namespace anon
3062
3063
3064 FileName Buffer::getAutosaveFilename() const
3065 {
3066         // if the document is unnamed try to save in the backup dir, else
3067         // in the default document path, and as a last try in the filePath, 
3068         // which will most often be the temporary directory
3069         string fpath;
3070         if (isUnnamed())
3071                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3072                         : lyxrc.backupdir_path;
3073         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3074                 fpath = filePath();
3075
3076         string const fname = "#" + d->filename.onlyFileName() + "#";
3077         return makeAbsPath(fname, fpath);
3078 }
3079
3080
3081 void Buffer::removeAutosaveFile() const
3082 {
3083         FileName const f = getAutosaveFilename();
3084         if (f.exists())
3085                 f.removeFile();
3086 }
3087
3088
3089 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3090 {
3091         FileName const newauto = getAutosaveFilename();
3092         if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3093                 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3094 }
3095
3096
3097 // Perfect target for a thread...
3098 void Buffer::autoSave() const
3099 {
3100         if (isBakClean() || isReadonly()) {
3101                 // We don't save now, but we'll try again later
3102                 resetAutosaveTimers();
3103                 return;
3104         }
3105
3106         // emit message signal.
3107         message(_("Autosaving current document..."));
3108         AutoSaveBuffer autosave(*this, getAutosaveFilename());
3109         autosave.start();
3110
3111         markBakClean();
3112         resetAutosaveTimers();
3113 }
3114
3115
3116 string Buffer::bufferFormat() const
3117 {
3118         string format = params().documentClass().outputFormat();
3119         if (format == "latex") {
3120                 if (params().useXetex)
3121                         return "xetex";
3122                 if (params().encoding().package() == Encoding::japanese)
3123                         return "platex";
3124         }
3125         return format;
3126 }
3127
3128
3129 string Buffer::getDefaultOutputFormat() const
3130 {
3131         if (!params().defaultOutputFormat.empty()
3132             && params().defaultOutputFormat != "default")
3133                 return params().defaultOutputFormat;
3134         typedef vector<Format const *> Formats;
3135         Formats formats = exportableFormats(true);
3136         if (isDocBook()
3137             || isLiterate()
3138             || params().useXetex
3139             || params().encoding().package() == Encoding::japanese) {
3140                 if (formats.empty())
3141                         return string();
3142                 // return the first we find
3143                 return formats.front()->name();
3144         }
3145         return lyxrc.default_view_format;
3146 }
3147
3148
3149
3150 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3151         bool includeall, string & result_file) const
3152 {
3153         string backend_format;
3154         OutputParams runparams(&params().encoding());
3155         runparams.flavor = OutputParams::LATEX;
3156         runparams.linelen = lyxrc.plaintext_linelen;
3157         runparams.includeall = includeall;
3158         vector<string> backs = backends();
3159         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3160                 // Get shortest path to format
3161                 Graph::EdgePath path;
3162                 for (vector<string>::const_iterator it = backs.begin();
3163                      it != backs.end(); ++it) {
3164                         Graph::EdgePath p = theConverters().getPath(*it, format);
3165                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3166                                 backend_format = *it;
3167                                 path = p;
3168                         }
3169                 }
3170                 if (path.empty()) {
3171                         if (!put_in_tempdir) {
3172                                 // Only show this alert if this is an export to a non-temporary
3173                                 // file (not for previewing).
3174                                 Alert::error(_("Couldn't export file"), bformat(
3175                                         _("No information for exporting the format %1$s."),
3176                                         formats.prettyName(format)));
3177                         }
3178                         return false;
3179                 }
3180                 runparams.flavor = theConverters().getFlavor(path);
3181
3182         } else {
3183                 backend_format = format;
3184                 // FIXME: Don't hardcode format names here, but use a flag
3185                 if (backend_format == "pdflatex")
3186                         runparams.flavor = OutputParams::PDFLATEX;
3187         }
3188
3189         string filename = latexName(false);
3190         filename = addName(temppath(), filename);
3191         filename = changeExtension(filename,
3192                                    formats.extension(backend_format));
3193
3194         // fix macros
3195         updateMacroInstances();
3196
3197         // Plain text backend
3198         if (backend_format == "text") {
3199                 runparams.flavor = OutputParams::TEXT;
3200                 writePlaintextFile(*this, FileName(filename), runparams);
3201         }
3202         // HTML backend
3203         else if (backend_format == "xhtml") {
3204                 runparams.flavor = OutputParams::HTML;
3205                 makeLyXHTMLFile(FileName(filename), runparams);
3206         }       else if (backend_format == "lyx")
3207                 writeFile(FileName(filename));
3208         // Docbook backend
3209         else if (isDocBook()) {
3210                 runparams.nice = !put_in_tempdir;
3211                 makeDocBookFile(FileName(filename), runparams);
3212         }
3213         // LaTeX backend
3214         else if (backend_format == format) {
3215                 runparams.nice = true;
3216                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3217                         return false;
3218         } else if (!lyxrc.tex_allows_spaces
3219                    && contains(filePath(), ' ')) {
3220                 Alert::error(_("File name error"),
3221                            _("The directory path to the document cannot contain spaces."));
3222                 return false;
3223         } else {
3224                 runparams.nice = false;
3225                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3226                         return false;
3227         }
3228
3229         string const error_type = (format == "program")
3230                 ? "Build" : bufferFormat();
3231         ErrorList & error_list = d->errorLists[error_type];
3232         string const ext = formats.extension(format);
3233         FileName const tmp_result_file(changeExtension(filename, ext));
3234         bool const success = theConverters().convert(this, FileName(filename),
3235                 tmp_result_file, FileName(absFileName()), backend_format, format,
3236                 error_list);
3237         // Emit the signal to show the error list.
3238         if (format != backend_format) {
3239                 errors(error_type);
3240                 // also to the children, in case of master-buffer-view
3241                 std::vector<Buffer *> clist = getChildren();
3242                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3243                      cit != clist.end(); ++cit)
3244                         (*cit)->errors(error_type, true);
3245         }
3246         if (!success)
3247                 return false;
3248
3249         if (d->cloned_buffer_) {
3250                 // Enable reverse dvi or pdf to work by copying back the texrow
3251                 // object to the cloned buffer.
3252                 // FIXME: There is a possibility of concurrent access to texrow
3253                 // here from the main GUI thread that should be securized.
3254                 d->cloned_buffer_->d->texrow = d->texrow;
3255         }
3256
3257         if (put_in_tempdir) {
3258                 result_file = tmp_result_file.absFilename();
3259                 return true;
3260         }
3261
3262         result_file = changeExtension(exportFileName().absFilename(), ext);
3263         // We need to copy referenced files (e. g. included graphics
3264         // if format == "dvi") to the result dir.
3265         vector<ExportedFile> const files =
3266                 runparams.exportdata->externalFiles(format);
3267         string const dest = onlyPath(result_file);
3268         CopyStatus status = SUCCESS;
3269         
3270         vector<ExportedFile>::const_iterator it = files.begin();
3271         vector<ExportedFile>::const_iterator const en = files.end();
3272         for (; it != en && status != CANCEL; ++it) {
3273                 string const fmt = formats.getFormatFromFile(it->sourceName);
3274                 status = copyFile(fmt, it->sourceName,
3275                         makeAbsPath(it->exportName, dest),
3276                         it->exportName, status == FORCE);
3277         }
3278
3279         if (status == CANCEL) {
3280                 message(_("Document export cancelled."));
3281         } else if (tmp_result_file.exists()) {
3282                 // Finally copy the main file
3283                 status = copyFile(format, tmp_result_file,
3284                         FileName(result_file), result_file,
3285                         status == FORCE);
3286                 message(bformat(_("Document exported as %1$s "
3287                         "to file `%2$s'"),
3288                         formats.prettyName(format),
3289                         makeDisplayPath(result_file)));
3290         } else {
3291                 // This must be a dummy converter like fax (bug 1888)
3292                 message(bformat(_("Document exported as %1$s"),
3293                         formats.prettyName(format)));
3294         }
3295
3296         return true;
3297 }
3298
3299
3300 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3301                       bool includeall) const
3302 {
3303         string result_file;
3304         // (1) export with all included children (omit \includeonly)
3305         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3306                 return false;
3307         // (2) export with included children only
3308         return doExport(format, put_in_tempdir, false, result_file);
3309 }
3310
3311
3312 bool Buffer::preview(string const & format, bool includeall) const
3313 {
3314         string result_file;
3315         // (1) export with all included children (omit \includeonly)
3316         if (includeall && !doExport(format, true, true))
3317                 return false;
3318         // (2) export with included children only
3319         if (!doExport(format, true, false, result_file))
3320                 return false;
3321         return formats.view(*this, FileName(result_file), format);
3322 }
3323
3324
3325 bool Buffer::isExportable(string const & format) const
3326 {
3327         vector<string> backs = backends();
3328         for (vector<string>::const_iterator it = backs.begin();
3329              it != backs.end(); ++it)
3330                 if (theConverters().isReachable(*it, format))
3331                         return true;
3332         return false;
3333 }
3334
3335
3336 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3337 {
3338         vector<string> const backs = backends();
3339         vector<Format const *> result =
3340                 theConverters().getReachable(backs[0], only_viewable, true);
3341         for (vector<string>::const_iterator it = backs.begin() + 1;
3342              it != backs.end(); ++it) {
3343                 vector<Format const *>  r =
3344                         theConverters().getReachable(*it, only_viewable, false);
3345                 result.insert(result.end(), r.begin(), r.end());
3346         }
3347         return result;
3348 }
3349
3350
3351 vector<string> Buffer::backends() const
3352 {
3353         vector<string> v;
3354         v.push_back(bufferFormat());
3355         // FIXME: Don't hardcode format names here, but use a flag
3356         if (v.back() == "latex")
3357                 v.push_back("pdflatex");
3358         v.push_back("xhtml");
3359         v.push_back("text");
3360         v.push_back("lyx");
3361         return v;
3362 }
3363
3364
3365 bool Buffer::readFileHelper(FileName const & s)
3366 {
3367         // File information about normal file
3368         if (!s.exists()) {
3369                 docstring const file = makeDisplayPath(s.absFilename(), 50);
3370                 docstring text = bformat(_("The specified document\n%1$s"
3371                                                      "\ncould not be read."), file);
3372                 Alert::error(_("Could not read document"), text);
3373                 return false;
3374         }
3375
3376         // Check if emergency save file exists and is newer.
3377         FileName const e(s.absFilename() + ".emergency");
3378
3379         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3380                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3381                 docstring const text =
3382                         bformat(_("An emergency save of the document "
3383                                   "%1$s exists.\n\n"
3384                                                "Recover emergency save?"), file);
3385                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3386                                       _("&Recover"),  _("&Load Original"),
3387                                       _("&Cancel")))
3388                 {
3389                 case 0: {
3390                         // the file is not saved if we load the emergency file.
3391                         markDirty();
3392                         docstring str;
3393                         bool res;
3394
3395                         if ((res = readFile(e)) == success)
3396                                 str = _("Document was successfully recovered.");
3397                         else
3398                                 str = _("Document was NOT successfully recovered.");
3399                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3400                                                 from_utf8(e.absFilename()));
3401
3402                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3403                                         _("&Remove"), _("&Keep it"))) {
3404                                 e.removeFile();
3405                                 if (res == success)
3406                                         Alert::warning(_("Emergency file deleted"),
3407                                                 _("Do not forget to save your file now!"), true);
3408                                 }
3409                         return res;
3410                 }
3411                 case 1:
3412                         if (!Alert::prompt(_("Delete emergency file?"),
3413                                         _("Remove emergency file now?"), 1, 1,
3414                                         _("&Remove"), _("&Keep it")))
3415                                 e.removeFile();
3416                         break;
3417                 default:
3418                         return false;
3419                 }
3420         }
3421
3422         // Now check if autosave file is newer.
3423         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3424
3425         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3426                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3427                 docstring const text =
3428                         bformat(_("The backup of the document "
3429                                   "%1$s is newer.\n\nLoad the "
3430                                                "backup instead?"), file);
3431                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3432                                       _("&Load backup"), _("Load &original"),
3433                                       _("&Cancel") ))
3434                 {
3435                 case 0:
3436                         // the file is not saved if we load the autosave file.
3437                         markDirty();
3438                         return readFile(a);
3439                 case 1:
3440                         // Here we delete the autosave
3441                         a.removeFile();
3442                         break;
3443                 default:
3444                         return false;
3445                 }
3446         }
3447         return readFile(s);
3448 }
3449
3450
3451 bool Buffer::loadLyXFile(FileName const & s)
3452 {
3453         // If the file is not readable, we try to
3454         // retrieve the file from version control.
3455         if (!s.isReadableFile()
3456                   && !LyXVC::file_not_found_hook(s))
3457                 return false;
3458         
3459         if (s.isReadableFile()
3460                   && readFileHelper(s)) {
3461                 lyxvc().file_found_hook(s);
3462                 setReadonly(!s.isWritable());
3463                 return true;
3464         }
3465         return false;
3466 }
3467
3468
3469 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3470 {
3471         TeXErrors::Errors::const_iterator cit = terr.begin();
3472         TeXErrors::Errors::const_iterator end = terr.end();
3473
3474         for (; cit != end; ++cit) {
3475                 int id_start = -1;
3476                 int pos_start = -1;
3477                 int errorRow = cit->error_in_line;
3478                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3479                                                        pos_start);
3480                 int id_end = -1;
3481                 int pos_end = -1;
3482                 do {
3483                         ++errorRow;
3484                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3485                 } while (found && id_start == id_end && pos_start == pos_end);
3486
3487                 errorList.push_back(ErrorItem(cit->error_desc,
3488                         cit->error_text, id_start, pos_start, pos_end));
3489         }
3490 }
3491
3492
3493 void Buffer::setBuffersForInsets() const
3494 {
3495         inset().setBuffer(const_cast<Buffer &>(*this)); 
3496 }
3497
3498
3499 void Buffer::updateLabels(UpdateScope scope, UpdateType utype) const
3500 {
3501         // Use the master text class also for child documents
3502         Buffer const * const master = masterBuffer();
3503         DocumentClass const & textclass = master->params().documentClass();
3504         
3505         // do this only if we are the top-level Buffer
3506         if (scope != UpdateMaster || master == this)
3507                 checkBibInfoCache();
3508
3509         // keep the buffers to be children in this set. If the call from the
3510         // master comes back we can see which of them were actually seen (i.e.
3511         // via an InsetInclude). The remaining ones in the set need still be updated.
3512         static std::set<Buffer const *> bufToUpdate;
3513         if (scope == UpdateMaster) {
3514                 // If this is a child document start with the master
3515                 if (master != this) {
3516                         bufToUpdate.insert(this);
3517                         master->updateLabels(UpdateMaster, utype);
3518                         // Do this here in case the master has no gui associated with it. Then, 
3519                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3520                         if (!master->gui_)
3521                                 structureChanged();
3522
3523                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3524                         if (bufToUpdate.find(this) == bufToUpdate.end())
3525                                 return;
3526                 }
3527
3528                 // start over the counters in the master
3529                 textclass.counters().reset();
3530         }
3531
3532         // update will be done below for this buffer
3533         bufToUpdate.erase(this);
3534
3535         // update all caches
3536         clearReferenceCache();
3537         updateMacros();
3538
3539         Buffer & cbuf = const_cast<Buffer &>(*this);
3540
3541         LASSERT(!text().paragraphs().empty(), /**/);
3542
3543         // do the real work
3544         ParIterator parit = cbuf.par_iterator_begin();
3545         updateLabels(parit, utype);
3546
3547         if (master != this)
3548                 // TocBackend update will be done later.
3549                 return;
3550
3551         cbuf.tocBackend().update();
3552         if (scope == UpdateMaster)
3553                 cbuf.structureChanged();
3554 }
3555
3556
3557 static depth_type getDepth(DocIterator const & it)
3558 {
3559         depth_type depth = 0;
3560         for (size_t i = 0 ; i < it.depth() ; ++i)
3561                 if (!it[i].inset().inMathed())
3562                         depth += it[i].paragraph().getDepth() + 1;
3563         // remove 1 since the outer inset does not count
3564         return depth - 1;
3565 }
3566
3567 static depth_type getItemDepth(ParIterator const & it)
3568 {
3569         Paragraph const & par = *it;
3570         LabelType const labeltype = par.layout().labeltype;
3571
3572         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3573                 return 0;
3574
3575         // this will hold the lowest depth encountered up to now.
3576         depth_type min_depth = getDepth(it);
3577         ParIterator prev_it = it;
3578         while (true) {
3579                 if (prev_it.pit())
3580                         --prev_it.top().pit();
3581                 else {
3582                         // start of nested inset: go to outer par
3583                         prev_it.pop_back();
3584                         if (prev_it.empty()) {
3585                                 // start of document: nothing to do
3586                                 return 0;
3587                         }
3588                 }
3589
3590                 // We search for the first paragraph with same label
3591                 // that is not more deeply nested.
3592                 Paragraph & prev_par = *prev_it;
3593                 depth_type const prev_depth = getDepth(prev_it);
3594                 if (labeltype == prev_par.layout().labeltype) {
3595                         if (prev_depth < min_depth)
3596                                 return prev_par.itemdepth + 1;
3597                         if (prev_depth == min_depth)
3598                                 return prev_par.itemdepth;
3599                 }
3600                 min_depth = min(min_depth, prev_depth);
3601                 // small optimization: if we are at depth 0, we won't
3602                 // find anything else
3603                 if (prev_depth == 0)
3604                         return 0;
3605         }
3606 }
3607
3608
3609 static bool needEnumCounterReset(ParIterator const & it)
3610 {
3611         Paragraph const & par = *it;
3612         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3613         depth_type const cur_depth = par.getDepth();
3614         ParIterator prev_it = it;
3615         while (prev_it.pit()) {
3616                 --prev_it.top().pit();
3617                 Paragraph const & prev_par = *prev_it;
3618                 if (prev_par.getDepth() <= cur_depth)
3619                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3620         }
3621         // start of nested inset: reset
3622         return true;
3623 }
3624
3625
3626 // set the label of a paragraph. This includes the counters.
3627 void Buffer::setLabel(ParIterator & it, UpdateType utype) const
3628 {
3629         BufferParams const & bp = this->masterBuffer()->params();
3630         DocumentClass const & textclass = bp.documentClass();
3631         Paragraph & par = it.paragraph();
3632         Layout const & layout = par.layout();
3633         Counters & counters = textclass.counters();
3634
3635         if (par.params().startOfAppendix()) {
3636                 // FIXME: only the counter corresponding to toplevel
3637                 // sectioning should be reset
3638                 counters.reset();
3639                 counters.appendix(true);
3640         }
3641         par.params().appendix(counters.appendix());
3642
3643         // Compute the item depth of the paragraph
3644         par.itemdepth = getItemDepth(it);
3645
3646         if (layout.margintype == MARGIN_MANUAL
3647             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3648                 if (par.params().labelWidthString().empty())
3649                         par.params().labelWidthString(par.expandLabel(layout, bp));
3650         } else {
3651                 par.params().labelWidthString(docstring());
3652         }
3653
3654         switch(layout.labeltype) {
3655         case LABEL_COUNTER:
3656                 if (layout.toclevel <= bp.secnumdepth
3657                     && (layout.latextype != LATEX_ENVIRONMENT
3658                         || it.text()->isFirstInSequence(it.pit()))) {
3659                         counters.step(layout.counter, utype);
3660                         par.params().labelString(
3661                                 par.expandLabel(layout, bp));
3662                 } else
3663                         par.params().labelString(docstring());
3664                 break;
3665
3666         case LABEL_ITEMIZE: {
3667                 // At some point of time we should do something more
3668                 // clever here, like:
3669                 //   par.params().labelString(
3670                 //    bp.user_defined_bullet(par.itemdepth).getText());
3671                 // for now, use a simple hardcoded label
3672                 docstring itemlabel;
3673                 switch (par.itemdepth) {
3674                 case 0:
3675                         itemlabel = char_type(0x2022);
3676                         break;
3677                 case 1:
3678                         itemlabel = char_type(0x2013);
3679                         break;
3680                 case 2:
3681                         itemlabel = char_type(0x2217);
3682                         break;
3683                 case 3:
3684                         itemlabel = char_type(0x2219); // or 0x00b7
3685                         break;
3686                 }
3687                 par.params().labelString(itemlabel);
3688                 break;
3689         }
3690
3691         case LABEL_ENUMERATE: {
3692                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3693
3694                 switch (par.itemdepth) {
3695                 case 2:
3696                         enumcounter += 'i';
3697                 case 1:
3698                         enumcounter += 'i';
3699                 case 0:
3700                         enumcounter += 'i';
3701                         break;
3702                 case 3:
3703                         enumcounter += "iv";
3704                         break;
3705                 default:
3706                         // not a valid enumdepth...
3707                         break;
3708                 }
3709
3710                 // Maybe we have to reset the enumeration counter.
3711                 if (needEnumCounterReset(it))
3712                         counters.reset(enumcounter);
3713                 counters.step(enumcounter, utype);
3714
3715                 string const & lang = par.getParLanguage(bp)->code();
3716                 par.params().labelString(counters.theCounter(enumcounter, lang));
3717
3718                 break;
3719         }
3720
3721         case LABEL_SENSITIVE: {
3722                 string const & type = counters.current_float();
3723                 docstring full_label;
3724                 if (type.empty())
3725                         full_label = this->B_("Senseless!!! ");
3726                 else {
3727                         docstring name = this->B_(textclass.floats().getType(type).name());
3728                         if (counters.hasCounter(from_utf8(type))) {
3729                                 string const & lang = par.getParLanguage(bp)->code();
3730                                 counters.step(from_utf8(type), utype);
3731                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3732                                                      name, 
3733                                                      counters.theCounter(from_utf8(type), lang));
3734                         } else
3735                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3736                 }
3737                 par.params().labelString(full_label);   
3738                 break;
3739         }
3740
3741         case LABEL_NO_LABEL:
3742                 par.params().labelString(docstring());
3743                 break;
3744
3745         case LABEL_MANUAL:
3746         case LABEL_TOP_ENVIRONMENT:
3747         case LABEL_CENTERED_TOP_ENVIRONMENT:
3748         case LABEL_STATIC:      
3749         case LABEL_BIBLIO:
3750                 par.params().labelString(par.expandLabel(layout, bp));
3751                 break;
3752         }
3753 }
3754
3755
3756 void Buffer::updateLabels(ParIterator & parit, UpdateType utype) const
3757 {
3758         LASSERT(parit.pit() == 0, /**/);
3759
3760         // set the position of the text in the buffer to be able
3761         // to resolve macros in it. This has nothing to do with
3762         // labels, but by putting it here we avoid implementing
3763         // a whole bunch of traversal routines just for this call.
3764         parit.text()->setMacrocontextPosition(parit);
3765
3766         depth_type maxdepth = 0;
3767         pit_type const lastpit = parit.lastpit();
3768         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3769                 // reduce depth if necessary
3770                 parit->params().depth(min(parit->params().depth(), maxdepth));
3771                 maxdepth = parit->getMaxDepthAfter();
3772
3773                 if (utype == OutputUpdate) {
3774                         // track the active counters
3775                         // we have to do this for the master buffer, since the local
3776                         // buffer isn't tracking anything.
3777                         masterBuffer()->params().documentClass().counters().
3778                                         setActiveLayout(parit->layout());
3779                 }
3780                 
3781                 // set the counter for this paragraph
3782                 setLabel(parit, utype);
3783
3784                 // now the insets
3785                 InsetList::const_iterator iit = parit->insetList().begin();
3786                 InsetList::const_iterator end = parit->insetList().end();
3787                 for (; iit != end; ++iit) {
3788                         parit.pos() = iit->pos;
3789                         iit->inset->updateLabels(parit, utype);
3790                 }
3791         }
3792 }
3793
3794
3795 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3796         WordLangTuple & word_lang, docstring_list & suggestions) const
3797 {
3798         int progress = 0;
3799         WordLangTuple wl;
3800         suggestions.clear();
3801         word_lang = WordLangTuple();
3802         // OK, we start from here.
3803         DocIterator const end = doc_iterator_end(this);
3804         for (; from != end; from.forwardPos()) {
3805                 // We are only interested in text so remove the math CursorSlice.
3806                 while (from.inMathed()) {
3807                         from.pop_back();
3808                         from.pos()++;
3809                 }
3810                 // If from is at the end of the document (which is possible
3811                 // when leaving the mathed) LyX will crash later.
3812                 if (from == end)
3813                         break;
3814                 to = from;
3815                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3816                         word_lang = wl;
3817                         break;
3818                 }
3819
3820                 // Do not increase progress when from == to, otherwise the word
3821                 // count will be wrong.
3822                 if (from != to) {
3823                         from = to;
3824                         ++progress;
3825                 }
3826         }
3827         return progress;
3828 }
3829
3830
3831 bool Buffer::reload()
3832 {
3833         setBusy(true);
3834         // e.g., read-only status could have changed due to version control
3835         d->filename.refresh();
3836         docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3837
3838         bool const success = loadLyXFile(d->filename);
3839         if (success) {
3840                 updateLabels();
3841                 changed(true);
3842                 markClean();
3843                 message(bformat(_("Document %1$s reloaded."), disp_fn));
3844         } else {
3845                 message(bformat(_("Could not reload document %1$s."), disp_fn));
3846         }       
3847         setBusy(false);
3848         errors("Parse");
3849         return success;
3850 }
3851
3852
3853 } // namespace lyx