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