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