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