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