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