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