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