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