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