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