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