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