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