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