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