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