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