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