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