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