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