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