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