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