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