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