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