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