]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Cmake url tests: Added summary files.
[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 const 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         bool const needBackup = lyxrc.make_backup || d->need_format_backup;
1405         if (needBackup) {
1406                 if (d->need_format_backup)
1407                         backupName = getBackupName();
1408
1409                 // If we for some reason failed to find a backup name in case of
1410                 // a format change, this will still set one. It's the best we can
1411                 // do in this case.
1412                 if (backupName.empty()) {
1413                         backupName.set(fileName().absFileName() + "~");
1414                         if (!lyxrc.backupdir_path.empty()) {
1415                                 string const mangledName =
1416                                         subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1417                                 backupName.set(addName(lyxrc.backupdir_path, mangledName));
1418                         }
1419                 }
1420
1421                 LYXERR(Debug::FILES, "Backing up original file to " <<
1422                                 backupName.absFileName());
1423                 // Except file is symlink do not copy because of #6587.
1424                 // Hard links have bad luck.
1425                 made_backup = symlink ?
1426                         fileName().copyTo(backupName):
1427                         fileName().moveTo(backupName);
1428
1429                 if (!made_backup) {
1430                         Alert::error(_("Backup failure"),
1431                                      bformat(_("Cannot create backup file %1$s.\n"
1432                                                "Please check whether the directory exists and is writable."),
1433                                              from_utf8(backupName.absFileName())));
1434                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1435                 } else if (d->need_format_backup) {
1436                         // the original file has been backed up successfully, so we
1437                         // will not need to do that again
1438                         d->need_format_backup = false;
1439                 }
1440         }
1441
1442         // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1443         // Only do this if tempfile is not in autoremove mode
1444         if (!symlink)
1445                 tempfile.reset();
1446         // If we have no symlink, we can simply rename the temp file.
1447         // Otherwise, we need to copy it so the symlink stays intact.
1448         if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1449                                            savefile.moveTo(fileName()))
1450         {
1451                 // saveCheckSum() was already called by writeFile(), but the
1452                 // time stamp is invalidated by copying/moving
1453                 saveCheckSum();
1454                 markClean();
1455                 if (d->file_format != LYX_FORMAT)
1456                         // the file associated with this buffer is now in the current format
1457                         d->file_format = LYX_FORMAT;
1458                 return true;
1459         }
1460         // else we saved the file, but failed to move it to the right location.
1461
1462         if (needBackup && made_backup && !symlink) {
1463                 // the original file was moved to some new location, so it will look
1464                 // to the user as if it was deleted. (see bug #9234.) we could try
1465                 // to restore it, but that would basically mean trying to do again
1466                 // what we just failed to do. better to leave things as they are.
1467                 Alert::error(_("Write failure"),
1468                              bformat(_("The file has successfully been saved as:\n  %1$s.\n"
1469                                        "But LyX could not move it to:\n  %2$s.\n"
1470                                        "Your original file has been backed up to:\n  %3$s"),
1471                                      from_utf8(savefile.absFileName()),
1472                                      from_utf8(fileName().absFileName()),
1473                                      from_utf8(backupName.absFileName())));
1474         } else {
1475                 // either we did not try to make a backup, or else we tried and failed,
1476                 // or else the original file was a symlink, in which case it was copied,
1477                 // not moved. so the original file is intact.
1478                 Alert::error(_("Write failure"),
1479                              bformat(_("Cannot move saved file to:\n  %1$s.\n"
1480                                        "But the file has successfully been saved as:\n  %2$s."),
1481                                      from_utf8(fileName().absFileName()),
1482                          from_utf8(savefile.absFileName())));
1483         }
1484         return false;
1485 }
1486
1487
1488 bool Buffer::writeFile(FileName const & fname) const
1489 {
1490         if (d->read_only && fname == d->filename)
1491                 return false;
1492
1493         bool retval = false;
1494
1495         docstring const str = bformat(_("Saving document %1$s..."),
1496                 makeDisplayPath(fname.absFileName()));
1497         message(str);
1498
1499         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1500
1501         if (params().compressed) {
1502                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1503                 retval = ofs && write(ofs);
1504         } else {
1505                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1506                 retval = ofs && write(ofs);
1507         }
1508
1509         if (!retval) {
1510                 message(str + _(" could not write file!"));
1511                 return false;
1512         }
1513
1514         // see bug 6587
1515         // removeAutosaveFile();
1516
1517         saveCheckSum();
1518         message(str + _(" done."));
1519
1520         return true;
1521 }
1522
1523
1524 docstring Buffer::emergencyWrite()
1525 {
1526         // No need to save if the buffer has not changed.
1527         if (isClean())
1528                 return docstring();
1529
1530         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1531
1532         docstring user_message = bformat(
1533                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1534
1535         // We try to save three places:
1536         // 1) Same place as document. Unless it is an unnamed doc.
1537         if (!isUnnamed()) {
1538                 string s = absFileName();
1539                 s += ".emergency";
1540                 LYXERR0("  " << s);
1541                 if (writeFile(FileName(s))) {
1542                         markClean();
1543                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1544                         return user_message;
1545                 } else {
1546                         user_message += "  " + _("Save failed! Trying again...\n");
1547                 }
1548         }
1549
1550         // 2) In HOME directory.
1551         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1552         s += ".emergency";
1553         lyxerr << ' ' << s << endl;
1554         if (writeFile(FileName(s))) {
1555                 markClean();
1556                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1557                 return user_message;
1558         }
1559
1560         user_message += "  " + _("Save failed! Trying yet again...\n");
1561
1562         // 3) In "/tmp" directory.
1563         // MakeAbsPath to prepend the current
1564         // drive letter on OS/2
1565         s = addName(package().temp_dir().absFileName(), absFileName());
1566         s += ".emergency";
1567         lyxerr << ' ' << s << endl;
1568         if (writeFile(FileName(s))) {
1569                 markClean();
1570                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1571                 return user_message;
1572         }
1573
1574         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1575         // Don't try again.
1576         markClean();
1577         return user_message;
1578 }
1579
1580
1581 bool Buffer::write(ostream & ofs) const
1582 {
1583 #ifdef HAVE_LOCALE
1584         // Use the standard "C" locale for file output.
1585         ofs.imbue(locale::classic());
1586 #endif
1587
1588         // The top of the file should not be written by params().
1589
1590         // write out a comment in the top of the file
1591         // Important: Keep the version formatting in sync with lyx2lyx and
1592         //            tex2lyx (bug 7951)
1593         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1594             << " created this file. For more info see http://www.lyx.org/\n"
1595             << "\\lyxformat " << LYX_FORMAT << "\n"
1596             << "\\begin_document\n";
1597
1598         /// For each author, set 'used' to true if there is a change
1599         /// by this author in the document; otherwise set it to 'false'.
1600         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1601         AuthorList::Authors::const_iterator a_end = params().authors().end();
1602         for (; a_it != a_end; ++a_it)
1603                 a_it->setUsed(false);
1604
1605         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1606         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1607         for ( ; it != end; ++it)
1608                 it->checkAuthors(params().authors());
1609
1610         // now write out the buffer parameters.
1611         ofs << "\\begin_header\n";
1612         params().writeFile(ofs, this);
1613         ofs << "\\end_header\n";
1614
1615         // write the text
1616         ofs << "\n\\begin_body\n";
1617         text().write(ofs);
1618         ofs << "\n\\end_body\n";
1619
1620         // Write marker that shows file is complete
1621         ofs << "\\end_document" << endl;
1622
1623         // Shouldn't really be needed....
1624         //ofs.close();
1625
1626         // how to check if close went ok?
1627         // Following is an attempt... (BE 20001011)
1628
1629         // good() returns false if any error occurred, including some
1630         //        formatting error.
1631         // bad()  returns true if something bad happened in the buffer,
1632         //        which should include file system full errors.
1633
1634         bool status = true;
1635         if (!ofs) {
1636                 status = false;
1637                 lyxerr << "File was not closed properly." << endl;
1638         }
1639
1640         return status;
1641 }
1642
1643
1644 bool Buffer::makeLaTeXFile(FileName const & fname,
1645                            string const & original_path,
1646                            OutputParams const & runparams_in,
1647                            OutputWhat output) const
1648 {
1649         OutputParams runparams = runparams_in;
1650
1651         // XeTeX with TeX fonts is only safe with ASCII encoding,
1652         // but the "flavor" is not known in BufferParams::encoding().
1653         if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1654                 runparams.encoding = encodings.fromLyXName("ascii");
1655
1656         string const encoding = runparams.encoding->iconvName();
1657         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1658
1659         ofdocstream ofs;
1660         try { ofs.reset(encoding); }
1661         catch (iconv_codecvt_facet_exception const & e) {
1662                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1663                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1664                         "verify that the support software for your encoding (%1$s) is "
1665                         "properly installed"), from_ascii(encoding)));
1666                 return false;
1667         }
1668         if (!openFileWrite(ofs, fname))
1669                 return false;
1670
1671         ErrorList & errorList = d->errorLists["Export"];
1672         errorList.clear();
1673         bool failed_export = false;
1674         otexstream os(ofs, d->texrow);
1675
1676         // make sure we are ready to export
1677         // this needs to be done before we validate
1678         // FIXME Do we need to do this all the time? I.e., in children
1679         // of a master we are exporting?
1680         updateBuffer();
1681         updateMacroInstances(OutputUpdate);
1682
1683         try {
1684                 os.texrow().reset();
1685                 writeLaTeXSource(os, original_path, runparams, output);
1686         }
1687         catch (EncodingException const & e) {
1688                 docstring const failed(1, e.failed_char);
1689                 ostringstream oss;
1690                 oss << "0x" << hex << e.failed_char << dec;
1691                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1692                                           " (code point %2$s)"),
1693                                           failed, from_utf8(oss.str()));
1694                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1695                                 "representable in the chosen encoding.\n"
1696                                 "Changing the document encoding to utf8 could help."),
1697                                 e.par_id, e.pos, e.pos + 1));
1698                 failed_export = true;
1699         }
1700         catch (iconv_codecvt_facet_exception const & e) {
1701                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1702                         _(e.what()), -1, 0, 0));
1703                 failed_export = true;
1704         }
1705         catch (exception const & e) {
1706                 errorList.push_back(ErrorItem(_("conversion failed"),
1707                         _(e.what()), -1, 0, 0));
1708                 failed_export = true;
1709         }
1710         catch (...) {
1711                 lyxerr << "Caught some really weird exception..." << endl;
1712                 lyx_exit(1);
1713         }
1714
1715         ofs.close();
1716         if (ofs.fail()) {
1717                 failed_export = true;
1718                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1719         }
1720
1721         if (runparams_in.silent)
1722                 errorList.clear();
1723         else
1724                 errors("Export");
1725         return !failed_export;
1726 }
1727
1728
1729 void Buffer::writeLaTeXSource(otexstream & os,
1730                            string const & original_path,
1731                            OutputParams const & runparams_in,
1732                            OutputWhat output) const
1733 {
1734         // The child documents, if any, shall be already loaded at this point.
1735
1736         OutputParams runparams = runparams_in;
1737
1738         // XeTeX with TeX fonts is only safe with ASCII encoding,
1739         // but the "flavor" is not known in BufferParams::encoding().
1740         if (!params().useNonTeXFonts && (runparams.flavor == OutputParams::XETEX))
1741                 runparams.encoding = encodings.fromLyXName("ascii");
1742         // FIXME: when only the current paragraph is shown, this is ignored
1743         //        (or not reached) and characters encodable in the current
1744         //        encoding are not converted to ASCII-representation.
1745
1746         // If we are compiling a file standalone, even if this is the
1747         // child of some other buffer, let's cut the link here, so the
1748         // file is really independent and no concurring settings from
1749         // the master (e.g. branch state) interfere (see #8100).
1750         if (!runparams.is_child)
1751                 d->ignore_parent = true;
1752
1753         // Classify the unicode characters appearing in math insets
1754         BufferEncodings::initUnicodeMath(*this);
1755
1756         // validate the buffer.
1757         LYXERR(Debug::LATEX, "  Validating buffer...");
1758         LaTeXFeatures features(*this, params(), runparams);
1759         validate(features);
1760         // This is only set once per document (in master)
1761         if (!runparams.is_child)
1762                 runparams.use_polyglossia = features.usePolyglossia();
1763         LYXERR(Debug::LATEX, "  Buffer validation done.");
1764
1765         bool const output_preamble =
1766                 output == FullSource || output == OnlyPreamble;
1767         bool const output_body =
1768                 output == FullSource || output == OnlyBody;
1769
1770         // The starting paragraph of the coming rows is the
1771         // first paragraph of the document. (Asger)
1772         if (output_preamble && runparams.nice) {
1773                 os << "%% LyX " << lyx_version << " created this file.  "
1774                         "For more info, see http://www.lyx.org/.\n"
1775                         "%% Do not edit unless you really know what "
1776                         "you are doing.\n";
1777         }
1778         LYXERR(Debug::INFO, "lyx document header finished");
1779
1780         // There are a few differences between nice LaTeX and usual files:
1781         // usual files have \batchmode and special input@path to allow
1782         // inclusion of figures specified by an explicitly relative path
1783         // (i.e., a path starting with './' or '../') with either \input or
1784         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1785         // input@path is set when the actual parameter original_path is set.
1786         // This is done for usual tex-file, but not for nice-latex-file.
1787         // (Matthias 250696)
1788         // Note that input@path is only needed for something the user does
1789         // in the preamble, included .tex files or ERT, files included by
1790         // LyX work without it.
1791         if (output_preamble) {
1792                 if (!runparams.nice) {
1793                         // code for usual, NOT nice-latex-file
1794                         os << "\\batchmode\n"; // changed from \nonstopmode
1795                 }
1796                 if (!original_path.empty()) {
1797                         // FIXME UNICODE
1798                         // We don't know the encoding of inputpath
1799                         docstring const inputpath = from_utf8(original_path);
1800                         docstring uncodable_glyphs;
1801                         Encoding const * const enc = runparams.encoding;
1802                         if (enc) {
1803                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1804                                         if (!enc->encodable(inputpath[n])) {
1805                                                 docstring const glyph(1, inputpath[n]);
1806                                                 LYXERR0("Uncodable character '"
1807                                                         << glyph
1808                                                         << "' in input path!");
1809                                                 uncodable_glyphs += glyph;
1810                                         }
1811                                 }
1812                         }
1813
1814                         // warn user if we found uncodable glyphs.
1815                         if (!uncodable_glyphs.empty()) {
1816                                 frontend::Alert::warning(
1817                                         _("Uncodable character in file path"),
1818                                         support::bformat(
1819                                           _("The path of your document\n"
1820                                             "(%1$s)\n"
1821                                             "contains glyphs that are unknown "
1822                                             "in the current document encoding "
1823                                             "(namely %2$s). This may result in "
1824                                             "incomplete output, unless "
1825                                             "TEXINPUTS contains the document "
1826                                             "directory and you don't use "
1827                                             "explicitly relative paths (i.e., "
1828                                             "paths starting with './' or "
1829                                             "'../') in the preamble or in ERT."
1830                                             "\n\nIn case of problems, choose "
1831                                             "an appropriate document encoding\n"
1832                                             "(such as utf8) or change the "
1833                                             "file path name."),
1834                                           inputpath, uncodable_glyphs));
1835                         } else {
1836                                 string docdir =
1837                                         support::latex_path(original_path);
1838                                 if (contains(docdir, '#')) {
1839                                         docdir = subst(docdir, "#", "\\#");
1840                                         os << "\\catcode`\\#=11"
1841                                               "\\def\\#{#}\\catcode`\\#=6\n";
1842                                 }
1843                                 if (contains(docdir, '%')) {
1844                                         docdir = subst(docdir, "%", "\\%");
1845                                         os << "\\catcode`\\%=11"
1846                                               "\\def\\%{%}\\catcode`\\%=14\n";
1847                                 }
1848                                 os << "\\makeatletter\n"
1849                                    << "\\def\\input@path{{"
1850                                    << docdir << "}}\n"
1851                                    << "\\makeatother\n";
1852                         }
1853                 }
1854
1855                 // get parent macros (if this buffer has a parent) which will be
1856                 // written at the document begin further down.
1857                 MacroSet parentMacros;
1858                 listParentMacros(parentMacros, features);
1859
1860                 // Write the preamble
1861                 runparams.use_babel = params().writeLaTeX(os, features,
1862                                                           d->filename.onlyPath());
1863
1864                 // Japanese might be required only in some children of a document,
1865                 // but once required, we must keep use_japanese true.
1866                 runparams.use_japanese |= features.isRequired("japanese");
1867
1868                 if (!output_body) {
1869                         // Restore the parenthood if needed
1870                         if (!runparams.is_child)
1871                                 d->ignore_parent = false;
1872                         return;
1873                 }
1874
1875                 // make the body.
1876                 os << "\\begin{document}\n";
1877
1878                 // output the parent macros
1879                 MacroSet::iterator it = parentMacros.begin();
1880                 MacroSet::iterator end = parentMacros.end();
1881                 for (; it != end; ++it) {
1882                         int num_lines = (*it)->write(os.os(), true);
1883                         os.texrow().newlines(num_lines);
1884                 }
1885
1886         } // output_preamble
1887
1888         os.texrow().start(paragraphs().begin()->id(), 0);
1889
1890         LYXERR(Debug::INFO, "preamble finished, now the body.");
1891
1892         // the real stuff
1893         latexParagraphs(*this, text(), os, runparams);
1894
1895         // Restore the parenthood if needed
1896         if (!runparams.is_child)
1897                 d->ignore_parent = false;
1898
1899         // add this just in case after all the paragraphs
1900         os << endl;
1901
1902         if (output_preamble) {
1903                 os << "\\end{document}\n";
1904                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1905         } else {
1906                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1907         }
1908         runparams_in.encoding = runparams.encoding;
1909
1910         os.texrow().finalize();
1911
1912         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1913         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1914 }
1915
1916
1917 void Buffer::makeDocBookFile(FileName const & fname,
1918                               OutputParams const & runparams,
1919                               OutputWhat output) const
1920 {
1921         LYXERR(Debug::LATEX, "makeDocBookFile...");
1922
1923         ofdocstream ofs;
1924         if (!openFileWrite(ofs, fname))
1925                 return;
1926
1927         // make sure we are ready to export
1928         // this needs to be done before we validate
1929         updateBuffer();
1930         updateMacroInstances(OutputUpdate);
1931
1932         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1933
1934         ofs.close();
1935         if (ofs.fail())
1936                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1937 }
1938
1939
1940 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1941                              OutputParams const & runparams,
1942                              OutputWhat output) const
1943 {
1944         LaTeXFeatures features(*this, params(), runparams);
1945         validate(features);
1946
1947         d->texrow.reset(false);
1948
1949         DocumentClass const & tclass = params().documentClass();
1950         string const & top_element = tclass.latexname();
1951
1952         bool const output_preamble =
1953                 output == FullSource || output == OnlyPreamble;
1954         bool const output_body =
1955           output == FullSource || output == OnlyBody;
1956
1957         if (output_preamble) {
1958                 if (runparams.flavor == OutputParams::XML)
1959                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1960
1961                 // FIXME UNICODE
1962                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1963
1964                 // FIXME UNICODE
1965                 if (! tclass.class_header().empty())
1966                         os << from_ascii(tclass.class_header());
1967                 else if (runparams.flavor == OutputParams::XML)
1968                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1969                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1970                 else
1971                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1972
1973                 docstring preamble = from_utf8(params().preamble);
1974                 if (runparams.flavor != OutputParams::XML ) {
1975                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1976                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1977                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1978                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1979                 }
1980
1981                 string const name = runparams.nice
1982                         ? changeExtension(absFileName(), ".sgml") : fname;
1983                 preamble += features.getIncludedFiles(name);
1984                 preamble += features.getLyXSGMLEntities();
1985
1986                 if (!preamble.empty()) {
1987                         os << "\n [ " << preamble << " ]";
1988                 }
1989                 os << ">\n\n";
1990         }
1991
1992         if (output_body) {
1993                 string top = top_element;
1994                 top += " lang=\"";
1995                 if (runparams.flavor == OutputParams::XML)
1996                         top += params().language->code();
1997                 else
1998                         top += params().language->code().substr(0, 2);
1999                 top += '"';
2000
2001                 if (!params().options.empty()) {
2002                         top += ' ';
2003                         top += params().options;
2004                 }
2005
2006                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
2007                                 << " file was created by LyX " << lyx_version
2008                                 << "\n  See http://www.lyx.org/ for more information -->\n";
2009
2010                 params().documentClass().counters().reset();
2011
2012                 sgml::openTag(os, top);
2013                 os << '\n';
2014                 docbookParagraphs(text(), *this, os, runparams);
2015                 sgml::closeTag(os, top_element);
2016         }
2017 }
2018
2019
2020 void Buffer::makeLyXHTMLFile(FileName const & fname,
2021                               OutputParams const & runparams) const
2022 {
2023         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
2024
2025         ofdocstream ofs;
2026         if (!openFileWrite(ofs, fname))
2027                 return;
2028
2029         // make sure we are ready to export
2030         // this has to be done before we validate
2031         updateBuffer(UpdateMaster, OutputUpdate);
2032         updateMacroInstances(OutputUpdate);
2033
2034         writeLyXHTMLSource(ofs, runparams, FullSource);
2035
2036         ofs.close();
2037         if (ofs.fail())
2038                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
2039 }
2040
2041
2042 void Buffer::writeLyXHTMLSource(odocstream & os,
2043                              OutputParams const & runparams,
2044                              OutputWhat output) const
2045 {
2046         LaTeXFeatures features(*this, params(), runparams);
2047         validate(features);
2048         d->bibinfo_.makeCitationLabels(*this);
2049
2050         bool const output_preamble =
2051                 output == FullSource || output == OnlyPreamble;
2052         bool const output_body =
2053           output == FullSource || output == OnlyBody || output == IncludedFile;
2054
2055         if (output_preamble) {
2056                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2057                    << "<!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"
2058                    // FIXME Language should be set properly.
2059                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2060                    << "<head>\n"
2061                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2062                    // FIXME Presumably need to set this right
2063                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2064
2065                 docstring const & doctitle = features.htmlTitle();
2066                 os << "<title>"
2067                    << (doctitle.empty() ?
2068                          from_ascii("LyX Document") :
2069                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2070                    << "</title>\n";
2071
2072                 docstring styles = features.getTClassHTMLPreamble();
2073                 if (!styles.empty())
2074                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2075
2076                 styles = from_utf8(features.getPreambleSnippets());
2077                 if (!styles.empty())
2078                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2079
2080                 // we will collect CSS information in a stream, and then output it
2081                 // either here, as part of the header, or else in a separate file.
2082                 odocstringstream css;
2083                 styles = from_utf8(features.getCSSSnippets());
2084                 if (!styles.empty())
2085                         css << "/* LyX Provided Styles */\n" << styles << '\n';
2086
2087                 styles = features.getTClassHTMLStyles();
2088                 if (!styles.empty())
2089                         css << "/* Layout-provided Styles */\n" << styles << '\n';
2090
2091                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2092                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2093                 if (needfg || needbg) {
2094                                 css << "\nbody {\n";
2095                                 if (needfg)
2096                                    css << "  color: "
2097                                             << from_ascii(X11hexname(params().fontcolor))
2098                                             << ";\n";
2099                                 if (needbg)
2100                                    css << "  background-color: "
2101                                             << from_ascii(X11hexname(params().backgroundcolor))
2102                                             << ";\n";
2103                                 css << "}\n";
2104                 }
2105
2106                 docstring const dstyles = css.str();
2107                 if (!dstyles.empty()) {
2108                         bool written = false;
2109                         if (params().html_css_as_file) {
2110                                 // open a file for CSS info
2111                                 ofdocstream ocss;
2112                                 string const fcssname = addName(temppath(), "docstyle.css");
2113                                 FileName const fcssfile = FileName(fcssname);
2114                                 if (openFileWrite(ocss, fcssfile)) {
2115                                         ocss << dstyles;
2116                                         ocss.close();
2117                                         written = true;
2118                                         // write link to header
2119                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2120                                         // register file
2121                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
2122                                 }
2123                         }
2124                         // we are here if the CSS is supposed to be written to the header
2125                         // or if we failed to write it to an external file.
2126                         if (!written) {
2127                                 os << "<style type='text/css'>\n"
2128                                          << dstyles
2129                                          << "\n</style>\n";
2130                         }
2131                 }
2132                 os << "</head>\n";
2133         }
2134
2135         if (output_body) {
2136                 bool const output_body_tag = (output != IncludedFile);
2137                 if (output_body_tag)
2138                         os << "<body>\n";
2139                 XHTMLStream xs(os);
2140                 if (output != IncludedFile)
2141                         // if we're an included file, the counters are in the master.
2142                         params().documentClass().counters().reset();
2143                 xhtmlParagraphs(text(), *this, xs, runparams);
2144                 if (output_body_tag)
2145                         os << "</body>\n";
2146         }
2147
2148         if (output_preamble)
2149                 os << "</html>\n";
2150 }
2151
2152
2153 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2154 // Other flags: -wall -v0 -x
2155 int Buffer::runChktex()
2156 {
2157         setBusy(true);
2158
2159         // get LaTeX-Filename
2160         FileName const path(temppath());
2161         string const name = addName(path.absFileName(), latexName());
2162         string const org_path = filePath();
2163
2164         PathChanger p(path); // path to LaTeX file
2165         message(_("Running chktex..."));
2166
2167         // Generate the LaTeX file if neccessary
2168         OutputParams runparams(&params().encoding());
2169         runparams.flavor = OutputParams::LATEX;
2170         runparams.nice = false;
2171         runparams.linelen = lyxrc.plaintext_linelen;
2172         makeLaTeXFile(FileName(name), org_path, runparams);
2173
2174         TeXErrors terr;
2175         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2176         int const res = chktex.run(terr); // run chktex
2177
2178         if (res == -1) {
2179                 Alert::error(_("chktex failure"),
2180                              _("Could not run chktex successfully."));
2181         } else {
2182                 ErrorList & errlist = d->errorLists["ChkTeX"];
2183                 errlist.clear();
2184                 bufferErrors(terr, errlist);
2185         }
2186
2187         setBusy(false);
2188
2189         if (runparams.silent)
2190                 d->errorLists["ChkTeX"].clear();
2191         else
2192                 errors("ChkTeX");
2193
2194         return res;
2195 }
2196
2197
2198 void Buffer::validate(LaTeXFeatures & features) const
2199 {
2200         // Validate the buffer params, but not for included
2201         // files, since they also use the parent buffer's
2202         // params (# 5941)
2203         if (!features.runparams().is_child)
2204                 params().validate(features);
2205
2206         for_each(paragraphs().begin(), paragraphs().end(),
2207                  bind(&Paragraph::validate, _1, ref(features)));
2208
2209         if (lyxerr.debugging(Debug::LATEX)) {
2210                 features.showStruct();
2211         }
2212 }
2213
2214
2215 void Buffer::getLabelList(vector<docstring> & list) const
2216 {
2217         // If this is a child document, use the master's list instead.
2218         if (parent()) {
2219                 masterBuffer()->getLabelList(list);
2220                 return;
2221         }
2222
2223         list.clear();
2224         shared_ptr<Toc> toc = d->toc_backend.toc("label");
2225         TocIterator toc_it = toc->begin();
2226         TocIterator end = toc->end();
2227         for (; toc_it != end; ++toc_it) {
2228                 if (toc_it->depth() == 0)
2229                         list.push_back(toc_it->str());
2230         }
2231 }
2232
2233
2234 void Buffer::updateBibfilesCache(UpdateScope scope) const
2235 {
2236         // FIXME This is probably unnecssary, given where we call this.
2237         // If this is a child document, use the parent's cache instead.
2238         if (parent() && scope != UpdateChildOnly) {
2239                 masterBuffer()->updateBibfilesCache();
2240                 return;
2241         }
2242
2243         d->bibfiles_cache_.clear();
2244         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2245                 if (it->lyxCode() == BIBTEX_CODE) {
2246                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2247                         support::FileNameList const bibfiles = inset.getBibFiles();
2248                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2249                                 bibfiles.begin(),
2250                                 bibfiles.end());
2251                 } else if (it->lyxCode() == INCLUDE_CODE) {
2252                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2253                         Buffer const * const incbuf = inset.getChildBuffer();
2254                         if (!incbuf)
2255                                 continue;
2256                         support::FileNameList const & bibfiles =
2257                                         incbuf->getBibfilesCache(UpdateChildOnly);
2258                         if (!bibfiles.empty()) {
2259                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2260                                         bibfiles.begin(),
2261                                         bibfiles.end());
2262                         }
2263                 }
2264         }
2265         d->bibfile_cache_valid_ = true;
2266         d->bibinfo_cache_valid_ = false;
2267         d->cite_labels_valid_ = false;
2268 }
2269
2270
2271 void Buffer::invalidateBibinfoCache() const
2272 {
2273         d->bibinfo_cache_valid_ = false;
2274         d->cite_labels_valid_ = false;
2275         // also invalidate the cache for the parent buffer
2276         Buffer const * const pbuf = d->parent();
2277         if (pbuf)
2278                 pbuf->invalidateBibinfoCache();
2279 }
2280
2281
2282 void Buffer::invalidateBibfileCache() const
2283 {
2284         d->bibfile_cache_valid_ = false;
2285         d->bibinfo_cache_valid_ = false;
2286         d->cite_labels_valid_ = false;
2287         // also invalidate the cache for the parent buffer
2288         Buffer const * const pbuf = d->parent();
2289         if (pbuf)
2290                 pbuf->invalidateBibfileCache();
2291 }
2292
2293
2294 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2295 {
2296         // FIXME This is probably unnecessary, given where we call this.
2297         // If this is a child document, use the master's cache instead.
2298         Buffer const * const pbuf = masterBuffer();
2299         if (pbuf != this && scope != UpdateChildOnly)
2300                 return pbuf->getBibfilesCache();
2301
2302         if (!d->bibfile_cache_valid_)
2303                 this->updateBibfilesCache(scope);
2304
2305         return d->bibfiles_cache_;
2306 }
2307
2308
2309 BiblioInfo const & Buffer::masterBibInfo() const
2310 {
2311         Buffer const * const tmp = masterBuffer();
2312         if (tmp != this)
2313                 return tmp->masterBibInfo();
2314         return d->bibinfo_;
2315 }
2316
2317
2318 void Buffer::checkIfBibInfoCacheIsValid() const
2319 {
2320         // use the master's cache
2321         Buffer const * const tmp = masterBuffer();
2322         if (tmp != this) {
2323                 tmp->checkIfBibInfoCacheIsValid();
2324                 return;
2325         }
2326
2327         // compare the cached timestamps with the actual ones.
2328         FileNameList const & bibfiles_cache = getBibfilesCache();
2329         FileNameList::const_iterator ei = bibfiles_cache.begin();
2330         FileNameList::const_iterator en = bibfiles_cache.end();
2331         for (; ei != en; ++ ei) {
2332                 time_t lastw = ei->lastModified();
2333                 time_t prevw = d->bibfile_status_[*ei];
2334                 if (lastw != prevw) {
2335                         d->bibinfo_cache_valid_ = false;
2336                         d->cite_labels_valid_ = false;
2337                         d->bibfile_status_[*ei] = lastw;
2338                 }
2339         }
2340 }
2341
2342
2343 void Buffer::reloadBibInfoCache() const
2344 {
2345         // use the master's cache
2346         Buffer const * const tmp = masterBuffer();
2347         if (tmp != this) {
2348                 tmp->reloadBibInfoCache();
2349                 return;
2350         }
2351
2352         checkIfBibInfoCacheIsValid();
2353         if (d->bibinfo_cache_valid_)
2354                 return;
2355
2356         d->bibinfo_.clear();
2357         collectBibKeys();
2358         d->bibinfo_cache_valid_ = true;
2359 }
2360
2361
2362 void Buffer::collectBibKeys() const
2363 {
2364         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2365                 it->collectBibKeys(it);
2366 }
2367
2368
2369 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2370 {
2371         Buffer const * tmp = masterBuffer();
2372         BiblioInfo & masterbi = (tmp == this) ?
2373                 d->bibinfo_ : tmp->d->bibinfo_;
2374         masterbi.mergeBiblioInfo(bi);
2375 }
2376
2377
2378 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2379 {
2380         Buffer const * tmp = masterBuffer();
2381         BiblioInfo & masterbi = (tmp == this) ?
2382                 d->bibinfo_ : tmp->d->bibinfo_;
2383         masterbi[key] = bi;
2384 }
2385
2386
2387 void Buffer::makeCitationLabels() const
2388 {
2389         Buffer const * const master = masterBuffer();
2390         return d->bibinfo_.makeCitationLabels(*master);
2391 }
2392
2393
2394 bool Buffer::citeLabelsValid() const
2395 {
2396         return masterBuffer()->d->cite_labels_valid_;
2397 }
2398
2399
2400 void Buffer::removeBiblioTempFiles() const
2401 {
2402         // We remove files that contain LaTeX commands specific to the
2403         // particular bibliographic style being used, in order to avoid
2404         // LaTeX errors when we switch style.
2405         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2406         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2407         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2408         aux_file.removeFile();
2409         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2410         bbl_file.removeFile();
2411         // Also for the parent buffer
2412         Buffer const * const pbuf = parent();
2413         if (pbuf)
2414                 pbuf->removeBiblioTempFiles();
2415 }
2416
2417
2418 bool Buffer::isDepClean(string const & name) const
2419 {
2420         DepClean::const_iterator const it = d->dep_clean.find(name);
2421         if (it == d->dep_clean.end())
2422                 return true;
2423         return it->second;
2424 }
2425
2426
2427 void Buffer::markDepClean(string const & name)
2428 {
2429         d->dep_clean[name] = true;
2430 }
2431
2432
2433 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2434 {
2435         if (isInternal()) {
2436                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2437                 // if internal, put a switch '(cmd.action)' here.
2438                 return false;
2439         }
2440
2441         bool enable = true;
2442
2443         switch (cmd.action()) {
2444
2445         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2446                 flag.setOnOff(isReadonly());
2447                 break;
2448
2449                 // FIXME: There is need for a command-line import.
2450                 //case LFUN_BUFFER_IMPORT:
2451
2452         case LFUN_BUFFER_AUTO_SAVE:
2453                 break;
2454
2455         case LFUN_BUFFER_EXPORT_CUSTOM:
2456                 // FIXME: Nothing to check here?
2457                 break;
2458
2459         case LFUN_BUFFER_EXPORT: {
2460                 docstring const arg = cmd.argument();
2461                 if (arg == "custom") {
2462                         enable = true;
2463                         break;
2464                 }
2465                 string format = to_utf8(arg);
2466                 size_t pos = format.find(' ');
2467                 if (pos != string::npos)
2468                         format = format.substr(0, pos);
2469                 enable = params().isExportable(format);
2470                 if (!enable)
2471                         flag.message(bformat(
2472                                              _("Don't know how to export to format: %1$s"), arg));
2473                 break;
2474         }
2475
2476         case LFUN_BUFFER_CHKTEX:
2477                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2478                 break;
2479
2480         case LFUN_BUILD_PROGRAM:
2481                 enable = params().isExportable("program");
2482                 break;
2483
2484         case LFUN_BRANCH_ACTIVATE:
2485         case LFUN_BRANCH_DEACTIVATE:
2486         case LFUN_BRANCH_MASTER_ACTIVATE:
2487         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2488                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2489                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2490                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2491                         : params().branchlist();
2492                 docstring const branchName = cmd.argument();
2493                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2494                 break;
2495         }
2496
2497         case LFUN_BRANCH_ADD:
2498         case LFUN_BRANCHES_RENAME:
2499                 // if no Buffer is present, then of course we won't be called!
2500                 break;
2501
2502         case LFUN_BUFFER_LANGUAGE:
2503                 enable = !isReadonly();
2504                 break;
2505
2506         case LFUN_BUFFER_VIEW_CACHE:
2507                 (d->preview_file_).refresh();
2508                 enable = (d->preview_file_).exists() && !(d->preview_file_).isFileEmpty();
2509                 break;
2510
2511         case LFUN_CHANGES_TRACK:
2512                 flag.setEnabled(true);
2513                 flag.setOnOff(params().track_changes);
2514                 break;
2515
2516         case LFUN_CHANGES_OUTPUT:
2517                 flag.setEnabled(true);
2518                 flag.setOnOff(params().output_changes);
2519                 break;
2520
2521         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
2522                 flag.setOnOff(params().compressed);
2523                 break;
2524         }
2525
2526         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC: {
2527                 flag.setOnOff(params().output_sync);
2528                 break;
2529         }
2530
2531         default:
2532                 return false;
2533         }
2534         flag.setEnabled(enable);
2535         return true;
2536 }
2537
2538
2539 void Buffer::dispatch(string const & command, DispatchResult & result)
2540 {
2541         return dispatch(lyxaction.lookupFunc(command), result);
2542 }
2543
2544
2545 // NOTE We can end up here even if we have no GUI, because we are called
2546 // by LyX::exec to handled command-line requests. So we may need to check
2547 // whether we have a GUI or not. The boolean use_gui holds this information.
2548 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2549 {
2550         if (isInternal()) {
2551                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2552                 // if internal, put a switch '(cmd.action())' here.
2553                 dr.dispatched(false);
2554                 return;
2555         }
2556         string const argument = to_utf8(func.argument());
2557         // We'll set this back to false if need be.
2558         bool dispatched = true;
2559         undo().beginUndoGroup();
2560
2561         switch (func.action()) {
2562         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2563                 if (lyxvc().inUse()) {
2564                         string log = lyxvc().toggleReadOnly();
2565                         if (!log.empty())
2566                                 dr.setMessage(log);
2567                 }
2568                 else
2569                         setReadonly(!isReadonly());
2570                 break;
2571
2572         case LFUN_BUFFER_EXPORT: {
2573                 ExportStatus const status = doExport(argument, false);
2574                 dr.setError(status != ExportSuccess);
2575                 if (status != ExportSuccess)
2576                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2577                                               func.argument()));
2578                 break;
2579         }
2580
2581         case LFUN_BUILD_PROGRAM: {
2582                 ExportStatus const status = doExport("program", true);
2583                 dr.setError(status != ExportSuccess);
2584                 if (status != ExportSuccess)
2585                         dr.setMessage(_("Error generating literate programming code."));
2586                 break;
2587         }
2588
2589         case LFUN_BUFFER_CHKTEX:
2590                 runChktex();
2591                 break;
2592
2593         case LFUN_BUFFER_EXPORT_CUSTOM: {
2594                 string format_name;
2595                 string command = split(argument, format_name, ' ');
2596                 Format const * format = formats.getFormat(format_name);
2597                 if (!format) {
2598                         lyxerr << "Format \"" << format_name
2599                                 << "\" not recognized!"
2600                                 << endl;
2601                         break;
2602                 }
2603
2604                 // The name of the file created by the conversion process
2605                 string filename;
2606
2607                 // Output to filename
2608                 if (format->name() == "lyx") {
2609                         string const latexname = latexName(false);
2610                         filename = changeExtension(latexname,
2611                                 format->extension());
2612                         filename = addName(temppath(), filename);
2613
2614                         if (!writeFile(FileName(filename)))
2615                                 break;
2616
2617                 } else {
2618                         doExport(format_name, true, filename);
2619                 }
2620
2621                 // Substitute $$FName for filename
2622                 if (!contains(command, "$$FName"))
2623                         command = "( " + command + " ) < $$FName";
2624                 command = subst(command, "$$FName", filename);
2625
2626                 // Execute the command in the background
2627                 Systemcall call;
2628                 call.startscript(Systemcall::DontWait, command,
2629                                  filePath(), layoutPos());
2630                 break;
2631         }
2632
2633         // FIXME: There is need for a command-line import.
2634         /*
2635         case LFUN_BUFFER_IMPORT:
2636                 doImport(argument);
2637                 break;
2638         */
2639
2640         case LFUN_BUFFER_AUTO_SAVE:
2641                 autoSave();
2642                 resetAutosaveTimers();
2643                 break;
2644
2645         case LFUN_BRANCH_ACTIVATE:
2646         case LFUN_BRANCH_DEACTIVATE:
2647         case LFUN_BRANCH_MASTER_ACTIVATE:
2648         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2649                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2650                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2651                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2652                                       : this;
2653
2654                 docstring const branch_name = func.argument();
2655                 // the case without a branch name is handled elsewhere
2656                 if (branch_name.empty()) {
2657                         dispatched = false;
2658                         break;
2659                 }
2660                 Branch * branch = buf->params().branchlist().find(branch_name);
2661                 if (!branch) {
2662                         LYXERR0("Branch " << branch_name << " does not exist.");
2663                         dr.setError(true);
2664                         docstring const msg =
2665                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2666                         dr.setMessage(msg);
2667                         break;
2668                 }
2669                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2670                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2671                 if (branch->isSelected() != activate) {
2672                         buf->undo().recordUndoBufferParams(CursorData());
2673                         branch->setSelected(activate);
2674                         dr.setError(false);
2675                         dr.screenUpdate(Update::Force);
2676                         dr.forceBufferUpdate();
2677                 }
2678                 break;
2679         }
2680
2681         case LFUN_BRANCH_ADD: {
2682                 docstring branch_name = func.argument();
2683                 if (branch_name.empty()) {
2684                         dispatched = false;
2685                         break;
2686                 }
2687                 BranchList & branch_list = params().branchlist();
2688                 vector<docstring> const branches =
2689                         getVectorFromString(branch_name, branch_list.separator());
2690                 docstring msg;
2691                 for (vector<docstring>::const_iterator it = branches.begin();
2692                      it != branches.end(); ++it) {
2693                         branch_name = *it;
2694                         Branch * branch = branch_list.find(branch_name);
2695                         if (branch) {
2696                                 LYXERR0("Branch " << branch_name << " already exists.");
2697                                 dr.setError(true);
2698                                 if (!msg.empty())
2699                                         msg += ("\n");
2700                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2701                         } else {
2702                                 undo().recordUndoBufferParams(CursorData());
2703                                 branch_list.add(branch_name);
2704                                 branch = branch_list.find(branch_name);
2705                                 string const x11hexname = X11hexname(branch->color());
2706                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2707                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2708                                 dr.setError(false);
2709                                 dr.screenUpdate(Update::Force);
2710                         }
2711                 }
2712                 if (!msg.empty())
2713                         dr.setMessage(msg);
2714                 break;
2715         }
2716
2717         case LFUN_BRANCHES_RENAME: {
2718                 if (func.argument().empty())
2719                         break;
2720
2721                 docstring const oldname = from_utf8(func.getArg(0));
2722                 docstring const newname = from_utf8(func.getArg(1));
2723                 InsetIterator it  = inset_iterator_begin(inset());
2724                 InsetIterator const end = inset_iterator_end(inset());
2725                 bool success = false;
2726                 for (; it != end; ++it) {
2727                         if (it->lyxCode() == BRANCH_CODE) {
2728                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2729                                 if (ins.branch() == oldname) {
2730                                         undo().recordUndo(CursorData(it));
2731                                         ins.rename(newname);
2732                                         success = true;
2733                                         continue;
2734                                 }
2735                         }
2736                         if (it->lyxCode() == INCLUDE_CODE) {
2737                                 // get buffer of external file
2738                                 InsetInclude const & ins =
2739                                         static_cast<InsetInclude const &>(*it);
2740                                 Buffer * child = ins.getChildBuffer();
2741                                 if (!child)
2742                                         continue;
2743                                 child->dispatch(func, dr);
2744                         }
2745                 }
2746
2747                 if (success) {
2748                         dr.screenUpdate(Update::Force);
2749                         dr.forceBufferUpdate();
2750                 }
2751                 break;
2752         }
2753
2754         case LFUN_BUFFER_VIEW_CACHE:
2755                 if (!formats.view(*this, d->preview_file_,
2756                                   d->preview_format_))
2757                         dr.setMessage(_("Error viewing the output file."));
2758                 break;
2759
2760         case LFUN_CHANGES_TRACK:
2761                 undo().recordUndoBufferParams(CursorData());
2762                 params().track_changes = !params().track_changes;
2763                 break;
2764
2765         case LFUN_CHANGES_OUTPUT:
2766                 undo().recordUndoBufferParams(CursorData());
2767                 params().output_changes = !params().output_changes;
2768                 if (params().output_changes) {
2769                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
2770                         bool xcolorulem = LaTeXFeatures::isAvailable("ulem") &&
2771                                           LaTeXFeatures::isAvailable("xcolor");
2772
2773                         if (!dvipost && !xcolorulem) {
2774                                 Alert::warning(_("Changes not shown in LaTeX output"),
2775                                                _("Changes will not be highlighted in LaTeX output, "
2776                                                  "because neither dvipost nor xcolor/ulem are installed.\n"
2777                                                  "Please install these packages or redefine "
2778                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2779                         } else if (!xcolorulem) {
2780                                 Alert::warning(_("Changes not shown in LaTeX output"),
2781                                                _("Changes will not be highlighted in LaTeX output "
2782                                                  "when using pdflatex, because xcolor and ulem are not installed.\n"
2783                                                  "Please install both packages or redefine "
2784                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
2785                         }
2786                 }
2787                 break;
2788
2789         case LFUN_BUFFER_TOGGLE_COMPRESSION:
2790                 // turn compression on/off
2791                 undo().recordUndoBufferParams(CursorData());
2792                 params().compressed = !params().compressed;
2793                 break;
2794
2795         case LFUN_BUFFER_TOGGLE_OUTPUT_SYNC:
2796                 undo().recordUndoBufferParams(CursorData());
2797                 params().output_sync = !params().output_sync;
2798                 break;
2799
2800         default:
2801                 dispatched = false;
2802                 break;
2803         }
2804         dr.dispatched(dispatched);
2805         undo().endUndoGroup();
2806 }
2807
2808
2809 void Buffer::changeLanguage(Language const * from, Language const * to)
2810 {
2811         LASSERT(from, return);
2812         LASSERT(to, return);
2813
2814         for_each(par_iterator_begin(),
2815                  par_iterator_end(),
2816                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2817 }
2818
2819
2820 bool Buffer::isMultiLingual() const
2821 {
2822         ParConstIterator end = par_iterator_end();
2823         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2824                 if (it->isMultiLingual(params()))
2825                         return true;
2826
2827         return false;
2828 }
2829
2830
2831 std::set<Language const *> Buffer::getLanguages() const
2832 {
2833         std::set<Language const *> languages;
2834         getLanguages(languages);
2835         return languages;
2836 }
2837
2838
2839 void Buffer::getLanguages(std::set<Language const *> & languages) const
2840 {
2841         ParConstIterator end = par_iterator_end();
2842         // add the buffer language, even if it's not actively used
2843         languages.insert(language());
2844         // iterate over the paragraphs
2845         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2846                 it->getLanguages(languages);
2847         // also children
2848         ListOfBuffers clist = getDescendents();
2849         ListOfBuffers::const_iterator cit = clist.begin();
2850         ListOfBuffers::const_iterator const cen = clist.end();
2851         for (; cit != cen; ++cit)
2852                 (*cit)->getLanguages(languages);
2853 }
2854
2855
2856 DocIterator Buffer::getParFromID(int const id) const
2857 {
2858         Buffer * buf = const_cast<Buffer *>(this);
2859         if (id < 0) {
2860                 // John says this is called with id == -1 from undo
2861                 lyxerr << "getParFromID(), id: " << id << endl;
2862                 return doc_iterator_end(buf);
2863         }
2864
2865         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2866                 if (it.paragraph().id() == id)
2867                         return it;
2868
2869         return doc_iterator_end(buf);
2870 }
2871
2872
2873 bool Buffer::hasParWithID(int const id) const
2874 {
2875         return !getParFromID(id).atEnd();
2876 }
2877
2878
2879 ParIterator Buffer::par_iterator_begin()
2880 {
2881         return ParIterator(doc_iterator_begin(this));
2882 }
2883
2884
2885 ParIterator Buffer::par_iterator_end()
2886 {
2887         return ParIterator(doc_iterator_end(this));
2888 }
2889
2890
2891 ParConstIterator Buffer::par_iterator_begin() const
2892 {
2893         return ParConstIterator(doc_iterator_begin(this));
2894 }
2895
2896
2897 ParConstIterator Buffer::par_iterator_end() const
2898 {
2899         return ParConstIterator(doc_iterator_end(this));
2900 }
2901
2902
2903 Language const * Buffer::language() const
2904 {
2905         return params().language;
2906 }
2907
2908
2909 docstring const Buffer::B_(string const & l10n) const
2910 {
2911         return params().B_(l10n);
2912 }
2913
2914
2915 bool Buffer::isClean() const
2916 {
2917         return d->lyx_clean;
2918 }
2919
2920
2921 bool Buffer::isExternallyModified(CheckMethod method) const
2922 {
2923         LASSERT(d->filename.exists(), return false);
2924         // if method == timestamp, check timestamp before checksum
2925         return (method == checksum_method
2926                 || d->timestamp_ != d->filename.lastModified())
2927                 && d->checksum_ != d->filename.checksum();
2928 }
2929
2930
2931 void Buffer::saveCheckSum() const
2932 {
2933         FileName const & file = d->filename;
2934
2935         file.refresh();
2936         if (file.exists()) {
2937                 d->timestamp_ = file.lastModified();
2938                 d->checksum_ = file.checksum();
2939         } else {
2940                 // in the case of save to a new file.
2941                 d->timestamp_ = 0;
2942                 d->checksum_ = 0;
2943         }
2944 }
2945
2946
2947 void Buffer::markClean() const
2948 {
2949         if (!d->lyx_clean) {
2950                 d->lyx_clean = true;
2951                 updateTitles();
2952         }
2953         // if the .lyx file has been saved, we don't need an
2954         // autosave
2955         d->bak_clean = true;
2956         d->undo_.markDirty();
2957 }
2958
2959
2960 void Buffer::setUnnamed(bool flag)
2961 {
2962         d->unnamed = flag;
2963 }
2964
2965
2966 bool Buffer::isUnnamed() const
2967 {
2968         return d->unnamed;
2969 }
2970
2971
2972 /// \note
2973 /// Don't check unnamed, here: isInternal() is used in
2974 /// newBuffer(), where the unnamed flag has not been set by anyone
2975 /// yet. Also, for an internal buffer, there should be no need for
2976 /// retrieving fileName() nor for checking if it is unnamed or not.
2977 bool Buffer::isInternal() const
2978 {
2979         return d->internal_buffer;
2980 }
2981
2982
2983 void Buffer::setInternal(bool flag)
2984 {
2985         d->internal_buffer = flag;
2986 }
2987
2988
2989 void Buffer::markDirty()
2990 {
2991         if (d->lyx_clean) {
2992                 d->lyx_clean = false;
2993                 updateTitles();
2994         }
2995         d->bak_clean = false;
2996
2997         DepClean::iterator it = d->dep_clean.begin();
2998         DepClean::const_iterator const end = d->dep_clean.end();
2999
3000         for (; it != end; ++it)
3001                 it->second = false;
3002 }
3003
3004
3005 FileName Buffer::fileName() const
3006 {
3007         return d->filename;
3008 }
3009
3010
3011 string Buffer::absFileName() const
3012 {
3013         return d->filename.absFileName();
3014 }
3015
3016
3017 string Buffer::filePath() const
3018 {
3019         string const abs = d->filename.onlyPath().absFileName();
3020         if (abs.empty())
3021                 return abs;
3022         int last = abs.length() - 1;
3023
3024         return abs[last] == '/' ? abs : abs + '/';
3025 }
3026
3027
3028 string Buffer::originFilePath() const
3029 {
3030         if (FileName::isAbsolute(params().origin))
3031                 return params().origin;
3032
3033         return filePath();
3034 }
3035
3036
3037 string Buffer::layoutPos() const
3038 {
3039         return d->layout_position;
3040 }
3041
3042
3043 void Buffer::setLayoutPos(string const & path)
3044 {
3045         if (path.empty()) {
3046                 d->layout_position.clear();
3047                 return;
3048         }
3049
3050         LATTEST(FileName::isAbsolute(path));
3051
3052         d->layout_position =
3053                 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3054
3055         if (d->layout_position.empty())
3056                 d->layout_position = ".";
3057 }
3058
3059
3060 bool Buffer::isReadonly() const
3061 {
3062         return d->read_only;
3063 }
3064
3065
3066 void Buffer::setParent(Buffer const * buffer)
3067 {
3068         // Avoids recursive include.
3069         d->setParent(buffer == this ? 0 : buffer);
3070         updateMacros();
3071 }
3072
3073
3074 Buffer const * Buffer::parent() const
3075 {
3076         return d->parent();
3077 }
3078
3079
3080 ListOfBuffers Buffer::allRelatives() const
3081 {
3082         ListOfBuffers lb = masterBuffer()->getDescendents();
3083         lb.push_front(const_cast<Buffer *>(masterBuffer()));
3084         return lb;
3085 }
3086
3087
3088 Buffer const * Buffer::masterBuffer() const
3089 {
3090         // FIXME Should be make sure we are not in some kind
3091         // of recursive include? A -> B -> A will crash this.
3092         Buffer const * const pbuf = d->parent();
3093         if (!pbuf)
3094                 return this;
3095
3096         return pbuf->masterBuffer();
3097 }
3098
3099
3100 bool Buffer::isChild(Buffer * child) const
3101 {
3102         return d->children_positions.find(child) != d->children_positions.end();
3103 }
3104
3105
3106 DocIterator Buffer::firstChildPosition(Buffer const * child)
3107 {
3108         Impl::BufferPositionMap::iterator it;
3109         it = d->children_positions.find(child);
3110         if (it == d->children_positions.end())
3111                 return DocIterator(this);
3112         return it->second;
3113 }
3114
3115
3116 bool Buffer::hasChildren() const
3117 {
3118         return !d->children_positions.empty();
3119 }
3120
3121
3122 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3123 {
3124         // loop over children
3125         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3126         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3127         for (; it != end; ++it) {
3128                 Buffer * child = const_cast<Buffer *>(it->first);
3129                 // No duplicates
3130                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3131                 if (bit != clist.end())
3132                         continue;
3133                 clist.push_back(child);
3134                 if (grand_children)
3135                         // there might be grandchildren
3136                         child->collectChildren(clist, true);
3137         }
3138 }
3139
3140
3141 ListOfBuffers Buffer::getChildren() const
3142 {
3143         ListOfBuffers v;
3144         collectChildren(v, false);
3145         // Make sure we have not included ourselves.
3146         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3147         if (bit != v.end()) {
3148                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3149                 v.erase(bit);
3150         }
3151         return v;
3152 }
3153
3154
3155 ListOfBuffers Buffer::getDescendents() const
3156 {
3157         ListOfBuffers v;
3158         collectChildren(v, true);
3159         // Make sure we have not included ourselves.
3160         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3161         if (bit != v.end()) {
3162                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3163                 v.erase(bit);
3164         }
3165         return v;
3166 }
3167
3168
3169 template<typename M>
3170 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3171 {
3172         if (m.empty())
3173                 return m.end();
3174
3175         typename M::const_iterator it = m.lower_bound(x);
3176         if (it == m.begin())
3177                 return m.end();
3178
3179         it--;
3180         return it;
3181 }
3182
3183
3184 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3185                                          DocIterator const & pos) const
3186 {
3187         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3188
3189         // if paragraphs have no macro context set, pos will be empty
3190         if (pos.empty())
3191                 return 0;
3192
3193         // we haven't found anything yet
3194         DocIterator bestPos = owner_->par_iterator_begin();
3195         MacroData const * bestData = 0;
3196
3197         // find macro definitions for name
3198         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3199         if (nameIt != macros.end()) {
3200                 // find last definition in front of pos or at pos itself
3201                 PositionScopeMacroMap::const_iterator it
3202                         = greatest_below(nameIt->second, pos);
3203                 if (it != nameIt->second.end()) {
3204                         while (true) {
3205                                 // scope ends behind pos?
3206                                 if (pos < it->second.scope) {
3207                                         // Looks good, remember this. If there
3208                                         // is no external macro behind this,
3209                                         // we found the right one already.
3210                                         bestPos = it->first;
3211                                         bestData = &it->second.macro;
3212                                         break;
3213                                 }
3214
3215                                 // try previous macro if there is one
3216                                 if (it == nameIt->second.begin())
3217                                         break;
3218                                 --it;
3219                         }
3220                 }
3221         }
3222
3223         // find macros in included files
3224         PositionScopeBufferMap::const_iterator it
3225                 = greatest_below(position_to_children, pos);
3226         if (it == position_to_children.end())
3227                 // no children before
3228                 return bestData;
3229
3230         while (true) {
3231                 // do we know something better (i.e. later) already?
3232                 if (it->first < bestPos )
3233                         break;
3234
3235                 // scope ends behind pos?
3236                 if (pos < it->second.scope
3237                         && (cloned_buffer_ ||
3238                             theBufferList().isLoaded(it->second.buffer))) {
3239                         // look for macro in external file
3240                         macro_lock = true;
3241                         MacroData const * data
3242                                 = it->second.buffer->getMacro(name, false);
3243                         macro_lock = false;
3244                         if (data) {
3245                                 bestPos = it->first;
3246                                 bestData = data;
3247                                 break;
3248                         }
3249                 }
3250
3251                 // try previous file if there is one
3252                 if (it == position_to_children.begin())
3253                         break;
3254                 --it;
3255         }
3256
3257         // return the best macro we have found
3258         return bestData;
3259 }
3260
3261
3262 MacroData const * Buffer::getMacro(docstring const & name,
3263         DocIterator const & pos, bool global) const
3264 {
3265         if (d->macro_lock)
3266                 return 0;
3267
3268         // query buffer macros
3269         MacroData const * data = d->getBufferMacro(name, pos);
3270         if (data != 0)
3271                 return data;
3272
3273         // If there is a master buffer, query that
3274         Buffer const * const pbuf = d->parent();
3275         if (pbuf) {
3276                 d->macro_lock = true;
3277                 MacroData const * macro = pbuf->getMacro(
3278                         name, *this, false);
3279                 d->macro_lock = false;
3280                 if (macro)
3281                         return macro;
3282         }
3283
3284         if (global) {
3285                 data = MacroTable::globalMacros().get(name);
3286                 if (data != 0)
3287                         return data;
3288         }
3289
3290         return 0;
3291 }
3292
3293
3294 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3295 {
3296         // set scope end behind the last paragraph
3297         DocIterator scope = par_iterator_begin();
3298         scope.pit() = scope.lastpit() + 1;
3299
3300         return getMacro(name, scope, global);
3301 }
3302
3303
3304 MacroData const * Buffer::getMacro(docstring const & name,
3305         Buffer const & child, bool global) const
3306 {
3307         // look where the child buffer is included first
3308         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3309         if (it == d->children_positions.end())
3310                 return 0;
3311
3312         // check for macros at the inclusion position
3313         return getMacro(name, it->second, global);
3314 }
3315
3316
3317 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3318 {
3319         pit_type const lastpit = it.lastpit();
3320
3321         // look for macros in each paragraph
3322         while (it.pit() <= lastpit) {
3323                 Paragraph & par = it.paragraph();
3324
3325                 // iterate over the insets of the current paragraph
3326                 InsetList const & insets = par.insetList();
3327                 InsetList::const_iterator iit = insets.begin();
3328                 InsetList::const_iterator end = insets.end();
3329                 for (; iit != end; ++iit) {
3330                         it.pos() = iit->pos;
3331
3332                         // is it a nested text inset?
3333                         if (iit->inset->asInsetText()) {
3334                                 // Inset needs its own scope?
3335                                 InsetText const * itext = iit->inset->asInsetText();
3336                                 bool newScope = itext->isMacroScope();
3337
3338                                 // scope which ends just behind the inset
3339                                 DocIterator insetScope = it;
3340                                 ++insetScope.pos();
3341
3342                                 // collect macros in inset
3343                                 it.push_back(CursorSlice(*iit->inset));
3344                                 updateMacros(it, newScope ? insetScope : scope);
3345                                 it.pop_back();
3346                                 continue;
3347                         }
3348
3349                         if (iit->inset->asInsetTabular()) {
3350                                 CursorSlice slice(*iit->inset);
3351                                 size_t const numcells = slice.nargs();
3352                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3353                                         it.push_back(slice);
3354                                         updateMacros(it, scope);
3355                                         it.pop_back();
3356                                 }
3357                                 continue;
3358                         }
3359
3360                         // is it an external file?
3361                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3362                                 // get buffer of external file
3363                                 InsetInclude const & inset =
3364                                         static_cast<InsetInclude const &>(*iit->inset);
3365                                 macro_lock = true;
3366                                 Buffer * child = inset.getChildBuffer();
3367                                 macro_lock = false;
3368                                 if (!child)
3369                                         continue;
3370
3371                                 // register its position, but only when it is
3372                                 // included first in the buffer
3373                                 if (children_positions.find(child) ==
3374                                         children_positions.end())
3375                                                 children_positions[child] = it;
3376
3377                                 // register child with its scope
3378                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3379                                 continue;
3380                         }
3381
3382                         InsetMath * im = iit->inset->asInsetMath();
3383                         if (doing_export && im)  {
3384                                 InsetMathHull * hull = im->asHullInset();
3385                                 if (hull)
3386                                         hull->recordLocation(it);
3387                         }
3388
3389                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3390                                 continue;
3391
3392                         // get macro data
3393                         MathMacroTemplate & macroTemplate =
3394                                 *iit->inset->asInsetMath()->asMacroTemplate();
3395                         MacroContext mc(owner_, it);
3396                         macroTemplate.updateToContext(mc);
3397
3398                         // valid?
3399                         bool valid = macroTemplate.validMacro();
3400                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3401                         // then the BufferView's cursor will be invalid in
3402                         // some cases which leads to crashes.
3403                         if (!valid)
3404                                 continue;
3405
3406                         // register macro
3407                         // FIXME (Abdel), I don't understand why we pass 'it' here
3408                         // instead of 'macroTemplate' defined above... is this correct?
3409                         macros[macroTemplate.name()][it] =
3410                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3411                 }
3412
3413                 // next paragraph
3414                 it.pit()++;
3415                 it.pos() = 0;
3416         }
3417 }
3418
3419
3420 void Buffer::updateMacros() const
3421 {
3422         if (d->macro_lock)
3423                 return;
3424
3425         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3426
3427         // start with empty table
3428         d->macros.clear();
3429         d->children_positions.clear();
3430         d->position_to_children.clear();
3431
3432         // Iterate over buffer, starting with first paragraph
3433         // The scope must be bigger than any lookup DocIterator
3434         // later. For the global lookup, lastpit+1 is used, hence
3435         // we use lastpit+2 here.
3436         DocIterator it = par_iterator_begin();
3437         DocIterator outerScope = it;
3438         outerScope.pit() = outerScope.lastpit() + 2;
3439         d->updateMacros(it, outerScope);
3440 }
3441
3442
3443 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3444 {
3445         InsetIterator it  = inset_iterator_begin(inset());
3446         InsetIterator const end = inset_iterator_end(inset());
3447         for (; it != end; ++it) {
3448                 if (it->lyxCode() == BRANCH_CODE) {
3449                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3450                         docstring const name = br.branch();
3451                         if (!from_master && !params().branchlist().find(name))
3452                                 result.push_back(name);
3453                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3454                                 result.push_back(name);
3455                         continue;
3456                 }
3457                 if (it->lyxCode() == INCLUDE_CODE) {
3458                         // get buffer of external file
3459                         InsetInclude const & ins =
3460                                 static_cast<InsetInclude const &>(*it);
3461                         Buffer * child = ins.getChildBuffer();
3462                         if (!child)
3463                                 continue;
3464                         child->getUsedBranches(result, true);
3465                 }
3466         }
3467         // remove duplicates
3468         result.unique();
3469 }
3470
3471
3472 void Buffer::updateMacroInstances(UpdateType utype) const
3473 {
3474         LYXERR(Debug::MACROS, "updateMacroInstances for "
3475                 << d->filename.onlyFileName());
3476         DocIterator it = doc_iterator_begin(this);
3477         it.forwardInset();
3478         DocIterator const end = doc_iterator_end(this);
3479         for (; it != end; it.forwardInset()) {
3480                 // look for MathData cells in InsetMathNest insets
3481                 InsetMath * minset = it.nextInset()->asInsetMath();
3482                 if (!minset)
3483                         continue;
3484
3485                 // update macro in all cells of the InsetMathNest
3486                 DocIterator::idx_type n = minset->nargs();
3487                 MacroContext mc = MacroContext(this, it);
3488                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3489                         MathData & data = minset->cell(i);
3490                         data.updateMacros(0, mc, utype);
3491                 }
3492         }
3493 }
3494
3495
3496 void Buffer::listMacroNames(MacroNameSet & macros) const
3497 {
3498         if (d->macro_lock)
3499                 return;
3500
3501         d->macro_lock = true;
3502
3503         // loop over macro names
3504         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3505         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3506         for (; nameIt != nameEnd; ++nameIt)
3507                 macros.insert(nameIt->first);
3508
3509         // loop over children
3510         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3511         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3512         for (; it != end; ++it)
3513                 it->first->listMacroNames(macros);
3514
3515         // call parent
3516         Buffer const * const pbuf = d->parent();
3517         if (pbuf)
3518                 pbuf->listMacroNames(macros);
3519
3520         d->macro_lock = false;
3521 }
3522
3523
3524 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3525 {
3526         Buffer const * const pbuf = d->parent();
3527         if (!pbuf)
3528                 return;
3529
3530         MacroNameSet names;
3531         pbuf->listMacroNames(names);
3532
3533         // resolve macros
3534         MacroNameSet::iterator it = names.begin();
3535         MacroNameSet::iterator end = names.end();
3536         for (; it != end; ++it) {
3537                 // defined?
3538                 MacroData const * data =
3539                 pbuf->getMacro(*it, *this, false);
3540                 if (data) {
3541                         macros.insert(data);
3542
3543                         // we cannot access the original MathMacroTemplate anymore
3544                         // here to calls validate method. So we do its work here manually.
3545                         // FIXME: somehow make the template accessible here.
3546                         if (data->optionals() > 0)
3547                                 features.require("xargs");
3548                 }
3549         }
3550 }
3551
3552
3553 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3554 {
3555         if (d->parent())
3556                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3557
3558         RefCache::iterator it = d->ref_cache_.find(label);
3559         if (it != d->ref_cache_.end())
3560                 return it->second.second;
3561
3562         static InsetLabel const * dummy_il = 0;
3563         static References const dummy_refs = References();
3564         it = d->ref_cache_.insert(
3565                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3566         return it->second.second;
3567 }
3568
3569
3570 Buffer::References const & Buffer::references(docstring const & label) const
3571 {
3572         return const_cast<Buffer *>(this)->getReferenceCache(label);
3573 }
3574
3575
3576 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3577 {
3578         References & refs = getReferenceCache(label);
3579         refs.push_back(make_pair(inset, it));
3580 }
3581
3582
3583 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3584 {
3585         masterBuffer()->d->ref_cache_[label].first = il;
3586 }
3587
3588
3589 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3590 {
3591         return masterBuffer()->d->ref_cache_[label].first;
3592 }
3593
3594
3595 void Buffer::clearReferenceCache() const
3596 {
3597         if (!d->parent())
3598                 d->ref_cache_.clear();
3599 }
3600
3601
3602 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3603 {
3604         //FIXME: This does not work for child documents yet.
3605         reloadBibInfoCache();
3606
3607         // Check if the label 'from' appears more than once
3608         BiblioInfo const & keys = masterBibInfo();
3609         BiblioInfo::const_iterator bit  = keys.begin();
3610         BiblioInfo::const_iterator bend = keys.end();
3611         vector<docstring> labels;
3612
3613         for (; bit != bend; ++bit)
3614                 // FIXME UNICODE
3615                 labels.push_back(bit->first);
3616
3617         if (count(labels.begin(), labels.end(), from) > 1)
3618                 return;
3619
3620         string const paramName = "key";
3621         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3622                 if (it->lyxCode() != CITE_CODE)
3623                         continue;
3624                 InsetCommand * inset = it->asInsetCommand();
3625                 docstring const oldValue = inset->getParam(paramName);
3626                 if (oldValue == from)
3627                         inset->setParam(paramName, to);
3628         }
3629 }
3630
3631 // returns NULL if id-to-row conversion is unsupported
3632 auto_ptr<TexRow> Buffer::getSourceCode(odocstream & os, string const & format,
3633                            pit_type par_begin, pit_type par_end,
3634                            OutputWhat output, bool master) const
3635 {
3636         auto_ptr<TexRow> texrow(NULL);
3637         OutputParams runparams(&params().encoding());
3638         runparams.nice = true;
3639         runparams.flavor = params().getOutputFlavor(format);
3640         runparams.linelen = lyxrc.plaintext_linelen;
3641         // No side effect of file copying and image conversion
3642         runparams.dryrun = true;
3643
3644         if (output == CurrentParagraph) {
3645                 runparams.par_begin = par_begin;
3646                 runparams.par_end = par_end;
3647                 if (par_begin + 1 == par_end) {
3648                         os << "% "
3649                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3650                            << "\n\n";
3651                 } else {
3652                         os << "% "
3653                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3654                                         convert<docstring>(par_begin),
3655                                         convert<docstring>(par_end - 1))
3656                            << "\n\n";
3657                 }
3658                 // output paragraphs
3659                 if (runparams.flavor == OutputParams::LYX) {
3660                         Paragraph const & par = text().paragraphs()[par_begin];
3661                         ostringstream ods;
3662                         depth_type dt = par.getDepth();
3663                         par.write(ods, params(), dt);
3664                         os << from_utf8(ods.str());
3665                 } else if (runparams.flavor == OutputParams::HTML) {
3666                         XHTMLStream xs(os);
3667                         setMathFlavor(runparams);
3668                         xhtmlParagraphs(text(), *this, xs, runparams);
3669                 } else if (runparams.flavor == OutputParams::TEXT) {
3670                         bool dummy = false;
3671                         // FIXME Handles only one paragraph, unlike the others.
3672                         // Probably should have some routine with a signature like them.
3673                         writePlaintextParagraph(*this,
3674                                 text().paragraphs()[par_begin], os, runparams, dummy);
3675                 } else if (params().isDocBook()) {
3676                         docbookParagraphs(text(), *this, os, runparams);
3677                 } else {
3678                         // If we are previewing a paragraph, even if this is the
3679                         // child of some other buffer, let's cut the link here,
3680                         // so that no concurring settings from the master
3681                         // (e.g. branch state) interfere (see #8101).
3682                         if (!master)
3683                                 d->ignore_parent = true;
3684                         // We need to validate the Buffer params' features here
3685                         // in order to know if we should output polyglossia
3686                         // macros (instead of babel macros)
3687                         LaTeXFeatures features(*this, params(), runparams);
3688                         params().validate(features);
3689                         runparams.use_polyglossia = features.usePolyglossia();
3690                         texrow.reset(new TexRow());
3691                         texrow->newline();
3692                         texrow->newline();
3693                         // latex or literate
3694                         otexstream ots(os, *texrow);
3695
3696                         // the real stuff
3697                         latexParagraphs(*this, text(), ots, runparams);
3698                         texrow->finalize();
3699
3700                         // Restore the parenthood
3701                         if (!master)
3702                                 d->ignore_parent = false;
3703                 }
3704         } else {
3705                 os << "% ";
3706                 if (output == FullSource)
3707                         os << _("Preview source code");
3708                 else if (output == OnlyPreamble)
3709                         os << _("Preview preamble");
3710                 else if (output == OnlyBody)
3711                         os << _("Preview body");
3712                 os << "\n\n";
3713                 if (runparams.flavor == OutputParams::LYX) {
3714                         ostringstream ods;
3715                         if (output == FullSource)
3716                                 write(ods);
3717                         else if (output == OnlyPreamble)
3718                                 params().writeFile(ods, this);
3719                         else if (output == OnlyBody)
3720                                 text().write(ods);
3721                         os << from_utf8(ods.str());
3722                 } else if (runparams.flavor == OutputParams::HTML) {
3723                         writeLyXHTMLSource(os, runparams, output);
3724                 } else if (runparams.flavor == OutputParams::TEXT) {
3725                         if (output == OnlyPreamble) {
3726                                 os << "% "<< _("Plain text does not have a preamble.");
3727                         } else
3728                                 writePlaintextFile(*this, os, runparams);
3729                 } else if (params().isDocBook()) {
3730                                 writeDocBookSource(os, absFileName(), runparams, output);
3731                 } else {
3732                         // latex or literate
3733                         texrow.reset(new TexRow());
3734                         texrow->newline();
3735                         texrow->newline();
3736                         otexstream ots(os, *texrow);
3737                         if (master)
3738                                 runparams.is_child = true;
3739                         writeLaTeXSource(ots, string(), runparams, output);
3740                         texrow->finalize();
3741                 }
3742         }
3743         return texrow;
3744 }
3745
3746
3747 ErrorList & Buffer::errorList(string const & type) const
3748 {
3749         return d->errorLists[type];
3750 }
3751
3752
3753 void Buffer::updateTocItem(std::string const & type,
3754         DocIterator const & dit) const
3755 {
3756         if (d->gui_)
3757                 d->gui_->updateTocItem(type, dit);
3758 }
3759
3760
3761 void Buffer::structureChanged() const
3762 {
3763         if (d->gui_)
3764                 d->gui_->structureChanged();
3765 }
3766
3767
3768 void Buffer::errors(string const & err, bool from_master) const
3769 {
3770         if (d->gui_)
3771                 d->gui_->errors(err, from_master);
3772 }
3773
3774
3775 void Buffer::message(docstring const & msg) const
3776 {
3777         if (d->gui_)
3778                 d->gui_->message(msg);
3779 }
3780
3781
3782 void Buffer::setBusy(bool on) const
3783 {
3784         if (d->gui_)
3785                 d->gui_->setBusy(on);
3786 }
3787
3788
3789 void Buffer::updateTitles() const
3790 {
3791         if (d->wa_)
3792                 d->wa_->updateTitles();
3793 }
3794
3795
3796 void Buffer::resetAutosaveTimers() const
3797 {
3798         if (d->gui_)
3799                 d->gui_->resetAutosaveTimers();
3800 }
3801
3802
3803 bool Buffer::hasGuiDelegate() const
3804 {
3805         return d->gui_;
3806 }
3807
3808
3809 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3810 {
3811         d->gui_ = gui;
3812 }
3813
3814
3815
3816 namespace {
3817
3818 class AutoSaveBuffer : public ForkedProcess {
3819 public:
3820         ///
3821         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3822                 : buffer_(buffer), fname_(fname) {}
3823         ///
3824         virtual shared_ptr<ForkedProcess> clone() const
3825         {
3826                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3827         }
3828         ///
3829         int start()
3830         {
3831                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3832                                                  from_utf8(fname_.absFileName())));
3833                 return run(DontWait);
3834         }
3835 private:
3836         ///
3837         virtual int generateChild();
3838         ///
3839         Buffer const & buffer_;
3840         FileName fname_;
3841 };
3842
3843
3844 int AutoSaveBuffer::generateChild()
3845 {
3846 #if defined(__APPLE__)
3847         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3848          *   We should use something else like threads.
3849          *
3850          * Since I do not know how to determine at run time what is the OS X
3851          * version, I just disable forking altogether for now (JMarc)
3852          */
3853         pid_t const pid = -1;
3854 #else
3855         // tmp_ret will be located (usually) in /tmp
3856         // will that be a problem?
3857         // Note that this calls ForkedCalls::fork(), so it's
3858         // ok cross-platform.
3859         pid_t const pid = fork();
3860         // If you want to debug the autosave
3861         // you should set pid to -1, and comment out the fork.
3862         if (pid != 0 && pid != -1)
3863                 return pid;
3864 #endif
3865
3866         // pid = -1 signifies that lyx was unable
3867         // to fork. But we will do the save
3868         // anyway.
3869         bool failed = false;
3870         TempFile tempfile("lyxautoXXXXXX.lyx");
3871         tempfile.setAutoRemove(false);
3872         FileName const tmp_ret = tempfile.name();
3873         if (!tmp_ret.empty()) {
3874                 if (!buffer_.writeFile(tmp_ret))
3875                         failed = true;
3876                 else if (!tmp_ret.moveTo(fname_))
3877                         failed = true;
3878         } else
3879                 failed = true;
3880
3881         if (failed) {
3882                 // failed to write/rename tmp_ret so try writing direct
3883                 if (!buffer_.writeFile(fname_)) {
3884                         // It is dangerous to do this in the child,
3885                         // but safe in the parent, so...
3886                         if (pid == -1) // emit message signal.
3887                                 buffer_.message(_("Autosave failed!"));
3888                 }
3889         }
3890
3891         if (pid == 0) // we are the child so...
3892                 _exit(0);
3893
3894         return pid;
3895 }
3896
3897 } // namespace anon
3898
3899
3900 FileName Buffer::getEmergencyFileName() const
3901 {
3902         return FileName(d->filename.absFileName() + ".emergency");
3903 }
3904
3905
3906 FileName Buffer::getAutosaveFileName() const
3907 {
3908         // if the document is unnamed try to save in the backup dir, else
3909         // in the default document path, and as a last try in the filePath,
3910         // which will most often be the temporary directory
3911         string fpath;
3912         if (isUnnamed())
3913                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3914                         : lyxrc.backupdir_path;
3915         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3916                 fpath = filePath();
3917
3918         string const fname = "#" + d->filename.onlyFileName() + "#";
3919
3920         return makeAbsPath(fname, fpath);
3921 }
3922
3923
3924 void Buffer::removeAutosaveFile() const
3925 {
3926         FileName const f = getAutosaveFileName();
3927         if (f.exists())
3928                 f.removeFile();
3929 }
3930
3931
3932 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3933 {
3934         FileName const newauto = getAutosaveFileName();
3935         oldauto.refresh();
3936         if (newauto != oldauto && oldauto.exists())
3937                 if (!oldauto.moveTo(newauto))
3938                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3939 }
3940
3941
3942 bool Buffer::autoSave() const
3943 {
3944         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3945         if (buf->d->bak_clean || isReadonly())
3946                 return true;
3947
3948         message(_("Autosaving current document..."));
3949         buf->d->bak_clean = true;
3950
3951         FileName const fname = getAutosaveFileName();
3952         LASSERT(d->cloned_buffer_, return false);
3953
3954         // If this buffer is cloned, we assume that
3955         // we are running in a separate thread already.
3956         TempFile tempfile("lyxautoXXXXXX.lyx");
3957         tempfile.setAutoRemove(false);
3958         FileName const tmp_ret = tempfile.name();
3959         if (!tmp_ret.empty()) {
3960                 writeFile(tmp_ret);
3961                 // assume successful write of tmp_ret
3962                 if (tmp_ret.moveTo(fname))
3963                         return true;
3964         }
3965         // failed to write/rename tmp_ret so try writing direct
3966         return writeFile(fname);
3967 }
3968
3969
3970 void Buffer::setExportStatus(bool e) const
3971 {
3972         d->doing_export = e;
3973         ListOfBuffers clist = getDescendents();
3974         ListOfBuffers::const_iterator cit = clist.begin();
3975         ListOfBuffers::const_iterator const cen = clist.end();
3976         for (; cit != cen; ++cit)
3977                 (*cit)->d->doing_export = e;
3978 }
3979
3980
3981 bool Buffer::isExporting() const
3982 {
3983         return d->doing_export;
3984 }
3985
3986
3987 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3988         const
3989 {
3990         string result_file;
3991         return doExport(target, put_in_tempdir, result_file);
3992 }
3993
3994 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
3995         string & result_file) const
3996 {
3997         bool const update_unincluded =
3998                         params().maintain_unincluded_children
3999                         && !params().getIncludedChildren().empty();
4000
4001         // (1) export with all included children (omit \includeonly)
4002         if (update_unincluded) {
4003                 ExportStatus const status =
4004                         doExport(target, put_in_tempdir, true, result_file);
4005                 if (status != ExportSuccess)
4006                         return status;
4007         }
4008         // (2) export with included children only
4009         return doExport(target, put_in_tempdir, false, result_file);
4010 }
4011
4012
4013 void Buffer::setMathFlavor(OutputParams & op) const
4014 {
4015         switch (params().html_math_output) {
4016         case BufferParams::MathML:
4017                 op.math_flavor = OutputParams::MathAsMathML;
4018                 break;
4019         case BufferParams::HTML:
4020                 op.math_flavor = OutputParams::MathAsHTML;
4021                 break;
4022         case BufferParams::Images:
4023                 op.math_flavor = OutputParams::MathAsImages;
4024                 break;
4025         case BufferParams::LaTeX:
4026                 op.math_flavor = OutputParams::MathAsLaTeX;
4027                 break;
4028         }
4029 }
4030
4031
4032 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4033         bool includeall, string & result_file) const
4034 {
4035         LYXERR(Debug::FILES, "target=" << target);
4036         OutputParams runparams(&params().encoding());
4037         string format = target;
4038         string dest_filename;
4039         size_t pos = target.find(' ');
4040         if (pos != string::npos) {
4041                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4042                 format = target.substr(0, pos);
4043                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4044                 FileName(dest_filename).onlyPath().createPath();
4045                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4046         }
4047         MarkAsExporting exporting(this);
4048         string backend_format;
4049         runparams.flavor = OutputParams::LATEX;
4050         runparams.linelen = lyxrc.plaintext_linelen;
4051         runparams.includeall = includeall;
4052         vector<string> backs = params().backends();
4053         Converters converters = theConverters();
4054         bool need_nice_file = false;
4055         if (find(backs.begin(), backs.end(), format) == backs.end()) {
4056                 // Get shortest path to format
4057                 converters.buildGraph();
4058                 Graph::EdgePath path;
4059                 for (vector<string>::const_iterator it = backs.begin();
4060                      it != backs.end(); ++it) {
4061                         Graph::EdgePath p = converters.getPath(*it, format);
4062                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
4063                                 backend_format = *it;
4064                                 path = p;
4065                         }
4066                 }
4067                 if (path.empty()) {
4068                         if (!put_in_tempdir) {
4069                                 // Only show this alert if this is an export to a non-temporary
4070                                 // file (not for previewing).
4071                                 Alert::error(_("Couldn't export file"), bformat(
4072                                         _("No information for exporting the format %1$s."),
4073                                         formats.prettyName(format)));
4074                         }
4075                         return ExportNoPathToFormat;
4076                 }
4077                 runparams.flavor = converters.getFlavor(path, this);
4078                 Graph::EdgePath::const_iterator it = path.begin();
4079                 Graph::EdgePath::const_iterator en = path.end();
4080                 for (; it != en; ++it)
4081                         if (theConverters().get(*it).nice()) {
4082                                 need_nice_file = true;
4083                                 break;
4084                         }
4085
4086         } else {
4087                 backend_format = format;
4088                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4089                 // FIXME: Don't hardcode format names here, but use a flag
4090                 if (backend_format == "pdflatex")
4091                         runparams.flavor = OutputParams::PDFLATEX;
4092                 else if (backend_format == "luatex")
4093                         runparams.flavor = OutputParams::LUATEX;
4094                 else if (backend_format == "dviluatex")
4095                         runparams.flavor = OutputParams::DVILUATEX;
4096                 else if (backend_format == "xetex")
4097                         runparams.flavor = OutputParams::XETEX;
4098         }
4099
4100         string filename = latexName(false);
4101         filename = addName(temppath(), filename);
4102         filename = changeExtension(filename,
4103                                    formats.extension(backend_format));
4104         LYXERR(Debug::FILES, "filename=" << filename);
4105
4106         // Plain text backend
4107         if (backend_format == "text") {
4108                 runparams.flavor = OutputParams::TEXT;
4109                 writePlaintextFile(*this, FileName(filename), runparams);
4110         }
4111         // HTML backend
4112         else if (backend_format == "xhtml") {
4113                 runparams.flavor = OutputParams::HTML;
4114                 setMathFlavor(runparams);
4115                 makeLyXHTMLFile(FileName(filename), runparams);
4116         } else if (backend_format == "lyx")
4117                 writeFile(FileName(filename));
4118         // Docbook backend
4119         else if (params().isDocBook()) {
4120                 runparams.nice = !put_in_tempdir;
4121                 makeDocBookFile(FileName(filename), runparams);
4122         }
4123         // LaTeX backend
4124         else if (backend_format == format || need_nice_file) {
4125                 runparams.nice = true;
4126                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4127                 if (d->cloned_buffer_)
4128                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4129                 if (!success)
4130                         return ExportError;
4131         } else if (!lyxrc.tex_allows_spaces
4132                    && contains(filePath(), ' ')) {
4133                 Alert::error(_("File name error"),
4134                            _("The directory path to the document cannot contain spaces."));
4135                 return ExportTexPathHasSpaces;
4136         } else {
4137                 runparams.nice = false;
4138                 bool const success = makeLaTeXFile(
4139                         FileName(filename), filePath(), runparams);
4140                 if (d->cloned_buffer_)
4141                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4142                 if (!success)
4143                         return ExportError;
4144         }
4145
4146         string const error_type = (format == "program")
4147                 ? "Build" : params().bufferFormat();
4148         ErrorList & error_list = d->errorLists[error_type];
4149         string const ext = formats.extension(format);
4150         FileName const tmp_result_file(changeExtension(filename, ext));
4151         bool const success = converters.convert(this, FileName(filename),
4152                 tmp_result_file, FileName(absFileName()), backend_format, format,
4153                 error_list);
4154
4155         // Emit the signal to show the error list or copy it back to the
4156         // cloned Buffer so that it can be emitted afterwards.
4157         if (format != backend_format) {
4158                 if (runparams.silent)
4159                         error_list.clear();
4160                 else if (d->cloned_buffer_)
4161                         d->cloned_buffer_->d->errorLists[error_type] =
4162                                 d->errorLists[error_type];
4163                 else
4164                         errors(error_type);
4165                 // also to the children, in case of master-buffer-view
4166                 ListOfBuffers clist = getDescendents();
4167                 ListOfBuffers::const_iterator cit = clist.begin();
4168                 ListOfBuffers::const_iterator const cen = clist.end();
4169                 for (; cit != cen; ++cit) {
4170                         if (runparams.silent)
4171                                 (*cit)->d->errorLists[error_type].clear();
4172                         else if (d->cloned_buffer_) {
4173                                 // Enable reverse search by copying back the
4174                                 // texrow object to the cloned buffer.
4175                                 // FIXME: this is not thread safe.
4176                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4177                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4178                                         (*cit)->d->errorLists[error_type];
4179                         } else
4180                                 (*cit)->errors(error_type, true);
4181                 }
4182         }
4183
4184         if (d->cloned_buffer_) {
4185                 // Enable reverse dvi or pdf to work by copying back the texrow
4186                 // object to the cloned buffer.
4187                 // FIXME: There is a possibility of concurrent access to texrow
4188                 // here from the main GUI thread that should be securized.
4189                 d->cloned_buffer_->d->texrow = d->texrow;
4190                 string const error_type = params().bufferFormat();
4191                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4192         }
4193
4194
4195         if (put_in_tempdir) {
4196                 result_file = tmp_result_file.absFileName();
4197                 return success ? ExportSuccess : ExportConverterError;
4198         }
4199
4200         if (dest_filename.empty())
4201                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4202         else
4203                 result_file = dest_filename;
4204         // We need to copy referenced files (e. g. included graphics
4205         // if format == "dvi") to the result dir.
4206         vector<ExportedFile> const files =
4207                 runparams.exportdata->externalFiles(format);
4208         string const dest = runparams.export_folder.empty() ?
4209                 onlyPath(result_file) : runparams.export_folder;
4210         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4211                                  : force_overwrite == ALL_FILES;
4212         CopyStatus status = use_force ? FORCE : SUCCESS;
4213
4214         vector<ExportedFile>::const_iterator it = files.begin();
4215         vector<ExportedFile>::const_iterator const en = files.end();
4216         for (; it != en && status != CANCEL; ++it) {
4217                 string const fmt = formats.getFormatFromFile(it->sourceName);
4218                 string fixedName = it->exportName;
4219                 if (!runparams.export_folder.empty()) {
4220                         // Relative pathnames starting with ../ will be sanitized
4221                         // if exporting to a different folder
4222                         while (fixedName.substr(0, 3) == "../")
4223                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4224                 }
4225                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4226                 fixedFileName.onlyPath().createPath();
4227                 status = copyFile(fmt, it->sourceName,
4228                         fixedFileName,
4229                         it->exportName, status == FORCE,
4230                         runparams.export_folder.empty());
4231         }
4232
4233         if (status == CANCEL) {
4234                 message(_("Document export cancelled."));
4235                 return ExportCancel;
4236         }
4237
4238         if (tmp_result_file.exists()) {
4239                 // Finally copy the main file
4240                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4241                                     : force_overwrite != NO_FILES;
4242                 if (status == SUCCESS && use_force)
4243                         status = FORCE;
4244                 status = copyFile(format, tmp_result_file,
4245                         FileName(result_file), result_file,
4246                         status == FORCE);
4247                 if (status == CANCEL) {
4248                         message(_("Document export cancelled."));
4249                         return ExportCancel;
4250                 } else {
4251                         message(bformat(_("Document exported as %1$s "
4252                                 "to file `%2$s'"),
4253                                 formats.prettyName(format),
4254                                 makeDisplayPath(result_file)));
4255                 }
4256         } else {
4257                 // This must be a dummy converter like fax (bug 1888)
4258                 message(bformat(_("Document exported as %1$s"),
4259                         formats.prettyName(format)));
4260         }
4261
4262         return success ? ExportSuccess : ExportConverterError;
4263 }
4264
4265
4266 Buffer::ExportStatus Buffer::preview(string const & format) const
4267 {
4268         bool const update_unincluded =
4269                         params().maintain_unincluded_children
4270                         && !params().getIncludedChildren().empty();
4271         return preview(format, update_unincluded);
4272 }
4273
4274
4275 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4276 {
4277         MarkAsExporting exporting(this);
4278         string result_file;
4279         // (1) export with all included children (omit \includeonly)
4280         if (includeall) {
4281                 ExportStatus const status = doExport(format, true, true, result_file);
4282                 if (status != ExportSuccess)
4283                         return status;
4284         }
4285         // (2) export with included children only
4286         ExportStatus const status = doExport(format, true, false, result_file);
4287         FileName const previewFile(result_file);
4288
4289         LATTEST (isClone());
4290         d->cloned_buffer_->d->preview_file_ = previewFile;
4291         d->cloned_buffer_->d->preview_format_ = format;
4292         d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4293
4294         if (status != ExportSuccess)
4295                 return status;
4296         if (previewFile.exists()) {
4297                 if (!formats.view(*this, previewFile, format))
4298                         return PreviewError;
4299                 else
4300                         return PreviewSuccess;
4301         }
4302         else {
4303                 // Successful export but no output file?
4304                 // Probably a bug in error detection.
4305                 LATTEST (status != ExportSuccess);
4306
4307                 return status;
4308         }
4309 }
4310
4311
4312 Buffer::ReadStatus Buffer::extractFromVC()
4313 {
4314         bool const found = LyXVC::file_not_found_hook(d->filename);
4315         if (!found)
4316                 return ReadFileNotFound;
4317         if (!d->filename.isReadableFile())
4318                 return ReadVCError;
4319         return ReadSuccess;
4320 }
4321
4322
4323 Buffer::ReadStatus Buffer::loadEmergency()
4324 {
4325         FileName const emergencyFile = getEmergencyFileName();
4326         if (!emergencyFile.exists()
4327                   || emergencyFile.lastModified() <= d->filename.lastModified())
4328                 return ReadFileNotFound;
4329
4330         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4331         docstring const text = bformat(_("An emergency save of the document "
4332                 "%1$s exists.\n\nRecover emergency save?"), file);
4333
4334         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4335                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4336
4337         switch (load_emerg)
4338         {
4339         case 0: {
4340                 docstring str;
4341                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4342                 bool const success = (ret_llf == ReadSuccess);
4343                 if (success) {
4344                         if (isReadonly()) {
4345                                 Alert::warning(_("File is read-only"),
4346                                         bformat(_("An emergency file is successfully loaded, "
4347                                         "but the original file %1$s is marked read-only. "
4348                                         "Please make sure to save the document as a different "
4349                                         "file."), from_utf8(d->filename.absFileName())));
4350                         }
4351                         markDirty();
4352                         lyxvc().file_found_hook(d->filename);
4353                         str = _("Document was successfully recovered.");
4354                 } else
4355                         str = _("Document was NOT successfully recovered.");
4356                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4357                         makeDisplayPath(emergencyFile.absFileName()));
4358
4359                 int const del_emerg =
4360                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4361                                 _("&Remove"), _("&Keep"));
4362                 if (del_emerg == 0) {
4363                         emergencyFile.removeFile();
4364                         if (success)
4365                                 Alert::warning(_("Emergency file deleted"),
4366                                         _("Do not forget to save your file now!"), true);
4367                         }
4368                 return success ? ReadSuccess : ReadEmergencyFailure;
4369         }
4370         case 1: {
4371                 int const del_emerg =
4372                         Alert::prompt(_("Delete emergency file?"),
4373                                 _("Remove emergency file now?"), 1, 1,
4374                                 _("&Remove"), _("&Keep"));
4375                 if (del_emerg == 0)
4376                         emergencyFile.removeFile();
4377                 return ReadOriginal;
4378         }
4379
4380         default:
4381                 break;
4382         }
4383         return ReadCancel;
4384 }
4385
4386
4387 Buffer::ReadStatus Buffer::loadAutosave()
4388 {
4389         // Now check if autosave file is newer.
4390         FileName const autosaveFile = getAutosaveFileName();
4391         if (!autosaveFile.exists()
4392                   || autosaveFile.lastModified() <= d->filename.lastModified())
4393                 return ReadFileNotFound;
4394
4395         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4396         docstring const text = bformat(_("The backup of the document %1$s "
4397                 "is newer.\n\nLoad the backup instead?"), file);
4398         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4399                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4400
4401         switch (ret)
4402         {
4403         case 0: {
4404                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4405                 // the file is not saved if we load the autosave file.
4406                 if (ret_llf == ReadSuccess) {
4407                         if (isReadonly()) {
4408                                 Alert::warning(_("File is read-only"),
4409                                         bformat(_("A backup file is successfully loaded, "
4410                                         "but the original file %1$s is marked read-only. "
4411                                         "Please make sure to save the document as a "
4412                                         "different file."),
4413                                         from_utf8(d->filename.absFileName())));
4414                         }
4415                         markDirty();
4416                         lyxvc().file_found_hook(d->filename);
4417                         return ReadSuccess;
4418                 }
4419                 return ReadAutosaveFailure;
4420         }
4421         case 1:
4422                 // Here we delete the autosave
4423                 autosaveFile.removeFile();
4424                 return ReadOriginal;
4425         default:
4426                 break;
4427         }
4428         return ReadCancel;
4429 }
4430
4431
4432 Buffer::ReadStatus Buffer::loadLyXFile()
4433 {
4434         if (!d->filename.isReadableFile()) {
4435                 ReadStatus const ret_rvc = extractFromVC();
4436                 if (ret_rvc != ReadSuccess)
4437                         return ret_rvc;
4438         }
4439
4440         ReadStatus const ret_re = loadEmergency();
4441         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4442                 return ret_re;
4443
4444         ReadStatus const ret_ra = loadAutosave();
4445         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4446                 return ret_ra;
4447
4448         return loadThisLyXFile(d->filename);
4449 }
4450
4451
4452 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4453 {
4454         return readFile(fn);
4455 }
4456
4457
4458 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4459 {
4460         TeXErrors::Errors::const_iterator it = terr.begin();
4461         TeXErrors::Errors::const_iterator end = terr.end();
4462         ListOfBuffers clist = getDescendents();
4463         ListOfBuffers::const_iterator cen = clist.end();
4464
4465         for (; it != end; ++it) {
4466                 int id_start = -1;
4467                 int pos_start = -1;
4468                 int errorRow = it->error_in_line;
4469                 Buffer const * buf = 0;
4470                 Impl const * p = d;
4471                 if (it->child_name.empty())
4472                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4473                 else {
4474                         // The error occurred in a child
4475                         ListOfBuffers::const_iterator cit = clist.begin();
4476                         for (; cit != cen; ++cit) {
4477                                 string const child_name =
4478                                         DocFileName(changeExtension(
4479                                                 (*cit)->absFileName(), "tex")).
4480                                                         mangledFileName();
4481                                 if (it->child_name != child_name)
4482                                         continue;
4483                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4484                                                         id_start, pos_start);
4485                                 if (id_start != -1) {
4486                                         buf = d->cloned_buffer_
4487                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4488                                                 : (*cit)->d->owner_;
4489                                         p = (*cit)->d;
4490                                         break;
4491                                 }
4492                         }
4493                 }
4494                 int id_end = -1;
4495                 int pos_end = -1;
4496                 bool found;
4497                 do {
4498                         ++errorRow;
4499                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4500                 } while (found && id_start == id_end && pos_start == pos_end);
4501
4502                 if (id_start != id_end) {
4503                         // Next registered position is outside the inset where
4504                         // the error occurred, so signal end-of-paragraph
4505                         pos_end = 0;
4506                 }
4507
4508                 errorList.push_back(ErrorItem(it->error_desc,
4509                         it->error_text, id_start, pos_start, pos_end, buf));
4510         }
4511 }
4512
4513
4514 void Buffer::setBuffersForInsets() const
4515 {
4516         inset().setBuffer(const_cast<Buffer &>(*this));
4517 }
4518
4519
4520 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4521 {
4522         LBUFERR(!text().paragraphs().empty());
4523
4524         // Use the master text class also for child documents
4525         Buffer const * const master = masterBuffer();
4526         DocumentClass const & textclass = master->params().documentClass();
4527
4528         // do this only if we are the top-level Buffer
4529         if (master == this) {
4530                 textclass.counters().reset(from_ascii("bibitem"));
4531                 reloadBibInfoCache();
4532         }
4533
4534         // keep the buffers to be children in this set. If the call from the
4535         // master comes back we can see which of them were actually seen (i.e.
4536         // via an InsetInclude). The remaining ones in the set need still be updated.
4537         static std::set<Buffer const *> bufToUpdate;
4538         if (scope == UpdateMaster) {
4539                 // If this is a child document start with the master
4540                 if (master != this) {
4541                         bufToUpdate.insert(this);
4542                         master->updateBuffer(UpdateMaster, utype);
4543                         // If the master buffer has no gui associated with it, then the TocModel is
4544                         // not updated during the updateBuffer call and TocModel::toc_ is invalid
4545                         // (bug 5699). The same happens if the master buffer is open in a different
4546                         // window. This test catches both possibilities.
4547                         // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4548                         // There remains a problem here: If there is another child open in yet a third
4549                         // window, that TOC is not updated. So some more general solution is needed at
4550                         // some point.
4551                         if (master->d->gui_ != d->gui_)
4552                                 structureChanged();
4553
4554                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4555                         if (bufToUpdate.find(this) == bufToUpdate.end())
4556                                 return;
4557                 }
4558
4559                 // start over the counters in the master
4560                 textclass.counters().reset();
4561         }
4562
4563         // update will be done below for this buffer
4564         bufToUpdate.erase(this);
4565
4566         // update all caches
4567         clearReferenceCache();
4568         updateMacros();
4569
4570         Buffer & cbuf = const_cast<Buffer &>(*this);
4571
4572         // do the real work
4573         ParIterator parit = cbuf.par_iterator_begin();
4574         updateBuffer(parit, utype);
4575
4576         if (master != this)
4577                 // TocBackend update will be done later.
4578                 return;
4579
4580         d->bibinfo_cache_valid_ = true;
4581         d->cite_labels_valid_ = true;
4582         /// FIXME: Perf
4583         cbuf.tocBackend().update(true, utype);
4584         if (scope == UpdateMaster)
4585                 cbuf.structureChanged();
4586 }
4587
4588
4589 static depth_type getDepth(DocIterator const & it)
4590 {
4591         depth_type depth = 0;
4592         for (size_t i = 0 ; i < it.depth() ; ++i)
4593                 if (!it[i].inset().inMathed())
4594                         depth += it[i].paragraph().getDepth() + 1;
4595         // remove 1 since the outer inset does not count
4596         return depth - 1;
4597 }
4598
4599 static depth_type getItemDepth(ParIterator const & it)
4600 {
4601         Paragraph const & par = *it;
4602         LabelType const labeltype = par.layout().labeltype;
4603
4604         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4605                 return 0;
4606
4607         // this will hold the lowest depth encountered up to now.
4608         depth_type min_depth = getDepth(it);
4609         ParIterator prev_it = it;
4610         while (true) {
4611                 if (prev_it.pit())
4612                         --prev_it.top().pit();
4613                 else {
4614                         // start of nested inset: go to outer par
4615                         prev_it.pop_back();
4616                         if (prev_it.empty()) {
4617                                 // start of document: nothing to do
4618                                 return 0;
4619                         }
4620                 }
4621
4622                 // We search for the first paragraph with same label
4623                 // that is not more deeply nested.
4624                 Paragraph & prev_par = *prev_it;
4625                 depth_type const prev_depth = getDepth(prev_it);
4626                 if (labeltype == prev_par.layout().labeltype) {
4627                         if (prev_depth < min_depth)
4628                                 return prev_par.itemdepth + 1;
4629                         if (prev_depth == min_depth)
4630                                 return prev_par.itemdepth;
4631                 }
4632                 min_depth = min(min_depth, prev_depth);
4633                 // small optimization: if we are at depth 0, we won't
4634                 // find anything else
4635                 if (prev_depth == 0)
4636                         return 0;
4637         }
4638 }
4639
4640
4641 static bool needEnumCounterReset(ParIterator const & it)
4642 {
4643         Paragraph const & par = *it;
4644         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4645         depth_type const cur_depth = par.getDepth();
4646         ParIterator prev_it = it;
4647         while (prev_it.pit()) {
4648                 --prev_it.top().pit();
4649                 Paragraph const & prev_par = *prev_it;
4650                 if (prev_par.getDepth() <= cur_depth)
4651                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4652         }
4653         // start of nested inset: reset
4654         return true;
4655 }
4656
4657
4658 // set the label of a paragraph. This includes the counters.
4659 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4660 {
4661         BufferParams const & bp = owner_->masterBuffer()->params();
4662         DocumentClass const & textclass = bp.documentClass();
4663         Paragraph & par = it.paragraph();
4664         Layout const & layout = par.layout();
4665         Counters & counters = textclass.counters();
4666
4667         if (par.params().startOfAppendix()) {
4668                 // We want to reset the counter corresponding to toplevel sectioning
4669                 Layout const & lay = textclass.getTOCLayout();
4670                 docstring const cnt = lay.counter;
4671                 if (!cnt.empty())
4672                         counters.reset(cnt);
4673                 counters.appendix(true);
4674         }
4675         par.params().appendix(counters.appendix());
4676
4677         // Compute the item depth of the paragraph
4678         par.itemdepth = getItemDepth(it);
4679
4680         if (layout.margintype == MARGIN_MANUAL) {
4681                 if (par.params().labelWidthString().empty())
4682                         par.params().labelWidthString(par.expandLabel(layout, bp));
4683         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4684                 // we do not need to do anything here, since the empty case is
4685                 // handled during export.
4686         } else {
4687                 par.params().labelWidthString(docstring());
4688         }
4689
4690         switch(layout.labeltype) {
4691         case LABEL_ITEMIZE: {
4692                 // At some point of time we should do something more
4693                 // clever here, like:
4694                 //   par.params().labelString(
4695                 //    bp.user_defined_bullet(par.itemdepth).getText());
4696                 // for now, use a simple hardcoded label
4697                 docstring itemlabel;
4698                 switch (par.itemdepth) {
4699                 case 0:
4700                         itemlabel = char_type(0x2022);
4701                         break;
4702                 case 1:
4703                         itemlabel = char_type(0x2013);
4704                         break;
4705                 case 2:
4706                         itemlabel = char_type(0x2217);
4707                         break;
4708                 case 3:
4709                         itemlabel = char_type(0x2219); // or 0x00b7
4710                         break;
4711                 }
4712                 par.params().labelString(itemlabel);
4713                 break;
4714         }
4715
4716         case LABEL_ENUMERATE: {
4717                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4718
4719                 switch (par.itemdepth) {
4720                 case 2:
4721                         enumcounter += 'i';
4722                 case 1:
4723                         enumcounter += 'i';
4724                 case 0:
4725                         enumcounter += 'i';
4726                         break;
4727                 case 3:
4728                         enumcounter += "iv";
4729                         break;
4730                 default:
4731                         // not a valid enumdepth...
4732                         break;
4733                 }
4734
4735                 // Maybe we have to reset the enumeration counter.
4736                 if (needEnumCounterReset(it))
4737                         counters.reset(enumcounter);
4738                 counters.step(enumcounter, utype);
4739
4740                 string const & lang = par.getParLanguage(bp)->code();
4741                 par.params().labelString(counters.theCounter(enumcounter, lang));
4742
4743                 break;
4744         }
4745
4746         case LABEL_SENSITIVE: {
4747                 string const & type = counters.current_float();
4748                 docstring full_label;
4749                 if (type.empty())
4750                         full_label = owner_->B_("Senseless!!! ");
4751                 else {
4752                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4753                         if (counters.hasCounter(from_utf8(type))) {
4754                                 string const & lang = par.getParLanguage(bp)->code();
4755                                 counters.step(from_utf8(type), utype);
4756                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4757                                                      name,
4758                                                      counters.theCounter(from_utf8(type), lang));
4759                         } else
4760                                 full_label = bformat(from_ascii("%1$s #:"), name);
4761                 }
4762                 par.params().labelString(full_label);
4763                 break;
4764         }
4765
4766         case LABEL_NO_LABEL:
4767                 par.params().labelString(docstring());
4768                 break;
4769
4770         case LABEL_ABOVE:
4771         case LABEL_CENTERED:
4772         case LABEL_STATIC: {
4773                 docstring const & lcounter = layout.counter;
4774                 if (!lcounter.empty()) {
4775                         if (layout.toclevel <= bp.secnumdepth
4776                                                 && (layout.latextype != LATEX_ENVIRONMENT
4777                                         || it.text()->isFirstInSequence(it.pit()))) {
4778                                 if (counters.hasCounter(lcounter))
4779                                         counters.step(lcounter, utype);
4780                                 par.params().labelString(par.expandLabel(layout, bp));
4781                         } else
4782                                 par.params().labelString(docstring());
4783                 } else
4784                         par.params().labelString(par.expandLabel(layout, bp));
4785                 break;
4786         }
4787
4788         case LABEL_MANUAL:
4789         case LABEL_BIBLIO:
4790                 par.params().labelString(par.expandLabel(layout, bp));
4791         }
4792 }
4793
4794
4795 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4796 {
4797         // LASSERT: Is it safe to continue here, or should we just return?
4798         LASSERT(parit.pit() == 0, /**/);
4799
4800         // Set the position of the text in the buffer to be able
4801         // to resolve macros in it.
4802         parit.text()->setMacrocontextPosition(parit);
4803
4804         depth_type maxdepth = 0;
4805         pit_type const lastpit = parit.lastpit();
4806         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4807                 // reduce depth if necessary
4808                 if (parit->params().depth() > maxdepth) {
4809                         /** FIXME: this function is const, but
4810                          * nevertheless it modifies the buffer. To be
4811                          * cleaner, one should modify the buffer in
4812                          * another function, which is actually
4813                          * non-const. This would however be costly in
4814                          * terms of code duplication.
4815                          */
4816                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4817                         parit->params().depth(maxdepth);
4818                 }
4819                 maxdepth = parit->getMaxDepthAfter();
4820
4821                 if (utype == OutputUpdate) {
4822                         // track the active counters
4823                         // we have to do this for the master buffer, since the local
4824                         // buffer isn't tracking anything.
4825                         masterBuffer()->params().documentClass().counters().
4826                                         setActiveLayout(parit->layout());
4827                 }
4828
4829                 // set the counter for this paragraph
4830                 d->setLabel(parit, utype);
4831
4832                 // now the insets
4833                 InsetList::const_iterator iit = parit->insetList().begin();
4834                 InsetList::const_iterator end = parit->insetList().end();
4835                 for (; iit != end; ++iit) {
4836                         parit.pos() = iit->pos;
4837                         iit->inset->updateBuffer(parit, utype);
4838                 }
4839         }
4840 }
4841
4842
4843 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4844         WordLangTuple & word_lang, docstring_list & suggestions) const
4845 {
4846         int progress = 0;
4847         WordLangTuple wl;
4848         suggestions.clear();
4849         word_lang = WordLangTuple();
4850         bool const to_end = to.empty();
4851         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4852         // OK, we start from here.
4853         for (; from != end; from.forwardPos()) {
4854                 // This skips all insets with spell check disabled.
4855                 while (!from.allowSpellCheck()) {
4856                         from.pop_back();
4857                         from.pos()++;
4858                 }
4859                 // If from is at the end of the document (which is possible
4860                 // when "from" was changed above) LyX will crash later otherwise.
4861                 if (from.atEnd() || (!to_end && from >= end))
4862                         break;
4863                 to = from;
4864                 from.paragraph().spellCheck();
4865                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4866                 if (SpellChecker::misspelled(res)) {
4867                         word_lang = wl;
4868                         break;
4869                 }
4870                 // Do not increase progress when from == to, otherwise the word
4871                 // count will be wrong.
4872                 if (from != to) {
4873                         from = to;
4874                         ++progress;
4875                 }
4876         }
4877         return progress;
4878 }
4879
4880
4881 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4882 {
4883         bool inword = false;
4884         word_count_ = 0;
4885         char_count_ = 0;
4886         blank_count_ = 0;
4887
4888         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4889                 if (!dit.inTexted()) {
4890                         dit.forwardPos();
4891                         continue;
4892                 }
4893
4894                 Paragraph const & par = dit.paragraph();
4895                 pos_type const pos = dit.pos();
4896
4897                 // Copied and adapted from isWordSeparator() in Paragraph
4898                 if (pos == dit.lastpos()) {
4899                         inword = false;
4900                 } else {
4901                         Inset const * ins = par.getInset(pos);
4902                         if (ins && skipNoOutput && !ins->producesOutput()) {
4903                                 // skip this inset
4904                                 ++dit.top().pos();
4905                                 // stop if end of range was skipped
4906                                 if (!to.atEnd() && dit >= to)
4907                                         break;
4908                                 continue;
4909                         } else if (!par.isDeleted(pos)) {
4910                                 if (par.isWordSeparator(pos))
4911                                         inword = false;
4912                                 else if (!inword) {
4913                                         ++word_count_;
4914                                         inword = true;
4915                                 }
4916                                 if (ins && ins->isLetter())
4917                                         ++char_count_;
4918                                 else if (ins && ins->isSpace())
4919                                         ++blank_count_;
4920                                 else {
4921                                         char_type const c = par.getChar(pos);
4922                                         if (isPrintableNonspace(c))
4923                                                 ++char_count_;
4924                                         else if (isSpace(c))
4925                                                 ++blank_count_;
4926                                 }
4927                         }
4928                 }
4929                 dit.forwardPos();
4930         }
4931 }
4932
4933
4934 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4935 {
4936         d->updateStatistics(from, to, skipNoOutput);
4937 }
4938
4939
4940 int Buffer::wordCount() const
4941 {
4942         return d->wordCount();
4943 }
4944
4945
4946 int Buffer::charCount(bool with_blanks) const
4947 {
4948         return d->charCount(with_blanks);
4949 }
4950
4951
4952 Buffer::ReadStatus Buffer::reload()
4953 {
4954         setBusy(true);
4955         // c.f. bug http://www.lyx.org/trac/ticket/6587
4956         removeAutosaveFile();
4957         // e.g., read-only status could have changed due to version control
4958         d->filename.refresh();
4959         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4960
4961         // clear parent. this will get reset if need be.
4962         d->setParent(0);
4963         ReadStatus const status = loadLyXFile();
4964         if (status == ReadSuccess) {
4965                 updateBuffer();
4966                 changed(true);
4967                 updateTitles();
4968                 markClean();
4969                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4970                 d->undo_.clear();
4971         } else {
4972                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4973         }
4974         setBusy(false);
4975         removePreviews();
4976         updatePreviews();
4977         errors("Parse");
4978         return status;
4979 }
4980
4981
4982 bool Buffer::saveAs(FileName const & fn)
4983 {
4984         FileName const old_name = fileName();
4985         FileName const old_auto = getAutosaveFileName();
4986         bool const old_unnamed = isUnnamed();
4987         bool success = true;
4988         d->old_position = filePath();
4989
4990         setFileName(fn);
4991         markDirty();
4992         setUnnamed(false);
4993
4994         if (save()) {
4995                 // bring the autosave file with us, just in case.
4996                 moveAutosaveFile(old_auto);
4997                 // validate version control data and
4998                 // correct buffer title
4999                 lyxvc().file_found_hook(fileName());
5000                 updateTitles();
5001                 // the file has now been saved to the new location.
5002                 // we need to check that the locations of child buffers
5003                 // are still valid.
5004                 checkChildBuffers();
5005                 checkMasterBuffer();
5006         } else {
5007                 // save failed
5008                 // reset the old filename and unnamed state
5009                 setFileName(old_name);
5010                 setUnnamed(old_unnamed);
5011                 success = false;
5012         }
5013
5014         d->old_position.clear();
5015         return success;
5016 }
5017
5018
5019 void Buffer::checkChildBuffers()
5020 {
5021         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5022         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5023         for (; it != en; ++it) {
5024                 DocIterator dit = it->second;
5025                 Buffer * cbuf = const_cast<Buffer *>(it->first);
5026                 if (!cbuf || !theBufferList().isLoaded(cbuf))
5027                         continue;
5028                 Inset * inset = dit.nextInset();
5029                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5030                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5031                 docstring const & incfile = inset_inc->getParam("filename");
5032                 string oldloc = cbuf->absFileName();
5033                 string newloc = makeAbsPath(to_utf8(incfile),
5034                                 onlyPath(absFileName())).absFileName();
5035                 if (oldloc == newloc)
5036                         continue;
5037                 // the location of the child file is incorrect.
5038                 cbuf->setParent(0);
5039                 inset_inc->setChildBuffer(0);
5040         }
5041         // invalidate cache of children
5042         d->children_positions.clear();
5043         d->position_to_children.clear();
5044 }
5045
5046
5047 // If a child has been saved under a different name/path, it might have been
5048 // orphaned. Therefore the master needs to be reset (bug 8161).
5049 void Buffer::checkMasterBuffer()
5050 {
5051         Buffer const * const master = masterBuffer();
5052         if (master == this)
5053                 return;
5054
5055         // necessary to re-register the child (bug 5873)
5056         // FIXME: clean up updateMacros (here, only
5057         // child registering is needed).
5058         master->updateMacros();
5059         // (re)set master as master buffer, but only
5060         // if we are a real child
5061         if (master->isChild(this))
5062                 setParent(master);
5063         else
5064                 setParent(0);
5065 }
5066
5067
5068 string Buffer::includedFilePath(string const & name, string const & ext) const
5069 {
5070         bool isabsolute = FileName::isAbsolute(name);
5071         // old_position already contains a trailing path separator
5072         string const absname = isabsolute ? name : d->old_position + name;
5073
5074         if (d->old_position.empty()
5075             || equivalent(FileName(d->old_position), FileName(filePath()))
5076             || !FileName(addExtension(absname, ext)).exists())
5077                 return name;
5078
5079         if (isabsolute)
5080                 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5081
5082         return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5083                                    from_utf8(filePath())));
5084 }
5085
5086 } // namespace lyx