]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Fix bug #8603: We want unabbreviated TOC entries here.
[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 "Cursor.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "Encoding.h"
32 #include "ErrorList.h"
33 #include "Exporter.h"
34 #include "Format.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
40 #include "Language.h"
41 #include "LaTeXFeatures.h"
42 #include "LaTeX.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "LyXVC.h"
49 #include "output_docbook.h"
50 #include "output.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
59 #include "sgml.h"
60 #include "TexRow.h"
61 #include "TexStream.h"
62 #include "Text.h"
63 #include "TextClass.h"
64 #include "TocBackend.h"
65 #include "Undo.h"
66 #include "VCBackend.h"
67 #include "version.h"
68 #include "WordLangTuple.h"
69 #include "WordList.h"
70
71 #include "insets/InsetBibtex.h"
72 #include "insets/InsetBranch.h"
73 #include "insets/InsetInclude.h"
74 #include "insets/InsetTabular.h"
75 #include "insets/InsetText.h"
76
77 #include "mathed/InsetMathHull.h"
78 #include "mathed/MacroTable.h"
79 #include "mathed/MathMacroTemplate.h"
80 #include "mathed/MathSupport.h"
81
82 #include "graphics/PreviewLoader.h"
83
84 #include "frontends/alert.h"
85 #include "frontends/Delegates.h"
86 #include "frontends/WorkAreaManager.h"
87
88 #include "support/lassert.h"
89 #include "support/convert.h"
90 #include "support/debug.h"
91 #include "support/docstring_list.h"
92 #include "support/ExceptionMessage.h"
93 #include "support/FileName.h"
94 #include "support/FileNameList.h"
95 #include "support/filetools.h"
96 #include "support/ForkedCalls.h"
97 #include "support/gettext.h"
98 #include "support/gzstream.h"
99 #include "support/lstrings.h"
100 #include "support/lyxalgo.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/textutils.h"
106 #include "support/types.h"
107
108 #include "support/bind.h"
109 #include "support/shared_ptr.h"
110
111 #include <algorithm>
112 #include <fstream>
113 #include <iomanip>
114 #include <map>
115 #include <set>
116 #include <sstream>
117 #include <vector>
118
119 using namespace std;
120 using namespace lyx::support;
121 using namespace lyx::graphics;
122
123 namespace lyx {
124
125 namespace Alert = frontend::Alert;
126 namespace os = support::os;
127
128 namespace {
129
130 int const LYX_FORMAT = LYX_FORMAT_LYX;
131
132 typedef map<string, bool> DepClean;
133 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
134
135 void showPrintError(string const & name)
136 {
137         docstring str = bformat(_("Could not print the document %1$s.\n"
138                                             "Check that your printer is set up correctly."),
139                              makeDisplayPath(name, 50));
140         Alert::error(_("Print document failed"), str);
141 }
142
143 } // namespace anon
144
145
146 // A storehouse for the cloned buffers.
147 list<CloneList *> cloned_buffers;
148
149
150 class Buffer::Impl
151 {
152 public:
153         Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
154
155         ~Impl()
156         {
157                 delete preview_loader_;
158                 if (wa_) {
159                         wa_->closeAll();
160                         delete wa_;
161                 }
162                 delete inset;
163         }
164
165         /// search for macro in local (buffer) table or in children
166         MacroData const * getBufferMacro(docstring const & name,
167                 DocIterator const & pos) const;
168
169         /// Update macro table starting with position of it \param it in some
170         /// text inset.
171         void updateMacros(DocIterator & it, DocIterator & scope);
172         ///
173         void setLabel(ParIterator & it, UpdateType utype) const;
174
175         /** If we have branches that use the file suffix
176             feature, return the file name with suffix appended.
177         */
178         support::FileName exportFileName() const;
179
180         Buffer * owner_;
181
182         BufferParams params;
183         LyXVC lyxvc;
184         FileName temppath;
185         mutable TexRow texrow;
186
187         /// need to regenerate .tex?
188         DepClean dep_clean;
189
190         /// is save needed?
191         mutable bool lyx_clean;
192
193         /// is autosave needed?
194         mutable bool bak_clean;
195
196         /// is this an unnamed file (New...)?
197         bool unnamed;
198
199         /// is this an internal bufffer?
200         bool internal_buffer;
201
202         /// buffer is r/o
203         bool read_only;
204
205         /// name of the file the buffer is associated with.
206         FileName filename;
207
208         /** Set to true only when the file is fully loaded.
209          *  Used to prevent the premature generation of previews
210          *  and by the citation inset.
211          */
212         bool file_fully_loaded;
213
214         /// Ignore the parent (e.g. when exporting a child standalone)?
215         bool ignore_parent;
216
217         ///
218         mutable TocBackend toc_backend;
219
220         /// macro tables
221         typedef pair<DocIterator, MacroData> ScopeMacro;
222         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
223         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
224         /// map from the macro name to the position map,
225         /// which maps the macro definition position to the scope and the MacroData.
226         NamePositionScopeMacroMap macros;
227         /// This seem to change the way Buffer::getMacro() works
228         mutable bool macro_lock;
229
230         /// positions of child buffers in the buffer
231         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
232         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
233         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
234         /// position of children buffers in this buffer
235         BufferPositionMap children_positions;
236         /// map from children inclusion positions to their scope and their buffer
237         PositionScopeBufferMap position_to_children;
238
239         /// Container for all sort of Buffer dependant errors.
240         map<string, ErrorList> errorLists;
241
242         /// timestamp and checksum used to test if the file has been externally
243         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
244         time_t timestamp_;
245         unsigned long checksum_;
246
247         ///
248         frontend::WorkAreaManager * wa_;
249         ///
250         frontend::GuiBufferDelegate * gui_;
251
252         ///
253         Undo undo_;
254
255         /// A cache for the bibfiles (including bibfiles of loaded child
256         /// documents), needed for appropriate update of natbib labels.
257         mutable support::FileNameList bibfiles_cache_;
258
259         // FIXME The caching mechanism could be improved. At present, we have a
260         // cache for each Buffer, that caches all the bibliography info for that
261         // Buffer. A more efficient solution would be to have a global cache per
262         // file, and then to construct the Buffer's bibinfo from that.
263         /// A cache for bibliography info
264         mutable BiblioInfo bibinfo_;
265         /// whether the bibinfo cache is valid
266         mutable bool bibinfo_cache_valid_;
267         /// whether the bibfile cache is valid
268         mutable bool bibfile_cache_valid_;
269         /// Cache of timestamps of .bib files
270         map<FileName, time_t> bibfile_status_;
271         /// Indicates whether the bibinfo has changed since the last time
272         /// we ran updateBuffer(), i.e., whether citation labels may need
273         /// to be updated.
274         mutable bool cite_labels_valid_;
275
276         mutable RefCache ref_cache_;
277
278         /// our Text that should be wrapped in an InsetText
279         InsetText * inset;
280
281         ///
282         PreviewLoader * preview_loader_;
283
284         /// This is here to force the test to be done whenever parent_buffer
285         /// is accessed.
286         Buffer const * parent() const
287         {
288                 // ignore_parent temporarily "orphans" a buffer
289                 // (e.g. if a child is compiled standalone)
290                 if (ignore_parent)
291                         return 0;
292                 // if parent_buffer is not loaded, then it has been unloaded,
293                 // which means that parent_buffer is an invalid pointer. So we
294                 // set it to null in that case.
295                 // however, the BufferList doesn't know about cloned buffers, so
296                 // they will always be regarded as unloaded. in that case, we hope
297                 // for the best.
298                 if (!cloned_buffer_ && !theBufferList().isLoaded(parent_buffer))
299                         parent_buffer = 0;
300                 return parent_buffer;
301         }
302
303         ///
304         void setParent(Buffer const * pb)
305         {
306                 if (parent_buffer == pb)
307                         // nothing to do
308                         return;
309                 if (!cloned_buffer_ && parent_buffer && pb)
310                         LYXERR0("Warning: a buffer should not have two parents!");
311                 parent_buffer = pb;
312                 if (!cloned_buffer_ && parent_buffer) {
313                         parent_buffer->invalidateBibfileCache();
314                         parent_buffer->invalidateBibinfoCache();
315                 }
316         }
317
318         /// If non zero, this buffer is a clone of existing buffer \p cloned_buffer_
319         /// This one is useful for preview detached in a thread.
320         Buffer const * cloned_buffer_;
321         ///
322         CloneList * clone_list_;
323         /// are we in the process of exporting this buffer?
324         mutable bool doing_export;
325  
326         /// compute statistics
327         /// \p from initial position
328         /// \p to points to the end position
329         void updateStatistics(DocIterator & from, DocIterator & to,
330                               bool skipNoOutput = true);
331         /// statistics accessor functions
332         int wordCount() const
333         {
334                 return word_count_;
335         }
336         int charCount(bool with_blanks) const
337         {
338                 return char_count_
339                 + (with_blanks ? blank_count_ : 0);
340         }
341
342 private:
343         /// So we can force access via the accessors.
344         mutable Buffer const * parent_buffer;
345
346         int word_count_;
347         int char_count_;
348         int blank_count_;
349
350 };
351
352
353 /// Creates the per buffer temporary directory
354 static FileName createBufferTmpDir()
355 {
356         static int count;
357         // We are in our own directory.  Why bother to mangle name?
358         // In fact I wrote this code to circumvent a problematic behaviour
359         // (bug?) of EMX mkstemp().
360         FileName tmpfl(package().temp_dir().absFileName() + "/lyx_tmpbuf" +
361                 convert<string>(count++));
362
363         if (!tmpfl.createDirectory(0777)) {
364                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
365                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
366                         from_utf8(tmpfl.absFileName())));
367         }
368         return tmpfl;
369 }
370
371
372 Buffer::Impl::Impl(Buffer * owner, FileName const & file, bool readonly_,
373         Buffer const * cloned_buffer)
374         : owner_(owner), lyx_clean(true), bak_clean(true), unnamed(false),
375           internal_buffer(false), read_only(readonly_), filename(file),
376           file_fully_loaded(false), ignore_parent(false), toc_backend(owner),
377           macro_lock(false), timestamp_(0), checksum_(0), wa_(0), gui_(0),
378           undo_(*owner), bibinfo_cache_valid_(false), bibfile_cache_valid_(false),
379           cite_labels_valid_(false), preview_loader_(0),
380           cloned_buffer_(cloned_buffer), clone_list_(0),
381           doing_export(false), parent_buffer(0)
382 {
383         if (!cloned_buffer_) {
384                 temppath = createBufferTmpDir();
385                 lyxvc.setBuffer(owner_);
386                 if (use_gui)
387                         wa_ = new frontend::WorkAreaManager;
388                 return;
389         }
390         temppath = cloned_buffer_->d->temppath;
391         file_fully_loaded = true;
392         params = cloned_buffer_->d->params;
393         bibfiles_cache_ = cloned_buffer_->d->bibfiles_cache_;
394         bibinfo_ = cloned_buffer_->d->bibinfo_;
395         bibinfo_cache_valid_ = cloned_buffer_->d->bibinfo_cache_valid_;
396         bibfile_cache_valid_ = cloned_buffer_->d->bibfile_cache_valid_;
397         bibfile_status_ = cloned_buffer_->d->bibfile_status_;
398         cite_labels_valid_ = cloned_buffer_->d->cite_labels_valid_;
399         unnamed = cloned_buffer_->d->unnamed;
400         internal_buffer = cloned_buffer_->d->internal_buffer;
401 }
402
403
404 Buffer::Buffer(string const & file, bool readonly, Buffer const * cloned_buffer)
405         : d(new Impl(this, FileName(file), readonly, cloned_buffer))
406 {
407         LYXERR(Debug::INFO, "Buffer::Buffer()");
408         if (cloned_buffer) {
409                 d->inset = new InsetText(*cloned_buffer->d->inset);
410                 d->inset->setBuffer(*this);
411                 // FIXME: optimize this loop somewhat, maybe by creating a new
412                 // general recursive Inset::setId().
413                 DocIterator it = doc_iterator_begin(this);
414                 DocIterator cloned_it = doc_iterator_begin(cloned_buffer);
415                 for (; !it.atEnd(); it.forwardPar(), cloned_it.forwardPar())
416                         it.paragraph().setId(cloned_it.paragraph().id());
417         } else
418                 d->inset = new InsetText(this);
419         d->inset->setAutoBreakRows(true);
420         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
421 }
422
423
424 Buffer::~Buffer()
425 {
426         LYXERR(Debug::INFO, "Buffer::~Buffer()");
427         // here the buffer should take care that it is
428         // saved properly, before it goes into the void.
429
430         // GuiView already destroyed
431         d->gui_ = 0;
432
433         if (isInternal()) {
434                 // No need to do additional cleanups for internal buffer.
435                 delete d;
436                 return;
437         }
438
439         if (isClone()) {
440                 // this is in case of recursive includes: we won't try to delete
441                 // ourselves as a child.
442                 d->clone_list_->erase(this);
443                 // loop over children
444                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
445                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
446                 for (; it != end; ++it) {
447                         Buffer * child = const_cast<Buffer *>(it->first);
448                                 if (d->clone_list_->erase(child))
449                                         delete child;
450                 }
451                 // if we're the master buffer, then we should get rid of the list
452                 // of clones
453                 if (!parent()) {
454                         // if this is not empty, we have leaked something. worse, one of the
455                         // children still has a reference to this list.
456                         LASSERT(d->clone_list_->empty(), /* */);
457                         list<CloneList *>::iterator it =
458                                 find(cloned_buffers.begin(), cloned_buffers.end(), d->clone_list_);
459                         LASSERT(it != cloned_buffers.end(), /* */);
460                         cloned_buffers.erase(it);
461                         delete d->clone_list_;
462                 }
463                 // FIXME Do we really need to do this right before we delete d?
464                 // clear references to children in macro tables
465                 d->children_positions.clear();
466                 d->position_to_children.clear();
467         } else {
468                 // loop over children
469                 Impl::BufferPositionMap::iterator it = d->children_positions.begin();
470                 Impl::BufferPositionMap::iterator end = d->children_positions.end();
471                 for (; it != end; ++it) {
472                         Buffer * child = const_cast<Buffer *>(it->first);
473                         if (theBufferList().isLoaded(child))
474                                 theBufferList().releaseChild(this, child);
475                 }
476
477                 if (!isClean()) {
478                         docstring msg = _("LyX attempted to close a document that had unsaved changes!\n");
479                         msg += emergencyWrite();
480                         Alert::warning(_("Attempting to close changed document!"), msg);
481                 }
482
483                 // FIXME Do we really need to do this right before we delete d?
484                 // clear references to children in macro tables
485                 d->children_positions.clear();
486                 d->position_to_children.clear();
487
488                 if (!d->temppath.destroyDirectory()) {
489                         Alert::warning(_("Could not remove temporary directory"),
490                                 bformat(_("Could not remove the temporary directory %1$s"),
491                                 from_utf8(d->temppath.absFileName())));
492                 }
493                 removePreviews();
494         }
495
496         delete d;
497 }
498
499
500 Buffer * Buffer::cloneFromMaster() const
501 {
502         BufferMap bufmap;
503         cloned_buffers.push_back(new CloneList);
504         CloneList * clones = cloned_buffers.back();
505
506         masterBuffer()->cloneWithChildren(bufmap, clones);
507
508         // make sure we got cloned
509         BufferMap::const_iterator bit = bufmap.find(this);
510         LASSERT(bit != bufmap.end(), return 0);
511         Buffer * cloned_buffer = bit->second;
512
513         return cloned_buffer;
514 }
515
516
517 void Buffer::cloneWithChildren(BufferMap & bufmap, CloneList * clones) const
518 {
519         // have we already been cloned?
520         if (bufmap.find(this) != bufmap.end())
521                 return;
522
523         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
524
525         // The clone needs its own DocumentClass, since running updateBuffer() will
526         // modify it, and we would otherwise be sharing it with the original Buffer.
527         buffer_clone->params().makeDocumentClass();
528         ErrorList el;
529         cap::switchBetweenClasses(
530                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
531                         static_cast<InsetText &>(buffer_clone->inset()), el);
532
533         bufmap[this] = buffer_clone;
534         clones->insert(buffer_clone);
535         buffer_clone->d->clone_list_ = clones;
536         buffer_clone->d->macro_lock = true;
537         buffer_clone->d->children_positions.clear();
538
539         // FIXME (Abdel 09/01/2010): this is too complicated. The whole children_positions and
540         // math macro caches need to be rethought and simplified.
541         // I am not sure wether we should handle Buffer cloning here or in BufferList.
542         // Right now BufferList knows nothing about buffer clones.
543         Impl::PositionScopeBufferMap::iterator it = d->position_to_children.begin();
544         Impl::PositionScopeBufferMap::iterator end = d->position_to_children.end();
545         for (; it != end; ++it) {
546                 DocIterator dit = it->first.clone(buffer_clone);
547                 dit.setBuffer(buffer_clone);
548                 Buffer * child = const_cast<Buffer *>(it->second.second);
549
550                 child->cloneWithChildren(bufmap, clones);
551                 BufferMap::iterator const bit = bufmap.find(child);
552                 LASSERT(bit != bufmap.end(), continue);
553                 Buffer * child_clone = bit->second;
554
555                 Inset * inset = dit.nextInset();
556                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
557                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
558                 inset_inc->setChildBuffer(child_clone);
559                 child_clone->d->setParent(buffer_clone);
560                 // FIXME Do we need to do this now, or can we wait until we run updateMacros()?
561                 buffer_clone->setChild(dit, child_clone);
562         }
563         buffer_clone->d->macro_lock = false;
564         return;
565 }
566
567
568 Buffer * Buffer::cloneBufferOnly() const {
569         cloned_buffers.push_back(new CloneList);
570         CloneList * clones = cloned_buffers.back();
571         Buffer * buffer_clone = new Buffer(fileName().absFileName(), false, this);
572
573         // The clone needs its own DocumentClass, since running updateBuffer() will
574         // modify it, and we would otherwise be sharing it with the original Buffer.
575         buffer_clone->params().makeDocumentClass();
576         ErrorList el;
577         cap::switchBetweenClasses(
578                         params().documentClassPtr(), buffer_clone->params().documentClassPtr(),
579                         static_cast<InsetText &>(buffer_clone->inset()), el);
580
581         clones->insert(buffer_clone);
582         buffer_clone->d->clone_list_ = clones;
583
584         // we won't be cloning the children
585         buffer_clone->d->children_positions.clear();
586         return buffer_clone;
587 }
588
589
590 bool Buffer::isClone() const
591 {
592         return d->cloned_buffer_;
593 }
594
595
596 void Buffer::changed(bool update_metrics) const
597 {
598         if (d->wa_)
599                 d->wa_->redrawAll(update_metrics);
600 }
601
602
603 frontend::WorkAreaManager & Buffer::workAreaManager() const
604 {
605         LASSERT(d->wa_, /**/);
606         return *d->wa_;
607 }
608
609
610 Text & Buffer::text() const
611 {
612         return d->inset->text();
613 }
614
615
616 Inset & Buffer::inset() const
617 {
618         return *d->inset;
619 }
620
621
622 BufferParams & Buffer::params()
623 {
624         return d->params;
625 }
626
627
628 BufferParams const & Buffer::params() const
629 {
630         return d->params;
631 }
632
633
634 ParagraphList & Buffer::paragraphs()
635 {
636         return text().paragraphs();
637 }
638
639
640 ParagraphList const & Buffer::paragraphs() const
641 {
642         return text().paragraphs();
643 }
644
645
646 LyXVC & Buffer::lyxvc()
647 {
648         return d->lyxvc;
649 }
650
651
652 LyXVC const & Buffer::lyxvc() const
653 {
654         return d->lyxvc;
655 }
656
657
658 string const Buffer::temppath() const
659 {
660         return d->temppath.absFileName();
661 }
662
663
664 TexRow & Buffer::texrow()
665 {
666         return d->texrow;
667 }
668
669
670 TexRow const & Buffer::texrow() const
671 {
672         return d->texrow;
673 }
674
675
676 TocBackend & Buffer::tocBackend() const
677 {
678         return d->toc_backend;
679 }
680
681
682 Undo & Buffer::undo()
683 {
684         return d->undo_;
685 }
686
687
688 void Buffer::setChild(DocIterator const & dit, Buffer * child)
689 {
690         d->children_positions[child] = dit;
691 }
692
693
694 string Buffer::latexName(bool const no_path) const
695 {
696         FileName latex_name =
697                 makeLatexName(d->exportFileName());
698         return no_path ? latex_name.onlyFileName()
699                 : latex_name.absFileName();
700 }
701
702
703 FileName Buffer::Impl::exportFileName() const
704 {
705         docstring const branch_suffix =
706                 params.branchlist().getFileNameSuffix();
707         if (branch_suffix.empty())
708                 return filename;
709
710         string const name = filename.onlyFileNameWithoutExt()
711                 + to_utf8(branch_suffix);
712         FileName res(filename.onlyPath().absFileName() + "/" + name);
713         res.changeExtension(filename.extension());
714
715         return res;
716 }
717
718
719 string Buffer::logName(LogType * type) const
720 {
721         string const filename = latexName(false);
722
723         if (filename.empty()) {
724                 if (type)
725                         *type = latexlog;
726                 return string();
727         }
728
729         string const path = temppath();
730
731         FileName const fname(addName(temppath(),
732                                      onlyFileName(changeExtension(filename,
733                                                                   ".log"))));
734
735         // FIXME: how do we know this is the name of the build log?
736         FileName const bname(
737                 addName(path, onlyFileName(
738                         changeExtension(filename,
739                                         formats.extension(params().bufferFormat()) + ".out"))));
740
741         // Also consider the master buffer log file
742         FileName masterfname = fname;
743         LogType mtype;
744         if (masterBuffer() != this) {
745                 string const mlogfile = masterBuffer()->logName(&mtype);
746                 masterfname = FileName(mlogfile);
747         }
748
749         // If no Latex log or Build log is newer, show Build log
750         if (bname.exists() &&
751             ((!fname.exists() && !masterfname.exists())
752              || (fname.lastModified() < bname.lastModified()
753                  && masterfname.lastModified() < bname.lastModified()))) {
754                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
755                 if (type)
756                         *type = buildlog;
757                 return bname.absFileName();
758         // If we have a newer master file log or only a master log, show this
759         } else if (fname != masterfname
760                    && (!fname.exists() && (masterfname.exists()
761                    || fname.lastModified() < masterfname.lastModified()))) {
762                 LYXERR(Debug::FILES, "Log name calculated as: " << masterfname);
763                 if (type)
764                         *type = mtype;
765                 return masterfname.absFileName();
766         }
767         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
768         if (type)
769                         *type = latexlog;
770         return fname.absFileName();
771 }
772
773
774 void Buffer::setReadonly(bool const flag)
775 {
776         if (d->read_only != flag) {
777                 d->read_only = flag;
778                 changed(false);
779         }
780 }
781
782
783 void Buffer::setFileName(FileName const & fname)
784 {
785         bool const changed = fname != d->filename;
786         d->filename = fname;
787         if (changed)
788                 lyxvc().file_found_hook(fname);
789         setReadonly(d->filename.isReadOnly());
790         saveCheckSum();
791         updateTitles();
792 }
793
794
795 int Buffer::readHeader(Lexer & lex)
796 {
797         int unknown_tokens = 0;
798         int line = -1;
799         int begin_header_line = -1;
800
801         // Initialize parameters that may be/go lacking in header:
802         params().branchlist().clear();
803         params().preamble.erase();
804         params().options.erase();
805         params().master.erase();
806         params().float_placement.erase();
807         params().paperwidth.erase();
808         params().paperheight.erase();
809         params().leftmargin.erase();
810         params().rightmargin.erase();
811         params().topmargin.erase();
812         params().bottommargin.erase();
813         params().headheight.erase();
814         params().headsep.erase();
815         params().footskip.erase();
816         params().columnsep.erase();
817         params().fonts_cjk.erase();
818         params().listings_params.clear();
819         params().clearLayoutModules();
820         params().clearRemovedModules();
821         params().clearIncludedChildren();
822         params().pdfoptions().clear();
823         params().indiceslist().clear();
824         params().backgroundcolor = lyx::rgbFromHexName("#ffffff");
825         params().isbackgroundcolor = false;
826         params().fontcolor = RGBColor(0, 0, 0);
827         params().isfontcolor = false;
828         params().notefontcolor = RGBColor(0xCC, 0xCC, 0xCC);
829         params().boxbgcolor = RGBColor(0xFF, 0, 0);
830         params().html_latex_start.clear();
831         params().html_latex_end.clear();
832         params().html_math_img_scale = 1.0;
833         params().output_sync_macro.erase();
834         params().local_layout.clear();
835
836         for (int i = 0; i < 4; ++i) {
837                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
838                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
839         }
840
841         ErrorList & errorList = d->errorLists["Parse"];
842
843         while (lex.isOK()) {
844                 string token;
845                 lex >> token;
846
847                 if (token.empty())
848                         continue;
849
850                 if (token == "\\end_header")
851                         break;
852
853                 ++line;
854                 if (token == "\\begin_header") {
855                         begin_header_line = line;
856                         continue;
857                 }
858
859                 LYXERR(Debug::PARSER, "Handling document header token: `"
860                                       << token << '\'');
861
862                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
863                 if (!unknown.empty()) {
864                         if (unknown[0] != '\\' && token == "\\textclass") {
865                                 Alert::warning(_("Unknown document class"),
866                        bformat(_("Using the default document class, because the "
867                                               "class %1$s is unknown."), from_utf8(unknown)));
868                         } else {
869                                 ++unknown_tokens;
870                                 docstring const s = bformat(_("Unknown token: "
871                                                                         "%1$s %2$s\n"),
872                                                          from_utf8(token),
873                                                          lex.getDocString());
874                                 errorList.push_back(ErrorItem(_("Document header error"),
875                                         s, -1, 0, 0));
876                         }
877                 }
878         }
879         if (begin_header_line) {
880                 docstring const s = _("\\begin_header is missing");
881                 errorList.push_back(ErrorItem(_("Document header error"),
882                         s, -1, 0, 0));
883         }
884
885         params().makeDocumentClass();
886
887         return unknown_tokens;
888 }
889
890
891 // Uwe C. Schroeder
892 // changed to be public and have one parameter
893 // Returns true if "\end_document" is not read (Asger)
894 bool Buffer::readDocument(Lexer & lex)
895 {
896         ErrorList & errorList = d->errorLists["Parse"];
897         errorList.clear();
898
899         // remove dummy empty par
900         paragraphs().clear();
901
902         if (!lex.checkFor("\\begin_document")) {
903                 docstring const s = _("\\begin_document is missing");
904                 errorList.push_back(ErrorItem(_("Document header error"),
905                         s, -1, 0, 0));
906         }
907
908         readHeader(lex);
909
910         if (params().outputChanges) {
911                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
912                 bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
913                                   LaTeXFeatures::isAvailable("xcolor");
914
915                 if (!dvipost && !xcolorulem) {
916                         Alert::warning(_("Changes not shown in LaTeX output"),
917                                        _("Changes will not be highlighted in LaTeX output, "
918                                          "because neither dvipost nor xcolor/ulem are installed.\n"
919                                          "Please install these packages or redefine "
920                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
921                 } else if (!xcolorulem) {
922                         Alert::warning(_("Changes not shown in LaTeX output"),
923                                        _("Changes will not be highlighted in LaTeX output "
924                                          "when using pdflatex, because xcolor and ulem are not installed.\n"
925                                          "Please install both packages or redefine "
926                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
927                 }
928         }
929
930         if (!params().master.empty()) {
931                 FileName const master_file = makeAbsPath(params().master,
932                            onlyPath(absFileName()));
933                 if (isLyXFileName(master_file.absFileName())) {
934                         Buffer * master =
935                                 checkAndLoadLyXFile(master_file, true);
936                         if (master) {
937                                 // necessary e.g. after a reload
938                                 // to re-register the child (bug 5873)
939                                 // FIXME: clean up updateMacros (here, only
940                                 // child registering is needed).
941                                 master->updateMacros();
942                                 // set master as master buffer, but only
943                                 // if we are a real child
944                                 if (master->isChild(this))
945                                         setParent(master);
946                                 // if the master is not fully loaded
947                                 // it is probably just loading this
948                                 // child. No warning needed then.
949                                 else if (master->isFullyLoaded())
950                                         LYXERR0("The master '"
951                                                 << params().master
952                                                 << "' assigned to this document ("
953                                                 << absFileName()
954                                                 << ") does not include "
955                                                 "this document. Ignoring the master assignment.");
956                         }
957                 }
958         }
959
960         // assure we have a default index
961         params().indiceslist().addDefault(B_("Index"));
962
963         // read main text
964         bool const res = text().read(lex, errorList, d->inset);
965
966         // inform parent buffer about local macros
967         if (parent()) {
968                 Buffer const * pbuf = parent();
969                 UserMacroSet::const_iterator cit = usermacros.begin();
970                 UserMacroSet::const_iterator end = usermacros.end();
971                 for (; cit != end; ++cit)
972                         pbuf->usermacros.insert(*cit);
973         }
974         usermacros.clear();
975         updateMacros();
976         updateMacroInstances(InternalUpdate);
977         return res;
978 }
979
980
981 bool Buffer::readString(string const & s)
982 {
983         params().compressed = false;
984
985         Lexer lex;
986         istringstream is(s);
987         lex.setStream(is);
988         FileName const fn = FileName::tempName("Buffer_readString");
989
990         int file_format;
991         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
992         if (ret_plf != ReadSuccess)
993                 return ret_plf;
994
995         if (file_format != LYX_FORMAT) {
996                 // We need to call lyx2lyx, so write the input to a file
997                 ofstream os(fn.toFilesystemEncoding().c_str());
998                 os << s;
999                 os.close();
1000                 // lyxvc in readFile
1001                 return readFile(fn) == ReadSuccess;
1002         }
1003
1004         if (readDocument(lex))
1005                 return false;
1006         return true;
1007 }
1008
1009
1010 Buffer::ReadStatus Buffer::readFile(FileName const & fn)
1011 {
1012         FileName fname(fn);
1013         Lexer lex;
1014         if (!lex.setFile(fname)) {
1015                 Alert::error(_("File Not Found"),
1016                         bformat(_("Unable to open file `%1$s'."),
1017                                 from_utf8(fn.absFileName())));
1018                 return ReadFileNotFound;
1019         }
1020
1021         int file_format;
1022         ReadStatus const ret_plf = parseLyXFormat(lex, fn, file_format);
1023         if (ret_plf != ReadSuccess)
1024                 return ret_plf;
1025
1026         if (file_format != LYX_FORMAT) {
1027                 FileName tmpFile;
1028                 ReadStatus const ret_clf = convertLyXFormat(fn, tmpFile, file_format);
1029                 if (ret_clf != ReadSuccess)
1030                         return ret_clf;
1031                 return readFile(tmpFile);
1032         }
1033
1034         // FIXME: InsetInfo needs to know whether the file is under VCS
1035         // during the parse process, so this has to be done before.
1036         lyxvc().file_found_hook(d->filename);
1037
1038         if (readDocument(lex)) {
1039                 Alert::error(_("Document format failure"),
1040                         bformat(_("%1$s ended unexpectedly, which means"
1041                                 " that it is probably corrupted."),
1042                                         from_utf8(fn.absFileName())));
1043                 return ReadDocumentFailure;
1044         }
1045
1046         d->file_fully_loaded = true;
1047         d->read_only = !d->filename.isWritable();
1048         params().compressed = formats.isZippedFile(d->filename);
1049         saveCheckSum();
1050         return ReadSuccess;
1051 }
1052
1053
1054 bool Buffer::isFullyLoaded() const
1055 {
1056         return d->file_fully_loaded;
1057 }
1058
1059
1060 void Buffer::setFullyLoaded(bool value)
1061 {
1062         d->file_fully_loaded = value;
1063 }
1064
1065
1066 PreviewLoader * Buffer::loader() const
1067 {
1068         if (!isExporting() && lyxrc.preview == LyXRC::PREVIEW_OFF)
1069                 return 0;
1070         if (!d->preview_loader_)
1071                 d->preview_loader_ = new PreviewLoader(*this);
1072         return d->preview_loader_;
1073 }
1074
1075
1076 void Buffer::removePreviews() const
1077 {
1078         delete d->preview_loader_;
1079         d->preview_loader_ = 0;
1080 }
1081
1082
1083 void Buffer::updatePreviews() const
1084 {
1085         PreviewLoader * ploader = loader();
1086         if (!ploader)
1087                 return;
1088
1089         InsetIterator it = inset_iterator_begin(*d->inset);
1090         InsetIterator const end = inset_iterator_end(*d->inset);
1091         for (; it != end; ++it)
1092                 it->addPreview(it, *ploader);
1093
1094         ploader->startLoading();
1095 }
1096
1097
1098 Buffer::ReadStatus Buffer::parseLyXFormat(Lexer & lex,
1099         FileName const & fn, int & file_format) const
1100 {
1101         if(!lex.checkFor("\\lyxformat")) {
1102                 Alert::error(_("Document format failure"),
1103                         bformat(_("%1$s is not a readable LyX document."),
1104                                 from_utf8(fn.absFileName())));
1105                 return ReadNoLyXFormat;
1106         }
1107
1108         string tmp_format;
1109         lex >> tmp_format;
1110
1111         // LyX formats 217 and earlier were written as 2.17. This corresponds
1112         // to files from LyX versions < 1.1.6.3. We just remove the dot in
1113         // these cases. See also: www.lyx.org/trac/changeset/1313.
1114         size_t dot = tmp_format.find_first_of(".,");
1115         if (dot != string::npos)
1116                 tmp_format.erase(dot, 1);
1117
1118         file_format = convert<int>(tmp_format);
1119         return ReadSuccess;
1120 }
1121
1122
1123 Buffer::ReadStatus Buffer::convertLyXFormat(FileName const & fn,
1124         FileName & tmpfile, int from_format)
1125 {
1126         tmpfile = FileName::tempName("Buffer_convertLyXFormat");
1127         if(tmpfile.empty()) {
1128                 Alert::error(_("Conversion failed"),
1129                         bformat(_("%1$s is from a different"
1130                                 " version of LyX, but a temporary"
1131                                 " file for converting it could"
1132                                 " not be created."),
1133                                 from_utf8(fn.absFileName())));
1134                 return LyX2LyXNoTempFile;
1135         }
1136
1137         FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
1138         if (lyx2lyx.empty()) {
1139                 Alert::error(_("Conversion script not found"),
1140                      bformat(_("%1$s is from a different"
1141                                " version of LyX, but the"
1142                                " conversion script lyx2lyx"
1143                                " could not be found."),
1144                                from_utf8(fn.absFileName())));
1145                 return LyX2LyXNotFound;
1146         }
1147
1148         // Run lyx2lyx:
1149         //   $python$ "$lyx2lyx$" -t $LYX_FORMAT$ -o "$tempfile$" "$filetoread$"
1150         ostringstream command;
1151         command << os::python()
1152                 << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
1153                 << " -t " << convert<string>(LYX_FORMAT)
1154                 << " -o " << quoteName(tmpfile.toFilesystemEncoding())
1155                 << ' ' << quoteName(fn.toSafeFilesystemEncoding());
1156         string const command_str = command.str();
1157
1158         LYXERR(Debug::INFO, "Running '" << command_str << '\'');
1159
1160         cmd_ret const ret = runCommand(command_str);
1161         if (ret.first != 0) {
1162                 if (from_format < LYX_FORMAT) {
1163                         Alert::error(_("Conversion script failed"),
1164                                 bformat(_("%1$s is from an older version"
1165                                         " of LyX and the lyx2lyx script"
1166                                         " failed to convert it."),
1167                                         from_utf8(fn.absFileName())));
1168                         return LyX2LyXOlderFormat;
1169                 } else {
1170                         Alert::error(_("Conversion script failed"),
1171                                 bformat(_("%1$s is from a newer version"
1172                                         " of LyX and the lyx2lyx script"
1173                                         " failed to convert it."),
1174                                         from_utf8(fn.absFileName())));
1175                         return LyX2LyXNewerFormat;
1176                 }
1177         }
1178         return ReadSuccess;
1179 }
1180
1181
1182 // Should probably be moved to somewhere else: BufferView? GuiView?
1183 bool Buffer::save() const
1184 {
1185         docstring const file = makeDisplayPath(absFileName(), 20);
1186         d->filename.refresh();
1187
1188         // check the read-only status before moving the file as a backup
1189         if (d->filename.exists()) {
1190                 bool const read_only = !d->filename.isWritable();
1191                 if (read_only) {
1192                         Alert::warning(_("File is read-only"),
1193                                 bformat(_("The file %1$s cannot be written because it "
1194                                 "is marked as read-only."), file));
1195                         return false;
1196                 }
1197         }
1198
1199         // ask if the disk file has been externally modified (use checksum method)
1200         if (fileName().exists() && isExternallyModified(checksum_method)) {
1201                 docstring text =
1202                         bformat(_("Document %1$s has been externally modified. "
1203                                 "Are you sure you want to overwrite this file?"), file);
1204                 int const ret = Alert::prompt(_("Overwrite modified file?"),
1205                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
1206                 if (ret == 1)
1207                         return false;
1208         }
1209
1210         // We don't need autosaves in the immediate future. (Asger)
1211         resetAutosaveTimers();
1212
1213         FileName backupName;
1214         bool madeBackup = false;
1215
1216         // make a backup if the file already exists
1217         if (lyxrc.make_backup && fileName().exists()) {
1218                 backupName = FileName(absFileName() + '~');
1219                 if (!lyxrc.backupdir_path.empty()) {
1220                         string const mangledName =
1221                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1222                         backupName = FileName(addName(lyxrc.backupdir_path,
1223                                                       mangledName));
1224                 }
1225
1226                 // Except file is symlink do not copy because of #6587.
1227                 // Hard links have bad luck.
1228                 if (fileName().isSymLink())
1229                         madeBackup = fileName().copyTo(backupName);
1230                 else
1231                         madeBackup = fileName().moveTo(backupName);
1232
1233                 if (!madeBackup) {
1234                         Alert::error(_("Backup failure"),
1235                                      bformat(_("Cannot create backup file %1$s.\n"
1236                                                "Please check whether the directory exists and is writable."),
1237                                              from_utf8(backupName.absFileName())));
1238                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1239                 }
1240         }
1241
1242         if (writeFile(d->filename)) {
1243                 markClean();
1244                 return true;
1245         } else {
1246                 // Saving failed, so backup is not backup
1247                 if (madeBackup)
1248                         backupName.moveTo(d->filename);
1249                 return false;
1250         }
1251 }
1252
1253
1254 bool Buffer::writeFile(FileName const & fname) const
1255 {
1256         // FIXME Do we need to do these here? I don't think writing
1257         // the LyX file depends upon it. (RGH)
1258         // updateBuffer();
1259         // updateMacroInstances();
1260
1261         if (d->read_only && fname == d->filename)
1262                 return false;
1263
1264         bool retval = false;
1265
1266         docstring const str = bformat(_("Saving document %1$s..."),
1267                 makeDisplayPath(fname.absFileName()));
1268         message(str);
1269
1270         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1271
1272         if (params().compressed) {
1273                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1274                 retval = ofs && write(ofs);
1275         } else {
1276                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1277                 retval = ofs && write(ofs);
1278         }
1279
1280         if (!retval) {
1281                 message(str + _(" could not write file!"));
1282                 return false;
1283         }
1284
1285         // see bug 6587
1286         // removeAutosaveFile();
1287
1288         saveCheckSum();
1289         message(str + _(" done."));
1290
1291         return true;
1292 }
1293
1294
1295 docstring Buffer::emergencyWrite()
1296 {
1297         // No need to save if the buffer has not changed.
1298         if (isClean())
1299                 return docstring();
1300
1301         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1302
1303         docstring user_message = bformat(
1304                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1305
1306         // We try to save three places:
1307         // 1) Same place as document. Unless it is an unnamed doc.
1308         if (!isUnnamed()) {
1309                 string s = absFileName();
1310                 s += ".emergency";
1311                 LYXERR0("  " << s);
1312                 if (writeFile(FileName(s))) {
1313                         markClean();
1314                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1315                         return user_message;
1316                 } else {
1317                         user_message += "  " + _("Save failed! Trying again...\n");
1318                 }
1319         }
1320
1321         // 2) In HOME directory.
1322         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1323         s += ".emergency";
1324         lyxerr << ' ' << s << endl;
1325         if (writeFile(FileName(s))) {
1326                 markClean();
1327                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1328                 return user_message;
1329         }
1330
1331         user_message += "  " + _("Save failed! Trying yet again...\n");
1332
1333         // 3) In "/tmp" directory.
1334         // MakeAbsPath to prepend the current
1335         // drive letter on OS/2
1336         s = addName(package().temp_dir().absFileName(), absFileName());
1337         s += ".emergency";
1338         lyxerr << ' ' << s << endl;
1339         if (writeFile(FileName(s))) {
1340                 markClean();
1341                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1342                 return user_message;
1343         }
1344
1345         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1346         // Don't try again.
1347         markClean();
1348         return user_message;
1349 }
1350
1351
1352 bool Buffer::write(ostream & ofs) const
1353 {
1354 #ifdef HAVE_LOCALE
1355         // Use the standard "C" locale for file output.
1356         ofs.imbue(locale::classic());
1357 #endif
1358
1359         // The top of the file should not be written by params().
1360
1361         // write out a comment in the top of the file
1362         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1363             << " created this file. For more info see http://www.lyx.org/\n"
1364             << "\\lyxformat " << LYX_FORMAT << "\n"
1365             << "\\begin_document\n";
1366
1367         /// For each author, set 'used' to true if there is a change
1368         /// by this author in the document; otherwise set it to 'false'.
1369         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1370         AuthorList::Authors::const_iterator a_end = params().authors().end();
1371         for (; a_it != a_end; ++a_it)
1372                 a_it->setUsed(false);
1373
1374         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1375         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1376         for ( ; it != end; ++it)
1377                 it->checkAuthors(params().authors());
1378
1379         // now write out the buffer parameters.
1380         ofs << "\\begin_header\n";
1381         params().writeFile(ofs);
1382         ofs << "\\end_header\n";
1383
1384         // write the text
1385         ofs << "\n\\begin_body\n";
1386         text().write(ofs);
1387         ofs << "\n\\end_body\n";
1388
1389         // Write marker that shows file is complete
1390         ofs << "\\end_document" << endl;
1391
1392         // Shouldn't really be needed....
1393         //ofs.close();
1394
1395         // how to check if close went ok?
1396         // Following is an attempt... (BE 20001011)
1397
1398         // good() returns false if any error occured, including some
1399         //        formatting error.
1400         // bad()  returns true if something bad happened in the buffer,
1401         //        which should include file system full errors.
1402
1403         bool status = true;
1404         if (!ofs) {
1405                 status = false;
1406                 lyxerr << "File was not closed properly." << endl;
1407         }
1408
1409         return status;
1410 }
1411
1412
1413 bool Buffer::makeLaTeXFile(FileName const & fname,
1414                            string const & original_path,
1415                            OutputParams const & runparams_in,
1416                            OutputWhat output) const
1417 {
1418         OutputParams runparams = runparams_in;
1419
1420         // This is necessary for LuaTeX/XeTeX with tex fonts.
1421         // See FIXME in BufferParams::encoding()
1422         if (runparams.isFullUnicode())
1423                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1424
1425         string const encoding = runparams.encoding->iconvName();
1426         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1427
1428         ofdocstream ofs;
1429         try { ofs.reset(encoding); }
1430         catch (iconv_codecvt_facet_exception const & e) {
1431                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1432                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1433                         "verify that the support software for your encoding (%1$s) is "
1434                         "properly installed"), from_ascii(encoding)));
1435                 return false;
1436         }
1437         if (!openFileWrite(ofs, fname))
1438                 return false;
1439
1440         //TexStream ts(ofs.rdbuf(), &texrow());
1441         ErrorList & errorList = d->errorLists["Export"];
1442         errorList.clear();
1443         bool failed_export = false;
1444         otexstream os(ofs, d->texrow);
1445
1446         // make sure we are ready to export
1447         // this needs to be done before we validate
1448         // FIXME Do we need to do this all the time? I.e., in children
1449         // of a master we are exporting?
1450         updateBuffer();
1451         updateMacroInstances(OutputUpdate);
1452
1453         try {
1454                 os.texrow().reset();
1455                 writeLaTeXSource(os, original_path, runparams, output);
1456         }
1457         catch (EncodingException const & e) {
1458                 odocstringstream ods;
1459                 ods.put(e.failed_char);
1460                 ostringstream oss;
1461                 oss << "0x" << hex << e.failed_char << dec;
1462                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1463                                           " (code point %2$s)"),
1464                                           ods.str(), from_utf8(oss.str()));
1465                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1466                                 "representable in the chosen encoding.\n"
1467                                 "Changing the document encoding to utf8 could help."),
1468                                 e.par_id, e.pos, e.pos + 1));
1469                 failed_export = true;
1470         }
1471         catch (iconv_codecvt_facet_exception const & e) {
1472                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1473                         _(e.what()), -1, 0, 0));
1474                 failed_export = true;
1475         }
1476         catch (exception const & e) {
1477                 errorList.push_back(ErrorItem(_("conversion failed"),
1478                         _(e.what()), -1, 0, 0));
1479                 failed_export = true;
1480         }
1481         catch (...) {
1482                 lyxerr << "Caught some really weird exception..." << endl;
1483                 lyx_exit(1);
1484         }
1485
1486         ofs.close();
1487         if (ofs.fail()) {
1488                 failed_export = true;
1489                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1490         }
1491
1492         errors("Export");
1493         return !failed_export;
1494 }
1495
1496
1497 void Buffer::writeLaTeXSource(otexstream & os,
1498                            string const & original_path,
1499                            OutputParams const & runparams_in,
1500                            OutputWhat output) const
1501 {
1502         // The child documents, if any, shall be already loaded at this point.
1503
1504         OutputParams runparams = runparams_in;
1505
1506         // If we are compiling a file standalone, even if this is the
1507         // child of some other buffer, let's cut the link here, so the
1508         // file is really independent and no concurring settings from
1509         // the master (e.g. branch state) interfere (see #8100).
1510         if (!runparams.is_child)
1511                 d->ignore_parent = true;
1512
1513         // Classify the unicode characters appearing in math insets
1514         Encodings::initUnicodeMath(*this);
1515
1516         // validate the buffer.
1517         LYXERR(Debug::LATEX, "  Validating buffer...");
1518         LaTeXFeatures features(*this, params(), runparams);
1519         validate(features);
1520         runparams.use_polyglossia = features.usePolyglossia();
1521         LYXERR(Debug::LATEX, "  Buffer validation done.");
1522
1523         bool const output_preamble =
1524                 output == FullSource || output == OnlyPreamble;
1525         bool const output_body =
1526                 output == FullSource || output == OnlyBody;
1527
1528         // The starting paragraph of the coming rows is the
1529         // first paragraph of the document. (Asger)
1530         if (output_preamble && runparams.nice) {
1531                 os << "%% LyX " << lyx_version << " created this file.  "
1532                         "For more info, see http://www.lyx.org/.\n"
1533                         "%% Do not edit unless you really know what "
1534                         "you are doing.\n";
1535         }
1536         LYXERR(Debug::INFO, "lyx document header finished");
1537
1538         // There are a few differences between nice LaTeX and usual files:
1539         // usual files have \batchmode and special input@path to allow
1540         // inclusion of figures specified by an explicitly relative path
1541         // (i.e., a path starting with './' or '../') with either \input or
1542         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1543         // input@path is set when the actual parameter original_path is set.
1544         // This is done for usual tex-file, but not for nice-latex-file.
1545         // (Matthias 250696)
1546         // Note that input@path is only needed for something the user does
1547         // in the preamble, included .tex files or ERT, files included by
1548         // LyX work without it.
1549         if (output_preamble) {
1550                 if (!runparams.nice) {
1551                         // code for usual, NOT nice-latex-file
1552                         os << "\\batchmode\n"; // changed from \nonstopmode
1553                 }
1554                 if (!original_path.empty()) {
1555                         // FIXME UNICODE
1556                         // We don't know the encoding of inputpath
1557                         docstring const inputpath = from_utf8(original_path);
1558                         docstring uncodable_glyphs;
1559                         Encoding const * const enc = runparams.encoding;
1560                         if (enc) {
1561                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1562                                         if (!enc->encodable(inputpath[n])) {
1563                                                 docstring const glyph(1, inputpath[n]);
1564                                                 LYXERR0("Uncodable character '"
1565                                                         << glyph
1566                                                         << "' in input path!");
1567                                                 uncodable_glyphs += glyph;
1568                                         }
1569                                 }
1570                         }
1571
1572                         // warn user if we found uncodable glyphs.
1573                         if (!uncodable_glyphs.empty()) {
1574                                 frontend::Alert::warning(
1575                                         _("Uncodable character in file path"),
1576                                         support::bformat(
1577                                           _("The path of your document\n"
1578                                             "(%1$s)\n"
1579                                             "contains glyphs that are unknown "
1580                                             "in the current document encoding "
1581                                             "(namely %2$s). This may result in "
1582                                             "incomplete output, unless "
1583                                             "TEXINPUTS contains the document "
1584                                             "directory and you don't use "
1585                                             "explicitly relative paths (i.e., "
1586                                             "paths starting with './' or "
1587                                             "'../') in the preamble or in ERT."
1588                                             "\n\nIn case of problems, choose "
1589                                             "an appropriate document encoding\n"
1590                                             "(such as utf8) or change the "
1591                                             "file path name."),
1592                                           inputpath, uncodable_glyphs));
1593                         } else {
1594                                 string docdir =
1595                                         support::latex_path(original_path);
1596                                 if (contains(docdir, '#')) {
1597                                         docdir = subst(docdir, "#", "\\#");
1598                                         os << "\\catcode`\\#=11"
1599                                               "\\def\\#{#}\\catcode`\\#=6\n";
1600                                 }
1601                                 if (contains(docdir, '%')) {
1602                                         docdir = subst(docdir, "%", "\\%");
1603                                         os << "\\catcode`\\%=11"
1604                                               "\\def\\%{%}\\catcode`\\%=14\n";
1605                                 }
1606                                 os << "\\makeatletter\n"
1607                                    << "\\def\\input@path{{"
1608                                    << docdir << "/}}\n"
1609                                    << "\\makeatother\n";
1610                         }
1611                 }
1612
1613                 // get parent macros (if this buffer has a parent) which will be
1614                 // written at the document begin further down.
1615                 MacroSet parentMacros;
1616                 listParentMacros(parentMacros, features);
1617
1618                 // Write the preamble
1619                 runparams.use_babel = params().writeLaTeX(os, features,
1620                                                           d->filename.onlyPath());
1621
1622                 runparams.use_japanese = features.isRequired("japanese");
1623
1624                 if (!output_body) {
1625                         // Restore the parenthood if needed
1626                         if (!runparams.is_child)
1627                                 d->ignore_parent = false;
1628                         return;
1629                 }
1630
1631                 // make the body.
1632                 os << "\\begin{document}\n";
1633
1634                 // output the parent macros
1635                 MacroSet::iterator it = parentMacros.begin();
1636                 MacroSet::iterator end = parentMacros.end();
1637                 for (; it != end; ++it) {
1638                         int num_lines = (*it)->write(os.os(), true);
1639                         os.texrow().newlines(num_lines);
1640                 }
1641
1642         } // output_preamble
1643
1644         os.texrow().start(paragraphs().begin()->id(), 0);
1645
1646         LYXERR(Debug::INFO, "preamble finished, now the body.");
1647
1648         // the real stuff
1649         latexParagraphs(*this, text(), os, runparams);
1650
1651         // Restore the parenthood if needed
1652         if (!runparams.is_child)
1653                 d->ignore_parent = false;
1654
1655         // add this just in case after all the paragraphs
1656         os << endl;
1657
1658         if (output_preamble) {
1659                 os << "\\end{document}\n";
1660                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1661         } else {
1662                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1663         }
1664         runparams_in.encoding = runparams.encoding;
1665
1666         // Just to be sure. (Asger)
1667         os.texrow().newline();
1668
1669         //for (int i = 0; i<d->texrow.rows(); i++) {
1670         // int id,pos;
1671         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1672         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1673         //}
1674
1675         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1676         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1677 }
1678
1679
1680 void Buffer::makeDocBookFile(FileName const & fname,
1681                               OutputParams const & runparams,
1682                               OutputWhat output) const
1683 {
1684         LYXERR(Debug::LATEX, "makeDocBookFile...");
1685
1686         ofdocstream ofs;
1687         if (!openFileWrite(ofs, fname))
1688                 return;
1689
1690         // make sure we are ready to export
1691         // this needs to be done before we validate
1692         updateBuffer();
1693         updateMacroInstances(OutputUpdate);
1694
1695         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1696
1697         ofs.close();
1698         if (ofs.fail())
1699                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1700 }
1701
1702
1703 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1704                              OutputParams const & runparams,
1705                              OutputWhat output) const
1706 {
1707         LaTeXFeatures features(*this, params(), runparams);
1708         validate(features);
1709
1710         d->texrow.reset();
1711
1712         DocumentClass const & tclass = params().documentClass();
1713         string const top_element = tclass.latexname();
1714
1715         bool const output_preamble =
1716                 output == FullSource || output == OnlyPreamble;
1717         bool const output_body =
1718           output == FullSource || output == OnlyBody;
1719
1720         if (output_preamble) {
1721                 if (runparams.flavor == OutputParams::XML)
1722                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1723
1724                 // FIXME UNICODE
1725                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1726
1727                 // FIXME UNICODE
1728                 if (! tclass.class_header().empty())
1729                         os << from_ascii(tclass.class_header());
1730                 else if (runparams.flavor == OutputParams::XML)
1731                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1732                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1733                 else
1734                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1735
1736                 docstring preamble = from_utf8(params().preamble);
1737                 if (runparams.flavor != OutputParams::XML ) {
1738                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1739                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1740                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1741                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1742                 }
1743
1744                 string const name = runparams.nice
1745                         ? changeExtension(absFileName(), ".sgml") : fname;
1746                 preamble += features.getIncludedFiles(name);
1747                 preamble += features.getLyXSGMLEntities();
1748
1749                 if (!preamble.empty()) {
1750                         os << "\n [ " << preamble << " ]";
1751                 }
1752                 os << ">\n\n";
1753         }
1754
1755         if (output_body) {
1756                 string top = top_element;
1757                 top += " lang=\"";
1758                 if (runparams.flavor == OutputParams::XML)
1759                         top += params().language->code();
1760                 else
1761                         top += params().language->code().substr(0, 2);
1762                 top += '"';
1763
1764                 if (!params().options.empty()) {
1765                         top += ' ';
1766                         top += params().options;
1767                 }
1768
1769                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1770                                 << " file was created by LyX " << lyx_version
1771                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1772
1773                 params().documentClass().counters().reset();
1774
1775                 sgml::openTag(os, top);
1776                 os << '\n';
1777                 docbookParagraphs(text(), *this, os, runparams);
1778                 sgml::closeTag(os, top_element);
1779         }
1780 }
1781
1782
1783 void Buffer::makeLyXHTMLFile(FileName const & fname,
1784                               OutputParams const & runparams) const
1785 {
1786         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1787
1788         ofdocstream ofs;
1789         if (!openFileWrite(ofs, fname))
1790                 return;
1791
1792         // make sure we are ready to export
1793         // this has to be done before we validate
1794         updateBuffer(UpdateMaster, OutputUpdate);
1795         updateMacroInstances(OutputUpdate);
1796
1797         writeLyXHTMLSource(ofs, runparams, FullSource);
1798
1799         ofs.close();
1800         if (ofs.fail())
1801                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1802 }
1803
1804
1805 void Buffer::writeLyXHTMLSource(odocstream & os,
1806                              OutputParams const & runparams,
1807                              OutputWhat output) const
1808 {
1809         LaTeXFeatures features(*this, params(), runparams);
1810         validate(features);
1811         d->bibinfo_.makeCitationLabels(*this);
1812
1813         bool const output_preamble =
1814                 output == FullSource || output == OnlyPreamble;
1815         bool const output_body =
1816           output == FullSource || output == OnlyBody || output == IncludedFile;
1817
1818         if (output_preamble) {
1819                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
1820                    << "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN\" \"http://www.w3.org/TR/2001/REC-MathML2-20010221/dtd/xhtml-math11-f.dtd\">\n"
1821                    // FIXME Language should be set properly.
1822                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
1823                    << "<head>\n"
1824                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
1825                    // FIXME Presumably need to set this right
1826                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
1827
1828                 docstring const & doctitle = features.htmlTitle();
1829                 os << "<title>"
1830                    << (doctitle.empty() ?
1831                          from_ascii("LyX Document") :
1832                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
1833                    << "</title>\n";
1834
1835                 docstring styles = features.getTClassHTMLPreamble();
1836                 if (!styles.empty())
1837                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
1838
1839                 styles = from_utf8(features.getPreambleSnippets());
1840                 if (!styles.empty())
1841                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
1842
1843                 // we will collect CSS information in a stream, and then output it
1844                 // either here, as part of the header, or else in a separate file.
1845                 odocstringstream css;
1846                 styles = from_utf8(features.getCSSSnippets());
1847                 if (!styles.empty())
1848                         css << "/* LyX Provided Styles */\n" << styles << '\n';
1849
1850                 styles = features.getTClassHTMLStyles();
1851                 if (!styles.empty())
1852                         css << "/* Layout-provided Styles */\n" << styles << '\n';
1853
1854                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
1855                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
1856                 if (needfg || needbg) {
1857                                 css << "\nbody {\n";
1858                                 if (needfg)
1859                                    css << "  color: "
1860                                             << from_ascii(X11hexname(params().fontcolor))
1861                                             << ";\n";
1862                                 if (needbg)
1863                                    css << "  background-color: "
1864                                             << from_ascii(X11hexname(params().backgroundcolor))
1865                                             << ";\n";
1866                                 css << "}\n";
1867                 }
1868                 
1869                 docstring const dstyles = css.str();
1870                 if (!dstyles.empty()) {
1871                         bool written = false;
1872                         if (params().html_css_as_file) {
1873                                 // open a file for CSS info
1874                                 ofdocstream ocss;
1875                                 string const fcssname = addName(temppath(), "docstyle.css");
1876                                 FileName const fcssfile = FileName(fcssname);
1877                                 if (openFileWrite(ocss, fcssfile)) {
1878                                         ocss << dstyles;
1879                                         ocss.close();
1880                                         written = true;
1881                                         // write link to header
1882                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
1883                                         // register file
1884                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
1885                                 }
1886                         }
1887                         // we are here if the CSS is supposed to be written to the header
1888                         // or if we failed to write it to an external file.
1889                         if (!written) {
1890                                 os << "<style type='text/css'>\n"
1891                                          << dstyles
1892                                          << "\n</style>\n";
1893                         }
1894                 }
1895                 os << "</head>\n";
1896         }
1897
1898         if (output_body) {
1899                 bool const output_body_tag = (output != IncludedFile);
1900                 if (output_body_tag)
1901                         os << "<body>\n";
1902                 XHTMLStream xs(os);
1903                 if (output != IncludedFile)
1904                         // if we're an included file, the counters are in the master.
1905                         params().documentClass().counters().reset();
1906                 xhtmlParagraphs(text(), *this, xs, runparams);
1907                 if (output_body_tag)
1908                         os << "</body>\n";
1909         }
1910
1911         if (output_preamble)
1912                 os << "</html>\n";
1913 }
1914
1915
1916 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1917 // Other flags: -wall -v0 -x
1918 int Buffer::runChktex()
1919 {
1920         setBusy(true);
1921
1922         // get LaTeX-Filename
1923         FileName const path(temppath());
1924         string const name = addName(path.absFileName(), latexName());
1925         string const org_path = filePath();
1926
1927         PathChanger p(path); // path to LaTeX file
1928         message(_("Running chktex..."));
1929
1930         // Generate the LaTeX file if neccessary
1931         OutputParams runparams(&params().encoding());
1932         runparams.flavor = OutputParams::LATEX;
1933         runparams.nice = false;
1934         runparams.linelen = lyxrc.plaintext_linelen;
1935         makeLaTeXFile(FileName(name), org_path, runparams);
1936
1937         TeXErrors terr;
1938         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
1939         int const res = chktex.run(terr); // run chktex
1940
1941         if (res == -1) {
1942                 Alert::error(_("chktex failure"),
1943                              _("Could not run chktex successfully."));
1944         } else if (res > 0) {
1945                 ErrorList & errlist = d->errorLists["ChkTeX"];
1946                 errlist.clear();
1947                 bufferErrors(terr, errlist);
1948         }
1949
1950         setBusy(false);
1951
1952         errors("ChkTeX");
1953
1954         return res;
1955 }
1956
1957
1958 void Buffer::validate(LaTeXFeatures & features) const
1959 {
1960         // Validate the buffer params, but not for included
1961         // files, since they also use the parent buffer's
1962         // params (# 5941)
1963         if (!features.runparams().is_child)
1964                 params().validate(features);
1965
1966         for_each(paragraphs().begin(), paragraphs().end(),
1967                  bind(&Paragraph::validate, _1, ref(features)));
1968
1969         if (lyxerr.debugging(Debug::LATEX)) {
1970                 features.showStruct();
1971         }
1972 }
1973
1974
1975 void Buffer::getLabelList(vector<docstring> & list) const
1976 {
1977         // If this is a child document, use the master's list instead.
1978         if (parent()) {
1979                 masterBuffer()->getLabelList(list);
1980                 return;
1981         }
1982
1983         list.clear();
1984         Toc & toc = d->toc_backend.toc("label");
1985         TocIterator toc_it = toc.begin();
1986         TocIterator end = toc.end();
1987         for (; toc_it != end; ++toc_it) {
1988                 if (toc_it->depth() == 0)
1989                         list.push_back(toc_it->str());
1990         }
1991 }
1992
1993
1994 void Buffer::updateBibfilesCache(UpdateScope scope) const
1995 {
1996         // FIXME This is probably unnecssary, given where we call this.
1997         // If this is a child document, use the parent's cache instead.
1998         if (parent() && scope != UpdateChildOnly) {
1999                 masterBuffer()->updateBibfilesCache();
2000                 return;
2001         }
2002
2003         d->bibfiles_cache_.clear();
2004         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2005                 if (it->lyxCode() == BIBTEX_CODE) {
2006                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2007                         support::FileNameList const bibfiles = inset.getBibFiles();
2008                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2009                                 bibfiles.begin(),
2010                                 bibfiles.end());
2011                 } else if (it->lyxCode() == INCLUDE_CODE) {
2012                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2013                         Buffer const * const incbuf = inset.getChildBuffer();
2014                         if (!incbuf)
2015                                 continue;
2016                         support::FileNameList const & bibfiles =
2017                                         incbuf->getBibfilesCache(UpdateChildOnly);
2018                         if (!bibfiles.empty()) {
2019                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2020                                         bibfiles.begin(),
2021                                         bibfiles.end());
2022                         }
2023                 }
2024         }
2025         d->bibfile_cache_valid_ = true;
2026         d->bibinfo_cache_valid_ = false;
2027         d->cite_labels_valid_ = false;
2028 }
2029
2030
2031 void Buffer::invalidateBibinfoCache() const
2032 {
2033         d->bibinfo_cache_valid_ = false;
2034         d->cite_labels_valid_ = false;
2035         // also invalidate the cache for the parent buffer
2036         Buffer const * const pbuf = d->parent();
2037         if (pbuf)
2038                 pbuf->invalidateBibinfoCache();
2039 }
2040
2041
2042 void Buffer::invalidateBibfileCache() const
2043 {
2044         d->bibfile_cache_valid_ = false;
2045         d->bibinfo_cache_valid_ = false;
2046         d->cite_labels_valid_ = false;
2047         // also invalidate the cache for the parent buffer
2048         Buffer const * const pbuf = d->parent();
2049         if (pbuf)
2050                 pbuf->invalidateBibfileCache();
2051 }
2052
2053
2054 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2055 {
2056         // FIXME This is probably unnecessary, given where we call this.
2057         // If this is a child document, use the master's cache instead.
2058         Buffer const * const pbuf = masterBuffer();
2059         if (pbuf != this && scope != UpdateChildOnly)
2060                 return pbuf->getBibfilesCache();
2061
2062         if (!d->bibfile_cache_valid_)
2063                 this->updateBibfilesCache(scope);
2064
2065         return d->bibfiles_cache_;
2066 }
2067
2068
2069 BiblioInfo const & Buffer::masterBibInfo() const
2070 {
2071         Buffer const * const tmp = masterBuffer();
2072         if (tmp != this)
2073                 return tmp->masterBibInfo();
2074         return d->bibinfo_;
2075 }
2076
2077
2078 void Buffer::checkIfBibInfoCacheIsValid() const
2079 {
2080         // use the master's cache
2081         Buffer const * const tmp = masterBuffer();
2082         if (tmp != this) {
2083                 tmp->checkIfBibInfoCacheIsValid();
2084                 return;
2085         }
2086
2087         // compare the cached timestamps with the actual ones.
2088         FileNameList const & bibfiles_cache = getBibfilesCache();
2089         FileNameList::const_iterator ei = bibfiles_cache.begin();
2090         FileNameList::const_iterator en = bibfiles_cache.end();
2091         for (; ei != en; ++ ei) {
2092                 time_t lastw = ei->lastModified();
2093                 time_t prevw = d->bibfile_status_[*ei];
2094                 if (lastw != prevw) {
2095                         d->bibinfo_cache_valid_ = false;
2096                         d->cite_labels_valid_ = false;
2097                         d->bibfile_status_[*ei] = lastw;
2098                 }
2099         }
2100 }
2101
2102
2103 void Buffer::reloadBibInfoCache() const
2104 {
2105         // use the master's cache
2106         Buffer const * const tmp = masterBuffer();
2107         if (tmp != this) {
2108                 tmp->reloadBibInfoCache();
2109                 return;
2110         }
2111
2112         checkIfBibInfoCacheIsValid();
2113         if (d->bibinfo_cache_valid_)
2114                 return;
2115
2116         d->bibinfo_.clear();
2117         collectBibKeys();
2118         d->bibinfo_cache_valid_ = true;
2119 }
2120
2121
2122 void Buffer::collectBibKeys() const
2123 {
2124         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2125                 it->collectBibKeys(it);
2126 }
2127
2128
2129 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2130 {
2131         Buffer const * tmp = masterBuffer();
2132         BiblioInfo & masterbi = (tmp == this) ?
2133                 d->bibinfo_ : tmp->d->bibinfo_;
2134         masterbi.mergeBiblioInfo(bi);
2135 }
2136
2137
2138 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2139 {
2140         Buffer const * tmp = masterBuffer();
2141         BiblioInfo & masterbi = (tmp == this) ?
2142                 d->bibinfo_ : tmp->d->bibinfo_;
2143         masterbi[key] = bi;
2144 }
2145
2146
2147 void Buffer::makeCitationLabels() const
2148 {
2149         Buffer const * const master = masterBuffer();
2150         return d->bibinfo_.makeCitationLabels(*master);
2151 }
2152
2153
2154 bool Buffer::citeLabelsValid() const
2155 {
2156         return masterBuffer()->d->cite_labels_valid_;
2157 }
2158
2159
2160 void Buffer::removeBiblioTempFiles() const
2161 {
2162         // We remove files that contain LaTeX commands specific to the
2163         // particular bibliographic style being used, in order to avoid
2164         // LaTeX errors when we switch style.
2165         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2166         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2167         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2168         aux_file.removeFile();
2169         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2170         bbl_file.removeFile();
2171         // Also for the parent buffer
2172         Buffer const * const pbuf = parent();
2173         if (pbuf)
2174                 pbuf->removeBiblioTempFiles();
2175 }
2176
2177
2178 bool Buffer::isDepClean(string const & name) const
2179 {
2180         DepClean::const_iterator const it = d->dep_clean.find(name);
2181         if (it == d->dep_clean.end())
2182                 return true;
2183         return it->second;
2184 }
2185
2186
2187 void Buffer::markDepClean(string const & name)
2188 {
2189         d->dep_clean[name] = true;
2190 }
2191
2192
2193 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2194 {
2195         if (isInternal()) {
2196                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2197                 // if internal, put a switch '(cmd.action)' here.
2198                 return false;
2199         }
2200
2201         bool enable = true;
2202
2203         switch (cmd.action()) {
2204
2205                 case LFUN_BUFFER_TOGGLE_READ_ONLY:
2206                         flag.setOnOff(isReadonly());
2207                         break;
2208
2209                 // FIXME: There is need for a command-line import.
2210                 //case LFUN_BUFFER_IMPORT:
2211
2212                 case LFUN_BUFFER_AUTO_SAVE:
2213                         break;
2214
2215                 case LFUN_BUFFER_EXPORT_CUSTOM:
2216                         // FIXME: Nothing to check here?
2217                         break;
2218
2219                 case LFUN_BUFFER_EXPORT: {
2220                         docstring const arg = cmd.argument();
2221                         if (arg == "custom") {
2222                                 enable = true;
2223                                 break;
2224                         }
2225                         string format = to_utf8(arg);
2226                         size_t pos = format.find(' ');
2227                         if (pos != string::npos)
2228                                 format = format.substr(0, pos);
2229                         enable = params().isExportable(format);
2230                         if (!enable)
2231                                 flag.message(bformat(
2232                                         _("Don't know how to export to format: %1$s"), arg));
2233                         break;
2234                 }
2235
2236                 case LFUN_BUFFER_CHKTEX:
2237                         enable = params().isLatex() && !lyxrc.chktex_command.empty();
2238                         break;
2239
2240                 case LFUN_BUILD_PROGRAM:
2241                         enable = params().isExportable("program");
2242                         break;
2243
2244                 case LFUN_BRANCH_ADD:
2245                 case LFUN_BRANCHES_RENAME:
2246                 case LFUN_BUFFER_PRINT:
2247                         // if no Buffer is present, then of course we won't be called!
2248                         break;
2249
2250                 case LFUN_BUFFER_LANGUAGE:
2251                         enable = !isReadonly();
2252                         break;
2253
2254                 default:
2255                         return false;
2256         }
2257         flag.setEnabled(enable);
2258         return true;
2259 }
2260
2261
2262 void Buffer::dispatch(string const & command, DispatchResult & result)
2263 {
2264         return dispatch(lyxaction.lookupFunc(command), result);
2265 }
2266
2267
2268 // NOTE We can end up here even if we have no GUI, because we are called
2269 // by LyX::exec to handled command-line requests. So we may need to check
2270 // whether we have a GUI or not. The boolean use_gui holds this information.
2271 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2272 {
2273         if (isInternal()) {
2274                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2275                 // if internal, put a switch '(cmd.action())' here.
2276                 dr.dispatched(false);
2277                 return;
2278         }
2279         string const argument = to_utf8(func.argument());
2280         // We'll set this back to false if need be.
2281         bool dispatched = true;
2282         undo().beginUndoGroup();
2283
2284         switch (func.action()) {
2285         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2286                 if (lyxvc().inUse()) {
2287                         string log = lyxvc().toggleReadOnly();
2288                         if (!log.empty())
2289                                 dr.setMessage(log);
2290                 }
2291                 else
2292                         setReadonly(!isReadonly());
2293                 break;
2294
2295         case LFUN_BUFFER_EXPORT: {
2296                 ExportStatus const status = doExport(argument, false);
2297                 dr.setError(status != ExportSuccess);
2298                 if (status != ExportSuccess)
2299                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2300                                               func.argument()));
2301                 break;
2302         }
2303
2304         case LFUN_BUILD_PROGRAM:
2305                 doExport("program", true);
2306                 break;
2307
2308         case LFUN_BUFFER_CHKTEX:
2309                 runChktex();
2310                 break;
2311
2312         case LFUN_BUFFER_EXPORT_CUSTOM: {
2313                 string format_name;
2314                 string command = split(argument, format_name, ' ');
2315                 Format const * format = formats.getFormat(format_name);
2316                 if (!format) {
2317                         lyxerr << "Format \"" << format_name
2318                                 << "\" not recognized!"
2319                                 << endl;
2320                         break;
2321                 }
2322
2323                 // The name of the file created by the conversion process
2324                 string filename;
2325
2326                 // Output to filename
2327                 if (format->name() == "lyx") {
2328                         string const latexname = latexName(false);
2329                         filename = changeExtension(latexname,
2330                                 format->extension());
2331                         filename = addName(temppath(), filename);
2332
2333                         if (!writeFile(FileName(filename)))
2334                                 break;
2335
2336                 } else {
2337                         doExport(format_name, true, filename);
2338                 }
2339
2340                 // Substitute $$FName for filename
2341                 if (!contains(command, "$$FName"))
2342                         command = "( " + command + " ) < $$FName";
2343                 command = subst(command, "$$FName", filename);
2344
2345                 // Execute the command in the background
2346                 Systemcall call;
2347                 call.startscript(Systemcall::DontWait, command, filePath());
2348                 break;
2349         }
2350
2351         // FIXME: There is need for a command-line import.
2352         /*
2353         case LFUN_BUFFER_IMPORT:
2354                 doImport(argument);
2355                 break;
2356         */
2357
2358         case LFUN_BUFFER_AUTO_SAVE:
2359                 autoSave();
2360                 resetAutosaveTimers();
2361                 break;
2362
2363         case LFUN_BRANCH_ADD: {
2364                 docstring branch_name = func.argument();
2365                 if (branch_name.empty()) {
2366                         dispatched = false;
2367                         break;
2368                 }
2369                 BranchList & branch_list = params().branchlist();
2370                 vector<docstring> const branches =
2371                         getVectorFromString(branch_name, branch_list.separator());
2372                 docstring msg;
2373                 for (vector<docstring>::const_iterator it = branches.begin();
2374                      it != branches.end(); ++it) {
2375                         branch_name = *it;
2376                         Branch * branch = branch_list.find(branch_name);
2377                         if (branch) {
2378                                 LYXERR0("Branch " << branch_name << " already exists.");
2379                                 dr.setError(true);
2380                                 if (!msg.empty())
2381                                         msg += ("\n");
2382                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2383                         } else {
2384                                 branch_list.add(branch_name);
2385                                 branch = branch_list.find(branch_name);
2386                                 string const x11hexname = X11hexname(branch->color());
2387                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2388                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2389                                 dr.setError(false);
2390                                 dr.screenUpdate(Update::Force);
2391                         }
2392                 }
2393                 if (!msg.empty())
2394                         dr.setMessage(msg);
2395                 break;
2396         }
2397
2398         case LFUN_BRANCHES_RENAME: {
2399                 if (func.argument().empty())
2400                         break;
2401
2402                 docstring const oldname = from_utf8(func.getArg(0));
2403                 docstring const newname = from_utf8(func.getArg(1));
2404                 InsetIterator it  = inset_iterator_begin(inset());
2405                 InsetIterator const end = inset_iterator_end(inset());
2406                 bool success = false;
2407                 for (; it != end; ++it) {
2408                         if (it->lyxCode() == BRANCH_CODE) {
2409                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2410                                 if (ins.branch() == oldname) {
2411                                         undo().recordUndo(CursorData(it));
2412                                         ins.rename(newname);
2413                                         success = true;
2414                                         continue;
2415                                 }
2416                         }
2417                         if (it->lyxCode() == INCLUDE_CODE) {
2418                                 // get buffer of external file
2419                                 InsetInclude const & ins =
2420                                         static_cast<InsetInclude const &>(*it);
2421                                 Buffer * child = ins.getChildBuffer();
2422                                 if (!child)
2423                                         continue;
2424                                 child->dispatch(func, dr);
2425                         }
2426                 }
2427
2428                 if (success) {
2429                         dr.screenUpdate(Update::Force);
2430                         dr.forceBufferUpdate();
2431                 }
2432                 break;
2433         }
2434
2435         case LFUN_BUFFER_PRINT: {
2436                 // we'll assume there's a problem until we succeed
2437                 dr.setError(true);
2438                 string target = func.getArg(0);
2439                 string target_name = func.getArg(1);
2440                 string command = func.getArg(2);
2441
2442                 if (target.empty()
2443                     || target_name.empty()
2444                     || command.empty()) {
2445                         LYXERR0("Unable to parse " << func.argument());
2446                         docstring const msg =
2447                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2448                         dr.setMessage(msg);
2449                         break;
2450                 }
2451                 if (target != "printer" && target != "file") {
2452                         LYXERR0("Unrecognized target \"" << target << '"');
2453                         docstring const msg =
2454                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2455                         dr.setMessage(msg);
2456                         break;
2457                 }
2458
2459                 if (!doExport("dvi", true)) {
2460                         showPrintError(absFileName());
2461                         dr.setMessage(_("Error exporting to DVI."));
2462                         break;
2463                 }
2464
2465                 // Push directory path.
2466                 string const path = temppath();
2467                 // Prevent the compiler from optimizing away p
2468                 FileName pp(path);
2469                 PathChanger p(pp);
2470
2471                 // there are three cases here:
2472                 // 1. we print to a file
2473                 // 2. we print directly to a printer
2474                 // 3. we print using a spool command (print to file first)
2475                 Systemcall one;
2476                 int res = 0;
2477                 string const dviname = changeExtension(latexName(true), "dvi");
2478
2479                 if (target == "printer") {
2480                         if (!lyxrc.print_spool_command.empty()) {
2481                                 // case 3: print using a spool
2482                                 string const psname = changeExtension(dviname,".ps");
2483                                 command += ' ' + lyxrc.print_to_file
2484                                         + quoteName(psname)
2485                                         + ' '
2486                                         + quoteName(dviname);
2487
2488                                 string command2 = lyxrc.print_spool_command + ' ';
2489                                 if (target_name != "default") {
2490                                         command2 += lyxrc.print_spool_printerprefix
2491                                                 + target_name
2492                                                 + ' ';
2493                                 }
2494                                 command2 += quoteName(psname);
2495                                 // First run dvips.
2496                                 // If successful, then spool command
2497                                 res = one.startscript(Systemcall::Wait, command,
2498                                                       filePath());
2499
2500                                 if (res == 0) {
2501                                         // If there's no GUI, we have to wait on this command. Otherwise,
2502                                         // LyX deletes the temporary directory, and with it the spooled
2503                                         // file, before it can be printed!!
2504                                         Systemcall::Starttype stype = use_gui ?
2505                                                 Systemcall::DontWait : Systemcall::Wait;
2506                                         res = one.startscript(stype, command2,
2507                                                               filePath());
2508                                 }
2509                         } else {
2510                                 // case 2: print directly to a printer
2511                                 if (target_name != "default")
2512                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2513                                 // as above....
2514                                 Systemcall::Starttype stype = use_gui ?
2515                                         Systemcall::DontWait : Systemcall::Wait;
2516                                 res = one.startscript(stype, command +
2517                                                 quoteName(dviname), filePath());
2518                         }
2519
2520                 } else {
2521                         // case 1: print to a file
2522                         FileName const filename(makeAbsPath(target_name, filePath()));
2523                         FileName const dvifile(makeAbsPath(dviname, path));
2524                         if (filename.exists()) {
2525                                 docstring text = bformat(
2526                                         _("The file %1$s already exists.\n\n"
2527                                           "Do you want to overwrite that file?"),
2528                                         makeDisplayPath(filename.absFileName()));
2529                                 if (Alert::prompt(_("Overwrite file?"),
2530                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2531                                         break;
2532                         }
2533                         command += ' ' + lyxrc.print_to_file
2534                                 + quoteName(filename.toFilesystemEncoding())
2535                                 + ' '
2536                                 + quoteName(dvifile.toFilesystemEncoding());
2537                         // as above....
2538                         Systemcall::Starttype stype = use_gui ?
2539                                 Systemcall::DontWait : Systemcall::Wait;
2540                         res = one.startscript(stype, command, filePath());
2541                 }
2542
2543                 if (res == 0)
2544                         dr.setError(false);
2545                 else {
2546                         dr.setMessage(_("Error running external commands."));
2547                         showPrintError(absFileName());
2548                 }
2549                 break;
2550         }
2551
2552         default:
2553                 dispatched = false;
2554                 break;
2555         }
2556         dr.dispatched(dispatched);
2557         undo().endUndoGroup();
2558 }
2559
2560
2561 void Buffer::changeLanguage(Language const * from, Language const * to)
2562 {
2563         LASSERT(from, /**/);
2564         LASSERT(to, /**/);
2565
2566         for_each(par_iterator_begin(),
2567                  par_iterator_end(),
2568                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2569 }
2570
2571
2572 bool Buffer::isMultiLingual() const
2573 {
2574         ParConstIterator end = par_iterator_end();
2575         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2576                 if (it->isMultiLingual(params()))
2577                         return true;
2578
2579         return false;
2580 }
2581
2582
2583 std::set<Language const *> Buffer::getLanguages() const
2584 {
2585         std::set<Language const *> languages;
2586         getLanguages(languages);
2587         return languages;
2588 }
2589
2590
2591 void Buffer::getLanguages(std::set<Language const *> & languages) const
2592 {
2593         ParConstIterator end = par_iterator_end();
2594         // add the buffer language, even if it's not actively used
2595         languages.insert(language());
2596         // iterate over the paragraphs
2597         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2598                 it->getLanguages(languages);
2599         // also children
2600         ListOfBuffers clist = getDescendents();
2601         ListOfBuffers::const_iterator cit = clist.begin();
2602         ListOfBuffers::const_iterator const cen = clist.end();
2603         for (; cit != cen; ++cit)
2604                 (*cit)->getLanguages(languages);
2605 }
2606
2607
2608 DocIterator Buffer::getParFromID(int const id) const
2609 {
2610         Buffer * buf = const_cast<Buffer *>(this);
2611         if (id < 0) {
2612                 // John says this is called with id == -1 from undo
2613                 lyxerr << "getParFromID(), id: " << id << endl;
2614                 return doc_iterator_end(buf);
2615         }
2616
2617         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2618                 if (it.paragraph().id() == id)
2619                         return it;
2620
2621         return doc_iterator_end(buf);
2622 }
2623
2624
2625 bool Buffer::hasParWithID(int const id) const
2626 {
2627         return !getParFromID(id).atEnd();
2628 }
2629
2630
2631 ParIterator Buffer::par_iterator_begin()
2632 {
2633         return ParIterator(doc_iterator_begin(this));
2634 }
2635
2636
2637 ParIterator Buffer::par_iterator_end()
2638 {
2639         return ParIterator(doc_iterator_end(this));
2640 }
2641
2642
2643 ParConstIterator Buffer::par_iterator_begin() const
2644 {
2645         return ParConstIterator(doc_iterator_begin(this));
2646 }
2647
2648
2649 ParConstIterator Buffer::par_iterator_end() const
2650 {
2651         return ParConstIterator(doc_iterator_end(this));
2652 }
2653
2654
2655 Language const * Buffer::language() const
2656 {
2657         return params().language;
2658 }
2659
2660
2661 docstring const Buffer::B_(string const & l10n) const
2662 {
2663         return params().B_(l10n);
2664 }
2665
2666
2667 bool Buffer::isClean() const
2668 {
2669         return d->lyx_clean;
2670 }
2671
2672
2673 bool Buffer::isExternallyModified(CheckMethod method) const
2674 {
2675         LASSERT(d->filename.exists(), /**/);
2676         // if method == timestamp, check timestamp before checksum
2677         return (method == checksum_method
2678                 || d->timestamp_ != d->filename.lastModified())
2679                 && d->checksum_ != d->filename.checksum();
2680 }
2681
2682
2683 void Buffer::saveCheckSum() const
2684 {
2685         FileName const & file = d->filename;
2686
2687         file.refresh();
2688         if (file.exists()) {
2689                 d->timestamp_ = file.lastModified();
2690                 d->checksum_ = file.checksum();
2691         } else {
2692                 // in the case of save to a new file.
2693                 d->timestamp_ = 0;
2694                 d->checksum_ = 0;
2695         }
2696 }
2697
2698
2699 void Buffer::markClean() const
2700 {
2701         if (!d->lyx_clean) {
2702                 d->lyx_clean = true;
2703                 updateTitles();
2704         }
2705         // if the .lyx file has been saved, we don't need an
2706         // autosave
2707         d->bak_clean = true;
2708         d->undo_.markDirty();
2709 }
2710
2711
2712 void Buffer::setUnnamed(bool flag)
2713 {
2714         d->unnamed = flag;
2715 }
2716
2717
2718 bool Buffer::isUnnamed() const
2719 {
2720         return d->unnamed;
2721 }
2722
2723
2724 /// \note
2725 /// Don't check unnamed, here: isInternal() is used in
2726 /// newBuffer(), where the unnamed flag has not been set by anyone
2727 /// yet. Also, for an internal buffer, there should be no need for
2728 /// retrieving fileName() nor for checking if it is unnamed or not.
2729 bool Buffer::isInternal() const
2730 {
2731         return d->internal_buffer;
2732 }
2733
2734
2735 void Buffer::setInternal(bool flag)
2736 {
2737         d->internal_buffer = flag;
2738 }
2739
2740
2741 void Buffer::markDirty()
2742 {
2743         if (d->lyx_clean) {
2744                 d->lyx_clean = false;
2745                 updateTitles();
2746         }
2747         d->bak_clean = false;
2748
2749         DepClean::iterator it = d->dep_clean.begin();
2750         DepClean::const_iterator const end = d->dep_clean.end();
2751
2752         for (; it != end; ++it)
2753                 it->second = false;
2754 }
2755
2756
2757 FileName Buffer::fileName() const
2758 {
2759         return d->filename;
2760 }
2761
2762
2763 string Buffer::absFileName() const
2764 {
2765         return d->filename.absFileName();
2766 }
2767
2768
2769 string Buffer::filePath() const
2770 {
2771         int last = d->filename.onlyPath().absFileName().length() - 1;
2772
2773         return d->filename.onlyPath().absFileName()[last] == '/'
2774                 ? d->filename.onlyPath().absFileName()
2775                 : d->filename.onlyPath().absFileName() + "/";
2776 }
2777
2778
2779 bool Buffer::isReadonly() const
2780 {
2781         return d->read_only;
2782 }
2783
2784
2785 void Buffer::setParent(Buffer const * buffer)
2786 {
2787         // Avoids recursive include.
2788         d->setParent(buffer == this ? 0 : buffer);
2789         updateMacros();
2790 }
2791
2792
2793 Buffer const * Buffer::parent() const
2794 {
2795         return d->parent();
2796 }
2797
2798
2799 ListOfBuffers Buffer::allRelatives() const
2800 {
2801         ListOfBuffers lb = masterBuffer()->getDescendents();
2802         lb.push_front(const_cast<Buffer *>(masterBuffer()));
2803         return lb;
2804 }
2805
2806
2807 Buffer const * Buffer::masterBuffer() const
2808 {
2809         // FIXME Should be make sure we are not in some kind
2810         // of recursive include? A -> B -> A will crash this.
2811         Buffer const * const pbuf = d->parent();
2812         if (!pbuf)
2813                 return this;
2814
2815         return pbuf->masterBuffer();
2816 }
2817
2818
2819 bool Buffer::isChild(Buffer * child) const
2820 {
2821         return d->children_positions.find(child) != d->children_positions.end();
2822 }
2823
2824
2825 DocIterator Buffer::firstChildPosition(Buffer const * child)
2826 {
2827         Impl::BufferPositionMap::iterator it;
2828         it = d->children_positions.find(child);
2829         if (it == d->children_positions.end())
2830                 return DocIterator(this);
2831         return it->second;
2832 }
2833
2834
2835 bool Buffer::hasChildren() const
2836 {
2837         return !d->children_positions.empty();
2838 }
2839
2840
2841 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
2842 {
2843         // loop over children
2844         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2845         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2846         for (; it != end; ++it) {
2847                 Buffer * child = const_cast<Buffer *>(it->first);
2848                 // No duplicates
2849                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
2850                 if (bit != clist.end())
2851                         continue;
2852                 clist.push_back(child);
2853                 if (grand_children)
2854                         // there might be grandchildren
2855                         child->collectChildren(clist, true);
2856         }
2857 }
2858
2859
2860 ListOfBuffers Buffer::getChildren() const
2861 {
2862         ListOfBuffers v;
2863         collectChildren(v, false);
2864         // Make sure we have not included ourselves.
2865         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2866         if (bit != v.end()) {
2867                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2868                 v.erase(bit);
2869         }
2870         return v;
2871 }
2872
2873
2874 ListOfBuffers Buffer::getDescendents() const
2875 {
2876         ListOfBuffers v;
2877         collectChildren(v, true);
2878         // Make sure we have not included ourselves.
2879         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
2880         if (bit != v.end()) {
2881                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
2882                 v.erase(bit);
2883         }
2884         return v;
2885 }
2886
2887
2888 template<typename M>
2889 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
2890 {
2891         if (m.empty())
2892                 return m.end();
2893
2894         typename M::const_iterator it = m.lower_bound(x);
2895         if (it == m.begin())
2896                 return m.end();
2897
2898         it--;
2899         return it;
2900 }
2901
2902
2903 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
2904                                          DocIterator const & pos) const
2905 {
2906         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
2907
2908         // if paragraphs have no macro context set, pos will be empty
2909         if (pos.empty())
2910                 return 0;
2911
2912         // we haven't found anything yet
2913         DocIterator bestPos = owner_->par_iterator_begin();
2914         MacroData const * bestData = 0;
2915
2916         // find macro definitions for name
2917         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
2918         if (nameIt != macros.end()) {
2919                 // find last definition in front of pos or at pos itself
2920                 PositionScopeMacroMap::const_iterator it
2921                         = greatest_below(nameIt->second, pos);
2922                 if (it != nameIt->second.end()) {
2923                         while (true) {
2924                                 // scope ends behind pos?
2925                                 if (pos < it->second.first) {
2926                                         // Looks good, remember this. If there
2927                                         // is no external macro behind this,
2928                                         // we found the right one already.
2929                                         bestPos = it->first;
2930                                         bestData = &it->second.second;
2931                                         break;
2932                                 }
2933
2934                                 // try previous macro if there is one
2935                                 if (it == nameIt->second.begin())
2936                                         break;
2937                                 --it;
2938                         }
2939                 }
2940         }
2941
2942         // find macros in included files
2943         PositionScopeBufferMap::const_iterator it
2944                 = greatest_below(position_to_children, pos);
2945         if (it == position_to_children.end())
2946                 // no children before
2947                 return bestData;
2948
2949         while (true) {
2950                 // do we know something better (i.e. later) already?
2951                 if (it->first < bestPos )
2952                         break;
2953
2954                 // scope ends behind pos?
2955                 if (pos < it->second.first
2956                         && (cloned_buffer_ ||
2957                             theBufferList().isLoaded(it->second.second))) {
2958                         // look for macro in external file
2959                         macro_lock = true;
2960                         MacroData const * data
2961                                 = it->second.second->getMacro(name, false);
2962                         macro_lock = false;
2963                         if (data) {
2964                                 bestPos = it->first;
2965                                 bestData = data;
2966                                 break;
2967                         }
2968                 }
2969
2970                 // try previous file if there is one
2971                 if (it == position_to_children.begin())
2972                         break;
2973                 --it;
2974         }
2975
2976         // return the best macro we have found
2977         return bestData;
2978 }
2979
2980
2981 MacroData const * Buffer::getMacro(docstring const & name,
2982         DocIterator const & pos, bool global) const
2983 {
2984         if (d->macro_lock)
2985                 return 0;
2986
2987         // query buffer macros
2988         MacroData const * data = d->getBufferMacro(name, pos);
2989         if (data != 0)
2990                 return data;
2991
2992         // If there is a master buffer, query that
2993         Buffer const * const pbuf = d->parent();
2994         if (pbuf) {
2995                 d->macro_lock = true;
2996                 MacroData const * macro = pbuf->getMacro(
2997                         name, *this, false);
2998                 d->macro_lock = false;
2999                 if (macro)
3000                         return macro;
3001         }
3002
3003         if (global) {
3004                 data = MacroTable::globalMacros().get(name);
3005                 if (data != 0)
3006                         return data;
3007         }
3008
3009         return 0;
3010 }
3011
3012
3013 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3014 {
3015         // set scope end behind the last paragraph
3016         DocIterator scope = par_iterator_begin();
3017         scope.pit() = scope.lastpit() + 1;
3018
3019         return getMacro(name, scope, global);
3020 }
3021
3022
3023 MacroData const * Buffer::getMacro(docstring const & name,
3024         Buffer const & child, bool global) const
3025 {
3026         // look where the child buffer is included first
3027         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3028         if (it == d->children_positions.end())
3029                 return 0;
3030
3031         // check for macros at the inclusion position
3032         return getMacro(name, it->second, global);
3033 }
3034
3035
3036 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3037 {
3038         pit_type const lastpit = it.lastpit();
3039
3040         // look for macros in each paragraph
3041         while (it.pit() <= lastpit) {
3042                 Paragraph & par = it.paragraph();
3043
3044                 // iterate over the insets of the current paragraph
3045                 InsetList const & insets = par.insetList();
3046                 InsetList::const_iterator iit = insets.begin();
3047                 InsetList::const_iterator end = insets.end();
3048                 for (; iit != end; ++iit) {
3049                         it.pos() = iit->pos;
3050
3051                         // is it a nested text inset?
3052                         if (iit->inset->asInsetText()) {
3053                                 // Inset needs its own scope?
3054                                 InsetText const * itext = iit->inset->asInsetText();
3055                                 bool newScope = itext->isMacroScope();
3056
3057                                 // scope which ends just behind the inset
3058                                 DocIterator insetScope = it;
3059                                 ++insetScope.pos();
3060
3061                                 // collect macros in inset
3062                                 it.push_back(CursorSlice(*iit->inset));
3063                                 updateMacros(it, newScope ? insetScope : scope);
3064                                 it.pop_back();
3065                                 continue;
3066                         }
3067
3068                         if (iit->inset->asInsetTabular()) {
3069                                 CursorSlice slice(*iit->inset);
3070                                 size_t const numcells = slice.nargs();
3071                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3072                                         it.push_back(slice);
3073                                         updateMacros(it, scope);
3074                                         it.pop_back();
3075                                 }
3076                                 continue;
3077                         }
3078
3079                         // is it an external file?
3080                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3081                                 // get buffer of external file
3082                                 InsetInclude const & inset =
3083                                         static_cast<InsetInclude const &>(*iit->inset);
3084                                 macro_lock = true;
3085                                 Buffer * child = inset.getChildBuffer();
3086                                 macro_lock = false;
3087                                 if (!child)
3088                                         continue;
3089
3090                                 // register its position, but only when it is
3091                                 // included first in the buffer
3092                                 if (children_positions.find(child) ==
3093                                         children_positions.end())
3094                                                 children_positions[child] = it;
3095
3096                                 // register child with its scope
3097                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3098                                 continue;
3099                         }
3100
3101                         InsetMath * im = iit->inset->asInsetMath();
3102                         if (doing_export && im)  {
3103                                 InsetMathHull * hull = im->asHullInset();
3104                                 if (hull)
3105                                         hull->recordLocation(it);
3106                         }
3107
3108                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3109                                 continue;
3110
3111                         // get macro data
3112                         MathMacroTemplate & macroTemplate =
3113                                 *iit->inset->asInsetMath()->asMacroTemplate();
3114                         MacroContext mc(owner_, it);
3115                         macroTemplate.updateToContext(mc);
3116
3117                         // valid?
3118                         bool valid = macroTemplate.validMacro();
3119                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3120                         // then the BufferView's cursor will be invalid in
3121                         // some cases which leads to crashes.
3122                         if (!valid)
3123                                 continue;
3124
3125                         // register macro
3126                         // FIXME (Abdel), I don't understandt why we pass 'it' here
3127                         // instead of 'macroTemplate' defined above... is this correct?
3128                         macros[macroTemplate.name()][it] =
3129                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3130                 }
3131
3132                 // next paragraph
3133                 it.pit()++;
3134                 it.pos() = 0;
3135         }
3136 }
3137
3138
3139 void Buffer::updateMacros() const
3140 {
3141         if (d->macro_lock)
3142                 return;
3143
3144         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3145
3146         // start with empty table
3147         d->macros.clear();
3148         d->children_positions.clear();
3149         d->position_to_children.clear();
3150
3151         // Iterate over buffer, starting with first paragraph
3152         // The scope must be bigger than any lookup DocIterator
3153         // later. For the global lookup, lastpit+1 is used, hence
3154         // we use lastpit+2 here.
3155         DocIterator it = par_iterator_begin();
3156         DocIterator outerScope = it;
3157         outerScope.pit() = outerScope.lastpit() + 2;
3158         d->updateMacros(it, outerScope);
3159 }
3160
3161
3162 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3163 {
3164         InsetIterator it  = inset_iterator_begin(inset());
3165         InsetIterator const end = inset_iterator_end(inset());
3166         for (; it != end; ++it) {
3167                 if (it->lyxCode() == BRANCH_CODE) {
3168                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3169                         docstring const name = br.branch();
3170                         if (!from_master && !params().branchlist().find(name))
3171                                 result.push_back(name);
3172                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3173                                 result.push_back(name);
3174                         continue;
3175                 }
3176                 if (it->lyxCode() == INCLUDE_CODE) {
3177                         // get buffer of external file
3178                         InsetInclude const & ins =
3179                                 static_cast<InsetInclude const &>(*it);
3180                         Buffer * child = ins.getChildBuffer();
3181                         if (!child)
3182                                 continue;
3183                         child->getUsedBranches(result, true);
3184                 }
3185         }
3186         // remove duplicates
3187         result.unique();
3188 }
3189
3190
3191 void Buffer::updateMacroInstances(UpdateType utype) const
3192 {
3193         LYXERR(Debug::MACROS, "updateMacroInstances for "
3194                 << d->filename.onlyFileName());
3195         DocIterator it = doc_iterator_begin(this);
3196         it.forwardInset();
3197         DocIterator const end = doc_iterator_end(this);
3198         for (; it != end; it.forwardInset()) {
3199                 // look for MathData cells in InsetMathNest insets
3200                 InsetMath * minset = it.nextInset()->asInsetMath();
3201                 if (!minset)
3202                         continue;
3203
3204                 // update macro in all cells of the InsetMathNest
3205                 DocIterator::idx_type n = minset->nargs();
3206                 MacroContext mc = MacroContext(this, it);
3207                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3208                         MathData & data = minset->cell(i);
3209                         data.updateMacros(0, mc, utype);
3210                 }
3211         }
3212 }
3213
3214
3215 void Buffer::listMacroNames(MacroNameSet & macros) const
3216 {
3217         if (d->macro_lock)
3218                 return;
3219
3220         d->macro_lock = true;
3221
3222         // loop over macro names
3223         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3224         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3225         for (; nameIt != nameEnd; ++nameIt)
3226                 macros.insert(nameIt->first);
3227
3228         // loop over children
3229         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3230         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3231         for (; it != end; ++it)
3232                 it->first->listMacroNames(macros);
3233
3234         // call parent
3235         Buffer const * const pbuf = d->parent();
3236         if (pbuf)
3237                 pbuf->listMacroNames(macros);
3238
3239         d->macro_lock = false;
3240 }
3241
3242
3243 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3244 {
3245         Buffer const * const pbuf = d->parent();
3246         if (!pbuf)
3247                 return;
3248
3249         MacroNameSet names;
3250         pbuf->listMacroNames(names);
3251
3252         // resolve macros
3253         MacroNameSet::iterator it = names.begin();
3254         MacroNameSet::iterator end = names.end();
3255         for (; it != end; ++it) {
3256                 // defined?
3257                 MacroData const * data =
3258                 pbuf->getMacro(*it, *this, false);
3259                 if (data) {
3260                         macros.insert(data);
3261
3262                         // we cannot access the original MathMacroTemplate anymore
3263                         // here to calls validate method. So we do its work here manually.
3264                         // FIXME: somehow make the template accessible here.
3265                         if (data->optionals() > 0)
3266                                 features.require("xargs");
3267                 }
3268         }
3269 }
3270
3271
3272 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3273 {
3274         if (d->parent())
3275                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3276
3277         RefCache::iterator it = d->ref_cache_.find(label);
3278         if (it != d->ref_cache_.end())
3279                 return it->second.second;
3280
3281         static InsetLabel const * dummy_il = 0;
3282         static References const dummy_refs;
3283         it = d->ref_cache_.insert(
3284                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3285         return it->second.second;
3286 }
3287
3288
3289 Buffer::References const & Buffer::references(docstring const & label) const
3290 {
3291         return const_cast<Buffer *>(this)->getReferenceCache(label);
3292 }
3293
3294
3295 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3296 {
3297         References & refs = getReferenceCache(label);
3298         refs.push_back(make_pair(inset, it));
3299 }
3300
3301
3302 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3303 {
3304         masterBuffer()->d->ref_cache_[label].first = il;
3305 }
3306
3307
3308 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3309 {
3310         return masterBuffer()->d->ref_cache_[label].first;
3311 }
3312
3313
3314 void Buffer::clearReferenceCache() const
3315 {
3316         if (!d->parent())
3317                 d->ref_cache_.clear();
3318 }
3319
3320
3321 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
3322         InsetCode code)
3323 {
3324         //FIXME: This does not work for child documents yet.
3325         LASSERT(code == CITE_CODE, /**/);
3326
3327         reloadBibInfoCache();
3328
3329         // Check if the label 'from' appears more than once
3330         BiblioInfo const & keys = masterBibInfo();
3331         BiblioInfo::const_iterator bit  = keys.begin();
3332         BiblioInfo::const_iterator bend = keys.end();
3333         vector<docstring> labels;
3334
3335         for (; bit != bend; ++bit)
3336                 // FIXME UNICODE
3337                 labels.push_back(bit->first);
3338
3339         if (count(labels.begin(), labels.end(), from) > 1)
3340                 return;
3341
3342         string const paramName = "key";
3343         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3344                 if (it->lyxCode() == code) {
3345                         InsetCommand * inset = it->asInsetCommand();
3346                         if (!inset)
3347                                 continue;
3348                         docstring const oldValue = inset->getParam(paramName);
3349                         if (oldValue == from)
3350                                 inset->setParam(paramName, to);
3351                 }
3352         }
3353 }
3354
3355
3356 void Buffer::getSourceCode(odocstream & os, string const format,
3357                            pit_type par_begin, pit_type par_end,
3358                            OutputWhat output, bool master) const
3359 {
3360         OutputParams runparams(&params().encoding());
3361         runparams.nice = true;
3362         runparams.flavor = params().getOutputFlavor(format);
3363         runparams.linelen = lyxrc.plaintext_linelen;
3364         // No side effect of file copying and image conversion
3365         runparams.dryrun = true;
3366
3367         if (output == CurrentParagraph) {
3368                 runparams.par_begin = par_begin;
3369                 runparams.par_end = par_end;
3370                 if (par_begin + 1 == par_end) {
3371                         os << "% "
3372                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3373                            << "\n\n";
3374                 } else {
3375                         os << "% "
3376                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3377                                         convert<docstring>(par_begin),
3378                                         convert<docstring>(par_end - 1))
3379                            << "\n\n";
3380                 }
3381                 // output paragraphs
3382                 if (runparams.flavor == OutputParams::LYX) {
3383                         Paragraph const & par = text().paragraphs()[par_begin];
3384                         ostringstream ods;
3385                         depth_type dt = par.getDepth();
3386                         par.write(ods, params(), dt);
3387                         os << from_utf8(ods.str());
3388                 } else if (runparams.flavor == OutputParams::HTML) {
3389                         XHTMLStream xs(os);
3390                         setMathFlavor(runparams);
3391                         xhtmlParagraphs(text(), *this, xs, runparams);
3392                 } else if (runparams.flavor == OutputParams::TEXT) {
3393                         bool dummy;
3394                         // FIXME Handles only one paragraph, unlike the others.
3395                         // Probably should have some routine with a signature like them.
3396                         writePlaintextParagraph(*this,
3397                                 text().paragraphs()[par_begin], os, runparams, dummy);
3398                 } else if (params().isDocBook()) {
3399                         docbookParagraphs(text(), *this, os, runparams);
3400                 } else {
3401                         // If we are previewing a paragraph, even if this is the
3402                         // child of some other buffer, let's cut the link here,
3403                         // so that no concurring settings from the master
3404                         // (e.g. branch state) interfere (see #8101).
3405                         if (!master)
3406                                 d->ignore_parent = true;
3407                         // We need to validate the Buffer params' features here
3408                         // in order to know if we should output polyglossia
3409                         // macros (instead of babel macros)
3410                         LaTeXFeatures features(*this, params(), runparams);
3411                         params().validate(features);
3412                         runparams.use_polyglossia = features.usePolyglossia();
3413                         TexRow texrow;
3414                         texrow.reset();
3415                         texrow.newline();
3416                         texrow.newline();
3417                         // latex or literate
3418                         otexstream ots(os, texrow);
3419
3420                         // the real stuff
3421                         latexParagraphs(*this, text(), ots, runparams);
3422
3423                         // Restore the parenthood
3424                         if (!master)
3425                                 d->ignore_parent = false;
3426                 }
3427         } else {
3428                 os << "% ";
3429                 if (output == FullSource)
3430                         os << _("Preview source code");
3431                 else if (output == OnlyPreamble)
3432                         os << _("Preview preamble");
3433                 else if (output == OnlyBody)
3434                         os << _("Preview body");
3435                 os << "\n\n";
3436                 if (runparams.flavor == OutputParams::LYX) {
3437                         ostringstream ods;
3438                         if (output == FullSource)
3439                                 write(ods);
3440                         else if (output == OnlyPreamble)
3441                                 params().writeFile(ods);
3442                         else if (output == OnlyBody)
3443                                 text().write(ods);
3444                         os << from_utf8(ods.str());
3445                 } else if (runparams.flavor == OutputParams::HTML) {
3446                         writeLyXHTMLSource(os, runparams, output);
3447                 } else if (runparams.flavor == OutputParams::TEXT) {
3448                         if (output == OnlyPreamble) {
3449                                 os << "% "<< _("Plain text does not have a preamble.");
3450                         } else
3451                                 writePlaintextFile(*this, os, runparams);
3452                 } else if (params().isDocBook()) {
3453                                 writeDocBookSource(os, absFileName(), runparams, output);
3454                 } else {
3455                         // latex or literate
3456                         d->texrow.reset();
3457                         d->texrow.newline();
3458                         d->texrow.newline();
3459                         otexstream ots(os, d->texrow);
3460                         if (master)
3461                                 runparams.is_child = true;
3462                         writeLaTeXSource(ots, string(), runparams, output);
3463                 }
3464         }
3465 }
3466
3467
3468 ErrorList & Buffer::errorList(string const & type) const
3469 {
3470         return d->errorLists[type];
3471 }
3472
3473
3474 void Buffer::updateTocItem(std::string const & type,
3475         DocIterator const & dit) const
3476 {
3477         if (d->gui_)
3478                 d->gui_->updateTocItem(type, dit);
3479 }
3480
3481
3482 void Buffer::structureChanged() const
3483 {
3484         if (d->gui_)
3485                 d->gui_->structureChanged();
3486 }
3487
3488
3489 void Buffer::errors(string const & err, bool from_master) const
3490 {
3491         if (d->gui_)
3492                 d->gui_->errors(err, from_master);
3493 }
3494
3495
3496 void Buffer::message(docstring const & msg) const
3497 {
3498         if (d->gui_)
3499                 d->gui_->message(msg);
3500 }
3501
3502
3503 void Buffer::setBusy(bool on) const
3504 {
3505         if (d->gui_)
3506                 d->gui_->setBusy(on);
3507 }
3508
3509
3510 void Buffer::updateTitles() const
3511 {
3512         if (d->wa_)
3513                 d->wa_->updateTitles();
3514 }
3515
3516
3517 void Buffer::resetAutosaveTimers() const
3518 {
3519         if (d->gui_)
3520                 d->gui_->resetAutosaveTimers();
3521 }
3522
3523
3524 bool Buffer::hasGuiDelegate() const
3525 {
3526         return d->gui_;
3527 }
3528
3529
3530 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3531 {
3532         d->gui_ = gui;
3533 }
3534
3535
3536
3537 namespace {
3538
3539 class AutoSaveBuffer : public ForkedProcess {
3540 public:
3541         ///
3542         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3543                 : buffer_(buffer), fname_(fname) {}
3544         ///
3545         virtual shared_ptr<ForkedProcess> clone() const
3546         {
3547                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3548         }
3549         ///
3550         int start()
3551         {
3552                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3553                                                  from_utf8(fname_.absFileName())));
3554                 return run(DontWait);
3555         }
3556 private:
3557         ///
3558         virtual int generateChild();
3559         ///
3560         Buffer const & buffer_;
3561         FileName fname_;
3562 };
3563
3564
3565 int AutoSaveBuffer::generateChild()
3566 {
3567 #if defined(__APPLE__)
3568         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3569          *   We should use something else like threads.
3570          *
3571          * Since I do not know how to determine at run time what is the OS X
3572          * version, I just disable forking altogether for now (JMarc)
3573          */
3574         pid_t const pid = -1;
3575 #else
3576         // tmp_ret will be located (usually) in /tmp
3577         // will that be a problem?
3578         // Note that this calls ForkedCalls::fork(), so it's
3579         // ok cross-platform.
3580         pid_t const pid = fork();
3581         // If you want to debug the autosave
3582         // you should set pid to -1, and comment out the fork.
3583         if (pid != 0 && pid != -1)
3584                 return pid;
3585 #endif
3586
3587         // pid = -1 signifies that lyx was unable
3588         // to fork. But we will do the save
3589         // anyway.
3590         bool failed = false;
3591         FileName const tmp_ret = FileName::tempName("lyxauto");
3592         if (!tmp_ret.empty()) {
3593                 buffer_.writeFile(tmp_ret);
3594                 // assume successful write of tmp_ret
3595                 if (!tmp_ret.moveTo(fname_))
3596                         failed = true;
3597         } else
3598                 failed = true;
3599
3600         if (failed) {
3601                 // failed to write/rename tmp_ret so try writing direct
3602                 if (!buffer_.writeFile(fname_)) {
3603                         // It is dangerous to do this in the child,
3604                         // but safe in the parent, so...
3605                         if (pid == -1) // emit message signal.
3606                                 buffer_.message(_("Autosave failed!"));
3607                 }
3608         }
3609
3610         if (pid == 0) // we are the child so...
3611                 _exit(0);
3612
3613         return pid;
3614 }
3615
3616 } // namespace anon
3617
3618
3619 FileName Buffer::getEmergencyFileName() const
3620 {
3621         return FileName(d->filename.absFileName() + ".emergency");
3622 }
3623
3624
3625 FileName Buffer::getAutosaveFileName() const
3626 {
3627         // if the document is unnamed try to save in the backup dir, else
3628         // in the default document path, and as a last try in the filePath,
3629         // which will most often be the temporary directory
3630         string fpath;
3631         if (isUnnamed())
3632                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3633                         : lyxrc.backupdir_path;
3634         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3635                 fpath = filePath();
3636
3637         string const fname = "#" + d->filename.onlyFileName() + "#";
3638
3639         return makeAbsPath(fname, fpath);
3640 }
3641
3642
3643 void Buffer::removeAutosaveFile() const
3644 {
3645         FileName const f = getAutosaveFileName();
3646         if (f.exists())
3647                 f.removeFile();
3648 }
3649
3650
3651 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3652 {
3653         FileName const newauto = getAutosaveFileName();
3654         oldauto.refresh();
3655         if (newauto != oldauto && oldauto.exists())
3656                 if (!oldauto.moveTo(newauto))
3657                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3658 }
3659
3660
3661 bool Buffer::autoSave() const
3662 {
3663         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3664         if (buf->d->bak_clean || isReadonly())
3665                 return true;
3666
3667         message(_("Autosaving current document..."));
3668         buf->d->bak_clean = true;
3669
3670         FileName const fname = getAutosaveFileName();
3671         LASSERT(d->cloned_buffer_, return false);
3672
3673         // If this buffer is cloned, we assume that
3674         // we are running in a separate thread already.
3675         FileName const tmp_ret = FileName::tempName("lyxauto");
3676         if (!tmp_ret.empty()) {
3677                 writeFile(tmp_ret);
3678                 // assume successful write of tmp_ret
3679                 if (tmp_ret.moveTo(fname))
3680                         return true;
3681         }
3682         // failed to write/rename tmp_ret so try writing direct
3683         return writeFile(fname);
3684 }
3685
3686
3687 // helper class, to guarantee this gets reset properly
3688 class Buffer::MarkAsExporting {
3689 public:
3690         MarkAsExporting(Buffer const * buf) : buf_(buf)
3691         {
3692                 LASSERT(buf_, /* */);
3693                 buf_->setExportStatus(true);
3694         }
3695         ~MarkAsExporting()
3696         {
3697                 buf_->setExportStatus(false);
3698         }
3699 private:
3700         Buffer const * const buf_;
3701 };
3702
3703
3704
3705 void Buffer::setExportStatus(bool e) const
3706 {
3707         d->doing_export = e;
3708         ListOfBuffers clist = getDescendents();
3709         ListOfBuffers::const_iterator cit = clist.begin();
3710         ListOfBuffers::const_iterator const cen = clist.end();
3711         for (; cit != cen; ++cit)
3712                 (*cit)->d->doing_export = e;
3713 }
3714
3715
3716 bool Buffer::isExporting() const
3717 {
3718         return d->doing_export;
3719 }
3720
3721
3722 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3723         const
3724 {
3725         string result_file;
3726         return doExport(target, put_in_tempdir, result_file);
3727 }
3728
3729 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3730         string & result_file) const
3731 {
3732         bool const update_unincluded =
3733                         params().maintain_unincluded_children
3734                         && !params().getIncludedChildren().empty();
3735
3736         // (1) export with all included children (omit \includeonly)
3737         if (update_unincluded) {
3738                 ExportStatus const status =
3739                         doExport(target, put_in_tempdir, true, result_file);
3740                 if (status != ExportSuccess)
3741                         return status;
3742         }
3743         // (2) export with included children only
3744         return doExport(target, put_in_tempdir, false, result_file);
3745 }
3746
3747
3748 void Buffer::setMathFlavor(OutputParams & op) const
3749 {
3750         switch (params().html_math_output) {
3751         case BufferParams::MathML:
3752                 op.math_flavor = OutputParams::MathAsMathML;
3753                 break;
3754         case BufferParams::HTML:
3755                 op.math_flavor = OutputParams::MathAsHTML;
3756                 break;
3757         case BufferParams::Images:
3758                 op.math_flavor = OutputParams::MathAsImages;
3759                 break;
3760         case BufferParams::LaTeX:
3761                 op.math_flavor = OutputParams::MathAsLaTeX;
3762                 break;
3763         }
3764 }
3765
3766
3767 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3768         bool includeall, string & result_file) const
3769 {
3770         LYXERR(Debug::FILES, "target=" << target);
3771         OutputParams runparams(&params().encoding());
3772         string format = target;
3773         string dest_filename;
3774         size_t pos = target.find(' ');
3775         if (pos != string::npos) {
3776                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
3777                 format = target.substr(0, pos);
3778                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
3779                 FileName(dest_filename).onlyPath().createPath();
3780                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
3781         }
3782         MarkAsExporting exporting(this);
3783         string backend_format;
3784         runparams.flavor = OutputParams::LATEX;
3785         runparams.linelen = lyxrc.plaintext_linelen;
3786         runparams.includeall = includeall;
3787         vector<string> backs = params().backends();
3788         Converters converters = theConverters();
3789         bool need_nice_file = false;
3790         if (find(backs.begin(), backs.end(), format) == backs.end()) {
3791                 // Get shortest path to format
3792                 converters.buildGraph();
3793                 Graph::EdgePath path;
3794                 for (vector<string>::const_iterator it = backs.begin();
3795                      it != backs.end(); ++it) {
3796                         Graph::EdgePath p = converters.getPath(*it, format);
3797                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
3798                                 backend_format = *it;
3799                                 path = p;
3800                         }
3801                 }
3802                 if (path.empty()) {
3803                         if (!put_in_tempdir) {
3804                                 // Only show this alert if this is an export to a non-temporary
3805                                 // file (not for previewing).
3806                                 Alert::error(_("Couldn't export file"), bformat(
3807                                         _("No information for exporting the format %1$s."),
3808                                         formats.prettyName(format)));
3809                         }
3810                         return ExportNoPathToFormat;
3811                 }
3812                 runparams.flavor = converters.getFlavor(path, this);
3813                 Graph::EdgePath::const_iterator it = path.begin();
3814                 Graph::EdgePath::const_iterator en = path.end();
3815                 for (; it != en; ++it)
3816                         if (theConverters().get(*it).nice) {
3817                                 need_nice_file = true;
3818                                 break;
3819                         }
3820
3821         } else {
3822                 backend_format = format;
3823                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
3824                 // FIXME: Don't hardcode format names here, but use a flag
3825                 if (backend_format == "pdflatex")
3826                         runparams.flavor = OutputParams::PDFLATEX;
3827                 else if (backend_format == "luatex")
3828                         runparams.flavor = OutputParams::LUATEX;
3829                 else if (backend_format == "dviluatex")
3830                         runparams.flavor = OutputParams::DVILUATEX;
3831                 else if (backend_format == "xetex")
3832                         runparams.flavor = OutputParams::XETEX;
3833         }
3834
3835         string filename = latexName(false);
3836         filename = addName(temppath(), filename);
3837         filename = changeExtension(filename,
3838                                    formats.extension(backend_format));
3839         LYXERR(Debug::FILES, "filename=" << filename);
3840
3841         // Plain text backend
3842         if (backend_format == "text") {
3843                 runparams.flavor = OutputParams::TEXT;
3844                 writePlaintextFile(*this, FileName(filename), runparams);
3845         }
3846         // HTML backend
3847         else if (backend_format == "xhtml") {
3848                 runparams.flavor = OutputParams::HTML;
3849                 setMathFlavor(runparams);
3850                 makeLyXHTMLFile(FileName(filename), runparams);
3851         } else if (backend_format == "lyx")
3852                 writeFile(FileName(filename));
3853         // Docbook backend
3854         else if (params().isDocBook()) {
3855                 runparams.nice = !put_in_tempdir;
3856                 makeDocBookFile(FileName(filename), runparams);
3857         }
3858         // LaTeX backend
3859         else if (backend_format == format || need_nice_file) {
3860                 runparams.nice = true;
3861                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
3862                 if (d->cloned_buffer_)
3863                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3864                 if (!success)
3865                         return ExportError;
3866         } else if (!lyxrc.tex_allows_spaces
3867                    && contains(filePath(), ' ')) {
3868                 Alert::error(_("File name error"),
3869                            _("The directory path to the document cannot contain spaces."));
3870                 return ExportTexPathHasSpaces;
3871         } else {
3872                 runparams.nice = false;
3873                 bool const success = makeLaTeXFile(
3874                         FileName(filename), filePath(), runparams);
3875                 if (d->cloned_buffer_)
3876                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
3877                 if (!success)
3878                         return ExportError;
3879         }
3880
3881         string const error_type = (format == "program")
3882                 ? "Build" : params().bufferFormat();
3883         ErrorList & error_list = d->errorLists[error_type];
3884         string const ext = formats.extension(format);
3885         FileName const tmp_result_file(changeExtension(filename, ext));
3886         bool const success = converters.convert(this, FileName(filename),
3887                 tmp_result_file, FileName(absFileName()), backend_format, format,
3888                 error_list);
3889
3890         // Emit the signal to show the error list or copy it back to the
3891         // cloned Buffer so that it can be emitted afterwards.
3892         if (format != backend_format) {
3893                 if (d->cloned_buffer_) {
3894                         d->cloned_buffer_->d->errorLists[error_type] =
3895                                 d->errorLists[error_type];
3896                 } else
3897                         errors(error_type);
3898                 // also to the children, in case of master-buffer-view
3899                 ListOfBuffers clist = getDescendents();
3900                 ListOfBuffers::const_iterator cit = clist.begin();
3901                 ListOfBuffers::const_iterator const cen = clist.end();
3902                 for (; cit != cen; ++cit) {
3903                         if (d->cloned_buffer_) {
3904                                 // Enable reverse search by copying back the
3905                                 // texrow object to the cloned buffer.
3906                                 // FIXME: this is not thread safe.
3907                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
3908                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
3909                                         (*cit)->d->errorLists[error_type];
3910                         } else
3911                                 (*cit)->errors(error_type, true);
3912                 }
3913         }
3914
3915         if (d->cloned_buffer_) {
3916                 // Enable reverse dvi or pdf to work by copying back the texrow
3917                 // object to the cloned buffer.
3918                 // FIXME: There is a possibility of concurrent access to texrow
3919                 // here from the main GUI thread that should be securized.
3920                 d->cloned_buffer_->d->texrow = d->texrow;
3921                 string const error_type = params().bufferFormat();
3922                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
3923         }
3924
3925         if (!success)
3926                 return ExportConverterError;
3927
3928         if (put_in_tempdir) {
3929                 result_file = tmp_result_file.absFileName();
3930                 return ExportSuccess;
3931         }
3932
3933         if (dest_filename.empty())
3934                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
3935         else
3936                 result_file = dest_filename;
3937         // We need to copy referenced files (e. g. included graphics
3938         // if format == "dvi") to the result dir.
3939         vector<ExportedFile> const files =
3940                 runparams.exportdata->externalFiles(format);
3941         string const dest = runparams.export_folder.empty() ?
3942                 onlyPath(result_file) : runparams.export_folder;
3943         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
3944                                  : force_overwrite == ALL_FILES;
3945         CopyStatus status = use_force ? FORCE : SUCCESS;
3946
3947         vector<ExportedFile>::const_iterator it = files.begin();
3948         vector<ExportedFile>::const_iterator const en = files.end();
3949         for (; it != en && status != CANCEL; ++it) {
3950                 string const fmt = formats.getFormatFromFile(it->sourceName);
3951                 string fixedName = it->exportName;
3952                 if (!runparams.export_folder.empty()) {
3953                         // Relative pathnames starting with ../ will be sanitized
3954                         // if exporting to a different folder
3955                         while (fixedName.substr(0, 3) == "../")
3956                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
3957                 }
3958                 FileName fixedFileName = makeAbsPath(fixedName, dest);
3959                 fixedFileName.onlyPath().createPath();
3960                 status = copyFile(fmt, it->sourceName,
3961                         fixedFileName,
3962                         it->exportName, status == FORCE,
3963                         runparams.export_folder.empty());
3964         }
3965
3966         if (status == CANCEL) {
3967                 message(_("Document export cancelled."));
3968                 return ExportCancel;
3969         }
3970
3971         if (tmp_result_file.exists()) {
3972                 // Finally copy the main file
3973                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
3974                                     : force_overwrite != NO_FILES;
3975                 if (status == SUCCESS && use_force)
3976                         status = FORCE;
3977                 status = copyFile(format, tmp_result_file,
3978                         FileName(result_file), result_file,
3979                         status == FORCE);
3980                 if (status == CANCEL) {
3981                         message(_("Document export cancelled."));
3982                         return ExportCancel;
3983                 } else {
3984                         message(bformat(_("Document exported as %1$s "
3985                                 "to file `%2$s'"),
3986                                 formats.prettyName(format),
3987                                 makeDisplayPath(result_file)));
3988                 }
3989         } else {
3990                 // This must be a dummy converter like fax (bug 1888)
3991                 message(bformat(_("Document exported as %1$s"),
3992                         formats.prettyName(format)));
3993         }
3994
3995         return ExportSuccess;
3996 }
3997
3998
3999 Buffer::ExportStatus Buffer::preview(string const & format) const
4000 {
4001         bool const update_unincluded =
4002                         params().maintain_unincluded_children
4003                         && !params().getIncludedChildren().empty();
4004         return preview(format, update_unincluded);
4005 }
4006
4007 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4008 {
4009         MarkAsExporting exporting(this);
4010         string result_file;
4011         // (1) export with all included children (omit \includeonly)
4012         if (includeall) {
4013                 ExportStatus const status = doExport(format, true, true, result_file);
4014                 if (status != ExportSuccess)
4015                         return status;
4016         }
4017         // (2) export with included children only
4018         ExportStatus const status = doExport(format, true, false, result_file);
4019         if (status != ExportSuccess)
4020                 return status;
4021         if (!formats.view(*this, FileName(result_file), format))
4022                 return PreviewError;
4023         return PreviewSuccess;
4024 }
4025
4026
4027 Buffer::ReadStatus Buffer::extractFromVC()
4028 {
4029         bool const found = LyXVC::file_not_found_hook(d->filename);
4030         if (!found)
4031                 return ReadFileNotFound;
4032         if (!d->filename.isReadableFile())
4033                 return ReadVCError;
4034         return ReadSuccess;
4035 }
4036
4037
4038 Buffer::ReadStatus Buffer::loadEmergency()
4039 {
4040         FileName const emergencyFile = getEmergencyFileName();
4041         if (!emergencyFile.exists()
4042                   || emergencyFile.lastModified() <= d->filename.lastModified())
4043                 return ReadFileNotFound;
4044
4045         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4046         docstring const text = bformat(_("An emergency save of the document "
4047                 "%1$s exists.\n\nRecover emergency save?"), file);
4048
4049         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4050                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4051
4052         switch (load_emerg)
4053         {
4054         case 0: {
4055                 docstring str;
4056                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4057                 bool const success = (ret_llf == ReadSuccess);
4058                 if (success) {
4059                         if (isReadonly()) {
4060                                 Alert::warning(_("File is read-only"),
4061                                         bformat(_("An emergency file is successfully loaded, "
4062                                         "but the original file %1$s is marked read-only. "
4063                                         "Please make sure to save the document as a different "
4064                                         "file."), from_utf8(d->filename.absFileName())));
4065                         }
4066                         markDirty();
4067                         lyxvc().file_found_hook(d->filename);
4068                         str = _("Document was successfully recovered.");
4069                 } else
4070                         str = _("Document was NOT successfully recovered.");
4071                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4072                         makeDisplayPath(emergencyFile.absFileName()));
4073
4074                 int const del_emerg =
4075                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4076                                 _("&Remove"), _("&Keep"));
4077                 if (del_emerg == 0) {
4078                         emergencyFile.removeFile();
4079                         if (success)
4080                                 Alert::warning(_("Emergency file deleted"),
4081                                         _("Do not forget to save your file now!"), true);
4082                         }
4083                 return success ? ReadSuccess : ReadEmergencyFailure;
4084         }
4085         case 1: {
4086                 int const del_emerg =
4087                         Alert::prompt(_("Delete emergency file?"),
4088                                 _("Remove emergency file now?"), 1, 1,
4089                                 _("&Remove"), _("&Keep"));
4090                 if (del_emerg == 0)
4091                         emergencyFile.removeFile();
4092                 return ReadOriginal;
4093         }
4094
4095         default:
4096                 break;
4097         }
4098         return ReadCancel;
4099 }
4100
4101
4102 Buffer::ReadStatus Buffer::loadAutosave()
4103 {
4104         // Now check if autosave file is newer.
4105         FileName const autosaveFile = getAutosaveFileName();
4106         if (!autosaveFile.exists()
4107                   || autosaveFile.lastModified() <= d->filename.lastModified())
4108                 return ReadFileNotFound;
4109
4110         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4111         docstring const text = bformat(_("The backup of the document %1$s "
4112                 "is newer.\n\nLoad the backup instead?"), file);
4113         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4114                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4115
4116         switch (ret)
4117         {
4118         case 0: {
4119                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4120                 // the file is not saved if we load the autosave file.
4121                 if (ret_llf == ReadSuccess) {
4122                         if (isReadonly()) {
4123                                 Alert::warning(_("File is read-only"),
4124                                         bformat(_("A backup file is successfully loaded, "
4125                                         "but the original file %1$s is marked read-only. "
4126                                         "Please make sure to save the document as a "
4127                                         "different file."),
4128                                         from_utf8(d->filename.absFileName())));
4129                         }
4130                         markDirty();
4131                         lyxvc().file_found_hook(d->filename);
4132                         return ReadSuccess;
4133                 }
4134                 return ReadAutosaveFailure;
4135         }
4136         case 1:
4137                 // Here we delete the autosave
4138                 autosaveFile.removeFile();
4139                 return ReadOriginal;
4140         default:
4141                 break;
4142         }
4143         return ReadCancel;
4144 }
4145
4146
4147 Buffer::ReadStatus Buffer::loadLyXFile()
4148 {
4149         if (!d->filename.isReadableFile()) {
4150                 ReadStatus const ret_rvc = extractFromVC();
4151                 if (ret_rvc != ReadSuccess)
4152                         return ret_rvc;
4153         }
4154
4155         ReadStatus const ret_re = loadEmergency();
4156         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4157                 return ret_re;
4158
4159         ReadStatus const ret_ra = loadAutosave();
4160         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4161                 return ret_ra;
4162
4163         return loadThisLyXFile(d->filename);
4164 }
4165
4166
4167 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4168 {
4169         return readFile(fn);
4170 }
4171
4172
4173 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4174 {
4175         TeXErrors::Errors::const_iterator it = terr.begin();
4176         TeXErrors::Errors::const_iterator end = terr.end();
4177         ListOfBuffers clist = getDescendents();
4178         ListOfBuffers::const_iterator cen = clist.end();
4179
4180         for (; it != end; ++it) {
4181                 int id_start = -1;
4182                 int pos_start = -1;
4183                 int errorRow = it->error_in_line;
4184                 Buffer const * buf = 0;
4185                 Impl const * p = d;
4186                 if (it->child_name.empty())
4187                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4188                 else {
4189                         // The error occurred in a child
4190                         ListOfBuffers::const_iterator cit = clist.begin();
4191                         for (; cit != cen; ++cit) {
4192                                 string const child_name =
4193                                         DocFileName(changeExtension(
4194                                                 (*cit)->absFileName(), "tex")).
4195                                                         mangledFileName();
4196                                 if (it->child_name != child_name)
4197                                         continue;
4198                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4199                                                         id_start, pos_start);
4200                                 if (id_start != -1) {
4201                                         buf = d->cloned_buffer_
4202                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4203                                                 : (*cit)->d->owner_;
4204                                         p = (*cit)->d;
4205                                         break;
4206                                 }
4207                         }
4208                 }
4209                 int id_end = -1;
4210                 int pos_end = -1;
4211                 bool found;
4212                 do {
4213                         ++errorRow;
4214                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4215                 } while (found && id_start == id_end && pos_start == pos_end);
4216
4217                 if (id_start != id_end) {
4218                         // Next registered position is outside the inset where
4219                         // the error occurred, so signal end-of-paragraph
4220                         pos_end = 0;
4221                 }
4222
4223                 errorList.push_back(ErrorItem(it->error_desc,
4224                         it->error_text, id_start, pos_start, pos_end, buf));
4225         }
4226 }
4227
4228
4229 void Buffer::setBuffersForInsets() const
4230 {
4231         inset().setBuffer(const_cast<Buffer &>(*this));
4232 }
4233
4234
4235 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4236 {
4237         // Use the master text class also for child documents
4238         Buffer const * const master = masterBuffer();
4239         DocumentClass const & textclass = master->params().documentClass();
4240
4241         // do this only if we are the top-level Buffer
4242         if (master == this)
4243                 reloadBibInfoCache();
4244
4245         // keep the buffers to be children in this set. If the call from the
4246         // master comes back we can see which of them were actually seen (i.e.
4247         // via an InsetInclude). The remaining ones in the set need still be updated.
4248         static std::set<Buffer const *> bufToUpdate;
4249         if (scope == UpdateMaster) {
4250                 // If this is a child document start with the master
4251                 if (master != this) {
4252                         bufToUpdate.insert(this);
4253                         master->updateBuffer(UpdateMaster, utype);
4254                         // Do this here in case the master has no gui associated with it. Then,
4255                         // the TocModel is not updated and TocModel::toc_ is invalid (bug 5699).
4256                         if (!master->d->gui_)
4257                                 structureChanged();
4258
4259                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4260                         if (bufToUpdate.find(this) == bufToUpdate.end())
4261                                 return;
4262                 }
4263
4264                 // start over the counters in the master
4265                 textclass.counters().reset();
4266         }
4267
4268         // update will be done below for this buffer
4269         bufToUpdate.erase(this);
4270
4271         // update all caches
4272         clearReferenceCache();
4273         updateMacros();
4274
4275         Buffer & cbuf = const_cast<Buffer &>(*this);
4276
4277         LASSERT(!text().paragraphs().empty(), /**/);
4278
4279         // do the real work
4280         ParIterator parit = cbuf.par_iterator_begin();
4281         updateBuffer(parit, utype);
4282
4283         if (master != this)
4284                 // TocBackend update will be done later.
4285                 return;
4286
4287         d->bibinfo_cache_valid_ = true;
4288         d->cite_labels_valid_ = true;
4289         cbuf.tocBackend().update(utype == OutputUpdate);
4290         if (scope == UpdateMaster)
4291                 cbuf.structureChanged();
4292 }
4293
4294
4295 static depth_type getDepth(DocIterator const & it)
4296 {
4297         depth_type depth = 0;
4298         for (size_t i = 0 ; i < it.depth() ; ++i)
4299                 if (!it[i].inset().inMathed())
4300                         depth += it[i].paragraph().getDepth() + 1;
4301         // remove 1 since the outer inset does not count
4302         return depth - 1;
4303 }
4304
4305 static depth_type getItemDepth(ParIterator const & it)
4306 {
4307         Paragraph const & par = *it;
4308         LabelType const labeltype = par.layout().labeltype;
4309
4310         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4311                 return 0;
4312
4313         // this will hold the lowest depth encountered up to now.
4314         depth_type min_depth = getDepth(it);
4315         ParIterator prev_it = it;
4316         while (true) {
4317                 if (prev_it.pit())
4318                         --prev_it.top().pit();
4319                 else {
4320                         // start of nested inset: go to outer par
4321                         prev_it.pop_back();
4322                         if (prev_it.empty()) {
4323                                 // start of document: nothing to do
4324                                 return 0;
4325                         }
4326                 }
4327
4328                 // We search for the first paragraph with same label
4329                 // that is not more deeply nested.
4330                 Paragraph & prev_par = *prev_it;
4331                 depth_type const prev_depth = getDepth(prev_it);
4332                 if (labeltype == prev_par.layout().labeltype) {
4333                         if (prev_depth < min_depth)
4334                                 return prev_par.itemdepth + 1;
4335                         if (prev_depth == min_depth)
4336                                 return prev_par.itemdepth;
4337                 }
4338                 min_depth = min(min_depth, prev_depth);
4339                 // small optimization: if we are at depth 0, we won't
4340                 // find anything else
4341                 if (prev_depth == 0)
4342                         return 0;
4343         }
4344 }
4345
4346
4347 static bool needEnumCounterReset(ParIterator const & it)
4348 {
4349         Paragraph const & par = *it;
4350         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
4351         depth_type const cur_depth = par.getDepth();
4352         ParIterator prev_it = it;
4353         while (prev_it.pit()) {
4354                 --prev_it.top().pit();
4355                 Paragraph const & prev_par = *prev_it;
4356                 if (prev_par.getDepth() <= cur_depth)
4357                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4358         }
4359         // start of nested inset: reset
4360         return true;
4361 }
4362
4363
4364 // set the label of a paragraph. This includes the counters.
4365 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4366 {
4367         BufferParams const & bp = owner_->masterBuffer()->params();
4368         DocumentClass const & textclass = bp.documentClass();
4369         Paragraph & par = it.paragraph();
4370         Layout const & layout = par.layout();
4371         Counters & counters = textclass.counters();
4372
4373         if (par.params().startOfAppendix()) {
4374                 // We want to reset the counter corresponding to toplevel sectioning
4375                 Layout const & lay = textclass.getTOCLayout();
4376                 docstring const cnt = lay.counter;
4377                 if (!cnt.empty())
4378                         counters.reset(cnt);
4379                 counters.appendix(true);
4380         }
4381         par.params().appendix(counters.appendix());
4382
4383         // Compute the item depth of the paragraph
4384         par.itemdepth = getItemDepth(it);
4385
4386         if (layout.margintype == MARGIN_MANUAL) {
4387                 if (par.params().labelWidthString().empty())
4388                         par.params().labelWidthString(par.expandLabel(layout, bp));
4389         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4390                 // we do not need to do anything here, since the empty case is
4391                 // handled during export.
4392         } else {
4393                 par.params().labelWidthString(docstring());
4394         }
4395
4396         switch(layout.labeltype) {
4397         case LABEL_ITEMIZE: {
4398                 // At some point of time we should do something more
4399                 // clever here, like:
4400                 //   par.params().labelString(
4401                 //    bp.user_defined_bullet(par.itemdepth).getText());
4402                 // for now, use a simple hardcoded label
4403                 docstring itemlabel;
4404                 switch (par.itemdepth) {
4405                 case 0:
4406                         itemlabel = char_type(0x2022);
4407                         break;
4408                 case 1:
4409                         itemlabel = char_type(0x2013);
4410                         break;
4411                 case 2:
4412                         itemlabel = char_type(0x2217);
4413                         break;
4414                 case 3:
4415                         itemlabel = char_type(0x2219); // or 0x00b7
4416                         break;
4417                 }
4418                 par.params().labelString(itemlabel);
4419                 break;
4420         }
4421
4422         case LABEL_ENUMERATE: {
4423                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4424
4425                 switch (par.itemdepth) {
4426                 case 2:
4427                         enumcounter += 'i';
4428                 case 1:
4429                         enumcounter += 'i';
4430                 case 0:
4431                         enumcounter += 'i';
4432                         break;
4433                 case 3:
4434                         enumcounter += "iv";
4435                         break;
4436                 default:
4437                         // not a valid enumdepth...
4438                         break;
4439                 }
4440
4441                 // Maybe we have to reset the enumeration counter.
4442                 if (needEnumCounterReset(it))
4443                         counters.reset(enumcounter);
4444                 counters.step(enumcounter, utype);
4445
4446                 string const & lang = par.getParLanguage(bp)->code();
4447                 par.params().labelString(counters.theCounter(enumcounter, lang));
4448
4449                 break;
4450         }
4451
4452         case LABEL_SENSITIVE: {
4453                 string const & type = counters.current_float();
4454                 docstring full_label;
4455                 if (type.empty())
4456                         full_label = owner_->B_("Senseless!!! ");
4457                 else {
4458                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4459                         if (counters.hasCounter(from_utf8(type))) {
4460                                 string const & lang = par.getParLanguage(bp)->code();
4461                                 counters.step(from_utf8(type), utype);
4462                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4463                                                      name,
4464                                                      counters.theCounter(from_utf8(type), lang));
4465                         } else
4466                                 full_label = bformat(from_ascii("%1$s #:"), name);
4467                 }
4468                 par.params().labelString(full_label);
4469                 break;
4470         }
4471
4472         case LABEL_NO_LABEL:
4473                 par.params().labelString(docstring());
4474                 break;
4475
4476         case LABEL_ABOVE:
4477         case LABEL_CENTERED:
4478         case LABEL_STATIC: {
4479                 docstring const & lcounter = layout.counter;
4480                 if (!lcounter.empty()) {
4481                         if (layout.toclevel <= bp.secnumdepth
4482                                                 && (layout.latextype != LATEX_ENVIRONMENT
4483                                         || it.text()->isFirstInSequence(it.pit()))) {
4484                                 if (counters.hasCounter(lcounter))
4485                                         counters.step(lcounter, utype);
4486                                 par.params().labelString(par.expandLabel(layout, bp));
4487                         } else
4488                                 par.params().labelString(docstring());
4489                 } else
4490                         par.params().labelString(par.expandLabel(layout, bp));
4491                 break;
4492         }
4493
4494         case LABEL_MANUAL:
4495         case LABEL_BIBLIO:
4496                 par.params().labelString(par.expandLabel(layout, bp));
4497         }
4498 }
4499
4500
4501 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4502 {
4503         LASSERT(parit.pit() == 0, /**/);
4504
4505         // Set the position of the text in the buffer to be able
4506         // to resolve macros in it.
4507         parit.text()->setMacrocontextPosition(parit);
4508
4509         depth_type maxdepth = 0;
4510         pit_type const lastpit = parit.lastpit();
4511         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4512                 // reduce depth if necessary
4513                 if (parit->params().depth() > maxdepth) {
4514                         /** FIXME: this function is const, but
4515                          * nevertheless it modifies the buffer. To be
4516                          * cleaner, one should modify the buffer in
4517                          * another function, which is actually
4518                          * non-const. This would however be costly in
4519                          * terms of code duplication.
4520                          */
4521                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4522                         parit->params().depth(maxdepth);
4523                 }
4524                 maxdepth = parit->getMaxDepthAfter();
4525
4526                 if (utype == OutputUpdate) {
4527                         // track the active counters
4528                         // we have to do this for the master buffer, since the local
4529                         // buffer isn't tracking anything.
4530                         masterBuffer()->params().documentClass().counters().
4531                                         setActiveLayout(parit->layout());
4532                 }
4533
4534                 // set the counter for this paragraph
4535                 d->setLabel(parit, utype);
4536
4537                 // now the insets
4538                 InsetList::const_iterator iit = parit->insetList().begin();
4539                 InsetList::const_iterator end = parit->insetList().end();
4540                 for (; iit != end; ++iit) {
4541                         parit.pos() = iit->pos;
4542                         iit->inset->updateBuffer(parit, utype);
4543                 }
4544         }
4545 }
4546
4547
4548 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4549         WordLangTuple & word_lang, docstring_list & suggestions) const
4550 {
4551         int progress = 0;
4552         WordLangTuple wl;
4553         suggestions.clear();
4554         word_lang = WordLangTuple();
4555         bool const to_end = to.empty();
4556         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4557         // OK, we start from here.
4558         for (; from != end; from.forwardPos()) {
4559                 // We are only interested in text so remove the math CursorSlice.
4560                 while (from.inMathed()) {
4561                         from.pop_back();
4562                         from.pos()++;
4563                 }
4564                 // If from is at the end of the document (which is possible
4565                 // when leaving the mathed) LyX will crash later otherwise.
4566                 if (from.atEnd() || (!to_end && from >= end))
4567                         break;
4568                 to = from;
4569                 from.paragraph().spellCheck();
4570                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4571                 if (SpellChecker::misspelled(res)) {
4572                         word_lang = wl;
4573                         break;
4574                 }
4575
4576                 // Do not increase progress when from == to, otherwise the word
4577                 // count will be wrong.
4578                 if (from != to) {
4579                         from = to;
4580                         ++progress;
4581                 }
4582         }
4583         return progress;
4584 }
4585
4586
4587 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4588 {
4589         bool inword = false;
4590         word_count_ = 0;
4591         char_count_ = 0;
4592         blank_count_ = 0;
4593  
4594         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4595                 if (!dit.inTexted()) {
4596                         dit.forwardPos();
4597                         continue;
4598                 }
4599                 
4600                 Paragraph const & par = dit.paragraph();
4601                 pos_type const pos = dit.pos();
4602                 
4603                 // Copied and adapted from isWordSeparator() in Paragraph
4604                 if (pos == dit.lastpos()) {
4605                         inword = false;
4606                 } else {
4607                         Inset const * ins = par.getInset(pos);
4608                         if (ins && skipNoOutput && !ins->producesOutput()) {
4609                                 // skip this inset
4610                                 ++dit.top().pos();
4611                                 // stop if end of range was skipped
4612                                 if (!to.atEnd() && dit >= to)
4613                                         break;
4614                                 continue;
4615                         } else if (!par.isDeleted(pos)) {
4616                                 if (par.isWordSeparator(pos)) 
4617                                         inword = false;
4618                                 else if (!inword) {
4619                                         ++word_count_;
4620                                         inword = true;
4621                                 }
4622                                 if (ins && ins->isLetter())
4623                                         ++char_count_;
4624                                 else if (ins && ins->isSpace())
4625                                         ++blank_count_;
4626                                 else {
4627                                         char_type const c = par.getChar(pos);
4628                                         if (isPrintableNonspace(c))
4629                                                 ++char_count_;
4630                                         else if (isSpace(c))
4631                                                 ++blank_count_;
4632                                 }
4633                         }
4634                 }
4635                 dit.forwardPos();
4636         }
4637 }
4638
4639
4640 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4641 {
4642         d->updateStatistics(from, to, skipNoOutput);
4643 }
4644
4645
4646 int Buffer::wordCount() const
4647 {
4648         return d->wordCount();
4649 }
4650
4651
4652 int Buffer::charCount(bool with_blanks) const
4653 {
4654         return d->charCount(with_blanks);
4655 }
4656
4657
4658 Buffer::ReadStatus Buffer::reload(bool clearUndo)
4659 {
4660         setBusy(true);
4661         // c.f. bug http://www.lyx.org/trac/ticket/6587
4662         removeAutosaveFile();
4663         // e.g., read-only status could have changed due to version control
4664         d->filename.refresh();
4665         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4666
4667         // clear parent. this will get reset if need be.
4668         d->setParent(0);
4669         ReadStatus const status = loadLyXFile();
4670         if (status == ReadSuccess) {
4671                 updateBuffer();
4672                 changed(true);
4673                 updateTitles();
4674                 markClean();
4675                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4676                 if (clearUndo)
4677                         d->undo_.clear();
4678         } else {
4679                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4680         }
4681         setBusy(false);
4682         removePreviews();
4683         updatePreviews();
4684         errors("Parse");
4685         return status;
4686 }
4687
4688
4689 bool Buffer::saveAs(FileName const & fn)
4690 {
4691         FileName const old_name = fileName();
4692         FileName const old_auto = getAutosaveFileName();
4693         bool const old_unnamed = isUnnamed();
4694
4695         setFileName(fn);
4696         markDirty();
4697         setUnnamed(false);
4698
4699         if (save()) {
4700                 // bring the autosave file with us, just in case.
4701                 moveAutosaveFile(old_auto);
4702                 // validate version control data and
4703                 // correct buffer title
4704                 lyxvc().file_found_hook(fileName());
4705                 updateTitles();
4706                 // the file has now been saved to the new location.
4707                 // we need to check that the locations of child buffers
4708                 // are still valid.
4709                 checkChildBuffers();
4710                 checkMasterBuffer();
4711                 return true;
4712         } else {
4713                 // save failed
4714                 // reset the old filename and unnamed state
4715                 setFileName(old_name);
4716                 setUnnamed(old_unnamed);
4717                 return false;
4718         }
4719 }
4720
4721
4722 // FIXME We could do better here, but it is complicated. What would be
4723 // nice is to offer either (a) to save the child buffer to an appropriate
4724 // location, so that it would "move with the master", or else (b) to update
4725 // the InsetInclude so that it pointed to the same file. But (a) is a bit
4726 // complicated, because the code for this lives in GuiView.
4727 void Buffer::checkChildBuffers()
4728 {
4729         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
4730         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
4731         for (; it != en; ++it) {
4732                 DocIterator dit = it->second;
4733                 Buffer * cbuf = const_cast<Buffer *>(it->first);
4734                 if (!cbuf || !theBufferList().isLoaded(cbuf))
4735                         continue;
4736                 Inset * inset = dit.nextInset();
4737                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
4738                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
4739                 docstring const & incfile = inset_inc->getParam("filename");
4740                 string oldloc = cbuf->absFileName();
4741                 string newloc = makeAbsPath(to_utf8(incfile),
4742                                 onlyPath(absFileName())).absFileName();
4743                 if (oldloc == newloc)
4744                         continue;
4745                 // the location of the child file is incorrect.
4746                 Alert::warning(_("Included File Invalid"),
4747                                 bformat(_("Saving this document to a new location has made the file:\n"
4748                                 "  %1$s\n"
4749                                 "inaccessible. You will need to update the included filename."),
4750                                 from_utf8(oldloc)));
4751                 cbuf->setParent(0);
4752                 inset_inc->setChildBuffer(0);
4753         }
4754         // invalidate cache of children
4755         d->children_positions.clear();
4756         d->position_to_children.clear();
4757 }
4758
4759
4760 // If a child has been saved under a different name/path, it might have been
4761 // orphaned. Therefore the master needs to be reset (bug 8161).
4762 void Buffer::checkMasterBuffer()
4763 {
4764         Buffer const * const master = masterBuffer();
4765         if (master == this)
4766                 return;
4767
4768         // necessary to re-register the child (bug 5873)
4769         // FIXME: clean up updateMacros (here, only
4770         // child registering is needed).
4771         master->updateMacros();
4772         // (re)set master as master buffer, but only
4773         // if we are a real child
4774         if (master->isChild(this))
4775                 setParent(master);
4776         else
4777                 setParent(0);
4778 }
4779
4780 } // namespace lyx