]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
avoid float-conversion warning and simplify size computation
[lyx.git] / src / Buffer.cpp
1 /**
2  * \file Buffer.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Stefan Schimanski
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "Buffer.h"
15
16 #include "Author.h"
17 #include "LayoutFile.h"
18 #include "BiblioInfo.h"
19 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "Bullet.h"
24 #include "Chktex.h"
25 #include "Converter.h"
26 #include "Counters.h"
27 #include "Cursor.h"
28 #include "CutAndPaste.h"
29 #include "DispatchResult.h"
30 #include "DocIterator.h"
31 #include "BufferEncodings.h"
32 #include "ErrorList.h"
33 #include "Exporter.h"
34 #include "Format.h"
35 #include "FuncRequest.h"
36 #include "FuncStatus.h"
37 #include "IndicesList.h"
38 #include "InsetIterator.h"
39 #include "InsetList.h"
40 #include "Language.h"
41 #include "LaTeXFeatures.h"
42 #include "LaTeX.h"
43 #include "Layout.h"
44 #include "Lexer.h"
45 #include "LyXAction.h"
46 #include "LyX.h"
47 #include "LyXRC.h"
48 #include "LyXVC.h"
49 #include "output_docbook.h"
50 #include "output.h"
51 #include "output_latex.h"
52 #include "output_xhtml.h"
53 #include "output_plaintext.h"
54 #include "Paragraph.h"
55 #include "ParagraphParameters.h"
56 #include "ParIterator.h"
57 #include "PDFOptions.h"
58 #include "SpellChecker.h"
59 #include "sgml.h"
60 #include "TexRow.h"
61 #include "Text.h"
62 #include "TextClass.h"
63 #include "TocBackend.h"
64 #include "Undo.h"
65 #include "VCBackend.h"
66 #include "version.h"
67 #include "WordLangTuple.h"
68 #include "WordList.h"
69
70 #include "insets/InsetBibtex.h"
71 #include "insets/InsetBranch.h"
72 #include "insets/InsetInclude.h"
73 #include "insets/InsetTabular.h"
74 #include "insets/InsetText.h"
75
76 #include "mathed/InsetMathHull.h"
77 #include "mathed/MacroTable.h"
78 #include "mathed/MathMacroTemplate.h"
79 #include "mathed/MathSupport.h"
80
81 #include "graphics/PreviewLoader.h"
82
83 #include "frontends/alert.h"
84 #include "frontends/Delegates.h"
85 #include "frontends/WorkAreaManager.h"
86
87 #include "support/lassert.h"
88 #include "support/convert.h"
89 #include "support/debug.h"
90 #include "support/docstring_list.h"
91 #include "support/ExceptionMessage.h"
92 #include "support/FileName.h"
93 #include "support/FileNameList.h"
94 #include "support/filetools.h"
95 #include "support/ForkedCalls.h"
96 #include "support/gettext.h"
97 #include "support/gzstream.h"
98 #include "support/lstrings.h"
99 #include "support/lyxalgo.h"
100 #include "support/mutex.h"
101 #include "support/os.h"
102 #include "support/Package.h"
103 #include "support/PathChanger.h"
104 #include "support/Systemcall.h"
105 #include "support/TempFile.h"
106 #include "support/textutils.h"
107 #include "support/types.h"
108
109 #include "support/bind.h"
110 #include "support/shared_ptr.h"
111
112 #include <algorithm>
113 #include <fstream>
114 #include <iomanip>
115 #include <map>
116 #include <set>
117 #include <sstream>
118 #include <vector>
119
120 using namespace std;
121 using namespace lyx::support;
122 using namespace lyx::graphics;
123
124 namespace lyx {
125
126 namespace Alert = frontend::Alert;
127 namespace os = support::os;
128
129 namespace {
130
131 int const LYX_FORMAT = LYX_FORMAT_LYX;
132
133 typedef map<string, bool> DepClean;
134 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
135
136 void showPrintError(string const & name)
137 {
138         docstring str = bformat(_("Could not print the document %1$s.\n"
139                                             "Check that your printer is set up correctly."),
140                              makeDisplayPath(name, 50));
141         Alert::error(_("Print document failed"), str);
142 }
143
144 } // namespace anon
145
146
147 // A storehouse for the cloned buffers.
148 list<CloneList *> cloned_buffers;
149
150
151 class Buffer::Impl
152 {
153 public:
154         Impl(Buffer * owner, FileName const & file, bool readonly, Buffer const * cloned_buffer);
155
156         ~Impl()
157         {
158                 delete preview_loader_;
159                 if (wa_) {
160                         wa_->closeAll();
161                         delete wa_;
162                 }
163                 delete inset;
164         }
165
166         /// search for macro in local (buffer) table or in children
167         MacroData const * getBufferMacro(docstring const & name,
168                 DocIterator const & pos) const;
169
170         /// Update macro table starting with position of it \param it in some
171         /// text inset.
172         void updateMacros(DocIterator & it, DocIterator & scope);
173         ///
174         void setLabel(ParIterator & it, UpdateType utype) const;
175
176         /** If we have branches that use the file suffix
177             feature, return the file name with suffix appended.
178         */
179         support::FileName exportFileName() const;
180
181         Buffer * owner_;
182
183         BufferParams params;
184         LyXVC lyxvc;
185         FileName temppath;
186         mutable TexRow texrow;
187
188         /// need to regenerate .tex?
189         DepClean dep_clean;
190
191         /// is save needed?
192         mutable bool lyx_clean;
193
194         /// is autosave needed?
195         mutable bool bak_clean;
196
197         /// is this an unnamed file (New...)?
198         bool unnamed;
199
200         /// is this an internal bufffer?
201         bool internal_buffer;
202
203         /// buffer is r/o
204         bool read_only;
205
206         /// name of the file the buffer is associated with.
207         FileName filename;
208
209         /** Set to true only when the file is fully loaded.
210          *  Used to prevent the premature generation of previews
211          *  and by the citation inset.
212          */
213         bool file_fully_loaded;
214
215         /// Ignore the parent (e.g. when exporting a child standalone)?
216         bool ignore_parent;
217
218         ///
219         mutable TocBackend toc_backend;
220
221         /// macro tables
222         struct ScopeMacro {
223                 ScopeMacro() {}
224                 ScopeMacro(DocIterator const & s, MacroData const & m)
225                         : scope(s), macro(m) {}
226                 DocIterator scope;
227                 MacroData macro;
228         };
229         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
230         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
231         /// map from the macro name to the position map,
232         /// which maps the macro definition position to the scope and the MacroData.
233         NamePositionScopeMacroMap macros;
234         /// This seem to change the way Buffer::getMacro() works
235         mutable bool macro_lock;
236
237         /// positions of child buffers in the buffer
238         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
239         struct ScopeBuffer {
240                 ScopeBuffer() {}
241                 ScopeBuffer(DocIterator const & s,Buffer const * b)
242                         : scope(s), buffer(b) {}
243                 DocIterator scope;
244                 Buffer const * buffer;
245         };
246         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
247         /// position of children buffers in this buffer
248         BufferPositionMap children_positions;
249         /// map from children inclusion positions to their scope and their buffer
250         PositionScopeBufferMap position_to_children;
251
252         /// 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                 if (!writeFile(fileName()))
1341       return false;
1342     markClean();
1343     return true;
1344   }
1345
1346         // we first write the file to a new name, then move it to its
1347         // proper location once that has been done successfully. that
1348         // way we preserve the original file if something goes wrong.
1349         string const justname = fileName().onlyFileNameWithoutExt();
1350         boost::scoped_ptr<TempFile>
1351                 tempfile(new TempFile(fileName().onlyPath(),
1352                    justname + "-XXXXXX.lyx"));
1353         bool const symlink = fileName().isSymLink();
1354         if (!symlink)
1355                 tempfile->setAutoRemove(false);
1356
1357         FileName savefile(tempfile->name());
1358         LYXERR(Debug::FILES, "Saving to " << savefile.absFileName());
1359         if (!writeFile(savefile))
1360                 return false;
1361
1362         // we will set this to false if we fail
1363         bool made_backup = true;
1364
1365         FileName backupName(absFileName() + '~');
1366         if (lyxrc.make_backup) {
1367                 if (!lyxrc.backupdir_path.empty()) {
1368                         string const mangledName =
1369                                 subst(subst(backupName.absFileName(), '/', '!'), ':', '!');
1370                         backupName = FileName(addName(lyxrc.backupdir_path,
1371                                                       mangledName));
1372                 }
1373
1374                 LYXERR(Debug::FILES, "Backing up original file to " <<
1375                                 backupName.absFileName());
1376                 // Except file is symlink do not copy because of #6587.
1377                 // Hard links have bad luck.
1378                 made_backup = symlink ?
1379                         fileName().copyTo(backupName):
1380                         fileName().moveTo(backupName);
1381
1382                 if (!made_backup) {
1383                         Alert::error(_("Backup failure"),
1384                                      bformat(_("Cannot create backup file %1$s.\n"
1385                                                "Please check whether the directory exists and is writable."),
1386                                              from_utf8(backupName.absFileName())));
1387                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
1388                 }
1389         }
1390
1391         // Destroy tempfile since it keeps the file locked on windows (bug 9234)
1392         // Only do this if tempfile is not in autoremove mode
1393         if (!symlink)
1394                 tempfile.reset();
1395         // If we have no symlink, we can simply rename the temp file.
1396         // Otherwise, we need to copy it so the symlink stays intact.
1397         if (made_backup && symlink ? savefile.copyTo(fileName(), true) :
1398                                            savefile.moveTo(fileName()))
1399         {
1400                 // saveCheckSum() was already called by writeFile(), but the
1401                 // time stamp is invalidated by copying/moving
1402                 saveCheckSum();
1403                 markClean();
1404                 return true;
1405         }
1406         // else we saved the file, but failed to move it to the right location.
1407
1408         if (lyxrc.make_backup && made_backup && !symlink) {
1409                 // the original file was moved to filename.lyx~, so it will look
1410                 // to the user as if it was deleted. (see bug #9234.) we could try
1411                 // to restore it, but that would basically mean trying to do again
1412                 // what we just failed to do. better to leave things as they are.
1413                 Alert::error(_("Write failure"),
1414                              bformat(_("The file has successfully been saved as:\n  %1$s.\n"
1415                                        "But LyX could not move it to:\n  %2$s.\n"
1416                                        "Your original file has been backed up to:\n  %3$s"),
1417                                      from_utf8(savefile.absFileName()),
1418                                      from_utf8(fileName().absFileName()),
1419                                      from_utf8(backupName.absFileName())));
1420         } else {
1421                 // either we did not try to make a backup, or else we tried and failed,
1422                 // or else the original file was a symlink, in which case it was copied,
1423                 // not moved. so the original file is intact.
1424                 Alert::error(_("Write failure"),
1425                              bformat(_("Cannot move saved file to:\n  %1$s.\n"
1426                                        "But the file has successfully been saved as:\n  %2$s."),
1427                                      from_utf8(fileName().absFileName()),
1428                          from_utf8(savefile.absFileName())));
1429         }
1430         return false;
1431 }
1432
1433
1434 bool Buffer::writeFile(FileName const & fname) const
1435 {
1436         if (d->read_only && fname == d->filename)
1437                 return false;
1438
1439         bool retval = false;
1440
1441         docstring const str = bformat(_("Saving document %1$s..."),
1442                 makeDisplayPath(fname.absFileName()));
1443         message(str);
1444
1445         string const encoded_fname = fname.toSafeFilesystemEncoding(os::CREATE);
1446
1447         if (params().compressed) {
1448                 gz::ogzstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1449                 retval = ofs && write(ofs);
1450         } else {
1451                 ofstream ofs(encoded_fname.c_str(), ios::out|ios::trunc);
1452                 retval = ofs && write(ofs);
1453         }
1454
1455         if (!retval) {
1456                 message(str + _(" could not write file!"));
1457                 return false;
1458         }
1459
1460         // see bug 6587
1461         // removeAutosaveFile();
1462
1463         saveCheckSum();
1464         message(str + _(" done."));
1465
1466         return true;
1467 }
1468
1469
1470 docstring Buffer::emergencyWrite()
1471 {
1472         // No need to save if the buffer has not changed.
1473         if (isClean())
1474                 return docstring();
1475
1476         string const doc = isUnnamed() ? onlyFileName(absFileName()) : absFileName();
1477
1478         docstring user_message = bformat(
1479                 _("LyX: Attempting to save document %1$s\n"), from_utf8(doc));
1480
1481         // We try to save three places:
1482         // 1) Same place as document. Unless it is an unnamed doc.
1483         if (!isUnnamed()) {
1484                 string s = absFileName();
1485                 s += ".emergency";
1486                 LYXERR0("  " << s);
1487                 if (writeFile(FileName(s))) {
1488                         markClean();
1489                         user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1490                         return user_message;
1491                 } else {
1492                         user_message += "  " + _("Save failed! Trying again...\n");
1493                 }
1494         }
1495
1496         // 2) In HOME directory.
1497         string s = addName(Package::get_home_dir().absFileName(), absFileName());
1498         s += ".emergency";
1499         lyxerr << ' ' << s << endl;
1500         if (writeFile(FileName(s))) {
1501                 markClean();
1502                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1503                 return user_message;
1504         }
1505
1506         user_message += "  " + _("Save failed! Trying yet again...\n");
1507
1508         // 3) In "/tmp" directory.
1509         // MakeAbsPath to prepend the current
1510         // drive letter on OS/2
1511         s = addName(package().temp_dir().absFileName(), absFileName());
1512         s += ".emergency";
1513         lyxerr << ' ' << s << endl;
1514         if (writeFile(FileName(s))) {
1515                 markClean();
1516                 user_message += "  " + bformat(_("Saved to %1$s. Phew.\n"), from_utf8(s));
1517                 return user_message;
1518         }
1519
1520         user_message += "  " + _("Save failed! Bummer. Document is lost.");
1521         // Don't try again.
1522         markClean();
1523         return user_message;
1524 }
1525
1526
1527 bool Buffer::write(ostream & ofs) const
1528 {
1529 #ifdef HAVE_LOCALE
1530         // Use the standard "C" locale for file output.
1531         ofs.imbue(locale::classic());
1532 #endif
1533
1534         // The top of the file should not be written by params().
1535
1536         // write out a comment in the top of the file
1537         // Important: Keep the version formatting in sync with lyx2lyx and
1538         //            tex2lyx (bug 7951)
1539         ofs << "#LyX " << lyx_version_major << "." << lyx_version_minor
1540             << " created this file. For more info see http://www.lyx.org/\n"
1541             << "\\lyxformat " << LYX_FORMAT << "\n"
1542             << "\\begin_document\n";
1543
1544         /// For each author, set 'used' to true if there is a change
1545         /// by this author in the document; otherwise set it to 'false'.
1546         AuthorList::Authors::const_iterator a_it = params().authors().begin();
1547         AuthorList::Authors::const_iterator a_end = params().authors().end();
1548         for (; a_it != a_end; ++a_it)
1549                 a_it->setUsed(false);
1550
1551         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
1552         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
1553         for ( ; it != end; ++it)
1554                 it->checkAuthors(params().authors());
1555
1556         // now write out the buffer parameters.
1557         ofs << "\\begin_header\n";
1558         params().writeFile(ofs, this);
1559         ofs << "\\end_header\n";
1560
1561         // write the text
1562         ofs << "\n\\begin_body\n";
1563         text().write(ofs);
1564         ofs << "\n\\end_body\n";
1565
1566         // Write marker that shows file is complete
1567         ofs << "\\end_document" << endl;
1568
1569         // Shouldn't really be needed....
1570         //ofs.close();
1571
1572         // how to check if close went ok?
1573         // Following is an attempt... (BE 20001011)
1574
1575         // good() returns false if any error occurred, including some
1576         //        formatting error.
1577         // bad()  returns true if something bad happened in the buffer,
1578         //        which should include file system full errors.
1579
1580         bool status = true;
1581         if (!ofs) {
1582                 status = false;
1583                 lyxerr << "File was not closed properly." << endl;
1584         }
1585
1586         return status;
1587 }
1588
1589
1590 bool Buffer::makeLaTeXFile(FileName const & fname,
1591                            string const & original_path,
1592                            OutputParams const & runparams_in,
1593                            OutputWhat output) const
1594 {
1595         OutputParams runparams = runparams_in;
1596
1597         // This is necessary for LuaTeX/XeTeX with tex fonts.
1598         // See FIXME in BufferParams::encoding()
1599         if (runparams.isFullUnicode())
1600                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1601
1602         string const encoding = runparams.encoding->iconvName();
1603         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << ", fname=" << fname.realPath());
1604
1605         ofdocstream ofs;
1606         try { ofs.reset(encoding); }
1607         catch (iconv_codecvt_facet_exception const & e) {
1608                 lyxerr << "Caught iconv exception: " << e.what() << endl;
1609                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
1610                         "verify that the support software for your encoding (%1$s) is "
1611                         "properly installed"), from_ascii(encoding)));
1612                 return false;
1613         }
1614         if (!openFileWrite(ofs, fname))
1615                 return false;
1616
1617         ErrorList & errorList = d->errorLists["Export"];
1618         errorList.clear();
1619         bool failed_export = false;
1620         otexstream os(ofs, d->texrow);
1621
1622         // make sure we are ready to export
1623         // this needs to be done before we validate
1624         // FIXME Do we need to do this all the time? I.e., in children
1625         // of a master we are exporting?
1626         updateBuffer();
1627         updateMacroInstances(OutputUpdate);
1628
1629         try {
1630                 os.texrow().reset();
1631                 writeLaTeXSource(os, original_path, runparams, output);
1632         }
1633         catch (EncodingException const & e) {
1634                 docstring const failed(1, e.failed_char);
1635                 ostringstream oss;
1636                 oss << "0x" << hex << e.failed_char << dec;
1637                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
1638                                           " (code point %2$s)"),
1639                                           failed, from_utf8(oss.str()));
1640                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
1641                                 "representable in the chosen encoding.\n"
1642                                 "Changing the document encoding to utf8 could help."),
1643                                 e.par_id, e.pos, e.pos + 1));
1644                 failed_export = true;
1645         }
1646         catch (iconv_codecvt_facet_exception const & e) {
1647                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1648                         _(e.what()), -1, 0, 0));
1649                 failed_export = true;
1650         }
1651         catch (exception const & e) {
1652                 errorList.push_back(ErrorItem(_("conversion failed"),
1653                         _(e.what()), -1, 0, 0));
1654                 failed_export = true;
1655         }
1656         catch (...) {
1657                 lyxerr << "Caught some really weird exception..." << endl;
1658                 lyx_exit(1);
1659         }
1660
1661         ofs.close();
1662         if (ofs.fail()) {
1663                 failed_export = true;
1664                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1665         }
1666
1667         if (runparams_in.silent)
1668                 errorList.clear();
1669         else
1670                 errors("Export");
1671         return !failed_export;
1672 }
1673
1674
1675 void Buffer::writeLaTeXSource(otexstream & os,
1676                            string const & original_path,
1677                            OutputParams const & runparams_in,
1678                            OutputWhat output) const
1679 {
1680         // The child documents, if any, shall be already loaded at this point.
1681
1682         OutputParams runparams = runparams_in;
1683
1684         // This is necessary for LuaTeX/XeTeX with tex fonts.
1685         // See FIXME in BufferParams::encoding()
1686         if (runparams.isFullUnicode())
1687                 runparams.encoding = encodings.fromLyXName("utf8-plain");
1688
1689         // If we are compiling a file standalone, even if this is the
1690         // child of some other buffer, let's cut the link here, so the
1691         // file is really independent and no concurring settings from
1692         // the master (e.g. branch state) interfere (see #8100).
1693         if (!runparams.is_child)
1694                 d->ignore_parent = true;
1695
1696         // Classify the unicode characters appearing in math insets
1697         BufferEncodings::initUnicodeMath(*this);
1698
1699         // validate the buffer.
1700         LYXERR(Debug::LATEX, "  Validating buffer...");
1701         LaTeXFeatures features(*this, params(), runparams);
1702         validate(features);
1703         // This is only set once per document (in master)
1704         if (!runparams.is_child)
1705                 runparams.use_polyglossia = features.usePolyglossia();
1706         LYXERR(Debug::LATEX, "  Buffer validation done.");
1707
1708         bool const output_preamble =
1709                 output == FullSource || output == OnlyPreamble;
1710         bool const output_body =
1711                 output == FullSource || output == OnlyBody;
1712
1713         // The starting paragraph of the coming rows is the
1714         // first paragraph of the document. (Asger)
1715         if (output_preamble && runparams.nice) {
1716                 os << "%% LyX " << lyx_version << " created this file.  "
1717                         "For more info, see http://www.lyx.org/.\n"
1718                         "%% Do not edit unless you really know what "
1719                         "you are doing.\n";
1720         }
1721         LYXERR(Debug::INFO, "lyx document header finished");
1722
1723         // There are a few differences between nice LaTeX and usual files:
1724         // usual files have \batchmode and special input@path to allow
1725         // inclusion of figures specified by an explicitly relative path
1726         // (i.e., a path starting with './' or '../') with either \input or
1727         // \includegraphics, as the TEXINPUTS method doesn't work in this case.
1728         // input@path is set when the actual parameter original_path is set.
1729         // This is done for usual tex-file, but not for nice-latex-file.
1730         // (Matthias 250696)
1731         // Note that input@path is only needed for something the user does
1732         // in the preamble, included .tex files or ERT, files included by
1733         // LyX work without it.
1734         if (output_preamble) {
1735                 if (!runparams.nice) {
1736                         // code for usual, NOT nice-latex-file
1737                         os << "\\batchmode\n"; // changed from \nonstopmode
1738                 }
1739                 if (!original_path.empty()) {
1740                         // FIXME UNICODE
1741                         // We don't know the encoding of inputpath
1742                         docstring const inputpath = from_utf8(original_path);
1743                         docstring uncodable_glyphs;
1744                         Encoding const * const enc = runparams.encoding;
1745                         if (enc) {
1746                                 for (size_t n = 0; n < inputpath.size(); ++n) {
1747                                         if (!enc->encodable(inputpath[n])) {
1748                                                 docstring const glyph(1, inputpath[n]);
1749                                                 LYXERR0("Uncodable character '"
1750                                                         << glyph
1751                                                         << "' in input path!");
1752                                                 uncodable_glyphs += glyph;
1753                                         }
1754                                 }
1755                         }
1756
1757                         // warn user if we found uncodable glyphs.
1758                         if (!uncodable_glyphs.empty()) {
1759                                 frontend::Alert::warning(
1760                                         _("Uncodable character in file path"),
1761                                         support::bformat(
1762                                           _("The path of your document\n"
1763                                             "(%1$s)\n"
1764                                             "contains glyphs that are unknown "
1765                                             "in the current document encoding "
1766                                             "(namely %2$s). This may result in "
1767                                             "incomplete output, unless "
1768                                             "TEXINPUTS contains the document "
1769                                             "directory and you don't use "
1770                                             "explicitly relative paths (i.e., "
1771                                             "paths starting with './' or "
1772                                             "'../') in the preamble or in ERT."
1773                                             "\n\nIn case of problems, choose "
1774                                             "an appropriate document encoding\n"
1775                                             "(such as utf8) or change the "
1776                                             "file path name."),
1777                                           inputpath, uncodable_glyphs));
1778                         } else {
1779                                 string docdir =
1780                                         support::latex_path(original_path);
1781                                 if (contains(docdir, '#')) {
1782                                         docdir = subst(docdir, "#", "\\#");
1783                                         os << "\\catcode`\\#=11"
1784                                               "\\def\\#{#}\\catcode`\\#=6\n";
1785                                 }
1786                                 if (contains(docdir, '%')) {
1787                                         docdir = subst(docdir, "%", "\\%");
1788                                         os << "\\catcode`\\%=11"
1789                                               "\\def\\%{%}\\catcode`\\%=14\n";
1790                                 }
1791                                 os << "\\makeatletter\n"
1792                                    << "\\def\\input@path{{"
1793                                    << docdir << "/}}\n"
1794                                    << "\\makeatother\n";
1795                         }
1796                 }
1797
1798                 // get parent macros (if this buffer has a parent) which will be
1799                 // written at the document begin further down.
1800                 MacroSet parentMacros;
1801                 listParentMacros(parentMacros, features);
1802
1803                 // Write the preamble
1804                 runparams.use_babel = params().writeLaTeX(os, features,
1805                                                           d->filename.onlyPath());
1806
1807                 // Japanese might be required only in some children of a document,
1808                 // but once required, we must keep use_japanese true.
1809                 runparams.use_japanese |= features.isRequired("japanese");
1810
1811                 if (!output_body) {
1812                         // Restore the parenthood if needed
1813                         if (!runparams.is_child)
1814                                 d->ignore_parent = false;
1815                         return;
1816                 }
1817
1818                 // make the body.
1819                 os << "\\begin{document}\n";
1820
1821                 // output the parent macros
1822                 MacroSet::iterator it = parentMacros.begin();
1823                 MacroSet::iterator end = parentMacros.end();
1824                 for (; it != end; ++it) {
1825                         int num_lines = (*it)->write(os.os(), true);
1826                         os.texrow().newlines(num_lines);
1827                 }
1828
1829         } // output_preamble
1830
1831         os.texrow().start(paragraphs().begin()->id(), 0);
1832
1833         LYXERR(Debug::INFO, "preamble finished, now the body.");
1834
1835         // the real stuff
1836         latexParagraphs(*this, text(), os, runparams);
1837
1838         // Restore the parenthood if needed
1839         if (!runparams.is_child)
1840                 d->ignore_parent = false;
1841
1842         // add this just in case after all the paragraphs
1843         os << endl;
1844
1845         if (output_preamble) {
1846                 os << "\\end{document}\n";
1847                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1848         } else {
1849                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1850         }
1851         runparams_in.encoding = runparams.encoding;
1852
1853         // Just to be sure. (Asger)
1854         os.texrow().newline();
1855
1856         //for (int i = 0; i<d->texrow.rows(); i++) {
1857         // int id,pos;
1858         // if (d->texrow.getIdFromRow(i+1,id,pos) && id>0)
1859         //      lyxerr << i+1 << ":" << id << ":" << getParFromID(id).paragraph().asString()<<"\n";
1860         //}
1861
1862         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1863         LYXERR(Debug::INFO, "Row count was " << os.texrow().rows() - 1 << '.');
1864 }
1865
1866
1867 void Buffer::makeDocBookFile(FileName const & fname,
1868                               OutputParams const & runparams,
1869                               OutputWhat output) const
1870 {
1871         LYXERR(Debug::LATEX, "makeDocBookFile...");
1872
1873         ofdocstream ofs;
1874         if (!openFileWrite(ofs, fname))
1875                 return;
1876
1877         // make sure we are ready to export
1878         // this needs to be done before we validate
1879         updateBuffer();
1880         updateMacroInstances(OutputUpdate);
1881
1882         writeDocBookSource(ofs, fname.absFileName(), runparams, output);
1883
1884         ofs.close();
1885         if (ofs.fail())
1886                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1887 }
1888
1889
1890 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1891                              OutputParams const & runparams,
1892                              OutputWhat output) const
1893 {
1894         LaTeXFeatures features(*this, params(), runparams);
1895         validate(features);
1896
1897         d->texrow.reset();
1898
1899         DocumentClass const & tclass = params().documentClass();
1900         string const & top_element = tclass.latexname();
1901
1902         bool const output_preamble =
1903                 output == FullSource || output == OnlyPreamble;
1904         bool const output_body =
1905           output == FullSource || output == OnlyBody;
1906
1907         if (output_preamble) {
1908                 if (runparams.flavor == OutputParams::XML)
1909                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1910
1911                 // FIXME UNICODE
1912                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1913
1914                 // FIXME UNICODE
1915                 if (! tclass.class_header().empty())
1916                         os << from_ascii(tclass.class_header());
1917                 else if (runparams.flavor == OutputParams::XML)
1918                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1919                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1920                 else
1921                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1922
1923                 docstring preamble = from_utf8(params().preamble);
1924                 if (runparams.flavor != OutputParams::XML ) {
1925                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1926                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1927                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1928                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1929                 }
1930
1931                 string const name = runparams.nice
1932                         ? changeExtension(absFileName(), ".sgml") : fname;
1933                 preamble += features.getIncludedFiles(name);
1934                 preamble += features.getLyXSGMLEntities();
1935
1936                 if (!preamble.empty()) {
1937                         os << "\n [ " << preamble << " ]";
1938                 }
1939                 os << ">\n\n";
1940         }
1941
1942         if (output_body) {
1943                 string top = top_element;
1944                 top += " lang=\"";
1945                 if (runparams.flavor == OutputParams::XML)
1946                         top += params().language->code();
1947                 else
1948                         top += params().language->code().substr(0, 2);
1949                 top += '"';
1950
1951                 if (!params().options.empty()) {
1952                         top += ' ';
1953                         top += params().options;
1954                 }
1955
1956                 os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1957                                 << " file was created by LyX " << lyx_version
1958                                 << "\n  See http://www.lyx.org/ for more information -->\n";
1959
1960                 params().documentClass().counters().reset();
1961
1962                 sgml::openTag(os, top);
1963                 os << '\n';
1964                 docbookParagraphs(text(), *this, os, runparams);
1965                 sgml::closeTag(os, top_element);
1966         }
1967 }
1968
1969
1970 void Buffer::makeLyXHTMLFile(FileName const & fname,
1971                               OutputParams const & runparams) const
1972 {
1973         LYXERR(Debug::LATEX, "makeLyXHTMLFile...");
1974
1975         ofdocstream ofs;
1976         if (!openFileWrite(ofs, fname))
1977                 return;
1978
1979         // make sure we are ready to export
1980         // this has to be done before we validate
1981         updateBuffer(UpdateMaster, OutputUpdate);
1982         updateMacroInstances(OutputUpdate);
1983
1984         writeLyXHTMLSource(ofs, runparams, FullSource);
1985
1986         ofs.close();
1987         if (ofs.fail())
1988                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1989 }
1990
1991
1992 void Buffer::writeLyXHTMLSource(odocstream & os,
1993                              OutputParams const & runparams,
1994                              OutputWhat output) const
1995 {
1996         LaTeXFeatures features(*this, params(), runparams);
1997         validate(features);
1998         d->bibinfo_.makeCitationLabels(*this);
1999
2000         bool const output_preamble =
2001                 output == FullSource || output == OnlyPreamble;
2002         bool const output_body =
2003           output == FullSource || output == OnlyBody || output == IncludedFile;
2004
2005         if (output_preamble) {
2006                 os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
2007                    << "<!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"
2008                    // FIXME Language should be set properly.
2009                    << "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
2010                    << "<head>\n"
2011                    << "<meta name=\"GENERATOR\" content=\"" << PACKAGE_STRING << "\" />\n"
2012                    // FIXME Presumably need to set this right
2013                    << "<meta http-equiv=\"Content-type\" content=\"text/html;charset=UTF-8\" />\n";
2014
2015                 docstring const & doctitle = features.htmlTitle();
2016                 os << "<title>"
2017                    << (doctitle.empty() ?
2018                          from_ascii("LyX Document") :
2019                          html::htmlize(doctitle, XHTMLStream::ESCAPE_ALL))
2020                    << "</title>\n";
2021
2022                 docstring styles = features.getTClassHTMLPreamble();
2023                 if (!styles.empty())
2024                         os << "\n<!-- Text Class Preamble -->\n" << styles << '\n';
2025
2026                 styles = from_utf8(features.getPreambleSnippets());
2027                 if (!styles.empty())
2028                         os << "\n<!-- Preamble Snippets -->\n" << styles << '\n';
2029
2030                 // we will collect CSS information in a stream, and then output it
2031                 // either here, as part of the header, or else in a separate file.
2032                 odocstringstream css;
2033                 styles = from_utf8(features.getCSSSnippets());
2034                 if (!styles.empty())
2035                         css << "/* LyX Provided Styles */\n" << styles << '\n';
2036
2037                 styles = features.getTClassHTMLStyles();
2038                 if (!styles.empty())
2039                         css << "/* Layout-provided Styles */\n" << styles << '\n';
2040
2041                 bool const needfg = params().fontcolor != RGBColor(0, 0, 0);
2042                 bool const needbg = params().backgroundcolor != RGBColor(0xFF, 0xFF, 0xFF);
2043                 if (needfg || needbg) {
2044                                 css << "\nbody {\n";
2045                                 if (needfg)
2046                                    css << "  color: "
2047                                             << from_ascii(X11hexname(params().fontcolor))
2048                                             << ";\n";
2049                                 if (needbg)
2050                                    css << "  background-color: "
2051                                             << from_ascii(X11hexname(params().backgroundcolor))
2052                                             << ";\n";
2053                                 css << "}\n";
2054                 }
2055
2056                 docstring const dstyles = css.str();
2057                 if (!dstyles.empty()) {
2058                         bool written = false;
2059                         if (params().html_css_as_file) {
2060                                 // open a file for CSS info
2061                                 ofdocstream ocss;
2062                                 string const fcssname = addName(temppath(), "docstyle.css");
2063                                 FileName const fcssfile = FileName(fcssname);
2064                                 if (openFileWrite(ocss, fcssfile)) {
2065                                         ocss << dstyles;
2066                                         ocss.close();
2067                                         written = true;
2068                                         // write link to header
2069                                         os << "<link rel='stylesheet' href='docstyle.css' type='text/css' />\n";
2070                                         // register file
2071                                         runparams.exportdata->addExternalFile("xhtml", fcssfile);
2072                                 }
2073                         }
2074                         // we are here if the CSS is supposed to be written to the header
2075                         // or if we failed to write it to an external file.
2076                         if (!written) {
2077                                 os << "<style type='text/css'>\n"
2078                                          << dstyles
2079                                          << "\n</style>\n";
2080                         }
2081                 }
2082                 os << "</head>\n";
2083         }
2084
2085         if (output_body) {
2086                 bool const output_body_tag = (output != IncludedFile);
2087                 if (output_body_tag)
2088                         os << "<body>\n";
2089                 XHTMLStream xs(os);
2090                 if (output != IncludedFile)
2091                         // if we're an included file, the counters are in the master.
2092                         params().documentClass().counters().reset();
2093                 xhtmlParagraphs(text(), *this, xs, runparams);
2094                 if (output_body_tag)
2095                         os << "</body>\n";
2096         }
2097
2098         if (output_preamble)
2099                 os << "</html>\n";
2100 }
2101
2102
2103 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
2104 // Other flags: -wall -v0 -x
2105 int Buffer::runChktex()
2106 {
2107         setBusy(true);
2108
2109         // get LaTeX-Filename
2110         FileName const path(temppath());
2111         string const name = addName(path.absFileName(), latexName());
2112         string const org_path = filePath();
2113
2114         PathChanger p(path); // path to LaTeX file
2115         message(_("Running chktex..."));
2116
2117         // Generate the LaTeX file if neccessary
2118         OutputParams runparams(&params().encoding());
2119         runparams.flavor = OutputParams::LATEX;
2120         runparams.nice = false;
2121         runparams.linelen = lyxrc.plaintext_linelen;
2122         makeLaTeXFile(FileName(name), org_path, runparams);
2123
2124         TeXErrors terr;
2125         Chktex chktex(lyxrc.chktex_command, onlyFileName(name), filePath());
2126         int const res = chktex.run(terr); // run chktex
2127
2128         if (res == -1) {
2129                 Alert::error(_("chktex failure"),
2130                              _("Could not run chktex successfully."));
2131         } else {
2132                 ErrorList & errlist = d->errorLists["ChkTeX"];
2133                 errlist.clear();
2134                 bufferErrors(terr, errlist);
2135         }
2136
2137         setBusy(false);
2138
2139         if (runparams.silent)
2140                 d->errorLists["ChkTeX"].clear();
2141         else
2142                 errors("ChkTeX");
2143
2144         return res;
2145 }
2146
2147
2148 void Buffer::validate(LaTeXFeatures & features) const
2149 {
2150         // Validate the buffer params, but not for included
2151         // files, since they also use the parent buffer's
2152         // params (# 5941)
2153         if (!features.runparams().is_child)
2154                 params().validate(features);
2155
2156         for_each(paragraphs().begin(), paragraphs().end(),
2157                  bind(&Paragraph::validate, _1, ref(features)));
2158
2159         if (lyxerr.debugging(Debug::LATEX)) {
2160                 features.showStruct();
2161         }
2162 }
2163
2164
2165 void Buffer::getLabelList(vector<docstring> & list) const
2166 {
2167         // If this is a child document, use the master's list instead.
2168         if (parent()) {
2169                 masterBuffer()->getLabelList(list);
2170                 return;
2171         }
2172
2173         list.clear();
2174         Toc & toc = d->toc_backend.toc("label");
2175         TocIterator toc_it = toc.begin();
2176         TocIterator end = toc.end();
2177         for (; toc_it != end; ++toc_it) {
2178                 if (toc_it->depth() == 0)
2179                         list.push_back(toc_it->str());
2180         }
2181 }
2182
2183
2184 void Buffer::updateBibfilesCache(UpdateScope scope) const
2185 {
2186         // FIXME This is probably unnecssary, given where we call this.
2187         // If this is a child document, use the parent's cache instead.
2188         if (parent() && scope != UpdateChildOnly) {
2189                 masterBuffer()->updateBibfilesCache();
2190                 return;
2191         }
2192
2193         d->bibfiles_cache_.clear();
2194         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2195                 if (it->lyxCode() == BIBTEX_CODE) {
2196                         InsetBibtex const & inset = static_cast<InsetBibtex const &>(*it);
2197                         support::FileNameList const bibfiles = inset.getBibFiles();
2198                         d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2199                                 bibfiles.begin(),
2200                                 bibfiles.end());
2201                 } else if (it->lyxCode() == INCLUDE_CODE) {
2202                         InsetInclude & inset = static_cast<InsetInclude &>(*it);
2203                         Buffer const * const incbuf = inset.getChildBuffer();
2204                         if (!incbuf)
2205                                 continue;
2206                         support::FileNameList const & bibfiles =
2207                                         incbuf->getBibfilesCache(UpdateChildOnly);
2208                         if (!bibfiles.empty()) {
2209                                 d->bibfiles_cache_.insert(d->bibfiles_cache_.end(),
2210                                         bibfiles.begin(),
2211                                         bibfiles.end());
2212                         }
2213                 }
2214         }
2215         d->bibfile_cache_valid_ = true;
2216         d->bibinfo_cache_valid_ = false;
2217         d->cite_labels_valid_ = false;
2218 }
2219
2220
2221 void Buffer::invalidateBibinfoCache() const
2222 {
2223         d->bibinfo_cache_valid_ = false;
2224         d->cite_labels_valid_ = false;
2225         // also invalidate the cache for the parent buffer
2226         Buffer const * const pbuf = d->parent();
2227         if (pbuf)
2228                 pbuf->invalidateBibinfoCache();
2229 }
2230
2231
2232 void Buffer::invalidateBibfileCache() const
2233 {
2234         d->bibfile_cache_valid_ = false;
2235         d->bibinfo_cache_valid_ = false;
2236         d->cite_labels_valid_ = false;
2237         // also invalidate the cache for the parent buffer
2238         Buffer const * const pbuf = d->parent();
2239         if (pbuf)
2240                 pbuf->invalidateBibfileCache();
2241 }
2242
2243
2244 support::FileNameList const & Buffer::getBibfilesCache(UpdateScope scope) const
2245 {
2246         // FIXME This is probably unnecessary, given where we call this.
2247         // If this is a child document, use the master's cache instead.
2248         Buffer const * const pbuf = masterBuffer();
2249         if (pbuf != this && scope != UpdateChildOnly)
2250                 return pbuf->getBibfilesCache();
2251
2252         if (!d->bibfile_cache_valid_)
2253                 this->updateBibfilesCache(scope);
2254
2255         return d->bibfiles_cache_;
2256 }
2257
2258
2259 BiblioInfo const & Buffer::masterBibInfo() const
2260 {
2261         Buffer const * const tmp = masterBuffer();
2262         if (tmp != this)
2263                 return tmp->masterBibInfo();
2264         return d->bibinfo_;
2265 }
2266
2267
2268 void Buffer::checkIfBibInfoCacheIsValid() const
2269 {
2270         // use the master's cache
2271         Buffer const * const tmp = masterBuffer();
2272         if (tmp != this) {
2273                 tmp->checkIfBibInfoCacheIsValid();
2274                 return;
2275         }
2276
2277         // compare the cached timestamps with the actual ones.
2278         FileNameList const & bibfiles_cache = getBibfilesCache();
2279         FileNameList::const_iterator ei = bibfiles_cache.begin();
2280         FileNameList::const_iterator en = bibfiles_cache.end();
2281         for (; ei != en; ++ ei) {
2282                 time_t lastw = ei->lastModified();
2283                 time_t prevw = d->bibfile_status_[*ei];
2284                 if (lastw != prevw) {
2285                         d->bibinfo_cache_valid_ = false;
2286                         d->cite_labels_valid_ = false;
2287                         d->bibfile_status_[*ei] = lastw;
2288                 }
2289         }
2290 }
2291
2292
2293 void Buffer::reloadBibInfoCache() const
2294 {
2295         // use the master's cache
2296         Buffer const * const tmp = masterBuffer();
2297         if (tmp != this) {
2298                 tmp->reloadBibInfoCache();
2299                 return;
2300         }
2301
2302         checkIfBibInfoCacheIsValid();
2303         if (d->bibinfo_cache_valid_)
2304                 return;
2305
2306         d->bibinfo_.clear();
2307         collectBibKeys();
2308         d->bibinfo_cache_valid_ = true;
2309 }
2310
2311
2312 void Buffer::collectBibKeys() const
2313 {
2314         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
2315                 it->collectBibKeys(it);
2316 }
2317
2318
2319 void Buffer::addBiblioInfo(BiblioInfo const & bi) const
2320 {
2321         Buffer const * tmp = masterBuffer();
2322         BiblioInfo & masterbi = (tmp == this) ?
2323                 d->bibinfo_ : tmp->d->bibinfo_;
2324         masterbi.mergeBiblioInfo(bi);
2325 }
2326
2327
2328 void Buffer::addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const
2329 {
2330         Buffer const * tmp = masterBuffer();
2331         BiblioInfo & masterbi = (tmp == this) ?
2332                 d->bibinfo_ : tmp->d->bibinfo_;
2333         masterbi[key] = bi;
2334 }
2335
2336
2337 void Buffer::makeCitationLabels() const
2338 {
2339         Buffer const * const master = masterBuffer();
2340         return d->bibinfo_.makeCitationLabels(*master);
2341 }
2342
2343
2344 bool Buffer::citeLabelsValid() const
2345 {
2346         return masterBuffer()->d->cite_labels_valid_;
2347 }
2348
2349
2350 void Buffer::removeBiblioTempFiles() const
2351 {
2352         // We remove files that contain LaTeX commands specific to the
2353         // particular bibliographic style being used, in order to avoid
2354         // LaTeX errors when we switch style.
2355         FileName const aux_file(addName(temppath(), changeExtension(latexName(),".aux")));
2356         FileName const bbl_file(addName(temppath(), changeExtension(latexName(),".bbl")));
2357         LYXERR(Debug::FILES, "Removing the .aux file " << aux_file);
2358         aux_file.removeFile();
2359         LYXERR(Debug::FILES, "Removing the .bbl file " << bbl_file);
2360         bbl_file.removeFile();
2361         // Also for the parent buffer
2362         Buffer const * const pbuf = parent();
2363         if (pbuf)
2364                 pbuf->removeBiblioTempFiles();
2365 }
2366
2367
2368 bool Buffer::isDepClean(string const & name) const
2369 {
2370         DepClean::const_iterator const it = d->dep_clean.find(name);
2371         if (it == d->dep_clean.end())
2372                 return true;
2373         return it->second;
2374 }
2375
2376
2377 void Buffer::markDepClean(string const & name)
2378 {
2379         d->dep_clean[name] = true;
2380 }
2381
2382
2383 bool Buffer::getStatus(FuncRequest const & cmd, FuncStatus & flag)
2384 {
2385         if (isInternal()) {
2386                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2387                 // if internal, put a switch '(cmd.action)' here.
2388                 return false;
2389         }
2390
2391         bool enable = true;
2392
2393         switch (cmd.action()) {
2394
2395         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2396                 flag.setOnOff(isReadonly());
2397                 break;
2398
2399                 // FIXME: There is need for a command-line import.
2400                 //case LFUN_BUFFER_IMPORT:
2401
2402         case LFUN_BUFFER_AUTO_SAVE:
2403                 break;
2404
2405         case LFUN_BUFFER_EXPORT_CUSTOM:
2406                 // FIXME: Nothing to check here?
2407                 break;
2408
2409         case LFUN_BUFFER_EXPORT: {
2410                 docstring const arg = cmd.argument();
2411                 if (arg == "custom") {
2412                         enable = true;
2413                         break;
2414                 }
2415                 string format = to_utf8(arg);
2416                 size_t pos = format.find(' ');
2417                 if (pos != string::npos)
2418                         format = format.substr(0, pos);
2419                 enable = params().isExportable(format);
2420                 if (!enable)
2421                         flag.message(bformat(
2422                                              _("Don't know how to export to format: %1$s"), arg));
2423                 break;
2424         }
2425
2426         case LFUN_BUFFER_CHKTEX:
2427                 enable = params().isLatex() && !lyxrc.chktex_command.empty();
2428                 break;
2429
2430         case LFUN_BUILD_PROGRAM:
2431                 enable = params().isExportable("program");
2432                 break;
2433
2434         case LFUN_BRANCH_ACTIVATE:
2435         case LFUN_BRANCH_DEACTIVATE:
2436         case LFUN_BRANCH_MASTER_ACTIVATE:
2437         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2438                 bool const master = (cmd.action() == LFUN_BRANCH_MASTER_ACTIVATE
2439                                      || cmd.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2440                 BranchList const & branchList = master ? masterBuffer()->params().branchlist()
2441                         : params().branchlist();
2442                 docstring const branchName = cmd.argument();
2443                 flag.setEnabled(!branchName.empty() && branchList.find(branchName));
2444                 break;
2445         }
2446
2447         case LFUN_BRANCH_ADD:
2448         case LFUN_BRANCHES_RENAME:
2449         case LFUN_BUFFER_PRINT:
2450                 // if no Buffer is present, then of course we won't be called!
2451                 break;
2452
2453         case LFUN_BUFFER_LANGUAGE:
2454                 enable = !isReadonly();
2455                 break;
2456
2457         case LFUN_BUFFER_VIEW_CACHE:
2458                 enable = (d->preview_file_).exists();
2459                 break;
2460
2461         default:
2462                 return false;
2463         }
2464         flag.setEnabled(enable);
2465         return true;
2466 }
2467
2468
2469 void Buffer::dispatch(string const & command, DispatchResult & result)
2470 {
2471         return dispatch(lyxaction.lookupFunc(command), result);
2472 }
2473
2474
2475 // NOTE We can end up here even if we have no GUI, because we are called
2476 // by LyX::exec to handled command-line requests. So we may need to check
2477 // whether we have a GUI or not. The boolean use_gui holds this information.
2478 void Buffer::dispatch(FuncRequest const & func, DispatchResult & dr)
2479 {
2480         if (isInternal()) {
2481                 // FIXME? if there is an Buffer LFUN that can be dispatched even
2482                 // if internal, put a switch '(cmd.action())' here.
2483                 dr.dispatched(false);
2484                 return;
2485         }
2486         string const argument = to_utf8(func.argument());
2487         // We'll set this back to false if need be.
2488         bool dispatched = true;
2489         undo().beginUndoGroup();
2490
2491         switch (func.action()) {
2492         case LFUN_BUFFER_TOGGLE_READ_ONLY:
2493                 if (lyxvc().inUse()) {
2494                         string log = lyxvc().toggleReadOnly();
2495                         if (!log.empty())
2496                                 dr.setMessage(log);
2497                 }
2498                 else
2499                         setReadonly(!isReadonly());
2500                 break;
2501
2502         case LFUN_BUFFER_EXPORT: {
2503                 ExportStatus const status = doExport(argument, false);
2504                 dr.setError(status != ExportSuccess);
2505                 if (status != ExportSuccess)
2506                         dr.setMessage(bformat(_("Error exporting to format: %1$s."),
2507                                               func.argument()));
2508                 break;
2509         }
2510
2511         case LFUN_BUILD_PROGRAM: {
2512                 ExportStatus const status = doExport("program", true);
2513                 dr.setError(status != ExportSuccess);
2514                 if (status != ExportSuccess)
2515                         dr.setMessage(_("Error generating literate programming code."));
2516                 break;
2517         }
2518
2519         case LFUN_BUFFER_CHKTEX:
2520                 runChktex();
2521                 break;
2522
2523         case LFUN_BUFFER_EXPORT_CUSTOM: {
2524                 string format_name;
2525                 string command = split(argument, format_name, ' ');
2526                 Format const * format = formats.getFormat(format_name);
2527                 if (!format) {
2528                         lyxerr << "Format \"" << format_name
2529                                 << "\" not recognized!"
2530                                 << endl;
2531                         break;
2532                 }
2533
2534                 // The name of the file created by the conversion process
2535                 string filename;
2536
2537                 // Output to filename
2538                 if (format->name() == "lyx") {
2539                         string const latexname = latexName(false);
2540                         filename = changeExtension(latexname,
2541                                 format->extension());
2542                         filename = addName(temppath(), filename);
2543
2544                         if (!writeFile(FileName(filename)))
2545                                 break;
2546
2547                 } else {
2548                         doExport(format_name, true, filename);
2549                 }
2550
2551                 // Substitute $$FName for filename
2552                 if (!contains(command, "$$FName"))
2553                         command = "( " + command + " ) < $$FName";
2554                 command = subst(command, "$$FName", filename);
2555
2556                 // Execute the command in the background
2557                 Systemcall call;
2558                 call.startscript(Systemcall::DontWait, command,
2559                                  filePath(), layoutPos());
2560                 break;
2561         }
2562
2563         // FIXME: There is need for a command-line import.
2564         /*
2565         case LFUN_BUFFER_IMPORT:
2566                 doImport(argument);
2567                 break;
2568         */
2569
2570         case LFUN_BUFFER_AUTO_SAVE:
2571                 autoSave();
2572                 resetAutosaveTimers();
2573                 break;
2574
2575         case LFUN_BRANCH_ACTIVATE:
2576         case LFUN_BRANCH_DEACTIVATE:
2577         case LFUN_BRANCH_MASTER_ACTIVATE:
2578         case LFUN_BRANCH_MASTER_DEACTIVATE: {
2579                 bool const master = (func.action() == LFUN_BRANCH_MASTER_ACTIVATE
2580                                      || func.action() == LFUN_BRANCH_MASTER_DEACTIVATE);
2581                 Buffer * buf = master ? const_cast<Buffer *>(masterBuffer())
2582                                       : this;
2583
2584                 docstring const branch_name = func.argument();
2585                 // the case without a branch name is handled elsewhere
2586                 if (branch_name.empty()) {
2587                         dispatched = false;
2588                         break;
2589                 }
2590                 Branch * branch = buf->params().branchlist().find(branch_name);
2591                 if (!branch) {
2592                         LYXERR0("Branch " << branch_name << " does not exist.");
2593                         dr.setError(true);
2594                         docstring const msg =
2595                                 bformat(_("Branch \"%1$s\" does not exist."), branch_name);
2596                         dr.setMessage(msg);
2597                         break;
2598                 }
2599                 bool const activate = (func.action() == LFUN_BRANCH_ACTIVATE
2600                                        || func.action() == LFUN_BRANCH_MASTER_ACTIVATE);
2601                 if (branch->isSelected() != activate) {
2602                         buf->undo().recordUndoBufferParams(CursorData());
2603                         branch->setSelected(activate);
2604                         dr.setError(false);
2605                         dr.screenUpdate(Update::Force);
2606                         dr.forceBufferUpdate();
2607                 }
2608                 break;
2609         }
2610
2611         case LFUN_BRANCH_ADD: {
2612                 docstring branch_name = func.argument();
2613                 if (branch_name.empty()) {
2614                         dispatched = false;
2615                         break;
2616                 }
2617                 BranchList & branch_list = params().branchlist();
2618                 vector<docstring> const branches =
2619                         getVectorFromString(branch_name, branch_list.separator());
2620                 docstring msg;
2621                 for (vector<docstring>::const_iterator it = branches.begin();
2622                      it != branches.end(); ++it) {
2623                         branch_name = *it;
2624                         Branch * branch = branch_list.find(branch_name);
2625                         if (branch) {
2626                                 LYXERR0("Branch " << branch_name << " already exists.");
2627                                 dr.setError(true);
2628                                 if (!msg.empty())
2629                                         msg += ("\n");
2630                                 msg += bformat(_("Branch \"%1$s\" already exists."), branch_name);
2631                         } else {
2632                                 undo().recordUndoBufferParams(CursorData());
2633                                 branch_list.add(branch_name);
2634                                 branch = branch_list.find(branch_name);
2635                                 string const x11hexname = X11hexname(branch->color());
2636                                 docstring const str = branch_name + ' ' + from_ascii(x11hexname);
2637                                 lyx::dispatch(FuncRequest(LFUN_SET_COLOR, str));
2638                                 dr.setError(false);
2639                                 dr.screenUpdate(Update::Force);
2640                         }
2641                 }
2642                 if (!msg.empty())
2643                         dr.setMessage(msg);
2644                 break;
2645         }
2646
2647         case LFUN_BRANCHES_RENAME: {
2648                 if (func.argument().empty())
2649                         break;
2650
2651                 docstring const oldname = from_utf8(func.getArg(0));
2652                 docstring const newname = from_utf8(func.getArg(1));
2653                 InsetIterator it  = inset_iterator_begin(inset());
2654                 InsetIterator const end = inset_iterator_end(inset());
2655                 bool success = false;
2656                 for (; it != end; ++it) {
2657                         if (it->lyxCode() == BRANCH_CODE) {
2658                                 InsetBranch & ins = static_cast<InsetBranch &>(*it);
2659                                 if (ins.branch() == oldname) {
2660                                         undo().recordUndo(CursorData(it));
2661                                         ins.rename(newname);
2662                                         success = true;
2663                                         continue;
2664                                 }
2665                         }
2666                         if (it->lyxCode() == INCLUDE_CODE) {
2667                                 // get buffer of external file
2668                                 InsetInclude const & ins =
2669                                         static_cast<InsetInclude const &>(*it);
2670                                 Buffer * child = ins.getChildBuffer();
2671                                 if (!child)
2672                                         continue;
2673                                 child->dispatch(func, dr);
2674                         }
2675                 }
2676
2677                 if (success) {
2678                         dr.screenUpdate(Update::Force);
2679                         dr.forceBufferUpdate();
2680                 }
2681                 break;
2682         }
2683
2684         case LFUN_BUFFER_PRINT: {
2685                 // we'll assume there's a problem until we succeed
2686                 dr.setError(true);
2687                 string target = func.getArg(0);
2688                 string target_name = func.getArg(1);
2689                 string command = func.getArg(2);
2690
2691                 if (target.empty()
2692                     || target_name.empty()
2693                     || command.empty()) {
2694                         LYXERR0("Unable to parse " << func.argument());
2695                         docstring const msg =
2696                                 bformat(_("Unable to parse \"%1$s\""), func.argument());
2697                         dr.setMessage(msg);
2698                         break;
2699                 }
2700                 if (target != "printer" && target != "file") {
2701                         LYXERR0("Unrecognized target \"" << target << '"');
2702                         docstring const msg =
2703                                 bformat(_("Unrecognized target \"%1$s\""), from_utf8(target));
2704                         dr.setMessage(msg);
2705                         break;
2706                 }
2707
2708                 if (doExport("dvi", true) != ExportSuccess) {
2709                         showPrintError(absFileName());
2710                         dr.setMessage(_("Error exporting to DVI."));
2711                         break;
2712                 }
2713
2714                 // Push directory path.
2715                 string const path = temppath();
2716                 // Prevent the compiler from optimizing away p
2717                 FileName pp(path);
2718                 PathChanger p(pp);
2719
2720                 // there are three cases here:
2721                 // 1. we print to a file
2722                 // 2. we print directly to a printer
2723                 // 3. we print using a spool command (print to file first)
2724                 Systemcall one;
2725                 int res = 0;
2726                 string const dviname = changeExtension(latexName(true), "dvi");
2727
2728                 if (target == "printer") {
2729                         if (!lyxrc.print_spool_command.empty()) {
2730                                 // case 3: print using a spool
2731                                 string const psname = changeExtension(dviname,".ps");
2732                                 command += ' ' + lyxrc.print_to_file
2733                                         + quoteName(psname)
2734                                         + ' '
2735                                         + quoteName(dviname);
2736
2737                                 string command2 = lyxrc.print_spool_command + ' ';
2738                                 if (target_name != "default") {
2739                                         command2 += lyxrc.print_spool_printerprefix
2740                                                 + target_name
2741                                                 + ' ';
2742                                 }
2743                                 command2 += quoteName(psname);
2744                                 // First run dvips.
2745                                 // If successful, then spool command
2746                                 res = one.startscript(Systemcall::Wait, command,
2747                                                       filePath(), layoutPos());
2748
2749                                 if (res == 0) {
2750                                         // If there's no GUI, we have to wait on this command. Otherwise,
2751                                         // LyX deletes the temporary directory, and with it the spooled
2752                                         // file, before it can be printed!!
2753                                         Systemcall::Starttype stype = use_gui ?
2754                                                 Systemcall::DontWait : Systemcall::Wait;
2755                                         res = one.startscript(stype, command2,
2756                                                               filePath(),
2757                                                               layoutPos());
2758                                 }
2759                         } else {
2760                                 // case 2: print directly to a printer
2761                                 if (target_name != "default")
2762                                         command += ' ' + lyxrc.print_to_printer + target_name + ' ';
2763                                 // as above....
2764                                 Systemcall::Starttype stype = use_gui ?
2765                                         Systemcall::DontWait : Systemcall::Wait;
2766                                 res = one.startscript(stype,
2767                                                 command + quoteName(dviname),
2768                                                 filePath(), layoutPos());
2769                         }
2770
2771                 } else {
2772                         // case 1: print to a file
2773                         FileName const filename(makeAbsPath(target_name, filePath()));
2774                         FileName const dvifile(makeAbsPath(dviname, path));
2775                         if (filename.exists()) {
2776                                 docstring text = bformat(
2777                                         _("The file %1$s already exists.\n\n"
2778                                           "Do you want to overwrite that file?"),
2779                                         makeDisplayPath(filename.absFileName()));
2780                                 if (Alert::prompt(_("Overwrite file?"),
2781                                                   text, 0, 1, _("&Overwrite"), _("&Cancel")) != 0)
2782                                         break;
2783                         }
2784                         command += ' ' + lyxrc.print_to_file
2785                                 + quoteName(filename.toFilesystemEncoding())
2786                                 + ' '
2787                                 + quoteName(dvifile.toFilesystemEncoding());
2788                         // as above....
2789                         Systemcall::Starttype stype = use_gui ?
2790                                 Systemcall::DontWait : Systemcall::Wait;
2791                         res = one.startscript(stype, command, filePath(), layoutPos());
2792                 }
2793
2794                 if (res == 0)
2795                         dr.setError(false);
2796                 else {
2797                         dr.setMessage(_("Error running external commands."));
2798                         showPrintError(absFileName());
2799                 }
2800                 break;
2801         }
2802
2803         case LFUN_BUFFER_VIEW_CACHE:
2804                 if (!formats.view(*this, d->preview_file_,
2805                                   d->preview_format_))
2806                         dr.setMessage(_("Error viewing the output file."));
2807                 break;
2808
2809         default:
2810                 dispatched = false;
2811                 break;
2812         }
2813         dr.dispatched(dispatched);
2814         undo().endUndoGroup();
2815 }
2816
2817
2818 void Buffer::changeLanguage(Language const * from, Language const * to)
2819 {
2820         LASSERT(from, return);
2821         LASSERT(to, return);
2822
2823         for_each(par_iterator_begin(),
2824                  par_iterator_end(),
2825                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
2826 }
2827
2828
2829 bool Buffer::isMultiLingual() const
2830 {
2831         ParConstIterator end = par_iterator_end();
2832         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2833                 if (it->isMultiLingual(params()))
2834                         return true;
2835
2836         return false;
2837 }
2838
2839
2840 std::set<Language const *> Buffer::getLanguages() const
2841 {
2842         std::set<Language const *> languages;
2843         getLanguages(languages);
2844         return languages;
2845 }
2846
2847
2848 void Buffer::getLanguages(std::set<Language const *> & languages) const
2849 {
2850         ParConstIterator end = par_iterator_end();
2851         // add the buffer language, even if it's not actively used
2852         languages.insert(language());
2853         // iterate over the paragraphs
2854         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
2855                 it->getLanguages(languages);
2856         // also children
2857         ListOfBuffers clist = getDescendents();
2858         ListOfBuffers::const_iterator cit = clist.begin();
2859         ListOfBuffers::const_iterator const cen = clist.end();
2860         for (; cit != cen; ++cit)
2861                 (*cit)->getLanguages(languages);
2862 }
2863
2864
2865 DocIterator Buffer::getParFromID(int const id) const
2866 {
2867         Buffer * buf = const_cast<Buffer *>(this);
2868         if (id < 0) {
2869                 // John says this is called with id == -1 from undo
2870                 lyxerr << "getParFromID(), id: " << id << endl;
2871                 return doc_iterator_end(buf);
2872         }
2873
2874         for (DocIterator it = doc_iterator_begin(buf); !it.atEnd(); it.forwardPar())
2875                 if (it.paragraph().id() == id)
2876                         return it;
2877
2878         return doc_iterator_end(buf);
2879 }
2880
2881
2882 bool Buffer::hasParWithID(int const id) const
2883 {
2884         return !getParFromID(id).atEnd();
2885 }
2886
2887
2888 ParIterator Buffer::par_iterator_begin()
2889 {
2890         return ParIterator(doc_iterator_begin(this));
2891 }
2892
2893
2894 ParIterator Buffer::par_iterator_end()
2895 {
2896         return ParIterator(doc_iterator_end(this));
2897 }
2898
2899
2900 ParConstIterator Buffer::par_iterator_begin() const
2901 {
2902         return ParConstIterator(doc_iterator_begin(this));
2903 }
2904
2905
2906 ParConstIterator Buffer::par_iterator_end() const
2907 {
2908         return ParConstIterator(doc_iterator_end(this));
2909 }
2910
2911
2912 Language const * Buffer::language() const
2913 {
2914         return params().language;
2915 }
2916
2917
2918 docstring const Buffer::B_(string const & l10n) const
2919 {
2920         return params().B_(l10n);
2921 }
2922
2923
2924 bool Buffer::isClean() const
2925 {
2926         return d->lyx_clean;
2927 }
2928
2929
2930 bool Buffer::isExternallyModified(CheckMethod method) const
2931 {
2932         LASSERT(d->filename.exists(), return false);
2933         // if method == timestamp, check timestamp before checksum
2934         return (method == checksum_method
2935                 || d->timestamp_ != d->filename.lastModified())
2936                 && d->checksum_ != d->filename.checksum();
2937 }
2938
2939
2940 void Buffer::saveCheckSum() const
2941 {
2942         FileName const & file = d->filename;
2943
2944         file.refresh();
2945         if (file.exists()) {
2946                 d->timestamp_ = file.lastModified();
2947                 d->checksum_ = file.checksum();
2948         } else {
2949                 // in the case of save to a new file.
2950                 d->timestamp_ = 0;
2951                 d->checksum_ = 0;
2952         }
2953 }
2954
2955
2956 void Buffer::markClean() const
2957 {
2958         if (!d->lyx_clean) {
2959                 d->lyx_clean = true;
2960                 updateTitles();
2961         }
2962         // if the .lyx file has been saved, we don't need an
2963         // autosave
2964         d->bak_clean = true;
2965         d->undo_.markDirty();
2966 }
2967
2968
2969 void Buffer::setUnnamed(bool flag)
2970 {
2971         d->unnamed = flag;
2972 }
2973
2974
2975 bool Buffer::isUnnamed() const
2976 {
2977         return d->unnamed;
2978 }
2979
2980
2981 /// \note
2982 /// Don't check unnamed, here: isInternal() is used in
2983 /// newBuffer(), where the unnamed flag has not been set by anyone
2984 /// yet. Also, for an internal buffer, there should be no need for
2985 /// retrieving fileName() nor for checking if it is unnamed or not.
2986 bool Buffer::isInternal() const
2987 {
2988         return d->internal_buffer;
2989 }
2990
2991
2992 void Buffer::setInternal(bool flag)
2993 {
2994         d->internal_buffer = flag;
2995 }
2996
2997
2998 void Buffer::markDirty()
2999 {
3000         if (d->lyx_clean) {
3001                 d->lyx_clean = false;
3002                 updateTitles();
3003         }
3004         d->bak_clean = false;
3005
3006         DepClean::iterator it = d->dep_clean.begin();
3007         DepClean::const_iterator const end = d->dep_clean.end();
3008
3009         for (; it != end; ++it)
3010                 it->second = false;
3011 }
3012
3013
3014 FileName Buffer::fileName() const
3015 {
3016         return d->filename;
3017 }
3018
3019
3020 string Buffer::absFileName() const
3021 {
3022         return d->filename.absFileName();
3023 }
3024
3025
3026 string Buffer::filePath() const
3027 {
3028         string const abs = d->filename.onlyPath().absFileName();
3029         if (abs.empty())
3030                 return abs;
3031         int last = abs.length() - 1;
3032
3033         return abs[last] == '/' ? abs : abs + '/';
3034 }
3035
3036
3037 string Buffer::originFilePath() const
3038 {
3039         if (FileName::isAbsolute(params().origin))
3040                 return params().origin;
3041
3042         return filePath();
3043 }
3044
3045
3046 string Buffer::layoutPos() const
3047 {
3048         return d->layout_position;
3049 }
3050
3051
3052 void Buffer::setLayoutPos(string const & path)
3053 {
3054         if (path.empty()) {
3055                 d->layout_position.clear();
3056                 return;
3057         }
3058
3059         LATTEST(FileName::isAbsolute(path));
3060
3061         d->layout_position =
3062                 to_utf8(makeRelPath(from_utf8(path), from_utf8(filePath())));
3063
3064         if (d->layout_position.empty())
3065                 d->layout_position = ".";
3066 }
3067
3068
3069 bool Buffer::isReadonly() const
3070 {
3071         return d->read_only;
3072 }
3073
3074
3075 void Buffer::setParent(Buffer const * buffer)
3076 {
3077         // Avoids recursive include.
3078         d->setParent(buffer == this ? 0 : buffer);
3079         updateMacros();
3080 }
3081
3082
3083 Buffer const * Buffer::parent() const
3084 {
3085         return d->parent();
3086 }
3087
3088
3089 ListOfBuffers Buffer::allRelatives() const
3090 {
3091         ListOfBuffers lb = masterBuffer()->getDescendents();
3092         lb.push_front(const_cast<Buffer *>(masterBuffer()));
3093         return lb;
3094 }
3095
3096
3097 Buffer const * Buffer::masterBuffer() const
3098 {
3099         // FIXME Should be make sure we are not in some kind
3100         // of recursive include? A -> B -> A will crash this.
3101         Buffer const * const pbuf = d->parent();
3102         if (!pbuf)
3103                 return this;
3104
3105         return pbuf->masterBuffer();
3106 }
3107
3108
3109 bool Buffer::isChild(Buffer * child) const
3110 {
3111         return d->children_positions.find(child) != d->children_positions.end();
3112 }
3113
3114
3115 DocIterator Buffer::firstChildPosition(Buffer const * child)
3116 {
3117         Impl::BufferPositionMap::iterator it;
3118         it = d->children_positions.find(child);
3119         if (it == d->children_positions.end())
3120                 return DocIterator(this);
3121         return it->second;
3122 }
3123
3124
3125 bool Buffer::hasChildren() const
3126 {
3127         return !d->children_positions.empty();
3128 }
3129
3130
3131 void Buffer::collectChildren(ListOfBuffers & clist, bool grand_children) const
3132 {
3133         // loop over children
3134         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3135         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3136         for (; it != end; ++it) {
3137                 Buffer * child = const_cast<Buffer *>(it->first);
3138                 // No duplicates
3139                 ListOfBuffers::const_iterator bit = find(clist.begin(), clist.end(), child);
3140                 if (bit != clist.end())
3141                         continue;
3142                 clist.push_back(child);
3143                 if (grand_children)
3144                         // there might be grandchildren
3145                         child->collectChildren(clist, true);
3146         }
3147 }
3148
3149
3150 ListOfBuffers Buffer::getChildren() const
3151 {
3152         ListOfBuffers v;
3153         collectChildren(v, false);
3154         // Make sure we have not included ourselves.
3155         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3156         if (bit != v.end()) {
3157                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3158                 v.erase(bit);
3159         }
3160         return v;
3161 }
3162
3163
3164 ListOfBuffers Buffer::getDescendents() const
3165 {
3166         ListOfBuffers v;
3167         collectChildren(v, true);
3168         // Make sure we have not included ourselves.
3169         ListOfBuffers::iterator bit = find(v.begin(), v.end(), this);
3170         if (bit != v.end()) {
3171                 LYXERR0("Recursive include detected in `" << fileName() << "'.");
3172                 v.erase(bit);
3173         }
3174         return v;
3175 }
3176
3177
3178 template<typename M>
3179 typename M::const_iterator greatest_below(M & m, typename M::key_type const & x)
3180 {
3181         if (m.empty())
3182                 return m.end();
3183
3184         typename M::const_iterator it = m.lower_bound(x);
3185         if (it == m.begin())
3186                 return m.end();
3187
3188         it--;
3189         return it;
3190 }
3191
3192
3193 MacroData const * Buffer::Impl::getBufferMacro(docstring const & name,
3194                                          DocIterator const & pos) const
3195 {
3196         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
3197
3198         // if paragraphs have no macro context set, pos will be empty
3199         if (pos.empty())
3200                 return 0;
3201
3202         // we haven't found anything yet
3203         DocIterator bestPos = owner_->par_iterator_begin();
3204         MacroData const * bestData = 0;
3205
3206         // find macro definitions for name
3207         NamePositionScopeMacroMap::const_iterator nameIt = macros.find(name);
3208         if (nameIt != macros.end()) {
3209                 // find last definition in front of pos or at pos itself
3210                 PositionScopeMacroMap::const_iterator it
3211                         = greatest_below(nameIt->second, pos);
3212                 if (it != nameIt->second.end()) {
3213                         while (true) {
3214                                 // scope ends behind pos?
3215                                 if (pos < it->second.scope) {
3216                                         // Looks good, remember this. If there
3217                                         // is no external macro behind this,
3218                                         // we found the right one already.
3219                                         bestPos = it->first;
3220                                         bestData = &it->second.macro;
3221                                         break;
3222                                 }
3223
3224                                 // try previous macro if there is one
3225                                 if (it == nameIt->second.begin())
3226                                         break;
3227                                 --it;
3228                         }
3229                 }
3230         }
3231
3232         // find macros in included files
3233         PositionScopeBufferMap::const_iterator it
3234                 = greatest_below(position_to_children, pos);
3235         if (it == position_to_children.end())
3236                 // no children before
3237                 return bestData;
3238
3239         while (true) {
3240                 // do we know something better (i.e. later) already?
3241                 if (it->first < bestPos )
3242                         break;
3243
3244                 // scope ends behind pos?
3245                 if (pos < it->second.scope
3246                         && (cloned_buffer_ ||
3247                             theBufferList().isLoaded(it->second.buffer))) {
3248                         // look for macro in external file
3249                         macro_lock = true;
3250                         MacroData const * data
3251                                 = it->second.buffer->getMacro(name, false);
3252                         macro_lock = false;
3253                         if (data) {
3254                                 bestPos = it->first;
3255                                 bestData = data;
3256                                 break;
3257                         }
3258                 }
3259
3260                 // try previous file if there is one
3261                 if (it == position_to_children.begin())
3262                         break;
3263                 --it;
3264         }
3265
3266         // return the best macro we have found
3267         return bestData;
3268 }
3269
3270
3271 MacroData const * Buffer::getMacro(docstring const & name,
3272         DocIterator const & pos, bool global) const
3273 {
3274         if (d->macro_lock)
3275                 return 0;
3276
3277         // query buffer macros
3278         MacroData const * data = d->getBufferMacro(name, pos);
3279         if (data != 0)
3280                 return data;
3281
3282         // If there is a master buffer, query that
3283         Buffer const * const pbuf = d->parent();
3284         if (pbuf) {
3285                 d->macro_lock = true;
3286                 MacroData const * macro = pbuf->getMacro(
3287                         name, *this, false);
3288                 d->macro_lock = false;
3289                 if (macro)
3290                         return macro;
3291         }
3292
3293         if (global) {
3294                 data = MacroTable::globalMacros().get(name);
3295                 if (data != 0)
3296                         return data;
3297         }
3298
3299         return 0;
3300 }
3301
3302
3303 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
3304 {
3305         // set scope end behind the last paragraph
3306         DocIterator scope = par_iterator_begin();
3307         scope.pit() = scope.lastpit() + 1;
3308
3309         return getMacro(name, scope, global);
3310 }
3311
3312
3313 MacroData const * Buffer::getMacro(docstring const & name,
3314         Buffer const & child, bool global) const
3315 {
3316         // look where the child buffer is included first
3317         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
3318         if (it == d->children_positions.end())
3319                 return 0;
3320
3321         // check for macros at the inclusion position
3322         return getMacro(name, it->second, global);
3323 }
3324
3325
3326 void Buffer::Impl::updateMacros(DocIterator & it, DocIterator & scope)
3327 {
3328         pit_type const lastpit = it.lastpit();
3329
3330         // look for macros in each paragraph
3331         while (it.pit() <= lastpit) {
3332                 Paragraph & par = it.paragraph();
3333
3334                 // iterate over the insets of the current paragraph
3335                 InsetList const & insets = par.insetList();
3336                 InsetList::const_iterator iit = insets.begin();
3337                 InsetList::const_iterator end = insets.end();
3338                 for (; iit != end; ++iit) {
3339                         it.pos() = iit->pos;
3340
3341                         // is it a nested text inset?
3342                         if (iit->inset->asInsetText()) {
3343                                 // Inset needs its own scope?
3344                                 InsetText const * itext = iit->inset->asInsetText();
3345                                 bool newScope = itext->isMacroScope();
3346
3347                                 // scope which ends just behind the inset
3348                                 DocIterator insetScope = it;
3349                                 ++insetScope.pos();
3350
3351                                 // collect macros in inset
3352                                 it.push_back(CursorSlice(*iit->inset));
3353                                 updateMacros(it, newScope ? insetScope : scope);
3354                                 it.pop_back();
3355                                 continue;
3356                         }
3357
3358                         if (iit->inset->asInsetTabular()) {
3359                                 CursorSlice slice(*iit->inset);
3360                                 size_t const numcells = slice.nargs();
3361                                 for (; slice.idx() < numcells; slice.forwardIdx()) {
3362                                         it.push_back(slice);
3363                                         updateMacros(it, scope);
3364                                         it.pop_back();
3365                                 }
3366                                 continue;
3367                         }
3368
3369                         // is it an external file?
3370                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
3371                                 // get buffer of external file
3372                                 InsetInclude const & inset =
3373                                         static_cast<InsetInclude const &>(*iit->inset);
3374                                 macro_lock = true;
3375                                 Buffer * child = inset.getChildBuffer();
3376                                 macro_lock = false;
3377                                 if (!child)
3378                                         continue;
3379
3380                                 // register its position, but only when it is
3381                                 // included first in the buffer
3382                                 if (children_positions.find(child) ==
3383                                         children_positions.end())
3384                                                 children_positions[child] = it;
3385
3386                                 // register child with its scope
3387                                 position_to_children[it] = Impl::ScopeBuffer(scope, child);
3388                                 continue;
3389                         }
3390
3391                         InsetMath * im = iit->inset->asInsetMath();
3392                         if (doing_export && im)  {
3393                                 InsetMathHull * hull = im->asHullInset();
3394                                 if (hull)
3395                                         hull->recordLocation(it);
3396                         }
3397
3398                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
3399                                 continue;
3400
3401                         // get macro data
3402                         MathMacroTemplate & macroTemplate =
3403                                 *iit->inset->asInsetMath()->asMacroTemplate();
3404                         MacroContext mc(owner_, it);
3405                         macroTemplate.updateToContext(mc);
3406
3407                         // valid?
3408                         bool valid = macroTemplate.validMacro();
3409                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
3410                         // then the BufferView's cursor will be invalid in
3411                         // some cases which leads to crashes.
3412                         if (!valid)
3413                                 continue;
3414
3415                         // register macro
3416                         // FIXME (Abdel), I don't understand why we pass 'it' here
3417                         // instead of 'macroTemplate' defined above... is this correct?
3418                         macros[macroTemplate.name()][it] =
3419                                 Impl::ScopeMacro(scope, MacroData(const_cast<Buffer *>(owner_), it));
3420                 }
3421
3422                 // next paragraph
3423                 it.pit()++;
3424                 it.pos() = 0;
3425         }
3426 }
3427
3428
3429 void Buffer::updateMacros() const
3430 {
3431         if (d->macro_lock)
3432                 return;
3433
3434         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
3435
3436         // start with empty table
3437         d->macros.clear();
3438         d->children_positions.clear();
3439         d->position_to_children.clear();
3440
3441         // Iterate over buffer, starting with first paragraph
3442         // The scope must be bigger than any lookup DocIterator
3443         // later. For the global lookup, lastpit+1 is used, hence
3444         // we use lastpit+2 here.
3445         DocIterator it = par_iterator_begin();
3446         DocIterator outerScope = it;
3447         outerScope.pit() = outerScope.lastpit() + 2;
3448         d->updateMacros(it, outerScope);
3449 }
3450
3451
3452 void Buffer::getUsedBranches(std::list<docstring> & result, bool const from_master) const
3453 {
3454         InsetIterator it  = inset_iterator_begin(inset());
3455         InsetIterator const end = inset_iterator_end(inset());
3456         for (; it != end; ++it) {
3457                 if (it->lyxCode() == BRANCH_CODE) {
3458                         InsetBranch & br = static_cast<InsetBranch &>(*it);
3459                         docstring const name = br.branch();
3460                         if (!from_master && !params().branchlist().find(name))
3461                                 result.push_back(name);
3462                         else if (from_master && !masterBuffer()->params().branchlist().find(name))
3463                                 result.push_back(name);
3464                         continue;
3465                 }
3466                 if (it->lyxCode() == INCLUDE_CODE) {
3467                         // get buffer of external file
3468                         InsetInclude const & ins =
3469                                 static_cast<InsetInclude const &>(*it);
3470                         Buffer * child = ins.getChildBuffer();
3471                         if (!child)
3472                                 continue;
3473                         child->getUsedBranches(result, true);
3474                 }
3475         }
3476         // remove duplicates
3477         result.unique();
3478 }
3479
3480
3481 void Buffer::updateMacroInstances(UpdateType utype) const
3482 {
3483         LYXERR(Debug::MACROS, "updateMacroInstances for "
3484                 << d->filename.onlyFileName());
3485         DocIterator it = doc_iterator_begin(this);
3486         it.forwardInset();
3487         DocIterator const end = doc_iterator_end(this);
3488         for (; it != end; it.forwardInset()) {
3489                 // look for MathData cells in InsetMathNest insets
3490                 InsetMath * minset = it.nextInset()->asInsetMath();
3491                 if (!minset)
3492                         continue;
3493
3494                 // update macro in all cells of the InsetMathNest
3495                 DocIterator::idx_type n = minset->nargs();
3496                 MacroContext mc = MacroContext(this, it);
3497                 for (DocIterator::idx_type i = 0; i < n; ++i) {
3498                         MathData & data = minset->cell(i);
3499                         data.updateMacros(0, mc, utype);
3500                 }
3501         }
3502 }
3503
3504
3505 void Buffer::listMacroNames(MacroNameSet & macros) const
3506 {
3507         if (d->macro_lock)
3508                 return;
3509
3510         d->macro_lock = true;
3511
3512         // loop over macro names
3513         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
3514         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
3515         for (; nameIt != nameEnd; ++nameIt)
3516                 macros.insert(nameIt->first);
3517
3518         // loop over children
3519         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
3520         Impl::BufferPositionMap::iterator end = d->children_positions.end();
3521         for (; it != end; ++it)
3522                 it->first->listMacroNames(macros);
3523
3524         // call parent
3525         Buffer const * const pbuf = d->parent();
3526         if (pbuf)
3527                 pbuf->listMacroNames(macros);
3528
3529         d->macro_lock = false;
3530 }
3531
3532
3533 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
3534 {
3535         Buffer const * const pbuf = d->parent();
3536         if (!pbuf)
3537                 return;
3538
3539         MacroNameSet names;
3540         pbuf->listMacroNames(names);
3541
3542         // resolve macros
3543         MacroNameSet::iterator it = names.begin();
3544         MacroNameSet::iterator end = names.end();
3545         for (; it != end; ++it) {
3546                 // defined?
3547                 MacroData const * data =
3548                 pbuf->getMacro(*it, *this, false);
3549                 if (data) {
3550                         macros.insert(data);
3551
3552                         // we cannot access the original MathMacroTemplate anymore
3553                         // here to calls validate method. So we do its work here manually.
3554                         // FIXME: somehow make the template accessible here.
3555                         if (data->optionals() > 0)
3556                                 features.require("xargs");
3557                 }
3558         }
3559 }
3560
3561
3562 Buffer::References & Buffer::getReferenceCache(docstring const & label)
3563 {
3564         if (d->parent())
3565                 return const_cast<Buffer *>(masterBuffer())->getReferenceCache(label);
3566
3567         RefCache::iterator it = d->ref_cache_.find(label);
3568         if (it != d->ref_cache_.end())
3569                 return it->second.second;
3570
3571         static InsetLabel const * dummy_il = 0;
3572         static References const dummy_refs;
3573         it = d->ref_cache_.insert(
3574                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
3575         return it->second.second;
3576 }
3577
3578
3579 Buffer::References const & Buffer::references(docstring const & label) const
3580 {
3581         return const_cast<Buffer *>(this)->getReferenceCache(label);
3582 }
3583
3584
3585 void Buffer::addReference(docstring const & label, Inset * inset, ParIterator it)
3586 {
3587         References & refs = getReferenceCache(label);
3588         refs.push_back(make_pair(inset, it));
3589 }
3590
3591
3592 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
3593 {
3594         masterBuffer()->d->ref_cache_[label].first = il;
3595 }
3596
3597
3598 InsetLabel const * Buffer::insetLabel(docstring const & label) const
3599 {
3600         return masterBuffer()->d->ref_cache_[label].first;
3601 }
3602
3603
3604 void Buffer::clearReferenceCache() const
3605 {
3606         if (!d->parent())
3607                 d->ref_cache_.clear();
3608 }
3609
3610
3611 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to)
3612 {
3613         //FIXME: This does not work for child documents yet.
3614         reloadBibInfoCache();
3615
3616         // Check if the label 'from' appears more than once
3617         BiblioInfo const & keys = masterBibInfo();
3618         BiblioInfo::const_iterator bit  = keys.begin();
3619         BiblioInfo::const_iterator bend = keys.end();
3620         vector<docstring> labels;
3621
3622         for (; bit != bend; ++bit)
3623                 // FIXME UNICODE
3624                 labels.push_back(bit->first);
3625
3626         if (count(labels.begin(), labels.end(), from) > 1)
3627                 return;
3628
3629         string const paramName = "key";
3630         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
3631                 if (it->lyxCode() != CITE_CODE)
3632                         continue;
3633                 InsetCommand * inset = it->asInsetCommand();
3634                 docstring const oldValue = inset->getParam(paramName);
3635                 if (oldValue == from)
3636                         inset->setParam(paramName, to);
3637         }
3638 }
3639
3640
3641 void Buffer::getSourceCode(odocstream & os, string const & format,
3642                            pit_type par_begin, pit_type par_end,
3643                            OutputWhat output, bool master) const
3644 {
3645         OutputParams runparams(&params().encoding());
3646         runparams.nice = true;
3647         runparams.flavor = params().getOutputFlavor(format);
3648         runparams.linelen = lyxrc.plaintext_linelen;
3649         // No side effect of file copying and image conversion
3650         runparams.dryrun = true;
3651
3652         if (output == CurrentParagraph) {
3653                 runparams.par_begin = par_begin;
3654                 runparams.par_end = par_end;
3655                 if (par_begin + 1 == par_end) {
3656                         os << "% "
3657                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
3658                            << "\n\n";
3659                 } else {
3660                         os << "% "
3661                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
3662                                         convert<docstring>(par_begin),
3663                                         convert<docstring>(par_end - 1))
3664                            << "\n\n";
3665                 }
3666                 // output paragraphs
3667                 if (runparams.flavor == OutputParams::LYX) {
3668                         Paragraph const & par = text().paragraphs()[par_begin];
3669                         ostringstream ods;
3670                         depth_type dt = par.getDepth();
3671                         par.write(ods, params(), dt);
3672                         os << from_utf8(ods.str());
3673                 } else if (runparams.flavor == OutputParams::HTML) {
3674                         XHTMLStream xs(os);
3675                         setMathFlavor(runparams);
3676                         xhtmlParagraphs(text(), *this, xs, runparams);
3677                 } else if (runparams.flavor == OutputParams::TEXT) {
3678                         bool dummy = false;
3679                         // FIXME Handles only one paragraph, unlike the others.
3680                         // Probably should have some routine with a signature like them.
3681                         writePlaintextParagraph(*this,
3682                                 text().paragraphs()[par_begin], os, runparams, dummy);
3683                 } else if (params().isDocBook()) {
3684                         docbookParagraphs(text(), *this, os, runparams);
3685                 } else {
3686                         // If we are previewing a paragraph, even if this is the
3687                         // child of some other buffer, let's cut the link here,
3688                         // so that no concurring settings from the master
3689                         // (e.g. branch state) interfere (see #8101).
3690                         if (!master)
3691                                 d->ignore_parent = true;
3692                         // We need to validate the Buffer params' features here
3693                         // in order to know if we should output polyglossia
3694                         // macros (instead of babel macros)
3695                         LaTeXFeatures features(*this, params(), runparams);
3696                         params().validate(features);
3697                         runparams.use_polyglossia = features.usePolyglossia();
3698                         TexRow texrow;
3699                         texrow.reset();
3700                         texrow.newline();
3701                         texrow.newline();
3702                         // latex or literate
3703                         otexstream ots(os, texrow);
3704
3705                         // the real stuff
3706                         latexParagraphs(*this, text(), ots, runparams);
3707
3708                         // Restore the parenthood
3709                         if (!master)
3710                                 d->ignore_parent = false;
3711                 }
3712         } else {
3713                 os << "% ";
3714                 if (output == FullSource)
3715                         os << _("Preview source code");
3716                 else if (output == OnlyPreamble)
3717                         os << _("Preview preamble");
3718                 else if (output == OnlyBody)
3719                         os << _("Preview body");
3720                 os << "\n\n";
3721                 if (runparams.flavor == OutputParams::LYX) {
3722                         ostringstream ods;
3723                         if (output == FullSource)
3724                                 write(ods);
3725                         else if (output == OnlyPreamble)
3726                                 params().writeFile(ods, this);
3727                         else if (output == OnlyBody)
3728                                 text().write(ods);
3729                         os << from_utf8(ods.str());
3730                 } else if (runparams.flavor == OutputParams::HTML) {
3731                         writeLyXHTMLSource(os, runparams, output);
3732                 } else if (runparams.flavor == OutputParams::TEXT) {
3733                         if (output == OnlyPreamble) {
3734                                 os << "% "<< _("Plain text does not have a preamble.");
3735                         } else
3736                                 writePlaintextFile(*this, os, runparams);
3737                 } else if (params().isDocBook()) {
3738                                 writeDocBookSource(os, absFileName(), runparams, output);
3739                 } else {
3740                         // latex or literate
3741                         d->texrow.reset();
3742                         d->texrow.newline();
3743                         d->texrow.newline();
3744                         otexstream ots(os, d->texrow);
3745                         if (master)
3746                                 runparams.is_child = true;
3747                         writeLaTeXSource(ots, string(), runparams, output);
3748                 }
3749         }
3750 }
3751
3752
3753 ErrorList & Buffer::errorList(string const & type) const
3754 {
3755         return d->errorLists[type];
3756 }
3757
3758
3759 void Buffer::updateTocItem(std::string const & type,
3760         DocIterator const & dit) const
3761 {
3762         if (d->gui_)
3763                 d->gui_->updateTocItem(type, dit);
3764 }
3765
3766
3767 void Buffer::structureChanged() const
3768 {
3769         if (d->gui_)
3770                 d->gui_->structureChanged();
3771 }
3772
3773
3774 void Buffer::errors(string const & err, bool from_master) const
3775 {
3776         if (d->gui_)
3777                 d->gui_->errors(err, from_master);
3778 }
3779
3780
3781 void Buffer::message(docstring const & msg) const
3782 {
3783         if (d->gui_)
3784                 d->gui_->message(msg);
3785 }
3786
3787
3788 void Buffer::setBusy(bool on) const
3789 {
3790         if (d->gui_)
3791                 d->gui_->setBusy(on);
3792 }
3793
3794
3795 void Buffer::updateTitles() const
3796 {
3797         if (d->wa_)
3798                 d->wa_->updateTitles();
3799 }
3800
3801
3802 void Buffer::resetAutosaveTimers() const
3803 {
3804         if (d->gui_)
3805                 d->gui_->resetAutosaveTimers();
3806 }
3807
3808
3809 bool Buffer::hasGuiDelegate() const
3810 {
3811         return d->gui_;
3812 }
3813
3814
3815 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
3816 {
3817         d->gui_ = gui;
3818 }
3819
3820
3821
3822 namespace {
3823
3824 class AutoSaveBuffer : public ForkedProcess {
3825 public:
3826         ///
3827         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
3828                 : buffer_(buffer), fname_(fname) {}
3829         ///
3830         virtual shared_ptr<ForkedProcess> clone() const
3831         {
3832                 return shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
3833         }
3834         ///
3835         int start()
3836         {
3837                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
3838                                                  from_utf8(fname_.absFileName())));
3839                 return run(DontWait);
3840         }
3841 private:
3842         ///
3843         virtual int generateChild();
3844         ///
3845         Buffer const & buffer_;
3846         FileName fname_;
3847 };
3848
3849
3850 int AutoSaveBuffer::generateChild()
3851 {
3852 #if defined(__APPLE__)
3853         /* FIXME fork() is not usable for autosave on Mac OS X 10.6 (snow leopard)
3854          *   We should use something else like threads.
3855          *
3856          * Since I do not know how to determine at run time what is the OS X
3857          * version, I just disable forking altogether for now (JMarc)
3858          */
3859         pid_t const pid = -1;
3860 #else
3861         // tmp_ret will be located (usually) in /tmp
3862         // will that be a problem?
3863         // Note that this calls ForkedCalls::fork(), so it's
3864         // ok cross-platform.
3865         pid_t const pid = fork();
3866         // If you want to debug the autosave
3867         // you should set pid to -1, and comment out the fork.
3868         if (pid != 0 && pid != -1)
3869                 return pid;
3870 #endif
3871
3872         // pid = -1 signifies that lyx was unable
3873         // to fork. But we will do the save
3874         // anyway.
3875         bool failed = false;
3876         TempFile tempfile("lyxautoXXXXXX.lyx");
3877         tempfile.setAutoRemove(false);
3878         FileName const tmp_ret = tempfile.name();
3879         if (!tmp_ret.empty()) {
3880                 if (!buffer_.writeFile(tmp_ret))
3881                         failed = true;
3882                 else if (!tmp_ret.moveTo(fname_))
3883                         failed = true;
3884         } else
3885                 failed = true;
3886
3887         if (failed) {
3888                 // failed to write/rename tmp_ret so try writing direct
3889                 if (!buffer_.writeFile(fname_)) {
3890                         // It is dangerous to do this in the child,
3891                         // but safe in the parent, so...
3892                         if (pid == -1) // emit message signal.
3893                                 buffer_.message(_("Autosave failed!"));
3894                 }
3895         }
3896
3897         if (pid == 0) // we are the child so...
3898                 _exit(0);
3899
3900         return pid;
3901 }
3902
3903 } // namespace anon
3904
3905
3906 FileName Buffer::getEmergencyFileName() const
3907 {
3908         return FileName(d->filename.absFileName() + ".emergency");
3909 }
3910
3911
3912 FileName Buffer::getAutosaveFileName() const
3913 {
3914         // if the document is unnamed try to save in the backup dir, else
3915         // in the default document path, and as a last try in the filePath,
3916         // which will most often be the temporary directory
3917         string fpath;
3918         if (isUnnamed())
3919                 fpath = lyxrc.backupdir_path.empty() ? lyxrc.document_path
3920                         : lyxrc.backupdir_path;
3921         if (!isUnnamed() || fpath.empty() || !FileName(fpath).exists())
3922                 fpath = filePath();
3923
3924         string const fname = "#" + d->filename.onlyFileName() + "#";
3925
3926         return makeAbsPath(fname, fpath);
3927 }
3928
3929
3930 void Buffer::removeAutosaveFile() const
3931 {
3932         FileName const f = getAutosaveFileName();
3933         if (f.exists())
3934                 f.removeFile();
3935 }
3936
3937
3938 void Buffer::moveAutosaveFile(support::FileName const & oldauto) const
3939 {
3940         FileName const newauto = getAutosaveFileName();
3941         oldauto.refresh();
3942         if (newauto != oldauto && oldauto.exists())
3943                 if (!oldauto.moveTo(newauto))
3944                         LYXERR0("Unable to move autosave file `" << oldauto << "'!");
3945 }
3946
3947
3948 bool Buffer::autoSave() const
3949 {
3950         Buffer const * buf = d->cloned_buffer_ ? d->cloned_buffer_ : this;
3951         if (buf->d->bak_clean || isReadonly())
3952                 return true;
3953
3954         message(_("Autosaving current document..."));
3955         buf->d->bak_clean = true;
3956
3957         FileName const fname = getAutosaveFileName();
3958         LASSERT(d->cloned_buffer_, return false);
3959
3960         // If this buffer is cloned, we assume that
3961         // we are running in a separate thread already.
3962         TempFile tempfile("lyxautoXXXXXX.lyx");
3963         tempfile.setAutoRemove(false);
3964         FileName const tmp_ret = tempfile.name();
3965         if (!tmp_ret.empty()) {
3966                 writeFile(tmp_ret);
3967                 // assume successful write of tmp_ret
3968                 if (tmp_ret.moveTo(fname))
3969                         return true;
3970         }
3971         // failed to write/rename tmp_ret so try writing direct
3972         return writeFile(fname);
3973 }
3974
3975
3976 void Buffer::setExportStatus(bool e) const
3977 {
3978         d->doing_export = e;
3979         ListOfBuffers clist = getDescendents();
3980         ListOfBuffers::const_iterator cit = clist.begin();
3981         ListOfBuffers::const_iterator const cen = clist.end();
3982         for (; cit != cen; ++cit)
3983                 (*cit)->d->doing_export = e;
3984 }
3985
3986
3987 bool Buffer::isExporting() const
3988 {
3989         return d->doing_export;
3990 }
3991
3992
3993 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir)
3994         const
3995 {
3996         string result_file;
3997         return doExport(target, put_in_tempdir, result_file);
3998 }
3999
4000 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4001         string & result_file) const
4002 {
4003         bool const update_unincluded =
4004                         params().maintain_unincluded_children
4005                         && !params().getIncludedChildren().empty();
4006
4007         // (1) export with all included children (omit \includeonly)
4008         if (update_unincluded) {
4009                 ExportStatus const status =
4010                         doExport(target, put_in_tempdir, true, result_file);
4011                 if (status != ExportSuccess)
4012                         return status;
4013         }
4014         // (2) export with included children only
4015         return doExport(target, put_in_tempdir, false, result_file);
4016 }
4017
4018
4019 void Buffer::setMathFlavor(OutputParams & op) const
4020 {
4021         switch (params().html_math_output) {
4022         case BufferParams::MathML:
4023                 op.math_flavor = OutputParams::MathAsMathML;
4024                 break;
4025         case BufferParams::HTML:
4026                 op.math_flavor = OutputParams::MathAsHTML;
4027                 break;
4028         case BufferParams::Images:
4029                 op.math_flavor = OutputParams::MathAsImages;
4030                 break;
4031         case BufferParams::LaTeX:
4032                 op.math_flavor = OutputParams::MathAsLaTeX;
4033                 break;
4034         }
4035 }
4036
4037
4038 Buffer::ExportStatus Buffer::doExport(string const & target, bool put_in_tempdir,
4039         bool includeall, string & result_file) const
4040 {
4041         LYXERR(Debug::FILES, "target=" << target);
4042         OutputParams runparams(&params().encoding());
4043         string format = target;
4044         string dest_filename;
4045         size_t pos = target.find(' ');
4046         if (pos != string::npos) {
4047                 dest_filename = target.substr(pos + 1, target.length() - pos - 1);
4048                 format = target.substr(0, pos);
4049                 runparams.export_folder = FileName(dest_filename).onlyPath().realPath();
4050                 FileName(dest_filename).onlyPath().createPath();
4051                 LYXERR(Debug::FILES, "format=" << format << ", dest_filename=" << dest_filename << ", export_folder=" << runparams.export_folder);
4052         }
4053         MarkAsExporting exporting(this);
4054         string backend_format;
4055         runparams.flavor = OutputParams::LATEX;
4056         runparams.linelen = lyxrc.plaintext_linelen;
4057         runparams.includeall = includeall;
4058         vector<string> backs = params().backends();
4059         Converters converters = theConverters();
4060         bool need_nice_file = false;
4061         if (find(backs.begin(), backs.end(), format) == backs.end()) {
4062                 // Get shortest path to format
4063                 converters.buildGraph();
4064                 Graph::EdgePath path;
4065                 for (vector<string>::const_iterator it = backs.begin();
4066                      it != backs.end(); ++it) {
4067                         Graph::EdgePath p = converters.getPath(*it, format);
4068                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
4069                                 backend_format = *it;
4070                                 path = p;
4071                         }
4072                 }
4073                 if (path.empty()) {
4074                         if (!put_in_tempdir) {
4075                                 // Only show this alert if this is an export to a non-temporary
4076                                 // file (not for previewing).
4077                                 Alert::error(_("Couldn't export file"), bformat(
4078                                         _("No information for exporting the format %1$s."),
4079                                         formats.prettyName(format)));
4080                         }
4081                         return ExportNoPathToFormat;
4082                 }
4083                 runparams.flavor = converters.getFlavor(path, this);
4084                 Graph::EdgePath::const_iterator it = path.begin();
4085                 Graph::EdgePath::const_iterator en = path.end();
4086                 for (; it != en; ++it)
4087                         if (theConverters().get(*it).nice()) {
4088                                 need_nice_file = true;
4089                                 break;
4090                         }
4091
4092         } else {
4093                 backend_format = format;
4094                 LYXERR(Debug::FILES, "backend_format=" << backend_format);
4095                 // FIXME: Don't hardcode format names here, but use a flag
4096                 if (backend_format == "pdflatex")
4097                         runparams.flavor = OutputParams::PDFLATEX;
4098                 else if (backend_format == "luatex")
4099                         runparams.flavor = OutputParams::LUATEX;
4100                 else if (backend_format == "dviluatex")
4101                         runparams.flavor = OutputParams::DVILUATEX;
4102                 else if (backend_format == "xetex")
4103                         runparams.flavor = OutputParams::XETEX;
4104         }
4105
4106         string filename = latexName(false);
4107         filename = addName(temppath(), filename);
4108         filename = changeExtension(filename,
4109                                    formats.extension(backend_format));
4110         LYXERR(Debug::FILES, "filename=" << filename);
4111
4112         // Plain text backend
4113         if (backend_format == "text") {
4114                 runparams.flavor = OutputParams::TEXT;
4115                 writePlaintextFile(*this, FileName(filename), runparams);
4116         }
4117         // HTML backend
4118         else if (backend_format == "xhtml") {
4119                 runparams.flavor = OutputParams::HTML;
4120                 setMathFlavor(runparams);
4121                 makeLyXHTMLFile(FileName(filename), runparams);
4122         } else if (backend_format == "lyx")
4123                 writeFile(FileName(filename));
4124         // Docbook backend
4125         else if (params().isDocBook()) {
4126                 runparams.nice = !put_in_tempdir;
4127                 makeDocBookFile(FileName(filename), runparams);
4128         }
4129         // LaTeX backend
4130         else if (backend_format == format || need_nice_file) {
4131                 runparams.nice = true;
4132                 bool const success = makeLaTeXFile(FileName(filename), string(), runparams);
4133                 if (d->cloned_buffer_)
4134                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4135                 if (!success)
4136                         return ExportError;
4137         } else if (!lyxrc.tex_allows_spaces
4138                    && contains(filePath(), ' ')) {
4139                 Alert::error(_("File name error"),
4140                            _("The directory path to the document cannot contain spaces."));
4141                 return ExportTexPathHasSpaces;
4142         } else {
4143                 runparams.nice = false;
4144                 bool const success = makeLaTeXFile(
4145                         FileName(filename), filePath(), runparams);
4146                 if (d->cloned_buffer_)
4147                         d->cloned_buffer_->d->errorLists["Export"] = d->errorLists["Export"];
4148                 if (!success)
4149                         return ExportError;
4150         }
4151
4152         string const error_type = (format == "program")
4153                 ? "Build" : params().bufferFormat();
4154         ErrorList & error_list = d->errorLists[error_type];
4155         string const ext = formats.extension(format);
4156         FileName const tmp_result_file(changeExtension(filename, ext));
4157         bool const success = converters.convert(this, FileName(filename),
4158                 tmp_result_file, FileName(absFileName()), backend_format, format,
4159                 error_list);
4160
4161         // Emit the signal to show the error list or copy it back to the
4162         // cloned Buffer so that it can be emitted afterwards.
4163         if (format != backend_format) {
4164                 if (runparams.silent)
4165                         error_list.clear();
4166                 else if (d->cloned_buffer_)
4167                         d->cloned_buffer_->d->errorLists[error_type] =
4168                                 d->errorLists[error_type];
4169                 else
4170                         errors(error_type);
4171                 // also to the children, in case of master-buffer-view
4172                 ListOfBuffers clist = getDescendents();
4173                 ListOfBuffers::const_iterator cit = clist.begin();
4174                 ListOfBuffers::const_iterator const cen = clist.end();
4175                 for (; cit != cen; ++cit) {
4176                         if (runparams.silent)
4177                                 (*cit)->d->errorLists[error_type].clear();
4178                         else if (d->cloned_buffer_) {
4179                                 // Enable reverse search by copying back the
4180                                 // texrow object to the cloned buffer.
4181                                 // FIXME: this is not thread safe.
4182                                 (*cit)->d->cloned_buffer_->d->texrow = (*cit)->d->texrow;
4183                                 (*cit)->d->cloned_buffer_->d->errorLists[error_type] =
4184                                         (*cit)->d->errorLists[error_type];
4185                         } else
4186                                 (*cit)->errors(error_type, true);
4187                 }
4188         }
4189
4190         if (d->cloned_buffer_) {
4191                 // Enable reverse dvi or pdf to work by copying back the texrow
4192                 // object to the cloned buffer.
4193                 // FIXME: There is a possibility of concurrent access to texrow
4194                 // here from the main GUI thread that should be securized.
4195                 d->cloned_buffer_->d->texrow = d->texrow;
4196                 string const error_type = params().bufferFormat();
4197                 d->cloned_buffer_->d->errorLists[error_type] = d->errorLists[error_type];
4198         }
4199
4200
4201         if (put_in_tempdir) {
4202                 result_file = tmp_result_file.absFileName();
4203                 return success ? ExportSuccess : ExportConverterError;
4204         }
4205
4206         if (dest_filename.empty())
4207                 result_file = changeExtension(d->exportFileName().absFileName(), ext);
4208         else
4209                 result_file = dest_filename;
4210         // We need to copy referenced files (e. g. included graphics
4211         // if format == "dvi") to the result dir.
4212         vector<ExportedFile> const files =
4213                 runparams.exportdata->externalFiles(format);
4214         string const dest = runparams.export_folder.empty() ?
4215                 onlyPath(result_file) : runparams.export_folder;
4216         bool use_force = use_gui ? lyxrc.export_overwrite == ALL_FILES
4217                                  : force_overwrite == ALL_FILES;
4218         CopyStatus status = use_force ? FORCE : SUCCESS;
4219
4220         vector<ExportedFile>::const_iterator it = files.begin();
4221         vector<ExportedFile>::const_iterator const en = files.end();
4222         for (; it != en && status != CANCEL; ++it) {
4223                 string const fmt = formats.getFormatFromFile(it->sourceName);
4224                 string fixedName = it->exportName;
4225                 if (!runparams.export_folder.empty()) {
4226                         // Relative pathnames starting with ../ will be sanitized
4227                         // if exporting to a different folder
4228                         while (fixedName.substr(0, 3) == "../")
4229                                 fixedName = fixedName.substr(3, fixedName.length() - 3);
4230                 }
4231                 FileName fixedFileName = makeAbsPath(fixedName, dest);
4232                 fixedFileName.onlyPath().createPath();
4233                 status = copyFile(fmt, it->sourceName,
4234                         fixedFileName,
4235                         it->exportName, status == FORCE,
4236                         runparams.export_folder.empty());
4237         }
4238
4239         if (status == CANCEL) {
4240                 message(_("Document export cancelled."));
4241                 return ExportCancel;
4242         }
4243
4244         if (tmp_result_file.exists()) {
4245                 // Finally copy the main file
4246                 use_force = use_gui ? lyxrc.export_overwrite != NO_FILES
4247                                     : force_overwrite != NO_FILES;
4248                 if (status == SUCCESS && use_force)
4249                         status = FORCE;
4250                 status = copyFile(format, tmp_result_file,
4251                         FileName(result_file), result_file,
4252                         status == FORCE);
4253                 if (status == CANCEL) {
4254                         message(_("Document export cancelled."));
4255                         return ExportCancel;
4256                 } else {
4257                         message(bformat(_("Document exported as %1$s "
4258                                 "to file `%2$s'"),
4259                                 formats.prettyName(format),
4260                                 makeDisplayPath(result_file)));
4261                 }
4262         } else {
4263                 // This must be a dummy converter like fax (bug 1888)
4264                 message(bformat(_("Document exported as %1$s"),
4265                         formats.prettyName(format)));
4266         }
4267
4268         return success ? ExportSuccess : ExportConverterError;
4269 }
4270
4271
4272 Buffer::ExportStatus Buffer::preview(string const & format) const
4273 {
4274         bool const update_unincluded =
4275                         params().maintain_unincluded_children
4276                         && !params().getIncludedChildren().empty();
4277         return preview(format, update_unincluded);
4278 }
4279
4280
4281 Buffer::ExportStatus Buffer::preview(string const & format, bool includeall) const
4282 {
4283         MarkAsExporting exporting(this);
4284         string result_file;
4285         // (1) export with all included children (omit \includeonly)
4286         if (includeall) {
4287                 ExportStatus const status = doExport(format, true, true, result_file);
4288                 if (status != ExportSuccess)
4289                         return status;
4290         }
4291         // (2) export with included children only
4292         ExportStatus const status = doExport(format, true, false, result_file);
4293         FileName const previewFile(result_file);
4294
4295         LATTEST (isClone());
4296         d->cloned_buffer_->d->preview_file_ = previewFile;
4297         d->cloned_buffer_->d->preview_format_ = format;
4298         d->cloned_buffer_->d->preview_error_ = (status != ExportSuccess);
4299
4300         if (status != ExportSuccess)
4301                 return status;
4302         if (previewFile.exists()) {
4303                 if (!formats.view(*this, previewFile, format))
4304                         return PreviewError;
4305                 else
4306                         return PreviewSuccess;
4307         }
4308         else {
4309                 // Successful export but no output file?
4310                 // Probably a bug in error detection.
4311                 LATTEST (status != ExportSuccess);
4312
4313                 return status;
4314         }
4315 }
4316
4317
4318 Buffer::ReadStatus Buffer::extractFromVC()
4319 {
4320         bool const found = LyXVC::file_not_found_hook(d->filename);
4321         if (!found)
4322                 return ReadFileNotFound;
4323         if (!d->filename.isReadableFile())
4324                 return ReadVCError;
4325         return ReadSuccess;
4326 }
4327
4328
4329 Buffer::ReadStatus Buffer::loadEmergency()
4330 {
4331         FileName const emergencyFile = getEmergencyFileName();
4332         if (!emergencyFile.exists()
4333                   || emergencyFile.lastModified() <= d->filename.lastModified())
4334                 return ReadFileNotFound;
4335
4336         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4337         docstring const text = bformat(_("An emergency save of the document "
4338                 "%1$s exists.\n\nRecover emergency save?"), file);
4339
4340         int const load_emerg = Alert::prompt(_("Load emergency save?"), text,
4341                 0, 2, _("&Recover"), _("&Load Original"), _("&Cancel"));
4342
4343         switch (load_emerg)
4344         {
4345         case 0: {
4346                 docstring str;
4347                 ReadStatus const ret_llf = loadThisLyXFile(emergencyFile);
4348                 bool const success = (ret_llf == ReadSuccess);
4349                 if (success) {
4350                         if (isReadonly()) {
4351                                 Alert::warning(_("File is read-only"),
4352                                         bformat(_("An emergency file is successfully loaded, "
4353                                         "but the original file %1$s is marked read-only. "
4354                                         "Please make sure to save the document as a different "
4355                                         "file."), from_utf8(d->filename.absFileName())));
4356                         }
4357                         markDirty();
4358                         lyxvc().file_found_hook(d->filename);
4359                         str = _("Document was successfully recovered.");
4360                 } else
4361                         str = _("Document was NOT successfully recovered.");
4362                 str += "\n\n" + bformat(_("Remove emergency file now?\n(%1$s)"),
4363                         makeDisplayPath(emergencyFile.absFileName()));
4364
4365                 int const del_emerg =
4366                         Alert::prompt(_("Delete emergency file?"), str, 1, 1,
4367                                 _("&Remove"), _("&Keep"));
4368                 if (del_emerg == 0) {
4369                         emergencyFile.removeFile();
4370                         if (success)
4371                                 Alert::warning(_("Emergency file deleted"),
4372                                         _("Do not forget to save your file now!"), true);
4373                         }
4374                 return success ? ReadSuccess : ReadEmergencyFailure;
4375         }
4376         case 1: {
4377                 int const del_emerg =
4378                         Alert::prompt(_("Delete emergency file?"),
4379                                 _("Remove emergency file now?"), 1, 1,
4380                                 _("&Remove"), _("&Keep"));
4381                 if (del_emerg == 0)
4382                         emergencyFile.removeFile();
4383                 return ReadOriginal;
4384         }
4385
4386         default:
4387                 break;
4388         }
4389         return ReadCancel;
4390 }
4391
4392
4393 Buffer::ReadStatus Buffer::loadAutosave()
4394 {
4395         // Now check if autosave file is newer.
4396         FileName const autosaveFile = getAutosaveFileName();
4397         if (!autosaveFile.exists()
4398                   || autosaveFile.lastModified() <= d->filename.lastModified())
4399                 return ReadFileNotFound;
4400
4401         docstring const file = makeDisplayPath(d->filename.absFileName(), 20);
4402         docstring const text = bformat(_("The backup of the document %1$s "
4403                 "is newer.\n\nLoad the backup instead?"), file);
4404         int const ret = Alert::prompt(_("Load backup?"), text, 0, 2,
4405                 _("&Load backup"), _("Load &original"), _("&Cancel"));
4406
4407         switch (ret)
4408         {
4409         case 0: {
4410                 ReadStatus const ret_llf = loadThisLyXFile(autosaveFile);
4411                 // the file is not saved if we load the autosave file.
4412                 if (ret_llf == ReadSuccess) {
4413                         if (isReadonly()) {
4414                                 Alert::warning(_("File is read-only"),
4415                                         bformat(_("A backup file is successfully loaded, "
4416                                         "but the original file %1$s is marked read-only. "
4417                                         "Please make sure to save the document as a "
4418                                         "different file."),
4419                                         from_utf8(d->filename.absFileName())));
4420                         }
4421                         markDirty();
4422                         lyxvc().file_found_hook(d->filename);
4423                         return ReadSuccess;
4424                 }
4425                 return ReadAutosaveFailure;
4426         }
4427         case 1:
4428                 // Here we delete the autosave
4429                 autosaveFile.removeFile();
4430                 return ReadOriginal;
4431         default:
4432                 break;
4433         }
4434         return ReadCancel;
4435 }
4436
4437
4438 Buffer::ReadStatus Buffer::loadLyXFile()
4439 {
4440         if (!d->filename.isReadableFile()) {
4441                 ReadStatus const ret_rvc = extractFromVC();
4442                 if (ret_rvc != ReadSuccess)
4443                         return ret_rvc;
4444         }
4445
4446         ReadStatus const ret_re = loadEmergency();
4447         if (ret_re == ReadSuccess || ret_re == ReadCancel)
4448                 return ret_re;
4449
4450         ReadStatus const ret_ra = loadAutosave();
4451         if (ret_ra == ReadSuccess || ret_ra == ReadCancel)
4452                 return ret_ra;
4453
4454         return loadThisLyXFile(d->filename);
4455 }
4456
4457
4458 Buffer::ReadStatus Buffer::loadThisLyXFile(FileName const & fn)
4459 {
4460         return readFile(fn);
4461 }
4462
4463
4464 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
4465 {
4466         TeXErrors::Errors::const_iterator it = terr.begin();
4467         TeXErrors::Errors::const_iterator end = terr.end();
4468         ListOfBuffers clist = getDescendents();
4469         ListOfBuffers::const_iterator cen = clist.end();
4470
4471         for (; it != end; ++it) {
4472                 int id_start = -1;
4473                 int pos_start = -1;
4474                 int errorRow = it->error_in_line;
4475                 Buffer const * buf = 0;
4476                 Impl const * p = d;
4477                 if (it->child_name.empty())
4478                     p->texrow.getIdFromRow(errorRow, id_start, pos_start);
4479                 else {
4480                         // The error occurred in a child
4481                         ListOfBuffers::const_iterator cit = clist.begin();
4482                         for (; cit != cen; ++cit) {
4483                                 string const child_name =
4484                                         DocFileName(changeExtension(
4485                                                 (*cit)->absFileName(), "tex")).
4486                                                         mangledFileName();
4487                                 if (it->child_name != child_name)
4488                                         continue;
4489                                 (*cit)->d->texrow.getIdFromRow(errorRow,
4490                                                         id_start, pos_start);
4491                                 if (id_start != -1) {
4492                                         buf = d->cloned_buffer_
4493                                                 ? (*cit)->d->cloned_buffer_->d->owner_
4494                                                 : (*cit)->d->owner_;
4495                                         p = (*cit)->d;
4496                                         break;
4497                                 }
4498                         }
4499                 }
4500                 int id_end = -1;
4501                 int pos_end = -1;
4502                 bool found;
4503                 do {
4504                         ++errorRow;
4505                         found = p->texrow.getIdFromRow(errorRow, id_end, pos_end);
4506                 } while (found && id_start == id_end && pos_start == pos_end);
4507
4508                 if (id_start != id_end) {
4509                         // Next registered position is outside the inset where
4510                         // the error occurred, so signal end-of-paragraph
4511                         pos_end = 0;
4512                 }
4513
4514                 errorList.push_back(ErrorItem(it->error_desc,
4515                         it->error_text, id_start, pos_start, pos_end, buf));
4516         }
4517 }
4518
4519
4520 void Buffer::setBuffersForInsets() const
4521 {
4522         inset().setBuffer(const_cast<Buffer &>(*this));
4523 }
4524
4525
4526 void Buffer::updateBuffer(UpdateScope scope, UpdateType utype) const
4527 {
4528         LBUFERR(!text().paragraphs().empty());
4529
4530         // Use the master text class also for child documents
4531         Buffer const * const master = masterBuffer();
4532         DocumentClass const & textclass = master->params().documentClass();
4533
4534         // do this only if we are the top-level Buffer
4535         if (master == this) {
4536                 textclass.counters().reset(from_ascii("bibitem"));
4537                 reloadBibInfoCache();
4538         }
4539
4540         // keep the buffers to be children in this set. If the call from the
4541         // master comes back we can see which of them were actually seen (i.e.
4542         // via an InsetInclude). The remaining ones in the set need still be updated.
4543         static std::set<Buffer const *> bufToUpdate;
4544         if (scope == UpdateMaster) {
4545                 // If this is a child document start with the master
4546                 if (master != this) {
4547                         bufToUpdate.insert(this);
4548                         master->updateBuffer(UpdateMaster, utype);
4549                         // If the master buffer has no gui associated with it, then the TocModel is
4550                         // not updated during the updateBuffer call and TocModel::toc_ is invalid
4551                         // (bug 5699). The same happens if the master buffer is open in a different
4552                         // window. This test catches both possibilities.
4553                         // See: http://marc.info/?l=lyx-devel&m=138590578911716&w=2
4554                         // There remains a problem here: If there is another child open in yet a third
4555                         // window, that TOC is not updated. So some more general solution is needed at
4556                         // some point.
4557                         if (master->d->gui_ != d->gui_)
4558                                 structureChanged();
4559
4560                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
4561                         if (bufToUpdate.find(this) == bufToUpdate.end())
4562                                 return;
4563                 }
4564
4565                 // start over the counters in the master
4566                 textclass.counters().reset();
4567         }
4568
4569         // update will be done below for this buffer
4570         bufToUpdate.erase(this);
4571
4572         // update all caches
4573         clearReferenceCache();
4574         updateMacros();
4575
4576         Buffer & cbuf = const_cast<Buffer &>(*this);
4577
4578         // do the real work
4579         ParIterator parit = cbuf.par_iterator_begin();
4580         updateBuffer(parit, utype);
4581
4582         if (master != this)
4583                 // TocBackend update will be done later.
4584                 return;
4585
4586         d->bibinfo_cache_valid_ = true;
4587         d->cite_labels_valid_ = true;
4588         cbuf.tocBackend().update(utype == OutputUpdate);
4589         if (scope == UpdateMaster)
4590                 cbuf.structureChanged();
4591 }
4592
4593
4594 static depth_type getDepth(DocIterator const & it)
4595 {
4596         depth_type depth = 0;
4597         for (size_t i = 0 ; i < it.depth() ; ++i)
4598                 if (!it[i].inset().inMathed())
4599                         depth += it[i].paragraph().getDepth() + 1;
4600         // remove 1 since the outer inset does not count
4601         return depth - 1;
4602 }
4603
4604 static depth_type getItemDepth(ParIterator const & it)
4605 {
4606         Paragraph const & par = *it;
4607         LabelType const labeltype = par.layout().labeltype;
4608
4609         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
4610                 return 0;
4611
4612         // this will hold the lowest depth encountered up to now.
4613         depth_type min_depth = getDepth(it);
4614         ParIterator prev_it = it;
4615         while (true) {
4616                 if (prev_it.pit())
4617                         --prev_it.top().pit();
4618                 else {
4619                         // start of nested inset: go to outer par
4620                         prev_it.pop_back();
4621                         if (prev_it.empty()) {
4622                                 // start of document: nothing to do
4623                                 return 0;
4624                         }
4625                 }
4626
4627                 // We search for the first paragraph with same label
4628                 // that is not more deeply nested.
4629                 Paragraph & prev_par = *prev_it;
4630                 depth_type const prev_depth = getDepth(prev_it);
4631                 if (labeltype == prev_par.layout().labeltype) {
4632                         if (prev_depth < min_depth)
4633                                 return prev_par.itemdepth + 1;
4634                         if (prev_depth == min_depth)
4635                                 return prev_par.itemdepth;
4636                 }
4637                 min_depth = min(min_depth, prev_depth);
4638                 // small optimization: if we are at depth 0, we won't
4639                 // find anything else
4640                 if (prev_depth == 0)
4641                         return 0;
4642         }
4643 }
4644
4645
4646 static bool needEnumCounterReset(ParIterator const & it)
4647 {
4648         Paragraph const & par = *it;
4649         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, return false);
4650         depth_type const cur_depth = par.getDepth();
4651         ParIterator prev_it = it;
4652         while (prev_it.pit()) {
4653                 --prev_it.top().pit();
4654                 Paragraph const & prev_par = *prev_it;
4655                 if (prev_par.getDepth() <= cur_depth)
4656                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
4657         }
4658         // start of nested inset: reset
4659         return true;
4660 }
4661
4662
4663 // set the label of a paragraph. This includes the counters.
4664 void Buffer::Impl::setLabel(ParIterator & it, UpdateType utype) const
4665 {
4666         BufferParams const & bp = owner_->masterBuffer()->params();
4667         DocumentClass const & textclass = bp.documentClass();
4668         Paragraph & par = it.paragraph();
4669         Layout const & layout = par.layout();
4670         Counters & counters = textclass.counters();
4671
4672         if (par.params().startOfAppendix()) {
4673                 // We want to reset the counter corresponding to toplevel sectioning
4674                 Layout const & lay = textclass.getTOCLayout();
4675                 docstring const cnt = lay.counter;
4676                 if (!cnt.empty())
4677                         counters.reset(cnt);
4678                 counters.appendix(true);
4679         }
4680         par.params().appendix(counters.appendix());
4681
4682         // Compute the item depth of the paragraph
4683         par.itemdepth = getItemDepth(it);
4684
4685         if (layout.margintype == MARGIN_MANUAL) {
4686                 if (par.params().labelWidthString().empty())
4687                         par.params().labelWidthString(par.expandLabel(layout, bp));
4688         } else if (layout.latextype == LATEX_BIB_ENVIRONMENT) {
4689                 // we do not need to do anything here, since the empty case is
4690                 // handled during export.
4691         } else {
4692                 par.params().labelWidthString(docstring());
4693         }
4694
4695         switch(layout.labeltype) {
4696         case LABEL_ITEMIZE: {
4697                 // At some point of time we should do something more
4698                 // clever here, like:
4699                 //   par.params().labelString(
4700                 //    bp.user_defined_bullet(par.itemdepth).getText());
4701                 // for now, use a simple hardcoded label
4702                 docstring itemlabel;
4703                 switch (par.itemdepth) {
4704                 case 0:
4705                         itemlabel = char_type(0x2022);
4706                         break;
4707                 case 1:
4708                         itemlabel = char_type(0x2013);
4709                         break;
4710                 case 2:
4711                         itemlabel = char_type(0x2217);
4712                         break;
4713                 case 3:
4714                         itemlabel = char_type(0x2219); // or 0x00b7
4715                         break;
4716                 }
4717                 par.params().labelString(itemlabel);
4718                 break;
4719         }
4720
4721         case LABEL_ENUMERATE: {
4722                 docstring enumcounter = layout.counter.empty() ? from_ascii("enum") : layout.counter;
4723
4724                 switch (par.itemdepth) {
4725                 case 2:
4726                         enumcounter += 'i';
4727                 case 1:
4728                         enumcounter += 'i';
4729                 case 0:
4730                         enumcounter += 'i';
4731                         break;
4732                 case 3:
4733                         enumcounter += "iv";
4734                         break;
4735                 default:
4736                         // not a valid enumdepth...
4737                         break;
4738                 }
4739
4740                 // Maybe we have to reset the enumeration counter.
4741                 if (needEnumCounterReset(it))
4742                         counters.reset(enumcounter);
4743                 counters.step(enumcounter, utype);
4744
4745                 string const & lang = par.getParLanguage(bp)->code();
4746                 par.params().labelString(counters.theCounter(enumcounter, lang));
4747
4748                 break;
4749         }
4750
4751         case LABEL_SENSITIVE: {
4752                 string const & type = counters.current_float();
4753                 docstring full_label;
4754                 if (type.empty())
4755                         full_label = owner_->B_("Senseless!!! ");
4756                 else {
4757                         docstring name = owner_->B_(textclass.floats().getType(type).name());
4758                         if (counters.hasCounter(from_utf8(type))) {
4759                                 string const & lang = par.getParLanguage(bp)->code();
4760                                 counters.step(from_utf8(type), utype);
4761                                 full_label = bformat(from_ascii("%1$s %2$s:"),
4762                                                      name,
4763                                                      counters.theCounter(from_utf8(type), lang));
4764                         } else
4765                                 full_label = bformat(from_ascii("%1$s #:"), name);
4766                 }
4767                 par.params().labelString(full_label);
4768                 break;
4769         }
4770
4771         case LABEL_NO_LABEL:
4772                 par.params().labelString(docstring());
4773                 break;
4774
4775         case LABEL_ABOVE:
4776         case LABEL_CENTERED:
4777         case LABEL_STATIC: {
4778                 docstring const & lcounter = layout.counter;
4779                 if (!lcounter.empty()) {
4780                         if (layout.toclevel <= bp.secnumdepth
4781                                                 && (layout.latextype != LATEX_ENVIRONMENT
4782                                         || it.text()->isFirstInSequence(it.pit()))) {
4783                                 if (counters.hasCounter(lcounter))
4784                                         counters.step(lcounter, utype);
4785                                 par.params().labelString(par.expandLabel(layout, bp));
4786                         } else
4787                                 par.params().labelString(docstring());
4788                 } else
4789                         par.params().labelString(par.expandLabel(layout, bp));
4790                 break;
4791         }
4792
4793         case LABEL_MANUAL:
4794         case LABEL_BIBLIO:
4795                 par.params().labelString(par.expandLabel(layout, bp));
4796         }
4797 }
4798
4799
4800 void Buffer::updateBuffer(ParIterator & parit, UpdateType utype) const
4801 {
4802         // LASSERT: Is it safe to continue here, or should we just return?
4803         LASSERT(parit.pit() == 0, /**/);
4804
4805         // Set the position of the text in the buffer to be able
4806         // to resolve macros in it.
4807         parit.text()->setMacrocontextPosition(parit);
4808
4809         depth_type maxdepth = 0;
4810         pit_type const lastpit = parit.lastpit();
4811         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
4812                 // reduce depth if necessary
4813                 if (parit->params().depth() > maxdepth) {
4814                         /** FIXME: this function is const, but
4815                          * nevertheless it modifies the buffer. To be
4816                          * cleaner, one should modify the buffer in
4817                          * another function, which is actually
4818                          * non-const. This would however be costly in
4819                          * terms of code duplication.
4820                          */
4821                         const_cast<Buffer *>(this)->undo().recordUndo(CursorData(parit));
4822                         parit->params().depth(maxdepth);
4823                 }
4824                 maxdepth = parit->getMaxDepthAfter();
4825
4826                 if (utype == OutputUpdate) {
4827                         // track the active counters
4828                         // we have to do this for the master buffer, since the local
4829                         // buffer isn't tracking anything.
4830                         masterBuffer()->params().documentClass().counters().
4831                                         setActiveLayout(parit->layout());
4832                 }
4833
4834                 // set the counter for this paragraph
4835                 d->setLabel(parit, utype);
4836
4837                 // now the insets
4838                 InsetList::const_iterator iit = parit->insetList().begin();
4839                 InsetList::const_iterator end = parit->insetList().end();
4840                 for (; iit != end; ++iit) {
4841                         parit.pos() = iit->pos;
4842                         iit->inset->updateBuffer(parit, utype);
4843                 }
4844         }
4845 }
4846
4847
4848 int Buffer::spellCheck(DocIterator & from, DocIterator & to,
4849         WordLangTuple & word_lang, docstring_list & suggestions) const
4850 {
4851         int progress = 0;
4852         WordLangTuple wl;
4853         suggestions.clear();
4854         word_lang = WordLangTuple();
4855         bool const to_end = to.empty();
4856         DocIterator const end = to_end ? doc_iterator_end(this) : to;
4857         // OK, we start from here.
4858         for (; from != end; from.forwardPos()) {
4859                 // This skips all insets with spell check disabled.
4860                 while (!from.allowSpellCheck()) {
4861                         from.pop_back();
4862                         from.pos()++;
4863                 }
4864                 // If from is at the end of the document (which is possible
4865                 // when "from" was changed above) LyX will crash later otherwise.
4866                 if (from.atEnd() || (!to_end && from >= end))
4867                         break;
4868                 to = from;
4869                 from.paragraph().spellCheck();
4870                 SpellChecker::Result res = from.paragraph().spellCheck(from.pos(), to.pos(), wl, suggestions);
4871                 if (SpellChecker::misspelled(res)) {
4872                         word_lang = wl;
4873                         break;
4874                 }
4875                 // Do not increase progress when from == to, otherwise the word
4876                 // count will be wrong.
4877                 if (from != to) {
4878                         from = to;
4879                         ++progress;
4880                 }
4881         }
4882         return progress;
4883 }
4884
4885
4886 void Buffer::Impl::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput)
4887 {
4888         bool inword = false;
4889         word_count_ = 0;
4890         char_count_ = 0;
4891         blank_count_ = 0;
4892
4893         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
4894                 if (!dit.inTexted()) {
4895                         dit.forwardPos();
4896                         continue;
4897                 }
4898
4899                 Paragraph const & par = dit.paragraph();
4900                 pos_type const pos = dit.pos();
4901
4902                 // Copied and adapted from isWordSeparator() in Paragraph
4903                 if (pos == dit.lastpos()) {
4904                         inword = false;
4905                 } else {
4906                         Inset const * ins = par.getInset(pos);
4907                         if (ins && skipNoOutput && !ins->producesOutput()) {
4908                                 // skip this inset
4909                                 ++dit.top().pos();
4910                                 // stop if end of range was skipped
4911                                 if (!to.atEnd() && dit >= to)
4912                                         break;
4913                                 continue;
4914                         } else if (!par.isDeleted(pos)) {
4915                                 if (par.isWordSeparator(pos))
4916                                         inword = false;
4917                                 else if (!inword) {
4918                                         ++word_count_;
4919                                         inword = true;
4920                                 }
4921                                 if (ins && ins->isLetter())
4922                                         ++char_count_;
4923                                 else if (ins && ins->isSpace())
4924                                         ++blank_count_;
4925                                 else {
4926                                         char_type const c = par.getChar(pos);
4927                                         if (isPrintableNonspace(c))
4928                                                 ++char_count_;
4929                                         else if (isSpace(c))
4930                                                 ++blank_count_;
4931                                 }
4932                         }
4933                 }
4934                 dit.forwardPos();
4935         }
4936 }
4937
4938
4939 void Buffer::updateStatistics(DocIterator & from, DocIterator & to, bool skipNoOutput) const
4940 {
4941         d->updateStatistics(from, to, skipNoOutput);
4942 }
4943
4944
4945 int Buffer::wordCount() const
4946 {
4947         return d->wordCount();
4948 }
4949
4950
4951 int Buffer::charCount(bool with_blanks) const
4952 {
4953         return d->charCount(with_blanks);
4954 }
4955
4956
4957 Buffer::ReadStatus Buffer::reload()
4958 {
4959         setBusy(true);
4960         // c.f. bug http://www.lyx.org/trac/ticket/6587
4961         removeAutosaveFile();
4962         // e.g., read-only status could have changed due to version control
4963         d->filename.refresh();
4964         docstring const disp_fn = makeDisplayPath(d->filename.absFileName());
4965
4966         // clear parent. this will get reset if need be.
4967         d->setParent(0);
4968         ReadStatus const status = loadLyXFile();
4969         if (status == ReadSuccess) {
4970                 updateBuffer();
4971                 changed(true);
4972                 updateTitles();
4973                 markClean();
4974                 message(bformat(_("Document %1$s reloaded."), disp_fn));
4975                 d->undo_.clear();
4976         } else {
4977                 message(bformat(_("Could not reload document %1$s."), disp_fn));
4978         }
4979         setBusy(false);
4980         removePreviews();
4981         updatePreviews();
4982         errors("Parse");
4983         return status;
4984 }
4985
4986
4987 bool Buffer::saveAs(FileName const & fn)
4988 {
4989         FileName const old_name = fileName();
4990         FileName const old_auto = getAutosaveFileName();
4991         bool const old_unnamed = isUnnamed();
4992         bool success = true;
4993         d->old_position = filePath();
4994
4995         setFileName(fn);
4996         markDirty();
4997         setUnnamed(false);
4998
4999         if (save()) {
5000                 // bring the autosave file with us, just in case.
5001                 moveAutosaveFile(old_auto);
5002                 // validate version control data and
5003                 // correct buffer title
5004                 lyxvc().file_found_hook(fileName());
5005                 updateTitles();
5006                 // the file has now been saved to the new location.
5007                 // we need to check that the locations of child buffers
5008                 // are still valid.
5009                 checkChildBuffers();
5010                 checkMasterBuffer();
5011         } else {
5012                 // save failed
5013                 // reset the old filename and unnamed state
5014                 setFileName(old_name);
5015                 setUnnamed(old_unnamed);
5016                 success = false;
5017         }
5018
5019         d->old_position.clear();
5020         return success;
5021 }
5022
5023
5024 void Buffer::checkChildBuffers()
5025 {
5026         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
5027         Impl::BufferPositionMap::iterator const en = d->children_positions.end();
5028         for (; it != en; ++it) {
5029                 DocIterator dit = it->second;
5030                 Buffer * cbuf = const_cast<Buffer *>(it->first);
5031                 if (!cbuf || !theBufferList().isLoaded(cbuf))
5032                         continue;
5033                 Inset * inset = dit.nextInset();
5034                 LASSERT(inset && inset->lyxCode() == INCLUDE_CODE, continue);
5035                 InsetInclude * inset_inc = static_cast<InsetInclude *>(inset);
5036                 docstring const & incfile = inset_inc->getParam("filename");
5037                 string oldloc = cbuf->absFileName();
5038                 string newloc = makeAbsPath(to_utf8(incfile),
5039                                 onlyPath(absFileName())).absFileName();
5040                 if (oldloc == newloc)
5041                         continue;
5042                 // the location of the child file is incorrect.
5043                 cbuf->setParent(0);
5044                 inset_inc->setChildBuffer(0);
5045         }
5046         // invalidate cache of children
5047         d->children_positions.clear();
5048         d->position_to_children.clear();
5049 }
5050
5051
5052 // If a child has been saved under a different name/path, it might have been
5053 // orphaned. Therefore the master needs to be reset (bug 8161).
5054 void Buffer::checkMasterBuffer()
5055 {
5056         Buffer const * const master = masterBuffer();
5057         if (master == this)
5058                 return;
5059
5060         // necessary to re-register the child (bug 5873)
5061         // FIXME: clean up updateMacros (here, only
5062         // child registering is needed).
5063         master->updateMacros();
5064         // (re)set master as master buffer, but only
5065         // if we are a real child
5066         if (master->isChild(this))
5067                 setParent(master);
5068         else
5069                 setParent(0);
5070 }
5071
5072
5073 string Buffer::includedFilePath(string const & name, string const & ext) const
5074 {
5075         bool isabsolute = FileName::isAbsolute(name);
5076         // old_position already contains a trailing path separator
5077         string const absname = isabsolute ? name : d->old_position + name;
5078
5079         if (d->old_position.empty() || d->old_position == filePath()
5080             || !FileName(addExtension(absname, ext)).exists())
5081                 return name;
5082
5083         if (isabsolute)
5084                 return to_utf8(makeRelPath(from_utf8(name), from_utf8(filePath())));
5085
5086         return to_utf8(makeRelPath(from_utf8(FileName(absname).realPath()),
5087                                    from_utf8(filePath())));
5088 }
5089
5090 } // namespace lyx