]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Part of r32942. We want to avoid reload flickering when
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "DispatchResult.h"
28 #include "DocIterator.h"
29 #include "Encoding.h"
30 #include "ErrorList.h"
31 #include "Exporter.h"
32 #include "Format.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "IndicesList.h"
36 #include "InsetIterator.h"
37 #include "InsetList.h"
38 #include "Language.h"
39 #include "LaTeXFeatures.h"
40 #include "LaTeX.h"
41 #include "Layout.h"
42 #include "Lexer.h"
43 #include "LyXAction.h"
44 #include "LyX.h"
45 #include "LyXFunc.h"
46 #include "LyXRC.h"
47 #include "LyXVC.h"
48 #include "output_docbook.h"
49 #include "output.h"
50 #include "output_latex.h"
51 #include "output_xhtml.h"
52 #include "output_plaintext.h"
53 #include "Paragraph.h"
54 #include "ParagraphParameters.h"
55 #include "ParIterator.h"
56 #include "PDFOptions.h"
57 #include "SpellChecker.h"
58 #include "sgml.h"
59 #include "TexRow.h"
60 #include "TexStream.h"
61 #include "Text.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
64 #include "Undo.h"
65 #include "VCBackend.h"
66 #include "version.h"
67 #include "WordLangTuple.h"
68 #include "WordList.h"
69
70 #include "insets/InsetBibitem.h"
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetText.h"
75
76 #include "mathed/MacroTable.h"
77 #include "mathed/MathMacroTemplate.h"
78 #include "mathed/MathSupport.h"
79
80 #include "frontends/alert.h"
81 #include "frontends/Delegates.h"
82 #include "frontends/WorkAreaManager.h"
83
84 #include "graphics/Previews.h"
85
86 #include "support/lassert.h"
87 #include "support/convert.h"
88 #include "support/debug.h"
89 #include "support/docstring_list.h"
90 #include "support/ExceptionMessage.h"
91 #include "support/FileName.h"
92 #include "support/FileNameList.h"
93 #include "support/filetools.h"
94 #include "support/ForkedCalls.h"
95 #include "support/gettext.h"
96 #include "support/gzstream.h"
97 #include "support/lstrings.h"
98 #include "support/lyxalgo.h"
99 #include "support/os.h"
100 #include "support/Package.h"
101 #include "support/Path.h"
102 #include "support/Systemcall.h"
103 #include "support/textutils.h"
104 #include "support/types.h"
105
106 #include <boost/bind.hpp>
107 #include <boost/shared_ptr.hpp>
108
109 #include <algorithm>
110 #include <fstream>
111 #include <iomanip>
112 #include <map>
113 #include <set>
114 #include <sstream>
115 #include <stack>
116 #include <vector>
117
118 using namespace std;
119 using namespace lyx::support;
120
121 namespace lyx {
122
123 namespace Alert = frontend::Alert;
124 namespace os = support::os;
125
126 namespace {
127
128 // Do not remove the comment below, so we get merge conflict in
129 // independent branches. Instead add your own.
130 int const LYX_FORMAT = 376; // jspitzm: support for unincluded file maintenance
131
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134
135 void showPrintError(string const & name)
136 {
137         docstring str = bformat(_("Could not print the document %1$s.\n"
138                                             "Check that your printer is set up correctly."),
139                              makeDisplayPath(name, 50));
140         Alert::error(_("Print document failed"), str);
141 }
142
143 } // namespace anon
144
145 class BufferSet : public std::set<Buffer const *> {};
146
147 class Buffer::Impl
148 {
149 public:
150         Impl(Buffer & parent, FileName const & file, bool readonly, Buffer const * cloned_buffer);
151
152         ~Impl()
153         {
154                 if (wa_) {
155                         wa_->closeAll();
156                         delete wa_;
157                 }
158                 delete inset;
159         }
160
161         BufferParams params;
162         LyXVC lyxvc;
163         FileName temppath;
164         mutable TexRow texrow;
165
166         /// need to regenerate .tex?
167         DepClean dep_clean;
168
169         /// is save needed?
170         mutable bool lyx_clean;
171
172         /// is autosave needed?
173         mutable bool bak_clean;
174
175         /// is this a unnamed file (New...)?
176         bool unnamed;
177
178         /// buffer is r/o
179         bool read_only;
180
181         /// name of the file the buffer is associated with.
182         FileName filename;
183
184         /** Set to true only when the file is fully loaded.
185          *  Used to prevent the premature generation of previews
186          *  and by the citation inset.
187          */
188         bool file_fully_loaded;
189
190         ///
191         mutable TocBackend toc_backend;
192
193         /// macro tables
194         typedef pair<DocIterator, MacroData> ScopeMacro;
195         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
196         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
197         /// map from the macro name to the position map,
198         /// which maps the macro definition position to the scope and the MacroData.
199         NamePositionScopeMacroMap macros;
200         bool macro_lock;
201
202         /// positions of child buffers in the buffer
203         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
204         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
205         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
206         /// position of children buffers in this buffer
207         BufferPositionMap children_positions;
208         /// map from children inclusion positions to their scope and their buffer
209         PositionScopeBufferMap position_to_children;
210
211         /// Container for all sort of Buffer dependant errors.
212         map<string, ErrorList> errorLists;
213
214         /// timestamp and checksum used to test if the file has been externally
215         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
216         time_t timestamp_;
217         unsigned long checksum_;
218
219         ///
220         frontend::WorkAreaManager * wa_;
221
222         ///
223         Undo undo_;
224
225         /// A cache for the bibfiles (including bibfiles of loaded child
226         /// documents), needed for appropriate update of natbib labels.
227         mutable support::FileNameList bibfiles_cache_;
228
229         // FIXME The caching mechanism could be improved. At present, we have a
230         // cache for each Buffer, that caches all the bibliography info for that
231         // Buffer. A more efficient solution would be to have a global cache per
232         // file, and then to construct the Buffer's bibinfo from that.
233         /// A cache for bibliography info
234         mutable BiblioInfo bibinfo_;
235         /// whether the bibinfo cache is valid
236         bool bibinfo_cache_valid_;
237         /// Cache of timestamps of .bib files
238         map<FileName, time_t> bibfile_status_;
239
240         mutable RefCache ref_cache_;
241
242         /// our Text that should be wrapped in an InsetText
243         InsetText * inset;
244
245         /// This is here to force the test to be done whenever parent_buffer
246         /// is accessed.
247         Buffer const * parent() const { 
248                 // if parent_buffer is not loaded, then it has been unloaded,
249                 // which means that parent_buffer is an invalid pointer. So we
250                 // set it to null in that case.
251                 if (!theBufferList().isLoaded(parent_buffer))
252                         parent_buffer = 0;
253                 return parent_buffer; 
254         }
255         ///
256         void setParent(Buffer const * pb) {
257                 if (parent_buffer && pb && parent_buffer != pb)
258                         LYXERR0("Warning: a buffer should not have two parents!");
259                 parent_buffer = pb;
260         }
261
262         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
263         /// This one is useful for preview detached in a thread.
264         Buffer const * cloned_buffer_;
265
266 private:
267         /// So we can force access via the accessors.
268         mutable Buffer const * parent_buffer;
269
270 };
271
272
273 /// Creates the per buffer temporary directory
274 static FileName createBufferTmpDir()
275 {
276         static int count;
277         // We are in our own directory.  Why bother to mangle name?
278         // In fact I wrote this code to circumvent a problematic behaviour
279         // (bug?) of EMX mkstemp().
280         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
281                 convert<string>(count++));
282
283         if (!tmpfl.createDirectory(0777)) {
284                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
285                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
286                         from_utf8(tmpfl.absFilename())));
287         }
288         return tmpfl;
289 }
290
291
292 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_,
293         Buffer const * cloned_buffer)
294         : lyx_clean(true), bak_clean(true), unnamed(false),
295           read_only(readonly_), filename(file), file_fully_loaded(false),
296           toc_backend(&parent), macro_lock(false), timestamp_(0),
297           checksum_(0), wa_(0), undo_(parent), bibinfo_cache_valid_(false),
298           cloned_buffer_(cloned_buffer), parent_buffer(0)
299 {
300         if (!cloned_buffer_) {
301                 temppath = createBufferTmpDir();
302                 lyxvc.setBuffer(&parent);
303                 if (use_gui)
304                         wa_ = new frontend::WorkAreaManager;
305                 return;
306         }
307         temppath = cloned_buffer_->d->temppath;
308         file_fully_loaded = true;
309         params = cloned_buffer_->d->params;
310         bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
311         bibinfo_ = cloned_buffer_->d->bibinfo_;
312         bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
313         bibfile_status_ = cloned_buffer_->d->bibfile_status_;
314 }
315
316
317 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
318         : d(new Impl(*this, FileName(file), readonly, cloned_buffer)), gui_(0)
319 {
320         LYXERR(Debug::INFO, "Buffer::Buffer()");
321         if (cloned_buffer) {
322                 d->inset = new InsetText(*cloned_buffer->d->inset);
323                 d->inset->setBuffer(*this);
324                 // FIXME: optimize this loop somewhat, maybe by creating a new
325                 // general recursive Inset::setId().
326                 DocIterator it = doc_iterator_begin(this);
327                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
328                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
329                         it.paragraph().setId(cloned_it.paragraph().id());
330         } else
331                 d->inset = new InsetText(this);
332         d->inset->setAutoBreakRows(true);
333         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
334 }
335
336
337 Buffer::~Buffer()
338 {
339         LYXERR(Debug::INFO, "Buffer::~Buffer()");
340         // here the buffer should take care that it is
341         // saved properly, before it goes into the void.
342
343         // GuiView already destroyed
344         gui_ = 0;
345
346         if (isInternal()) {
347                 // No need to do additional cleanups for internal buffer.
348                 delete d;
349                 return;
350         }
351
352         // loop over children
353         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
354         Impl::BufferPositionMap::iterator end = d->children_positions.end();
355         for (; it != end; ++it) {
356                 Buffer * child = const_cast<Buffer *>(it->first);
357                 if (d->cloned_buffer_)
358                         delete child;
359                 // The child buffer might have been closed already.
360                 else if (theBufferList().isLoaded(child))
361                         theBufferList().releaseChild(this, child);
362         }
363
364         if (!isClean()) {
365                 docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
366                 msg += emergencyWrite();
367                 Alert::warning(_("Attempting to close changed document!"), msg);
368         }
369                 
370         // clear references to children in macro tables
371         d->children_positions.clear();
372         d->position_to_children.clear();
373
374         if (!d->cloned_buffer_ && !d->temppath.destroyDirectory()) {
375                 Alert::warning(_("Could not remove temporary directory"),
376                         bformat(_("Could not remove the temporary directory %1$s"),
377                         from_utf8(d->temppath.absFilename())));
378         }
379
380         // Remove any previewed LaTeX snippets associated with this buffer.
381         thePreviews().removeLoader(*this);
382
383         delete d;
384 }
385
386
387 Buffer * Buffer::clone() const
388 {
389         Buffer * buffer_clone = new Buffer(fileName().absFilename(), false, this);
390         buffer_clone->d->macro_lock = true;
391         buffer_clone->d->children_positions.clear();
392         // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
393         // math macro caches need to be rethought and simplified.
394         // I am not sure wether we should handle Buffer cloning here or in BufferList.
395         // Right now BufferList knows nothing about buffer clones.
396         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
397         Impl::BufferPositionMap::iterator end = d->children_positions.end();
398         for (; it != end; ++it) {
399                 DocIterator dit = it->second.clone(buffer_clone);
400                 dit.setBuffer(buffer_clone);
401                 Buffer * child = const_cast<Buffer *>(it->first);
402                 Buffer * child_clone = child->clone();
403                 Inset * inset = dit.nextInset();
404                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
405                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
406                 inset_inc->setChildBuffer(child_clone);
407                 child_clone->d->setParent(buffer_clone);
408                 buffer_clone->setChild(dit, child_clone);
409         }
410         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, 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, false);
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, false, 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                 bool const update_unincluded =
2009                                 params().maintain_unincluded_children
2010                                 && !params().getIncludedChildren().empty();
2011                 if (!doExport("dvi", true, update_unincluded)) {
2012                         showPrintError(absFileName());
2013                         dr.setMessage(_("Error exporting to DVI."));
2014                         break;
2015                 }
2016
2017                 // Push directory path.
2018                 string const path = temppath();
2019                 // Prevent the compiler from optimizing away p
2020                 FileName pp(path);
2021                 PathChanger p(pp);
2022
2023                 // there are three cases here:
2024                 // 1. we print to a file
2025                 // 2. we print directly to a printer
2026                 // 3. we print using a spool command (print to file first)
2027                 Systemcall one;
2028                 int res = 0;
2029                 string const dviname = changeExtension(latexName(true), "dvi");
2030
2031                 if (target == "printer") {
2032                         if (!lyxrc.print_spool_command.empty()) {
2033                                 // case 3: print using a spool
2034                                 string const psname = changeExtension(dviname,".ps");
2035                                 command += ' ' + lyxrc.print_to_file
2036                                         + quoteName(psname)
2037                                         + ' '
2038                                         + quoteName(dviname);
2039
2040                                 string command2 = lyxrc.print_spool_command + ' ';
2041                                 if (target_name != "default") {
2042                                         command2 += lyxrc.print_spool_printerprefix
2043                                                 + target_name
2044                                                 + ' ';
2045                                 }
2046                                 command2 += quoteName(psname);
2047                                 // First run dvips.
2048                                 // If successful, then spool command
2049                                 res = one.startscript(Systemcall::Wait, command);
2050
2051                                 if (res == 0) {
2052                                         // If there's no GUI, we have to wait on this command. Otherwise,
2053                                         // LyX deletes the temporary directory, and with it the spooled
2054                                         // file, before it can be printed!!
2055                                         Systemcall::Starttype stype = use_gui ?
2056                                                 Systemcall::DontWait : Systemcall::Wait;
2057                                         res = one.startscript(stype, command2);
2058                                 }
2059                         } else {
2060                                 // case 2: print directly to a printer
2061                                 if (target_name != "default")
2062                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2063                                 // as above....
2064                                 Systemcall::Starttype stype = use_gui ?
2065                                         Systemcall::DontWait : Systemcall::Wait;
2066                                 res = one.startscript(stype, command + quoteName(dviname));
2067                         }
2068
2069                 } else {
2070                         // case 1: print to a file
2071                         FileName const filename(makeAbsPath(target_name, filePath()));
2072                         FileName const dvifile(makeAbsPath(dviname, path));
2073                         if (filename.exists()) {
2074                                 docstring text = bformat(
2075                                         _("The file %1$s already exists.\n\n"
2076                                           "Do you want to overwrite that file?"),
2077                                         makeDisplayPath(filename.absFilename()));
2078                                 if (Alert::prompt(_("Overwrite file?"),
2079                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2080                                         break;
2081                         }
2082                         command += ' ' + lyxrc.print_to_file
2083                                 + quoteName(filename.toFilesystemEncoding())
2084                                 + ' '
2085                                 + quoteName(dvifile.toFilesystemEncoding());
2086                         // as above....
2087                         Systemcall::Starttype stype = use_gui ?
2088                                 Systemcall::DontWait : Systemcall::Wait;
2089                         res = one.startscript(stype, command);
2090                 }
2091
2092                 if (res == 0) 
2093                         dr.setError(false);
2094                 else {
2095                         dr.setMessage(_("Error running external commands."));
2096                         showPrintError(absFileName());
2097                 }
2098                 break;
2099         }
2100
2101         case LFUN_BUFFER_LANGUAGE: {
2102                 Language const * oldL = params().language;
2103                 Language const * newL = languages.getLanguage(argument);
2104                 if (!newL || oldL == newL)
2105                         break;
2106                 if (oldL->rightToLeft() == newL->rightToLeft() && !isMultiLingual())
2107                         changeLanguage(oldL, newL);
2108                 break;
2109         }
2110
2111         default:
2112                 dispatched = false;
2113                 break;
2114         }
2115         dr.dispatched(dispatched);
2116         undo().endUndoGroup();
2117 }
2118
2119
2120 void Buffer::changeLanguage(Language const * from, Language const * to)
2121 {
2122         LASSERT(from, /**/);
2123         LASSERT(to, /**/);
2124
2125         for_each(par_iterator_begin(),
2126                  par_iterator_end(),
2127                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2128 }
2129
2130
2131 bool Buffer::isMultiLingual() const
2132 {
2133         ParConstIterator end = par_iterator_end();
2134         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2135                 if (it->isMultiLingual(params()))
2136                         return true;
2137
2138         return false;
2139 }
2140
2141
2142 DocIterator Buffer::getParFromID(int const id) const
2143 {
2144         Buffer * buf = const_cast<Buffer *>(this);
2145         if (id < 0) {
2146                 // John says this is called with id == -1 from undo
2147                 lyxerr << "getParFromID(), id: " << id << endl;
2148                 return doc_iterator_end(buf);
2149         }
2150
2151         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2152                 if (it.paragraph().id() == id)
2153                         return it;
2154
2155         return doc_iterator_end(buf);
2156 }
2157
2158
2159 bool Buffer::hasParWithID(int const id) const
2160 {
2161         return !getParFromID(id).atEnd();
2162 }
2163
2164
2165 ParIterator Buffer::par_iterator_begin()
2166 {
2167         return ParIterator(doc_iterator_begin(this));
2168 }
2169
2170
2171 ParIterator Buffer::par_iterator_end()
2172 {
2173         return ParIterator(doc_iterator_end(this));
2174 }
2175
2176
2177 ParConstIterator Buffer::par_iterator_begin() const
2178 {
2179         return ParConstIterator(doc_iterator_begin(this));
2180 }
2181
2182
2183 ParConstIterator Buffer::par_iterator_end() const
2184 {
2185         return ParConstIterator(doc_iterator_end(this));
2186 }
2187
2188
2189 Language const * Buffer::language() const
2190 {
2191         return params().language;
2192 }
2193
2194
2195 docstring const Buffer::B_(string const & l10n) const
2196 {
2197         return params().B_(l10n);
2198 }
2199
2200
2201 bool Buffer::isClean() const
2202 {
2203         return d->lyx_clean;
2204 }
2205
2206
2207 bool Buffer::isBakClean() const
2208 {
2209         return d->bak_clean;
2210 }
2211
2212
2213 bool Buffer::isExternallyModified(CheckMethod method) const
2214 {
2215         LASSERT(d->filename.exists(), /**/);
2216         // if method == timestamp, check timestamp before checksum
2217         return (method == checksum_method
2218                 || d->timestamp_ != d->filename.lastModified())
2219                 && d->checksum_ != d->filename.checksum();
2220 }
2221
2222
2223 void Buffer::saveCheckSum(FileName const & file) const
2224 {
2225         if (file.exists()) {
2226                 d->timestamp_ = file.lastModified();
2227                 d->checksum_ = file.checksum();
2228         } else {
2229                 // in the case of save to a new file.
2230                 d->timestamp_ = 0;
2231                 d->checksum_ = 0;
2232         }
2233 }
2234
2235
2236 void Buffer::markClean() const
2237 {
2238         if (!d->lyx_clean) {
2239                 d->lyx_clean = true;
2240                 updateTitles();
2241         }
2242         // if the .lyx file has been saved, we don't need an
2243         // autosave
2244         d->bak_clean = true;
2245 }
2246
2247
2248 void Buffer::markBakClean() const
2249 {
2250         d->bak_clean = true;
2251 }
2252
2253
2254 void Buffer::setUnnamed(bool flag)
2255 {
2256         d->unnamed = flag;
2257 }
2258
2259
2260 bool Buffer::isUnnamed() const
2261 {
2262         return d->unnamed;
2263 }
2264
2265
2266 /// \note
2267 /// Don't check unnamed, here: isInternal() is used in
2268 /// newBuffer(), where the unnamed flag has not been set by anyone
2269 /// yet. Also, for an internal buffer, there should be no need for
2270 /// retrieving fileName() nor for checking if it is unnamed or not.
2271 bool Buffer::isInternal() const
2272 {
2273         return fileName().extension() == "internal";
2274 }
2275
2276
2277 void Buffer::markDirty()
2278 {
2279         if (d->lyx_clean) {
2280                 d->lyx_clean = false;
2281                 updateTitles();
2282         }
2283         d->bak_clean = false;
2284
2285         DepClean::iterator it = d->dep_clean.begin();
2286         DepClean::const_iterator const end = d->dep_clean.end();
2287
2288         for (; it != end; ++it)
2289                 it->second = false;
2290 }
2291
2292
2293 FileName Buffer::fileName() const
2294 {
2295         return d->filename;
2296 }
2297
2298
2299 string Buffer::absFileName() const
2300 {
2301         return d->filename.absFilename();
2302 }
2303
2304
2305 string Buffer::filePath() const
2306 {
2307         return d->filename.onlyPath().absFilename() + "/";
2308 }
2309
2310
2311 bool Buffer::isReadonly() const
2312 {
2313         return d->read_only;
2314 }
2315
2316
2317 void Buffer::setParent(Buffer const * buffer)
2318 {
2319         // Avoids recursive include.
2320         d->setParent(buffer == this ? 0 : buffer);
2321         updateMacros();
2322 }
2323
2324
2325 Buffer const * Buffer::parent() const
2326 {
2327         return d->parent();
2328 }
2329
2330
2331 void Buffer::collectRelatives(BufferSet & bufs) const
2332 {
2333         bufs.insert(this);
2334         if (parent())
2335                 parent()->collectRelatives(bufs);
2336
2337         // loop over children
2338         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2339         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2340         for (; it != end; ++it)
2341                 bufs.insert(const_cast<Buffer *>(it->first));
2342 }
2343
2344
2345 std::vector<Buffer const *> Buffer::allRelatives() const
2346 {
2347         BufferSet bufs;
2348         collectRelatives(bufs);
2349         BufferSet::iterator it = bufs.begin();
2350         std::vector<Buffer const *> ret;
2351         for (; it != bufs.end(); ++it)
2352                 ret.push_back(*it);
2353         return ret;
2354 }
2355
2356
2357 Buffer const * Buffer::masterBuffer() const
2358 {
2359         Buffer const * const pbuf = d->parent();
2360         if (!pbuf)
2361                 return this;
2362
2363         return pbuf->masterBuffer();
2364 }
2365
2366
2367 bool Buffer::isChild(Buffer * child) const
2368 {
2369         return d->children_positions.find(child) != d->children_positions.end();
2370 }
2371
2372
2373 DocIterator Buffer::firstChildPosition(Buffer const * child)
2374 {
2375         Impl::BufferPositionMap::iterator it;
2376         it = d->children_positions.find(child);
2377         if (it == d->children_positions.end())
2378                 return DocIterator(this);
2379         return it->second;
2380 }
2381
2382
2383 void Buffer::getChildren(std::vector<Buffer *> & clist, bool grand_children) const
2384 {
2385         // loop over children
2386         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2387         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2388         for (; it != end; ++it) {
2389                 Buffer * child = const_cast<Buffer *>(it->first);
2390                 clist.push_back(child);
2391                 if (grand_children) {
2392                         // there might be grandchildren
2393                         std::vector<Buffer *> glist = child->getChildren();
2394                         for (vector<Buffer *>::const_iterator git = glist.begin();
2395                                  git != glist.end(); ++git)
2396                                 clist.push_back(*git);
2397                 }
2398         }
2399 }
2400
2401
2402 std::vector<Buffer *> Buffer::getChildren(bool grand_children) const
2403 {
2404         std::vector<Buffer *> v;
2405         getChildren(v, grand_children);
2406         return v;
2407 }
2408
2409
2410 template<typename M>
2411 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
2412 {
2413         if (m.empty())
2414                 return m.end();
2415
2416         typename M::iterator it = m.lower_bound(x);
2417         if (it == m.begin())
2418                 return m.end();
2419
2420         it--;
2421         return it;
2422 }
2423
2424
2425 MacroData const * Buffer::getBufferMacro(docstring const & name,
2426                                          DocIterator const & pos) const
2427 {
2428         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2429
2430         // if paragraphs have no macro context set, pos will be empty
2431         if (pos.empty())
2432                 return 0;
2433
2434         // we haven't found anything yet
2435         DocIterator bestPos = par_iterator_begin();
2436         MacroData const * bestData = 0;
2437
2438         // find macro definitions for name
2439         Impl::NamePositionScopeMacroMap::iterator nameIt
2440                 = d->macros.find(name);
2441         if (nameIt != d->macros.end()) {
2442                 // find last definition in front of pos or at pos itself
2443                 Impl::PositionScopeMacroMap::const_iterator it
2444                         = greatest_below(nameIt->second, pos);
2445                 if (it != nameIt->second.end()) {
2446                         while (true) {
2447                                 // scope ends behind pos?
2448                                 if (pos < it->second.first) {
2449                                         // Looks good, remember this. If there
2450                                         // is no external macro behind this,
2451                                         // we found the right one already.
2452                                         bestPos = it->first;
2453                                         bestData = &it->second.second;
2454                                         break;
2455                                 }
2456
2457                                 // try previous macro if there is one
2458                                 if (it == nameIt->second.begin())
2459                                         break;
2460                                 it--;
2461                         }
2462                 }
2463         }
2464
2465         // find macros in included files
2466         Impl::PositionScopeBufferMap::const_iterator it
2467                 = greatest_below(d->position_to_children, pos);
2468         if (it == d->position_to_children.end())
2469                 // no children before
2470                 return bestData;
2471
2472         while (true) {
2473                 // do we know something better (i.e. later) already?
2474                 if (it->first < bestPos )
2475                         break;
2476
2477                 // scope ends behind pos?
2478                 if (pos < it->second.first) {
2479                         // look for macro in external file
2480                         d->macro_lock = true;
2481                         MacroData const * data
2482                         = it->second.second->getMacro(name, false);
2483                         d->macro_lock = false;
2484                         if (data) {
2485                                 bestPos = it->first;
2486                                 bestData = data;
2487                                 break;
2488                         }
2489                 }
2490
2491                 // try previous file if there is one
2492                 if (it == d->position_to_children.begin())
2493                         break;
2494                 --it;
2495         }
2496
2497         // return the best macro we have found
2498         return bestData;
2499 }
2500
2501
2502 MacroData const * Buffer::getMacro(docstring const & name,
2503         DocIterator const & pos, bool global) const
2504 {
2505         if (d->macro_lock)
2506                 return 0;
2507
2508         // query buffer macros
2509         MacroData const * data = getBufferMacro(name, pos);
2510         if (data != 0)
2511                 return data;
2512
2513         // If there is a master buffer, query that
2514         Buffer const * const pbuf = d->parent();
2515         if (pbuf) {
2516                 d->macro_lock = true;
2517                 MacroData const * macro = pbuf->getMacro(
2518                         name, *this, false);
2519                 d->macro_lock = false;
2520                 if (macro)
2521                         return macro;
2522         }
2523
2524         if (global) {
2525                 data = MacroTable::globalMacros().get(name);
2526                 if (data != 0)
2527                         return data;
2528         }
2529
2530         return 0;
2531 }
2532
2533
2534 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
2535 {
2536         // set scope end behind the last paragraph
2537         DocIterator scope = par_iterator_begin();
2538         scope.pit() = scope.lastpit() + 1;
2539
2540         return getMacro(name, scope, global);
2541 }
2542
2543
2544 MacroData const * Buffer::getMacro(docstring const & name,
2545         Buffer const & child, bool global) const
2546 {
2547         // look where the child buffer is included first
2548         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
2549         if (it == d->children_positions.end())
2550                 return 0;
2551
2552         // check for macros at the inclusion position
2553         return getMacro(name, it->second, global);
2554 }
2555
2556
2557 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
2558 {
2559         pit_type lastpit = it.lastpit();
2560
2561         // look for macros in each paragraph
2562         while (it.pit() <= lastpit) {
2563                 Paragraph & par = it.paragraph();
2564
2565                 // iterate over the insets of the current paragraph
2566                 InsetList const & insets = par.insetList();
2567                 InsetList::const_iterator iit = insets.begin();
2568                 InsetList::const_iterator end = insets.end();
2569                 for (; iit != end; ++iit) {
2570                         it.pos() = iit->pos;
2571
2572                         // is it a nested text inset?
2573                         if (iit->inset->asInsetText()) {
2574                                 // Inset needs its own scope?
2575                                 InsetText const * itext = iit->inset->asInsetText();
2576                                 bool newScope = itext->isMacroScope();
2577
2578                                 // scope which ends just behind the inset
2579                                 DocIterator insetScope = it;
2580                                 ++insetScope.pos();
2581
2582                                 // collect macros in inset
2583                                 it.push_back(CursorSlice(*iit->inset));
2584                                 updateMacros(it, newScope ? insetScope : scope);
2585                                 it.pop_back();
2586                                 continue;
2587                         }
2588
2589                         // is it an external file?
2590                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
2591                                 // get buffer of external file
2592                                 InsetInclude const & inset =
2593                                         static_cast<InsetInclude const &>(*iit->inset);
2594                                 d->macro_lock = true;
2595                                 Buffer * child = inset.getChildBuffer();
2596                                 d->macro_lock = false;
2597                                 if (!child)
2598                                         continue;
2599
2600                                 // register its position, but only when it is
2601                                 // included first in the buffer
2602                                 if (d->children_positions.find(child) ==
2603                                         d->children_positions.end())
2604                                                 d->children_positions[child] = it;
2605
2606                                 // register child with its scope
2607                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
2608                                 continue;
2609                         }
2610
2611                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
2612                                 continue;
2613
2614                         // get macro data
2615                         MathMacroTemplate & macroTemplate =
2616                                 static_cast<MathMacroTemplate &>(*iit->inset);
2617                         MacroContext mc(this, it);
2618                         macroTemplate.updateToContext(mc);
2619
2620                         // valid?
2621                         bool valid = macroTemplate.validMacro();
2622                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
2623                         // then the BufferView's cursor will be invalid in
2624                         // some cases which leads to crashes.
2625                         if (!valid)
2626                                 continue;
2627
2628                         // register macro
2629                         // FIXME (Abdel), I don't understandt why we pass 'it' here
2630                         // instead of 'macroTemplate' defined above... is this correct?
2631                         d->macros[macroTemplate.name()][it] =
2632                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(this), it));
2633                 }
2634
2635                 // next paragraph
2636                 it.pit()++;
2637                 it.pos() = 0;
2638         }
2639 }
2640
2641
2642 void Buffer::updateMacros() const
2643 {
2644         if (d->macro_lock)
2645                 return;
2646
2647         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
2648
2649         // start with empty table
2650         d->macros.clear();
2651         d->children_positions.clear();
2652         d->position_to_children.clear();
2653
2654         // Iterate over buffer, starting with first paragraph
2655         // The scope must be bigger than any lookup DocIterator
2656         // later. For the global lookup, lastpit+1 is used, hence
2657         // we use lastpit+2 here.
2658         DocIterator it = par_iterator_begin();
2659         DocIterator outerScope = it;
2660         outerScope.pit() = outerScope.lastpit() + 2;
2661         updateMacros(it, outerScope);
2662 }
2663
2664
2665 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
2666 {
2667         InsetIterator it  = inset_iterator_begin(inset());
2668         InsetIterator const end = inset_iterator_end(inset());
2669         for (; it != end; ++it) {
2670                 if (it->lyxCode() == BRANCH_CODE) {
2671                         InsetBranch & br = static_cast<InsetBranch &>(*it);
2672                         docstring const name = br.branch();
2673                         if (!from_master && !params().branchlist().find(name))
2674                                 result.push_back(name);
2675                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
2676                                 result.push_back(name);
2677                         continue;
2678                 }
2679                 if (it->lyxCode() == INCLUDE_CODE) {
2680                         // get buffer of external file
2681                         InsetInclude const & ins =
2682                                 static_cast<InsetInclude const &>(*it);
2683                         Buffer * child = ins.getChildBuffer();
2684                         if (!child)
2685                                 continue;
2686                         child->getUsedBranches(result, true);
2687                 }
2688         }
2689         // remove duplicates
2690         result.unique();
2691 }
2692
2693
2694 void Buffer::updateMacroInstances() const
2695 {
2696         LYXERR(Debug::MACROS, "updateMacroInstances for "
2697                 << d->filename.onlyFileName());
2698         DocIterator it = doc_iterator_begin(this);
2699         it.forwardInset();
2700         DocIterator const end = doc_iterator_end(this);
2701         for (; it != end; it.forwardInset()) {
2702                 // look for MathData cells in InsetMathNest insets
2703                 InsetMath * minset = it.nextInset()->asInsetMath();
2704                 if (!minset)
2705                         continue;
2706
2707                 // update macro in all cells of the InsetMathNest
2708                 DocIterator::idx_type n = minset->nargs();
2709                 MacroContext mc = MacroContext(this, it);
2710                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2711                         MathData & data = minset->cell(i);
2712                         data.updateMacros(0, mc);
2713                 }
2714         }
2715 }
2716
2717
2718 void Buffer::listMacroNames(MacroNameSet & macros) const
2719 {
2720         if (d->macro_lock)
2721                 return;
2722
2723         d->macro_lock = true;
2724
2725         // loop over macro names
2726         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2727         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2728         for (; nameIt != nameEnd; ++nameIt)
2729                 macros.insert(nameIt->first);
2730
2731         // loop over children
2732         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2733         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2734         for (; it != end; ++it)
2735                 it->first->listMacroNames(macros);
2736
2737         // call parent
2738         Buffer const * const pbuf = d->parent();
2739         if (pbuf)
2740                 pbuf->listMacroNames(macros);
2741
2742         d->macro_lock = false;
2743 }
2744
2745
2746 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2747 {
2748         Buffer const * const pbuf = d->parent();
2749         if (!pbuf)
2750                 return;
2751
2752         MacroNameSet names;
2753         pbuf->listMacroNames(names);
2754
2755         // resolve macros
2756         MacroNameSet::iterator it = names.begin();
2757         MacroNameSet::iterator end = names.end();
2758         for (; it != end; ++it) {
2759                 // defined?
2760                 MacroData const * data =
2761                 pbuf->getMacro(*it, *this, false);
2762                 if (data) {
2763                         macros.insert(data);
2764
2765                         // we cannot access the original MathMacroTemplate anymore
2766                         // here to calls validate method. So we do its work here manually.
2767                         // FIXME: somehow make the template accessible here.
2768                         if (data->optionals() > 0)
2769                                 features.require("xargs");
2770                 }
2771         }
2772 }
2773
2774
2775 Buffer::References & Buffer::references(docstring const & label)
2776 {
2777         if (d->parent())
2778                 return const_cast<Buffer *>(masterBuffer())->references(label);
2779
2780         RefCache::iterator it = d->ref_cache_.find(label);
2781         if (it != d->ref_cache_.end())
2782                 return it->second.second;
2783
2784         static InsetLabel const * dummy_il = 0;
2785         static References const dummy_refs;
2786         it = d->ref_cache_.insert(
2787                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2788         return it->second.second;
2789 }
2790
2791
2792 Buffer::References const & Buffer::references(docstring const & label) const
2793 {
2794         return const_cast<Buffer *>(this)->references(label);
2795 }
2796
2797
2798 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2799 {
2800         masterBuffer()->d->ref_cache_[label].first = il;
2801 }
2802
2803
2804 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2805 {
2806         return masterBuffer()->d->ref_cache_[label].first;
2807 }
2808
2809
2810 void Buffer::clearReferenceCache() const
2811 {
2812         if (!d->parent())
2813                 d->ref_cache_.clear();
2814 }
2815
2816
2817 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2818         InsetCode code)
2819 {
2820         //FIXME: This does not work for child documents yet.
2821         LASSERT(code == CITE_CODE, /**/);
2822         // Check if the label 'from' appears more than once
2823         vector<docstring> labels;
2824         string paramName;
2825         BiblioInfo const & keys = masterBibInfo();
2826         BiblioInfo::const_iterator bit  = keys.begin();
2827         BiblioInfo::const_iterator bend = keys.end();
2828
2829         for (; bit != bend; ++bit)
2830                 // FIXME UNICODE
2831                 labels.push_back(bit->first);
2832         paramName = "key";
2833
2834         if (count(labels.begin(), labels.end(), from) > 1)
2835                 return;
2836
2837         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2838                 if (it->lyxCode() == code) {
2839                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2840                         docstring const oldValue = inset.getParam(paramName);
2841                         if (oldValue == from)
2842                                 inset.setParam(paramName, to);
2843                 }
2844         }
2845 }
2846
2847
2848 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2849         pit_type par_end, bool full_source) const
2850 {
2851         OutputParams runparams(&params().encoding());
2852         runparams.nice = true;
2853         runparams.flavor = params().useXetex ? 
2854                 OutputParams::XETEX : OutputParams::LATEX;
2855         runparams.linelen = lyxrc.plaintext_linelen;
2856         // No side effect of file copying and image conversion
2857         runparams.dryrun = true;
2858
2859         if (full_source) {
2860                 os << "% " << _("Preview source code") << "\n\n";
2861                 d->texrow.reset();
2862                 d->texrow.newline();
2863                 d->texrow.newline();
2864                 if (isDocBook())
2865                         writeDocBookSource(os, absFileName(), runparams, false);
2866                 else
2867                         // latex or literate
2868                         writeLaTeXSource(os, string(), runparams, true, true);
2869         } else {
2870                 runparams.par_begin = par_begin;
2871                 runparams.par_end = par_end;
2872                 if (par_begin + 1 == par_end) {
2873                         os << "% "
2874                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2875                            << "\n\n";
2876                 } else {
2877                         os << "% "
2878                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2879                                         convert<docstring>(par_begin),
2880                                         convert<docstring>(par_end - 1))
2881                            << "\n\n";
2882                 }
2883                 TexRow texrow;
2884                 texrow.reset();
2885                 texrow.newline();
2886                 texrow.newline();
2887                 // output paragraphs
2888                 if (isDocBook())
2889                         docbookParagraphs(text(), *this, os, runparams);
2890                 else 
2891                         // latex or literate
2892                         latexParagraphs(*this, text(), os, texrow, runparams);
2893         }
2894 }
2895
2896
2897 ErrorList & Buffer::errorList(string const & type) const
2898 {
2899         static ErrorList emptyErrorList;
2900         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2901         if (I == d->errorLists.end())
2902                 return emptyErrorList;
2903
2904         return I->second;
2905 }
2906
2907
2908 void Buffer::updateTocItem(std::string const & type,
2909         DocIterator const & dit) const
2910 {
2911         if (gui_)
2912                 gui_->updateTocItem(type, dit);
2913 }
2914
2915
2916 void Buffer::structureChanged() const
2917 {
2918         if (gui_)
2919                 gui_->structureChanged();
2920 }
2921
2922
2923 void Buffer::errors(string const & err, bool from_master) const
2924 {
2925         if (gui_)
2926                 gui_->errors(err, from_master);
2927 }
2928
2929
2930 void Buffer::message(docstring const & msg) const
2931 {
2932         if (gui_)
2933                 gui_->message(msg);
2934 }
2935
2936
2937 void Buffer::setBusy(bool on) const
2938 {
2939         if (gui_)
2940                 gui_->setBusy(on);
2941 }
2942
2943
2944 void Buffer::setReadOnly(bool on) const
2945 {
2946         if (d->wa_)
2947                 d->wa_->setReadOnly(on);
2948 }
2949
2950
2951 void Buffer::updateTitles() const
2952 {
2953         if (d->wa_)
2954                 d->wa_->updateTitles();
2955 }
2956
2957
2958 void Buffer::resetAutosaveTimers() const
2959 {
2960         if (gui_)
2961                 gui_->resetAutosaveTimers();
2962 }
2963
2964
2965 bool Buffer::hasGuiDelegate() const
2966 {
2967         return gui_;
2968 }
2969
2970
2971 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2972 {
2973         gui_ = gui;
2974 }
2975
2976
2977
2978 namespace {
2979
2980 class AutoSaveBuffer : public ForkedProcess {
2981 public:
2982         ///
2983         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2984                 : buffer_(buffer), fname_(fname) {}
2985         ///
2986         virtual boost::shared_ptr<ForkedProcess> clone() const
2987         {
2988                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2989         }
2990         ///
2991         int start()
2992         {
2993                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2994                                                  from_utf8(fname_.absFilename())));
2995                 return run(DontWait);
2996         }
2997 private:
2998         ///
2999         virtual int generateChild();
3000         ///
3001         Buffer const & buffer_;
3002         FileName fname_;
3003 };
3004
3005
3006 int AutoSaveBuffer::generateChild()
3007 {
3008 #if defined(__APPLE__)
3009         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard) 
3010          *   We should use something else like threads.
3011          *
3012          * Since I do not know how to determine at run time what is the OS X
3013          * version, I just disable forking altogether for now (JMarc)
3014          */
3015         pid_t const pid = -1;
3016 #else
3017         // tmp_ret will be located (usually) in /tmp
3018         // will that be a problem?
3019         // Note that this calls ForkedCalls::fork(), so it's
3020         // ok cross-platform.
3021         pid_t const pid = fork();
3022         // If you want to debug the autosave
3023         // you should set pid to -1, and comment out the fork.
3024         if (pid != 0 && pid != -1)
3025                 return pid;
3026 #endif
3027
3028         // pid = -1 signifies that lyx was unable
3029         // to fork. But we will do the save
3030         // anyway.
3031         bool failed = false;
3032         FileName const tmp_ret = FileName::tempName("lyxauto");
3033         if (!tmp_ret.empty()) {
3034                 buffer_.writeFile(tmp_ret);
3035                 // assume successful write of tmp_ret
3036                 if (!tmp_ret.moveTo(fname_))
3037                         failed = true;
3038         } else
3039                 failed = true;
3040
3041         if (failed) {
3042                 // failed to write/rename tmp_ret so try writing direct
3043                 if (!buffer_.writeFile(fname_)) {
3044                         // It is dangerous to do this in the child,
3045                         // but safe in the parent, so...
3046                         if (pid == -1) // emit message signal.
3047                                 buffer_.message(_("Autosave failed!"));
3048                 }
3049         }
3050
3051         if (pid == 0) // we are the child so...
3052                 _exit(0);
3053
3054         return pid;
3055 }
3056
3057 } // namespace anon
3058
3059
3060 FileName Buffer::getAutosaveFilename() const
3061 {
3062         // if the document is unnamed try to save in the backup dir, else
3063         // in the default document path, and as a last try in the filePath, 
3064         // which will most often be the temporary directory
3065         string fpath;
3066         if (isUnnamed())
3067                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3068                         : lyxrc.backupdir_path;
3069         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3070                 fpath = filePath();
3071
3072         string const fname = "#" + d->filename.onlyFileName() + "#";
3073         return makeAbsPath(fname, fpath);
3074 }
3075
3076
3077 void Buffer::removeAutosaveFile() const
3078 {
3079         FileName const f = getAutosaveFilename();
3080         if (f.exists())
3081                 f.removeFile();
3082 }
3083
3084
3085 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3086 {
3087         FileName const newauto = getAutosaveFilename();
3088         if (!(oldauto == newauto || oldauto.moveTo(newauto)))
3089                 LYXERR0("Unable to remove autosave file `" << oldauto << "'!");
3090 }
3091
3092
3093 // Perfect target for a thread...
3094 void Buffer::autoSave() const
3095 {
3096         if (isBakClean() || isReadonly()) {
3097                 // We don't save now, but we'll try again later
3098                 resetAutosaveTimers();
3099                 return;
3100         }
3101
3102         // emit message signal.
3103         message(_("Autosaving current document..."));
3104         AutoSaveBuffer autosave(*this, getAutosaveFilename());
3105         autosave.start();
3106
3107         markBakClean();
3108         resetAutosaveTimers();
3109 }
3110
3111
3112 string Buffer::bufferFormat() const
3113 {
3114         string format = params().documentClass().outputFormat();
3115         if (format == "latex") {
3116                 if (params().useXetex)
3117                         return "xetex";
3118                 if (params().encoding().package() == Encoding::japanese)
3119                         return "platex";
3120         }
3121         return format;
3122 }
3123
3124
3125 string Buffer::getDefaultOutputFormat() const
3126 {
3127         if (!params().defaultOutputFormat.empty()
3128             && params().defaultOutputFormat != "default")
3129                 return params().defaultOutputFormat;
3130         typedef vector<Format const *> Formats;
3131         Formats formats = exportableFormats(true);
3132         if (isDocBook()
3133             || isLiterate()
3134             || params().useXetex
3135             || params().encoding().package() == Encoding::japanese) {
3136                 if (formats.empty())
3137                         return string();
3138                 // return the first we find
3139                 return formats.front()->name();
3140         }
3141         return lyxrc.default_view_format;
3142 }
3143
3144
3145
3146 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3147         bool includeall, string & result_file) const
3148 {
3149         string backend_format;
3150         OutputParams runparams(&params().encoding());
3151         runparams.flavor = OutputParams::LATEX;
3152         runparams.linelen = lyxrc.plaintext_linelen;
3153         runparams.includeall = includeall;
3154         vector<string> backs = backends();
3155         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3156                 // Get shortest path to format
3157                 Graph::EdgePath path;
3158                 for (vector<string>::const_iterator it = backs.begin();
3159                      it != backs.end(); ++it) {
3160                         Graph::EdgePath p = theConverters().getPath(*it, format);
3161                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3162                                 backend_format = *it;
3163                                 path = p;
3164                         }
3165                 }
3166                 if (path.empty()) {
3167                         if (!put_in_tempdir) {
3168                                 // Only show this alert if this is an export to a non-temporary
3169                                 // file (not for previewing).
3170                                 Alert::error(_("Couldn't export file"), bformat(
3171                                         _("No information for exporting the format %1$s."),
3172                                         formats.prettyName(format)));
3173                         }
3174                         return false;
3175                 }
3176                 runparams.flavor = theConverters().getFlavor(path);
3177
3178         } else {
3179                 backend_format = format;
3180                 // FIXME: Don't hardcode format names here, but use a flag
3181                 if (backend_format == "pdflatex")
3182                         runparams.flavor = OutputParams::PDFLATEX;
3183         }
3184
3185         string filename = latexName(false);
3186         filename = addName(temppath(), filename);
3187         filename = changeExtension(filename,
3188                                    formats.extension(backend_format));
3189
3190         // fix macros
3191         updateMacroInstances();
3192
3193         // Plain text backend
3194         if (backend_format == "text") {
3195                 runparams.flavor = OutputParams::TEXT;
3196                 writePlaintextFile(*this, FileName(filename), runparams);
3197         }
3198         // HTML backend
3199         else if (backend_format == "xhtml") {
3200                 runparams.flavor = OutputParams::HTML;
3201                 makeLyXHTMLFile(FileName(filename), runparams);
3202         }       else if (backend_format == "lyx")
3203                 writeFile(FileName(filename));
3204         // Docbook backend
3205         else if (isDocBook()) {
3206                 runparams.nice = !put_in_tempdir;
3207                 makeDocBookFile(FileName(filename), runparams);
3208         }
3209         // LaTeX backend
3210         else if (backend_format == format) {
3211                 runparams.nice = true;
3212                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
3213                         return false;
3214         } else if (!lyxrc.tex_allows_spaces
3215                    && contains(filePath(), ' ')) {
3216                 Alert::error(_("File name error"),
3217                            _("The directory path to the document cannot contain spaces."));
3218                 return false;
3219         } else {
3220                 runparams.nice = false;
3221                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
3222                         return false;
3223         }
3224
3225         string const error_type = (format == "program")
3226                 ? "Build" : bufferFormat();
3227         ErrorList & error_list = d->errorLists[error_type];
3228         string const ext = formats.extension(format);
3229         FileName const tmp_result_file(changeExtension(filename, ext));
3230         bool const success = theConverters().convert(this, FileName(filename),
3231                 tmp_result_file, FileName(absFileName()), backend_format, format,
3232                 error_list);
3233         // Emit the signal to show the error list.
3234         if (format != backend_format) {
3235                 errors(error_type);
3236                 // also to the children, in case of master-buffer-view
3237                 std::vector<Buffer *> clist = getChildren();
3238                 for (vector<Buffer *>::const_iterator cit = clist.begin();
3239                      cit != clist.end(); ++cit)
3240                         (*cit)->errors(error_type, true);
3241         }
3242         if (!success)
3243                 return false;
3244
3245         if (d->cloned_buffer_) {
3246                 // Enable reverse dvi or pdf to work by copying back the texrow
3247                 // object to the cloned buffer.
3248                 // FIXME: There is a possibility of concurrent access to texrow
3249                 // here from the main GUI thread that should be securized.
3250                 d->cloned_buffer_->d->texrow = d->texrow;
3251         }
3252
3253         if (put_in_tempdir) {
3254                 result_file = tmp_result_file.absFilename();
3255                 return true;
3256         }
3257
3258         result_file = changeExtension(exportFileName().absFilename(), ext);
3259         // We need to copy referenced files (e. g. included graphics
3260         // if format == "dvi") to the result dir.
3261         vector<ExportedFile> const files =
3262                 runparams.exportdata->externalFiles(format);
3263         string const dest = onlyPath(result_file);
3264         CopyStatus status = SUCCESS;
3265         for (vector<ExportedFile>::const_iterator it = files.begin();
3266                 it != files.end() && status != CANCEL; ++it) {
3267                 string const fmt = formats.getFormatFromFile(it->sourceName);
3268                 status = copyFile(fmt, it->sourceName,
3269                         makeAbsPath(it->exportName, dest),
3270                         it->exportName, status == FORCE);
3271         }
3272         if (status == CANCEL) {
3273                 message(_("Document export cancelled."));
3274         } else if (tmp_result_file.exists()) {
3275                 // Finally copy the main file
3276                 status = copyFile(format, tmp_result_file,
3277                         FileName(result_file), result_file,
3278                         status == FORCE);
3279                 message(bformat(_("Document exported as %1$s "
3280                         "to file `%2$s'"),
3281                         formats.prettyName(format),
3282                         makeDisplayPath(result_file)));
3283         } else {
3284                 // This must be a dummy converter like fax (bug 1888)
3285                 message(bformat(_("Document exported as %1$s"),
3286                         formats.prettyName(format)));
3287         }
3288
3289         return true;
3290 }
3291
3292
3293 bool Buffer::doExport(string const & format, bool put_in_tempdir,
3294                       bool includeall) const
3295 {
3296         string result_file;
3297         // (1) export with all included children (omit \includeonly)
3298         if (includeall && !doExport(format, put_in_tempdir, true, result_file))
3299                 return false;
3300         // (2) export with included children only
3301         return doExport(format, put_in_tempdir, false, result_file);
3302 }
3303
3304
3305 bool Buffer::preview(string const & format, bool includeall) const
3306 {
3307         string result_file;
3308         // (1) export with all included children (omit \includeonly)
3309         if (includeall && !doExport(format, true, true))
3310                 return false;
3311         // (2) export with included children only
3312         if (!doExport(format, true, false, result_file))
3313                 return false;
3314         return formats.view(*this, FileName(result_file), format);
3315 }
3316
3317
3318 bool Buffer::isExportable(string const & format) const
3319 {
3320         vector<string> backs = backends();
3321         for (vector<string>::const_iterator it = backs.begin();
3322              it != backs.end(); ++it)
3323                 if (theConverters().isReachable(*it, format))
3324                         return true;
3325         return false;
3326 }
3327
3328
3329 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
3330 {
3331         vector<string> const backs = backends();
3332         vector<Format const *> result =
3333                 theConverters().getReachable(backs[0], only_viewable, true);
3334         for (vector<string>::const_iterator it = backs.begin() + 1;
3335              it != backs.end(); ++it) {
3336                 vector<Format const *>  r =
3337                         theConverters().getReachable(*it, only_viewable, false);
3338                 result.insert(result.end(), r.begin(), r.end());
3339         }
3340         return result;
3341 }
3342
3343
3344 vector<string> Buffer::backends() const
3345 {
3346         vector<string> v;
3347         v.push_back(bufferFormat());
3348         // FIXME: Don't hardcode format names here, but use a flag
3349         if (v.back() == "latex")
3350                 v.push_back("pdflatex");
3351         v.push_back("xhtml");
3352         v.push_back("text");
3353         v.push_back("lyx");
3354         return v;
3355 }
3356
3357
3358 bool Buffer::readFileHelper(FileName const & s)
3359 {
3360         // File information about normal file
3361         if (!s.exists()) {
3362                 docstring const file = makeDisplayPath(s.absFilename(), 50);
3363                 docstring text = bformat(_("The specified document\n%1$s"
3364                                                      "\ncould not be read."), file);
3365                 Alert::error(_("Could not read document"), text);
3366                 return false;
3367         }
3368
3369         // Check if emergency save file exists and is newer.
3370         FileName const e(s.absFilename() + ".emergency");
3371
3372         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
3373                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3374                 docstring const text =
3375                         bformat(_("An emergency save of the document "
3376                                   "%1$s exists.\n\n"
3377                                                "Recover emergency save?"), file);
3378                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
3379                                       _("&Recover"),  _("&Load Original"),
3380                                       _("&Cancel")))
3381                 {
3382                 case 0: {
3383                         // the file is not saved if we load the emergency file.
3384                         markDirty();
3385                         docstring str;
3386                         bool res;
3387
3388                         if ((res = readFile(e)) == success)
3389                                 str = _("Document was successfully recovered.");
3390                         else
3391                                 str = _("Document was NOT successfully recovered.");
3392                         str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
3393                                                 from_utf8(e.absFilename()));
3394
3395                         if (!Alert::prompt(_("Delete emergency file?"), str, 1, 1,
3396                                         _("&Remove"), _("&Keep it"))) {
3397                                 e.removeFile();
3398                                 if (res == success)
3399                                         Alert::warning(_("Emergency file deleted"),
3400                                                 _("Do not forget to save your file now!"), true);
3401                                 }
3402                         return res;
3403                 }
3404                 case 1:
3405                         if (!Alert::prompt(_("Delete emergency file?"),
3406                                         _("Remove emergency file now?"), 1, 1,
3407                                         _("&Remove"), _("&Keep it")))
3408                                 e.removeFile();
3409                         break;
3410                 default:
3411                         return false;
3412                 }
3413         }
3414
3415         // Now check if autosave file is newer.
3416         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
3417
3418         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
3419                 docstring const file = makeDisplayPath(s.absFilename(), 20);
3420                 docstring const text =
3421                         bformat(_("The backup of the document "
3422                                   "%1$s is newer.\n\nLoad the "
3423                                                "backup instead?"), file);
3424                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
3425                                       _("&Load backup"), _("Load &original"),
3426                                       _("&Cancel") ))
3427                 {
3428                 case 0:
3429                         // the file is not saved if we load the autosave file.
3430                         markDirty();
3431                         return readFile(a);
3432                 case 1:
3433                         // Here we delete the autosave
3434                         a.removeFile();
3435                         break;
3436                 default:
3437                         return false;
3438                 }
3439         }
3440         return readFile(s);
3441 }
3442
3443
3444 bool Buffer::loadLyXFile(FileName const & s)
3445 {
3446         // If the file is not readable, we try to
3447         // retrieve the file from version control.
3448         if (!s.isReadableFile()
3449                   && !LyXVC::file_not_found_hook(s))
3450                 return false;
3451         
3452         if (s.isReadableFile()
3453                   && readFileHelper(s)) {
3454                 lyxvc().file_found_hook(s);
3455                 setReadonly(!s.isWritable());
3456                 return true;
3457         }
3458         return false;
3459 }
3460
3461
3462 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
3463 {
3464         TeXErrors::Errors::const_iterator cit = terr.begin();
3465         TeXErrors::Errors::const_iterator end = terr.end();
3466
3467         for (; cit != end; ++cit) {
3468                 int id_start = -1;
3469                 int pos_start = -1;
3470                 int errorRow = cit->error_in_line;
3471                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
3472                                                        pos_start);
3473                 int id_end = -1;
3474                 int pos_end = -1;
3475                 do {
3476                         ++errorRow;
3477                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
3478                 } while (found && id_start == id_end && pos_start == pos_end);
3479
3480                 errorList.push_back(ErrorItem(cit->error_desc,
3481                         cit->error_text, id_start, pos_start, pos_end));
3482         }
3483 }
3484
3485
3486 void Buffer::setBuffersForInsets() const
3487 {
3488         inset().setBuffer(const_cast<Buffer &>(*this)); 
3489 }
3490
3491
3492 void Buffer::updateLabels(UpdateScope scope, bool out) const
3493 {
3494         // Use the master text class also for child documents
3495         Buffer const * const master = masterBuffer();
3496         DocumentClass const & textclass = master->params().documentClass();
3497
3498         // keep the buffers to be children in this set. If the call from the
3499         // master comes back we can see which of them were actually seen (i.e.
3500         // via an InsetInclude). The remaining ones in the set need still be updated.
3501         static std::set<Buffer const *> bufToUpdate;
3502         if (scope == UpdateMaster) {
3503                 // If this is a child document start with the master
3504                 if (master != this) {
3505                         bufToUpdate.insert(this);
3506                         master->updateLabels(UpdateMaster, out);
3507                         // Do this here in case the master has no gui associated with it. Then, 
3508                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
3509                         if (!master->gui_)
3510                                 structureChanged();
3511
3512                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
3513                         if (bufToUpdate.find(this) == bufToUpdate.end())
3514                                 return;
3515                 }
3516
3517                 // start over the counters in the master
3518                 textclass.counters().reset();
3519         }
3520
3521         // update will be done below for this buffer
3522         bufToUpdate.erase(this);
3523
3524         // update all caches
3525         clearReferenceCache();
3526         updateMacros();
3527
3528         Buffer & cbuf = const_cast<Buffer &>(*this);
3529
3530         LASSERT(!text().paragraphs().empty(), /**/);
3531
3532         // do the real work
3533         ParIterator parit = cbuf.par_iterator_begin();
3534         updateLabels(parit, out);
3535
3536         if (master != this)
3537                 // TocBackend update will be done later.
3538                 return;
3539
3540         cbuf.tocBackend().update();
3541         if (scope == UpdateMaster)
3542                 cbuf.structureChanged();
3543 }
3544
3545
3546 static depth_type getDepth(DocIterator const & it)
3547 {
3548         depth_type depth = 0;
3549         for (size_t i = 0 ; i < it.depth() ; ++i)
3550                 if (!it[i].inset().inMathed())
3551                         depth += it[i].paragraph().getDepth() + 1;
3552         // remove 1 since the outer inset does not count
3553         return depth - 1;
3554 }
3555
3556 static depth_type getItemDepth(ParIterator const & it)
3557 {
3558         Paragraph const & par = *it;
3559         LabelType const labeltype = par.layout().labeltype;
3560
3561         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
3562                 return 0;
3563
3564         // this will hold the lowest depth encountered up to now.
3565         depth_type min_depth = getDepth(it);
3566         ParIterator prev_it = it;
3567         while (true) {
3568                 if (prev_it.pit())
3569                         --prev_it.top().pit();
3570                 else {
3571                         // start of nested inset: go to outer par
3572                         prev_it.pop_back();
3573                         if (prev_it.empty()) {
3574                                 // start of document: nothing to do
3575                                 return 0;
3576                         }
3577                 }
3578
3579                 // We search for the first paragraph with same label
3580                 // that is not more deeply nested.
3581                 Paragraph & prev_par = *prev_it;
3582                 depth_type const prev_depth = getDepth(prev_it);
3583                 if (labeltype == prev_par.layout().labeltype) {
3584                         if (prev_depth < min_depth)
3585                                 return prev_par.itemdepth + 1;
3586                         if (prev_depth == min_depth)
3587                                 return prev_par.itemdepth;
3588                 }
3589                 min_depth = min(min_depth, prev_depth);
3590                 // small optimization: if we are at depth 0, we won't
3591                 // find anything else
3592                 if (prev_depth == 0)
3593                         return 0;
3594         }
3595 }
3596
3597
3598 static bool needEnumCounterReset(ParIterator const & it)
3599 {
3600         Paragraph const & par = *it;
3601         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
3602         depth_type const cur_depth = par.getDepth();
3603         ParIterator prev_it = it;
3604         while (prev_it.pit()) {
3605                 --prev_it.top().pit();
3606                 Paragraph const & prev_par = *prev_it;
3607                 if (prev_par.getDepth() <= cur_depth)
3608                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
3609         }
3610         // start of nested inset: reset
3611         return true;
3612 }
3613
3614
3615 // set the label of a paragraph. This includes the counters.
3616 void Buffer::setLabel(ParIterator & it) const
3617 {
3618         BufferParams const & bp = this->masterBuffer()->params();
3619         DocumentClass const & textclass = bp.documentClass();
3620         Paragraph & par = it.paragraph();
3621         Layout const & layout = par.layout();
3622         Counters & counters = textclass.counters();
3623
3624         if (par.params().startOfAppendix()) {
3625                 // FIXME: only the counter corresponding to toplevel
3626                 // sectioning should be reset
3627                 counters.reset();
3628                 counters.appendix(true);
3629         }
3630         par.params().appendix(counters.appendix());
3631
3632         // Compute the item depth of the paragraph
3633         par.itemdepth = getItemDepth(it);
3634
3635         if (layout.margintype == MARGIN_MANUAL
3636             || layout.latextype == LATEX_BIB_ENVIRONMENT) {
3637                 if (par.params().labelWidthString().empty())
3638                         par.params().labelWidthString(par.expandLabel(layout, bp));
3639         } else {
3640                 par.params().labelWidthString(docstring());
3641         }
3642
3643         switch(layout.labeltype) {
3644         case LABEL_COUNTER:
3645                 if (layout.toclevel <= bp.secnumdepth
3646                     && (layout.latextype != LATEX_ENVIRONMENT
3647                         || it.text()->isFirstInSequence(it.pit()))) {
3648                         counters.step(layout.counter);
3649                         par.params().labelString(
3650                                 par.expandLabel(layout, bp));
3651                 } else
3652                         par.params().labelString(docstring());
3653                 break;
3654
3655         case LABEL_ITEMIZE: {
3656                 // At some point of time we should do something more
3657                 // clever here, like:
3658                 //   par.params().labelString(
3659                 //    bp.user_defined_bullet(par.itemdepth).getText());
3660                 // for now, use a simple hardcoded label
3661                 docstring itemlabel;
3662                 switch (par.itemdepth) {
3663                 case 0:
3664                         itemlabel = char_type(0x2022);
3665                         break;
3666                 case 1:
3667                         itemlabel = char_type(0x2013);
3668                         break;
3669                 case 2:
3670                         itemlabel = char_type(0x2217);
3671                         break;
3672                 case 3:
3673                         itemlabel = char_type(0x2219); // or 0x00b7
3674                         break;
3675                 }
3676                 par.params().labelString(itemlabel);
3677                 break;
3678         }
3679
3680         case LABEL_ENUMERATE: {
3681                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
3682
3683                 switch (par.itemdepth) {
3684                 case 2:
3685                         enumcounter += 'i';
3686                 case 1:
3687                         enumcounter += 'i';
3688                 case 0:
3689                         enumcounter += 'i';
3690                         break;
3691                 case 3:
3692                         enumcounter += "iv";
3693                         break;
3694                 default:
3695                         // not a valid enumdepth...
3696                         break;
3697                 }
3698
3699                 // Maybe we have to reset the enumeration counter.
3700                 if (needEnumCounterReset(it))
3701                         counters.reset(enumcounter);
3702                 counters.step(enumcounter);
3703
3704                 string const & lang = par.getParLanguage(bp)->code();
3705                 par.params().labelString(counters.theCounter(enumcounter, lang));
3706
3707                 break;
3708         }
3709
3710         case LABEL_SENSITIVE: {
3711                 string const & type = counters.current_float();
3712                 docstring full_label;
3713                 if (type.empty())
3714                         full_label = this->B_("Senseless!!! ");
3715                 else {
3716                         docstring name = this->B_(textclass.floats().getType(type).name());
3717                         if (counters.hasCounter(from_utf8(type))) {
3718                                 string const & lang = par.getParLanguage(bp)->code();
3719                                 counters.step(from_utf8(type));
3720                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
3721                                                      name, 
3722                                                      counters.theCounter(from_utf8(type), lang));
3723                         } else
3724                                 full_label = bformat(from_ascii("%1$s #:"), name);      
3725                 }
3726                 par.params().labelString(full_label);   
3727                 break;
3728         }
3729
3730         case LABEL_NO_LABEL:
3731                 par.params().labelString(docstring());
3732                 break;
3733
3734         case LABEL_MANUAL:
3735         case LABEL_TOP_ENVIRONMENT:
3736         case LABEL_CENTERED_TOP_ENVIRONMENT:
3737         case LABEL_STATIC:      
3738         case LABEL_BIBLIO:
3739                 par.params().labelString(par.expandLabel(layout, bp));
3740                 break;
3741         }
3742 }
3743
3744
3745 void Buffer::updateLabels(ParIterator & parit, bool out) const
3746 {
3747         LASSERT(parit.pit() == 0, /**/);
3748
3749         // set the position of the text in the buffer to be able
3750         // to resolve macros in it. This has nothing to do with
3751         // labels, but by putting it here we avoid implementing
3752         // a whole bunch of traversal routines just for this call.
3753         parit.text()->setMacrocontextPosition(parit);
3754
3755         depth_type maxdepth = 0;
3756         pit_type const lastpit = parit.lastpit();
3757         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
3758                 // reduce depth if necessary
3759                 parit->params().depth(min(parit->params().depth(), maxdepth));
3760                 maxdepth = parit->getMaxDepthAfter();
3761
3762                 // set the counter for this paragraph
3763                 setLabel(parit);
3764
3765                 // Now the insets
3766                 InsetList::const_iterator iit = parit->insetList().begin();
3767                 InsetList::const_iterator end = parit->insetList().end();
3768                 for (; iit != end; ++iit) {
3769                         parit.pos() = iit->pos;
3770                         iit->inset->updateLabels(parit, out);
3771                 }
3772         }
3773 }
3774
3775
3776 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
3777         WordLangTuple & word_lang, docstring_list & suggestions) const
3778 {
3779         int progress = 0;
3780         WordLangTuple wl;
3781         suggestions.clear();
3782         word_lang = WordLangTuple();
3783         // OK, we start from here.
3784         DocIterator const end = doc_iterator_end(this);
3785         for (; from != end; from.forwardPos()) {
3786                 // We are only interested in text so remove the math CursorSlice.
3787                 while (from.inMathed()) {
3788                         from.pop_back();
3789                         from.pos()++;
3790                 }
3791                 // If from is at the end of the document (which is possible
3792                 // when leaving the mathed) LyX will crash later.
3793                 if (from == end)
3794                         break;
3795                 to = from;
3796                 if (from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions)) {
3797                         word_lang = wl;
3798                         break;
3799                 }
3800
3801                 // Do not increase progress when from == to, otherwise the word
3802                 // count will be wrong.
3803                 if (from != to) {
3804                         from = to;
3805                         ++progress;
3806                 }
3807         }
3808         return progress;
3809 }
3810
3811
3812 bool Buffer::reload()
3813 {
3814         setBusy(true);
3815         // e.g., read-only status could have changed due to version control
3816         d->filename.refresh();
3817         docstring const disp_fn = makeDisplayPath(d->filename.absFilename());
3818
3819         bool const success = loadLyXFile(d->filename);
3820         if (success) {
3821                 updateLabels();
3822                 changed(true);
3823                 markClean();
3824                 message(bformat(_("Document %1$s reloaded."), disp_fn));
3825         } else {
3826                 message(bformat(_("Could not reload document %1$s."), disp_fn));
3827         }       
3828         setBusy(false);
3829         errors("Parse");
3830         return success;
3831 }
3832
3833
3834 } // namespace lyx