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