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