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