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