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