]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
* "Goto label" in reference dialog works with master and child documents
[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 "DocIterator.h"
28 #include "Encoding.h"
29 #include "ErrorList.h"
30 #include "Exporter.h"
31 #include "Format.h"
32 #include "FuncRequest.h"
33 #include "InsetIterator.h"
34 #include "InsetList.h"
35 #include "Language.h"
36 #include "LaTeXFeatures.h"
37 #include "LaTeX.h"
38 #include "Layout.h"
39 #include "Lexer.h"
40 #include "LyXAction.h"
41 #include "LyX.h"
42 #include "LyXRC.h"
43 #include "LyXVC.h"
44 #include "output_docbook.h"
45 #include "output.h"
46 #include "output_latex.h"
47 #include "output_plaintext.h"
48 #include "paragraph_funcs.h"
49 #include "Paragraph.h"
50 #include "ParagraphParameters.h"
51 #include "ParIterator.h"
52 #include "PDFOptions.h"
53 #include "sgml.h"
54 #include "TexRow.h"
55 #include "TexStream.h"
56 #include "Text.h"
57 #include "TextClass.h"
58 #include "TocBackend.h"
59 #include "Undo.h"
60 #include "VCBackend.h"
61 #include "version.h"
62 #include "WordList.h"
63
64 #include "insets/InsetBibitem.h"
65 #include "insets/InsetBibtex.h"
66 #include "insets/InsetInclude.h"
67 #include "insets/InsetText.h"
68
69 #include "mathed/MacroTable.h"
70 #include "mathed/MathMacroTemplate.h"
71 #include "mathed/MathSupport.h"
72
73 #include "frontends/alert.h"
74 #include "frontends/Delegates.h"
75 #include "frontends/WorkAreaManager.h"
76
77 #include "graphics/Previews.h"
78
79 #include "support/lassert.h"
80 #include "support/convert.h"
81 #include "support/debug.h"
82 #include "support/ExceptionMessage.h"
83 #include "support/FileName.h"
84 #include "support/FileNameList.h"
85 #include "support/filetools.h"
86 #include "support/ForkedCalls.h"
87 #include "support/gettext.h"
88 #include "support/gzstream.h"
89 #include "support/lstrings.h"
90 #include "support/lyxalgo.h"
91 #include "support/os.h"
92 #include "support/Package.h"
93 #include "support/Path.h"
94 #include "support/textutils.h"
95 #include "support/types.h"
96
97 #include <boost/bind.hpp>
98 #include <boost/shared_ptr.hpp>
99
100 #include <algorithm>
101 #include <fstream>
102 #include <iomanip>
103 #include <map>
104 #include <set>
105 #include <sstream>
106 #include <stack>
107 #include <vector>
108
109 using namespace std;
110 using namespace lyx::support;
111
112 namespace lyx {
113
114 namespace Alert = frontend::Alert;
115 namespace os = support::os;
116
117 namespace {
118
119 // Do not remove the comment below, so we get merge conflict in
120 // independent branches. Instead add your own.
121 int const LYX_FORMAT = 345;  // jamatos: xml elements
122
123 typedef map<string, bool> DepClean;
124 typedef map<docstring, pair<InsetLabel const *, Buffer::References> > RefCache;
125
126 } // namespace anon
127
128 class BufferSet : public std::set<Buffer const *> {};
129
130 class Buffer::Impl
131 {
132 public:
133         Impl(Buffer & parent, FileName const & file, bool readonly);
134
135         ~Impl()
136         {
137                 if (wa_) {
138                         wa_->closeAll();
139                         delete wa_;
140                 }
141                 delete inset;
142         }
143
144         BufferParams params;
145         LyXVC lyxvc;
146         FileName temppath;
147         mutable TexRow texrow;
148         Buffer const * parent_buffer;
149
150         /// need to regenerate .tex?
151         DepClean dep_clean;
152
153         /// is save needed?
154         mutable bool lyx_clean;
155
156         /// is autosave needed?
157         mutable bool bak_clean;
158
159         /// is this a unnamed file (New...)?
160         bool unnamed;
161
162         /// buffer is r/o
163         bool read_only;
164
165         /// name of the file the buffer is associated with.
166         FileName filename;
167
168         /** Set to true only when the file is fully loaded.
169          *  Used to prevent the premature generation of previews
170          *  and by the citation inset.
171          */
172         bool file_fully_loaded;
173
174         ///
175         mutable TocBackend toc_backend;
176
177         /// macro tables
178         typedef pair<DocIterator, MacroData> ScopeMacro;
179         typedef map<DocIterator, ScopeMacro> PositionScopeMacroMap;
180         typedef map<docstring, PositionScopeMacroMap> NamePositionScopeMacroMap;
181         /// map from the macro name to the position map,
182         /// which maps the macro definition position to the scope and the MacroData.
183         NamePositionScopeMacroMap macros;
184         bool macro_lock;
185
186         /// positions of child buffers in the buffer
187         typedef map<Buffer const * const, DocIterator> BufferPositionMap;
188         typedef pair<DocIterator, Buffer const *> ScopeBuffer;
189         typedef map<DocIterator, ScopeBuffer> PositionScopeBufferMap;
190         /// position of children buffers in this buffer
191         BufferPositionMap children_positions;
192         /// map from children inclusion positions to their scope and their buffer
193         PositionScopeBufferMap position_to_children;
194
195         /// Container for all sort of Buffer dependant errors.
196         map<string, ErrorList> errorLists;
197
198         /// timestamp and checksum used to test if the file has been externally
199         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
200         time_t timestamp_;
201         unsigned long checksum_;
202
203         ///
204         frontend::WorkAreaManager * wa_;
205
206         ///
207         Undo undo_;
208
209         /// A cache for the bibfiles (including bibfiles of loaded child
210         /// documents), needed for appropriate update of natbib labels.
211         mutable support::FileNameList bibfilesCache_;
212
213         // FIXME The caching mechanism could be improved. At present, we have a
214         // cache for each Buffer, that caches all the bibliography info for that
215         // Buffer. A more efficient solution would be to have a global cache per
216         // file, and then to construct the Buffer's bibinfo from that.
217         /// A cache for bibliography info
218         mutable BiblioInfo bibinfo_;
219         /// whether the bibinfo cache is valid
220         bool bibinfoCacheValid_;
221         /// Cache of timestamps of .bib files
222         map<FileName, time_t> bibfileStatus_;
223
224         mutable RefCache ref_cache_;
225
226         /// our Text that should be wrapped in an InsetText
227         InsetText * inset;
228 };
229
230
231 /// Creates the per buffer temporary directory
232 static FileName createBufferTmpDir()
233 {
234         static int count;
235         // We are in our own directory.  Why bother to mangle name?
236         // In fact I wrote this code to circumvent a problematic behaviour
237         // (bug?) of EMX mkstemp().
238         FileName tmpfl(package().temp_dir().absFilename() + "/lyx_tmpbuf" +
239                 convert<string>(count++));
240
241         if (!tmpfl.createDirectory(0777)) {
242                 throw ExceptionMessage(WarningException, _("Disk Error: "), bformat(
243                         _("LyX could not create the temporary directory '%1$s' (Disk is full maybe?)"),
244                         from_utf8(tmpfl.absFilename())));
245         }
246         return tmpfl;
247 }
248
249
250 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
251         : parent_buffer(0), lyx_clean(true), bak_clean(true), unnamed(false),
252           read_only(readonly_), filename(file), file_fully_loaded(false),
253           toc_backend(&parent), macro_lock(false), timestamp_(0),
254           checksum_(0), wa_(0), undo_(parent), bibinfoCacheValid_(false)
255 {
256         temppath = createBufferTmpDir();
257         lyxvc.setBuffer(&parent);
258         if (use_gui)
259                 wa_ = new frontend::WorkAreaManager;
260 }
261
262
263 Buffer::Buffer(string const & file, bool readonly)
264         : d(new Impl(*this, FileName(file), readonly)), gui_(0)
265 {
266         LYXERR(Debug::INFO, "Buffer::Buffer()");
267
268         d->inset = new InsetText(*this);
269         d->inset->setAutoBreakRows(true);
270         d->inset->getText(0)->setMacrocontextPosition(par_iterator_begin());
271 }
272
273
274 Buffer::~Buffer()
275 {
276         LYXERR(Debug::INFO, "Buffer::~Buffer()");
277         // here the buffer should take care that it is
278         // saved properly, before it goes into the void.
279
280         // GuiView already destroyed
281         gui_ = 0;
282
283         if (d->unnamed && d->filename.extension() == "internal") {
284                 // No need to do additional cleanups for internal buffer.
285                 delete d;
286                 return;
287         }
288
289         // loop over children
290         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
291         Impl::BufferPositionMap::iterator end = d->children_positions.end();
292         for (; it != end; ++it)
293                 theBufferList().releaseChild(this, const_cast<Buffer *>(it->first));
294
295         // clear references to children in macro tables
296         d->children_positions.clear();
297         d->position_to_children.clear();
298
299         if (!d->temppath.destroyDirectory()) {
300                 Alert::warning(_("Could not remove temporary directory"),
301                         bformat(_("Could not remove the temporary directory %1$s"),
302                         from_utf8(d->temppath.absFilename())));
303         }
304
305         // Remove any previewed LaTeX snippets associated with this buffer.
306         thePreviews().removeLoader(*this);
307
308         delete d;
309 }
310
311
312 void Buffer::changed() const
313 {
314         if (d->wa_)
315                 d->wa_->redrawAll();
316 }
317
318
319 frontend::WorkAreaManager & Buffer::workAreaManager() const
320 {
321         LASSERT(d->wa_, /**/);
322         return *d->wa_;
323 }
324
325
326 Text & Buffer::text() const
327 {
328         return d->inset->text();
329 }
330
331
332 Inset & Buffer::inset() const
333 {
334         return *d->inset;
335 }
336
337
338 BufferParams & Buffer::params()
339 {
340         return d->params;
341 }
342
343
344 BufferParams const & Buffer::params() const
345 {
346         return d->params;
347 }
348
349
350 ParagraphList & Buffer::paragraphs()
351 {
352         return text().paragraphs();
353 }
354
355
356 ParagraphList const & Buffer::paragraphs() const
357 {
358         return text().paragraphs();
359 }
360
361
362 LyXVC & Buffer::lyxvc()
363 {
364         return d->lyxvc;
365 }
366
367
368 LyXVC const & Buffer::lyxvc() const
369 {
370         return d->lyxvc;
371 }
372
373
374 string const Buffer::temppath() const
375 {
376         return d->temppath.absFilename();
377 }
378
379
380 TexRow & Buffer::texrow()
381 {
382         return d->texrow;
383 }
384
385
386 TexRow const & Buffer::texrow() const
387 {
388         return d->texrow;
389 }
390
391
392 TocBackend & Buffer::tocBackend() const
393 {
394         return d->toc_backend;
395 }
396
397
398 Undo & Buffer::undo()
399 {
400         return d->undo_;
401 }
402
403
404 string Buffer::latexName(bool const no_path) const
405 {
406         FileName latex_name = makeLatexName(d->filename);
407         return no_path ? latex_name.onlyFileName()
408                 : latex_name.absFilename();
409 }
410
411
412 string Buffer::logName(LogType * type) const
413 {
414         string const filename = latexName(false);
415
416         if (filename.empty()) {
417                 if (type)
418                         *type = latexlog;
419                 return string();
420         }
421
422         string const path = temppath();
423
424         FileName const fname(addName(temppath(),
425                                      onlyFilename(changeExtension(filename,
426                                                                   ".log"))));
427         FileName const bname(
428                 addName(path, onlyFilename(
429                         changeExtension(filename,
430                                         formats.extension("literate") + ".out"))));
431
432         // If no Latex log or Build log is newer, show Build log
433
434         if (bname.exists() &&
435             (!fname.exists() || fname.lastModified() < bname.lastModified())) {
436                 LYXERR(Debug::FILES, "Log name calculated as: " << bname);
437                 if (type)
438                         *type = buildlog;
439                 return bname.absFilename();
440         }
441         LYXERR(Debug::FILES, "Log name calculated as: " << fname);
442         if (type)
443                         *type = latexlog;
444         return fname.absFilename();
445 }
446
447
448 void Buffer::setReadonly(bool const flag)
449 {
450         if (d->read_only != flag) {
451                 d->read_only = flag;
452                 setReadOnly(flag);
453         }
454 }
455
456
457 void Buffer::setFileName(string const & newfile)
458 {
459         d->filename = makeAbsPath(newfile);
460         setReadonly(d->filename.isReadOnly());
461         updateTitles();
462 }
463
464
465 int Buffer::readHeader(Lexer & lex)
466 {
467         int unknown_tokens = 0;
468         int line = -1;
469         int begin_header_line = -1;
470
471         // Initialize parameters that may be/go lacking in header:
472         params().branchlist().clear();
473         params().preamble.erase();
474         params().options.erase();
475         params().master.erase();
476         params().float_placement.erase();
477         params().paperwidth.erase();
478         params().paperheight.erase();
479         params().leftmargin.erase();
480         params().rightmargin.erase();
481         params().topmargin.erase();
482         params().bottommargin.erase();
483         params().headheight.erase();
484         params().headsep.erase();
485         params().footskip.erase();
486         params().columnsep.erase();
487         params().fontsCJK.erase();
488         params().listings_params.clear();
489         params().clearLayoutModules();
490         params().clearRemovedModules();
491         params().pdfoptions().clear();
492
493         for (int i = 0; i < 4; ++i) {
494                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
495                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
496         }
497
498         ErrorList & errorList = d->errorLists["Parse"];
499
500         while (lex.isOK()) {
501                 string token;
502                 lex >> token;
503
504                 if (token.empty())
505                         continue;
506
507                 if (token == "\\end_header")
508                         break;
509
510                 ++line;
511                 if (token == "\\begin_header") {
512                         begin_header_line = line;
513                         continue;
514                 }
515
516                 LYXERR(Debug::PARSER, "Handling document header token: `"
517                                       << token << '\'');
518
519                 string unknown = params().readToken(lex, token, d->filename.onlyPath());
520                 if (!unknown.empty()) {
521                         if (unknown[0] != '\\' && token == "\\textclass") {
522                                 Alert::warning(_("Unknown document class"),
523                        bformat(_("Using the default document class, because the "
524                                               "class %1$s is unknown."), from_utf8(unknown)));
525                         } else {
526                                 ++unknown_tokens;
527                                 docstring const s = bformat(_("Unknown token: "
528                                                                         "%1$s %2$s\n"),
529                                                          from_utf8(token),
530                                                          lex.getDocString());
531                                 errorList.push_back(ErrorItem(_("Document header error"),
532                                         s, -1, 0, 0));
533                         }
534                 }
535         }
536         if (begin_header_line) {
537                 docstring const s = _("\\begin_header is missing");
538                 errorList.push_back(ErrorItem(_("Document header error"),
539                         s, -1, 0, 0));
540         }
541
542         params().makeDocumentClass();
543
544         return unknown_tokens;
545 }
546
547
548 // Uwe C. Schroeder
549 // changed to be public and have one parameter
550 // Returns false if "\end_document" is not read (Asger)
551 bool Buffer::readDocument(Lexer & lex)
552 {
553         ErrorList & errorList = d->errorLists["Parse"];
554         errorList.clear();
555
556         if (!lex.checkFor("\\begin_document")) {
557                 docstring const s = _("\\begin_document is missing");
558                 errorList.push_back(ErrorItem(_("Document header error"),
559                         s, -1, 0, 0));
560         }
561
562         // we are reading in a brand new document
563         LASSERT(paragraphs().empty(), /**/);
564
565         readHeader(lex);
566
567         if (params().outputChanges) {
568                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
569                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
570                                   LaTeXFeatures::isAvailable("xcolor");
571
572                 if (!dvipost && !xcolorsoul) {
573                         Alert::warning(_("Changes not shown in LaTeX output"),
574                                        _("Changes will not be highlighted in LaTeX output, "
575                                          "because neither dvipost nor xcolor/soul are installed.\n"
576                                          "Please install these packages or redefine "
577                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
578                 } else if (!xcolorsoul) {
579                         Alert::warning(_("Changes not shown in LaTeX output"),
580                                        _("Changes will not be highlighted in LaTeX output "
581                                          "when using pdflatex, because xcolor and soul are not installed.\n"
582                                          "Please install both packages or redefine "
583                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
584                 }
585         }
586
587         if (!params().master.empty()) {
588                 FileName const master_file = makeAbsPath(params().master,
589                            onlyPath(absFileName()));
590                 if (isLyXFilename(master_file.absFilename())) {
591                         Buffer * master = checkAndLoadLyXFile(master_file);
592                         d->parent_buffer = master;
593                 }
594         }
595
596         // read main text
597         bool const res = text().read(*this, lex, errorList, d->inset);
598
599         updateMacros();
600         updateMacroInstances();
601         return res;
602 }
603
604
605 // needed to insert the selection
606 void Buffer::insertStringAsLines(ParagraphList & pars,
607         pit_type & pit, pos_type & pos,
608         Font const & fn, docstring const & str, bool autobreakrows)
609 {
610         Font font = fn;
611
612         // insert the string, don't insert doublespace
613         bool space_inserted = true;
614         for (docstring::const_iterator cit = str.begin();
615             cit != str.end(); ++cit) {
616                 Paragraph & par = pars[pit];
617                 if (*cit == '\n') {
618                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
619                                 breakParagraph(params(), pars, pit, pos,
620                                                par.layout().isEnvironment());
621                                 ++pit;
622                                 pos = 0;
623                                 space_inserted = true;
624                         } else {
625                                 continue;
626                         }
627                         // do not insert consecutive spaces if !free_spacing
628                 } else if ((*cit == ' ' || *cit == '\t') &&
629                            space_inserted && !par.isFreeSpacing()) {
630                         continue;
631                 } else if (*cit == '\t') {
632                         if (!par.isFreeSpacing()) {
633                                 // tabs are like spaces here
634                                 par.insertChar(pos, ' ', font, params().trackChanges);
635                                 ++pos;
636                                 space_inserted = true;
637                         } else {
638                                 par.insertChar(pos, *cit, font, params().trackChanges);
639                                 ++pos;
640                                 space_inserted = true;
641                         }
642                 } else if (!isPrintable(*cit)) {
643                         // Ignore unprintables
644                         continue;
645                 } else {
646                         // just insert the character
647                         par.insertChar(pos, *cit, font, params().trackChanges);
648                         ++pos;
649                         space_inserted = (*cit == ' ');
650                 }
651
652         }
653 }
654
655
656 bool Buffer::readString(string const & s)
657 {
658         params().compressed = false;
659
660         // remove dummy empty par
661         paragraphs().clear();
662         Lexer lex;
663         istringstream is(s);
664         lex.setStream(is);
665         FileName const name = FileName::tempName("Buffer_readString");
666         switch (readFile(lex, name, true)) {
667         case failure:
668                 return false;
669         case wrongversion: {
670                 // We need to call lyx2lyx, so write the input to a file
671                 ofstream os(name.toFilesystemEncoding().c_str());
672                 os << s;
673                 os.close();
674                 return readFile(name);
675         }
676         case success:
677                 break;
678         }
679
680         return true;
681 }
682
683
684 bool Buffer::readFile(FileName const & filename)
685 {
686         FileName fname(filename);
687
688         // remove dummy empty par
689         paragraphs().clear();
690         Lexer lex;
691         lex.setFile(fname);
692         if (readFile(lex, fname) != success)
693                 return false;
694
695         return true;
696 }
697
698
699 bool Buffer::isFullyLoaded() const
700 {
701         return d->file_fully_loaded;
702 }
703
704
705 void Buffer::setFullyLoaded(bool value)
706 {
707         d->file_fully_loaded = value;
708 }
709
710
711 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
712                 bool fromstring)
713 {
714         LASSERT(!filename.empty(), /**/);
715
716         // the first (non-comment) token _must_ be...
717         if (!lex.checkFor("\\lyxformat")) {
718                 Alert::error(_("Document format failure"),
719                              bformat(_("%1$s is not a readable LyX document."),
720                                        from_utf8(filename.absFilename())));
721                 return failure;
722         }
723
724         string tmp_format;
725         lex >> tmp_format;
726         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
727         // if present remove ".," from string.
728         size_t dot = tmp_format.find_first_of(".,");
729         //lyxerr << "           dot found at " << dot << endl;
730         if (dot != string::npos)
731                         tmp_format.erase(dot, 1);
732         int const file_format = convert<int>(tmp_format);
733         //lyxerr << "format: " << file_format << endl;
734
735         // save timestamp and checksum of the original disk file, making sure
736         // to not overwrite them with those of the file created in the tempdir
737         // when it has to be converted to the current format.
738         if (!d->checksum_) {
739                 // Save the timestamp and checksum of disk file. If filename is an
740                 // emergency file, save the timestamp and checksum of the original lyx file
741                 // because isExternallyModified will check for this file. (BUG4193)
742                 string diskfile = filename.absFilename();
743                 if (suffixIs(diskfile, ".emergency"))
744                         diskfile = diskfile.substr(0, diskfile.size() - 10);
745                 saveCheckSum(FileName(diskfile));
746         }
747
748         if (file_format != LYX_FORMAT) {
749
750                 if (fromstring)
751                         // lyx2lyx would fail
752                         return wrongversion;
753
754                 FileName const tmpfile = FileName::tempName("Buffer_readFile");
755                 if (tmpfile.empty()) {
756                         Alert::error(_("Conversion failed"),
757                                      bformat(_("%1$s is from a different"
758                                               " version of LyX, but a temporary"
759                                               " file for converting it could"
760                                                             " not be created."),
761                                               from_utf8(filename.absFilename())));
762                         return failure;
763                 }
764                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
765                 if (lyx2lyx.empty()) {
766                         Alert::error(_("Conversion script not found"),
767                                      bformat(_("%1$s is from a different"
768                                                " version of LyX, but the"
769                                                " conversion script lyx2lyx"
770                                                             " could not be found."),
771                                                from_utf8(filename.absFilename())));
772                         return failure;
773                 }
774                 ostringstream command;
775                 command << os::python()
776                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
777                         << " -t " << convert<string>(LYX_FORMAT)
778                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
779                         << ' ' << quoteName(filename.toFilesystemEncoding());
780                 string const command_str = command.str();
781
782                 LYXERR(Debug::INFO, "Running '" << command_str << '\'');
783
784                 cmd_ret const ret = runCommand(command_str);
785                 if (ret.first != 0) {
786                         Alert::error(_("Conversion script failed"),
787                                      bformat(_("%1$s is from a different version"
788                                               " of LyX, but the lyx2lyx script"
789                                                             " failed to convert it."),
790                                               from_utf8(filename.absFilename())));
791                         return failure;
792                 } else {
793                         bool const ret = readFile(tmpfile);
794                         // Do stuff with tmpfile name and buffer name here.
795                         return ret ? success : failure;
796                 }
797
798         }
799
800         if (readDocument(lex)) {
801                 Alert::error(_("Document format failure"),
802                              bformat(_("%1$s ended unexpectedly, which means"
803                                                     " that it is probably corrupted."),
804                                        from_utf8(filename.absFilename())));
805         }
806
807         d->file_fully_loaded = true;
808         return success;
809 }
810
811
812 // Should probably be moved to somewhere else: BufferView? LyXView?
813 bool Buffer::save() const
814 {
815         // We don't need autosaves in the immediate future. (Asger)
816         resetAutosaveTimers();
817
818         string const encodedFilename = d->filename.toFilesystemEncoding();
819
820         FileName backupName;
821         bool madeBackup = false;
822
823         // make a backup if the file already exists
824         if (lyxrc.make_backup && fileName().exists()) {
825                 backupName = FileName(absFileName() + '~');
826                 if (!lyxrc.backupdir_path.empty()) {
827                         string const mangledName =
828                                 subst(subst(backupName.absFilename(), '/', '!'), ':', '!');
829                         backupName = FileName(addName(lyxrc.backupdir_path,
830                                                       mangledName));
831                 }
832                 if (fileName().copyTo(backupName)) {
833                         madeBackup = true;
834                 } else {
835                         Alert::error(_("Backup failure"),
836                                      bformat(_("Cannot create backup file %1$s.\n"
837                                                "Please check whether the directory exists and is writeable."),
838                                              from_utf8(backupName.absFilename())));
839                         //LYXERR(Debug::DEBUG, "Fs error: " << fe.what());
840                 }
841         }
842
843         // ask if the disk file has been externally modified (use checksum method)
844         if (fileName().exists() && isExternallyModified(checksum_method)) {
845                 docstring const file = makeDisplayPath(absFileName(), 20);
846                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
847                                                              "you want to overwrite this file?"), file);
848                 int const ret = Alert::prompt(_("Overwrite modified file?"),
849                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
850                 if (ret == 1)
851                         return false;
852         }
853
854         if (writeFile(d->filename)) {
855                 markClean();
856                 return true;
857         } else {
858                 // Saving failed, so backup is not backup
859                 if (madeBackup)
860                         backupName.moveTo(d->filename);
861                 return false;
862         }
863 }
864
865
866 bool Buffer::writeFile(FileName const & fname) const
867 {
868         if (d->read_only && fname == d->filename)
869                 return false;
870
871         bool retval = false;
872
873         docstring const str = bformat(_("Saving document %1$s..."),
874                 makeDisplayPath(fname.absFilename()));
875         message(str);
876
877         if (params().compressed) {
878                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
879                 retval = ofs && write(ofs);
880         } else {
881                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
882                 retval = ofs && write(ofs);
883         }
884
885         if (!retval) {
886                 message(str + _(" could not write file!"));
887                 return false;
888         }
889
890         removeAutosaveFile(d->filename.absFilename());
891
892         saveCheckSum(d->filename);
893         message(str + _(" done."));
894
895         return true;
896 }
897
898
899 bool Buffer::write(ostream & ofs) const
900 {
901 #ifdef HAVE_LOCALE
902         // Use the standard "C" locale for file output.
903         ofs.imbue(locale::classic());
904 #endif
905
906         // The top of the file should not be written by params().
907
908         // write out a comment in the top of the file
909         ofs << "#LyX " << lyx_version
910             << " created this file. For more info see http://www.lyx.org/\n"
911             << "\\lyxformat " << LYX_FORMAT << "\n"
912             << "\\begin_document\n";
913
914         /// For each author, set 'used' to true if there is a change
915         /// by this author in the document; otherwise set it to 'false'.
916         AuthorList::Authors::const_iterator a_it = params().authors().begin();
917         AuthorList::Authors::const_iterator a_end = params().authors().end();
918         for (; a_it != a_end; ++a_it)
919                 a_it->second.setUsed(false);
920
921         ParIterator const end = const_cast<Buffer *>(this)->par_iterator_end();
922         ParIterator it = const_cast<Buffer *>(this)->par_iterator_begin();
923         for ( ; it != end; ++it)
924                 it->checkAuthors(params().authors());
925
926         // now write out the buffer parameters.
927         ofs << "\\begin_header\n";
928         params().writeFile(ofs);
929         ofs << "\\end_header\n";
930
931         // write the text
932         ofs << "\n\\begin_body\n";
933         text().write(*this, ofs);
934         ofs << "\n\\end_body\n";
935
936         // Write marker that shows file is complete
937         ofs << "\\end_document" << endl;
938
939         // Shouldn't really be needed....
940         //ofs.close();
941
942         // how to check if close went ok?
943         // Following is an attempt... (BE 20001011)
944
945         // good() returns false if any error occured, including some
946         //        formatting error.
947         // bad()  returns true if something bad happened in the buffer,
948         //        which should include file system full errors.
949
950         bool status = true;
951         if (!ofs) {
952                 status = false;
953                 lyxerr << "File was not closed properly." << endl;
954         }
955
956         return status;
957 }
958
959
960 bool Buffer::makeLaTeXFile(FileName const & fname,
961                            string const & original_path,
962                            OutputParams const & runparams,
963                            bool output_preamble, bool output_body) const
964 {
965         string const encoding = runparams.encoding->iconvName();
966         LYXERR(Debug::LATEX, "makeLaTeXFile encoding: " << encoding << "...");
967
968         ofdocstream ofs;
969         try { ofs.reset(encoding); }
970         catch (iconv_codecvt_facet_exception & e) {
971                 lyxerr << "Caught iconv exception: " << e.what() << endl;
972                 Alert::error(_("Iconv software exception Detected"), bformat(_("Please "
973                         "verify that the support software for your encoding (%1$s) is "
974                         "properly installed"), from_ascii(encoding)));
975                 return false;
976         }
977         if (!openFileWrite(ofs, fname))
978                 return false;
979
980         //TexStream ts(ofs.rdbuf(), &texrow());
981         ErrorList & errorList = d->errorLists["Export"];
982         errorList.clear();
983         bool failed_export = false;
984         try {
985                 d->texrow.reset();
986                 writeLaTeXSource(ofs, original_path,
987                       runparams, output_preamble, output_body);
988         }
989         catch (EncodingException & e) {
990                 odocstringstream ods;
991                 ods.put(e.failed_char);
992                 ostringstream oss;
993                 oss << "0x" << hex << e.failed_char << dec;
994                 docstring msg = bformat(_("Could not find LaTeX command for character '%1$s'"
995                                           " (code point %2$s)"),
996                                           ods.str(), from_utf8(oss.str()));
997                 errorList.push_back(ErrorItem(msg, _("Some characters of your document are probably not "
998                                 "representable in the chosen encoding.\n"
999                                 "Changing the document encoding to utf8 could help."),
1000                                 e.par_id, e.pos, e.pos + 1));
1001                 failed_export = true;
1002         }
1003         catch (iconv_codecvt_facet_exception & e) {
1004                 errorList.push_back(ErrorItem(_("iconv conversion failed"),
1005                         _(e.what()), -1, 0, 0));
1006                 failed_export = true;
1007         }
1008         catch (exception const & e) {
1009                 errorList.push_back(ErrorItem(_("conversion failed"),
1010                         _(e.what()), -1, 0, 0));
1011                 failed_export = true;
1012         }
1013         catch (...) {
1014                 lyxerr << "Caught some really weird exception..." << endl;
1015                 lyx_exit(1);
1016         }
1017
1018         ofs.close();
1019         if (ofs.fail()) {
1020                 failed_export = true;
1021                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1022         }
1023
1024         errors("Export");
1025         return !failed_export;
1026 }
1027
1028
1029 void Buffer::writeLaTeXSource(odocstream & os,
1030                            string const & original_path,
1031                            OutputParams const & runparams_in,
1032                            bool const output_preamble, bool const output_body) const
1033 {
1034         // The child documents, if any, shall be already loaded at this point.
1035
1036         OutputParams runparams = runparams_in;
1037
1038         // Classify the unicode characters appearing in math insets
1039         Encodings::initUnicodeMath(*this);
1040
1041         // validate the buffer.
1042         LYXERR(Debug::LATEX, "  Validating buffer...");
1043         LaTeXFeatures features(*this, params(), runparams);
1044         validate(features);
1045         LYXERR(Debug::LATEX, "  Buffer validation done.");
1046
1047         // The starting paragraph of the coming rows is the
1048         // first paragraph of the document. (Asger)
1049         if (output_preamble && runparams.nice) {
1050                 os << "%% LyX " << lyx_version << " created this file.  "
1051                         "For more info, see http://www.lyx.org/.\n"
1052                         "%% Do not edit unless you really know what "
1053                         "you are doing.\n";
1054                 d->texrow.newline();
1055                 d->texrow.newline();
1056         }
1057         LYXERR(Debug::INFO, "lyx document header finished");
1058
1059         // Don't move this behind the parent_buffer=0 code below,
1060         // because then the macros will not get the right "redefinition"
1061         // flag as they don't see the parent macros which are output before.
1062         updateMacros();
1063
1064         // fold macros if possible, still with parent buffer as the
1065         // macros will be put in the prefix anyway.
1066         updateMacroInstances();
1067
1068         // There are a few differences between nice LaTeX and usual files:
1069         // usual is \batchmode and has a
1070         // special input@path to allow the including of figures
1071         // with either \input or \includegraphics (what figinsets do).
1072         // input@path is set when the actual parameter
1073         // original_path is set. This is done for usual tex-file, but not
1074         // for nice-latex-file. (Matthias 250696)
1075         // Note that input@path is only needed for something the user does
1076         // in the preamble, included .tex files or ERT, files included by
1077         // LyX work without it.
1078         if (output_preamble) {
1079                 if (!runparams.nice) {
1080                         // code for usual, NOT nice-latex-file
1081                         os << "\\batchmode\n"; // changed
1082                         // from \nonstopmode
1083                         d->texrow.newline();
1084                 }
1085                 if (!original_path.empty()) {
1086                         // FIXME UNICODE
1087                         // We don't know the encoding of inputpath
1088                         docstring const inputpath = from_utf8(latex_path(original_path));
1089                         os << "\\makeatletter\n"
1090                            << "\\def\\input@path{{"
1091                            << inputpath << "/}}\n"
1092                            << "\\makeatother\n";
1093                         d->texrow.newline();
1094                         d->texrow.newline();
1095                         d->texrow.newline();
1096                 }
1097
1098                 // get parent macros (if this buffer has a parent) which will be
1099                 // written at the document begin further down.
1100                 MacroSet parentMacros;
1101                 listParentMacros(parentMacros, features);
1102
1103                 // Write the preamble
1104                 runparams.use_babel = params().writeLaTeX(os, features, d->texrow);
1105
1106                 runparams.use_japanese = features.isRequired("japanese");
1107
1108                 if (!output_body)
1109                         return;
1110
1111                 // make the body.
1112                 os << "\\begin{document}\n";
1113                 d->texrow.newline();
1114
1115                 // output the parent macros
1116                 MacroSet::iterator it = parentMacros.begin();
1117                 MacroSet::iterator end = parentMacros.end();
1118                 for (; it != end; ++it)
1119                         (*it)->write(os, true);
1120         } // output_preamble
1121
1122         d->texrow.start(paragraphs().begin()->id(), 0);
1123
1124         LYXERR(Debug::INFO, "preamble finished, now the body.");
1125
1126         // if we are doing a real file with body, even if this is the
1127         // child of some other buffer, let's cut the link here.
1128         // This happens for example if only a child document is printed.
1129         Buffer const * save_parent = 0;
1130         if (output_preamble) {
1131                 save_parent = d->parent_buffer;
1132                 d->parent_buffer = 0;
1133         }
1134
1135         // the real stuff
1136         latexParagraphs(*this, text(), os, d->texrow, runparams);
1137
1138         // Restore the parenthood if needed
1139         if (output_preamble)
1140                 d->parent_buffer = save_parent;
1141
1142         // add this just in case after all the paragraphs
1143         os << endl;
1144         d->texrow.newline();
1145
1146         if (output_preamble) {
1147                 os << "\\end{document}\n";
1148                 d->texrow.newline();
1149                 LYXERR(Debug::LATEX, "makeLaTeXFile...done");
1150         } else {
1151                 LYXERR(Debug::LATEX, "LaTeXFile for inclusion made.");
1152         }
1153         runparams_in.encoding = runparams.encoding;
1154
1155         // Just to be sure. (Asger)
1156         d->texrow.newline();
1157
1158         LYXERR(Debug::INFO, "Finished making LaTeX file.");
1159         LYXERR(Debug::INFO, "Row count was " << d->texrow.rows() - 1 << '.');
1160 }
1161
1162
1163 bool Buffer::isLatex() const
1164 {
1165         return params().documentClass().outputType() == LATEX;
1166 }
1167
1168
1169 bool Buffer::isLiterate() const
1170 {
1171         return params().documentClass().outputType() == LITERATE;
1172 }
1173
1174
1175 bool Buffer::isDocBook() const
1176 {
1177         return params().documentClass().outputType() == DOCBOOK;
1178 }
1179
1180
1181 void Buffer::makeDocBookFile(FileName const & fname,
1182                               OutputParams const & runparams,
1183                               bool const body_only) const
1184 {
1185         LYXERR(Debug::LATEX, "makeDocBookFile...");
1186
1187         ofdocstream ofs;
1188         if (!openFileWrite(ofs, fname))
1189                 return;
1190
1191         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1192
1193         ofs.close();
1194         if (ofs.fail())
1195                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1196 }
1197
1198
1199 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1200                              OutputParams const & runparams,
1201                              bool const only_body) const
1202 {
1203         LaTeXFeatures features(*this, params(), runparams);
1204         validate(features);
1205
1206         d->texrow.reset();
1207
1208         DocumentClass const & tclass = params().documentClass();
1209         string const top_element = tclass.latexname();
1210
1211         if (!only_body) {
1212                 if (runparams.flavor == OutputParams::XML)
1213                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1214
1215                 // FIXME UNICODE
1216                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1217
1218                 // FIXME UNICODE
1219                 if (! tclass.class_header().empty())
1220                         os << from_ascii(tclass.class_header());
1221                 else if (runparams.flavor == OutputParams::XML)
1222                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1223                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1224                 else
1225                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1226
1227                 docstring preamble = from_utf8(params().preamble);
1228                 if (runparams.flavor != OutputParams::XML ) {
1229                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1230                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1231                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1232                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1233                 }
1234
1235                 string const name = runparams.nice
1236                         ? changeExtension(absFileName(), ".sgml") : fname;
1237                 preamble += features.getIncludedFiles(name);
1238                 preamble += features.getLyXSGMLEntities();
1239
1240                 if (!preamble.empty()) {
1241                         os << "\n [ " << preamble << " ]";
1242                 }
1243                 os << ">\n\n";
1244         }
1245
1246         string top = top_element;
1247         top += " lang=\"";
1248         if (runparams.flavor == OutputParams::XML)
1249                 top += params().language->code();
1250         else
1251                 top += params().language->code().substr(0, 2);
1252         top += '"';
1253
1254         if (!params().options.empty()) {
1255                 top += ' ';
1256                 top += params().options;
1257         }
1258
1259         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1260             << " file was created by LyX " << lyx_version
1261             << "\n  See http://www.lyx.org/ for more information -->\n";
1262
1263         params().documentClass().counters().reset();
1264
1265         updateMacros();
1266
1267         sgml::openTag(os, top);
1268         os << '\n';
1269         docbookParagraphs(paragraphs(), *this, os, runparams);
1270         sgml::closeTag(os, top_element);
1271 }
1272
1273
1274 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1275 // Other flags: -wall -v0 -x
1276 int Buffer::runChktex()
1277 {
1278         setBusy(true);
1279
1280         // get LaTeX-Filename
1281         FileName const path(temppath());
1282         string const name = addName(path.absFilename(), latexName());
1283         string const org_path = filePath();
1284
1285         PathChanger p(path); // path to LaTeX file
1286         message(_("Running chktex..."));
1287
1288         // Generate the LaTeX file if neccessary
1289         OutputParams runparams(&params().encoding());
1290         runparams.flavor = OutputParams::LATEX;
1291         runparams.nice = false;
1292         makeLaTeXFile(FileName(name), org_path, runparams);
1293
1294         TeXErrors terr;
1295         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1296         int const res = chktex.run(terr); // run chktex
1297
1298         if (res == -1) {
1299                 Alert::error(_("chktex failure"),
1300                              _("Could not run chktex successfully."));
1301         } else if (res > 0) {
1302                 ErrorList & errlist = d->errorLists["ChkTeX"];
1303                 errlist.clear();
1304                 bufferErrors(terr, errlist);
1305         }
1306
1307         setBusy(false);
1308
1309         errors("ChkTeX");
1310
1311         return res;
1312 }
1313
1314
1315 void Buffer::validate(LaTeXFeatures & features) const
1316 {
1317         params().validate(features);
1318
1319         updateMacros();
1320
1321         for_each(paragraphs().begin(), paragraphs().end(),
1322                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1323
1324         if (lyxerr.debugging(Debug::LATEX)) {
1325                 features.showStruct();
1326         }
1327 }
1328
1329
1330 void Buffer::getLabelList(vector<docstring> & list) const
1331 {
1332         // If this is a child document, use the parent's list instead.
1333         if (d->parent_buffer) {
1334                 d->parent_buffer->getLabelList(list);
1335                 return;
1336         }
1337
1338         list.clear();
1339         Toc & toc = d->toc_backend.toc("label");
1340         TocIterator toc_it = toc.begin();
1341         TocIterator end = toc.end();
1342         for (; toc_it != end; ++toc_it) {
1343                 if (toc_it->depth() == 0)
1344                         list.push_back(toc_it->str());
1345         }
1346 }
1347
1348
1349 void Buffer::updateBibfilesCache() const
1350 {
1351         // If this is a child document, use the parent's cache instead.
1352         if (d->parent_buffer) {
1353                 d->parent_buffer->updateBibfilesCache();
1354                 return;
1355         }
1356
1357         d->bibfilesCache_.clear();
1358         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1359                 if (it->lyxCode() == BIBTEX_CODE) {
1360                         InsetBibtex const & inset =
1361                                 static_cast<InsetBibtex const &>(*it);
1362                         support::FileNameList const bibfiles = inset.getBibFiles();
1363                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1364                                 bibfiles.begin(),
1365                                 bibfiles.end());
1366                 } else if (it->lyxCode() == INCLUDE_CODE) {
1367                         InsetInclude & inset =
1368                                 static_cast<InsetInclude &>(*it);
1369                         inset.updateBibfilesCache();
1370                         support::FileNameList const & bibfiles =
1371                                         inset.getBibfilesCache(*this);
1372                         d->bibfilesCache_.insert(d->bibfilesCache_.end(),
1373                                 bibfiles.begin(),
1374                                 bibfiles.end());
1375                 }
1376         }
1377         // the bibinfo cache is now invalid
1378         d->bibinfoCacheValid_ = false;
1379 }
1380
1381
1382 void Buffer::invalidateBibinfoCache()
1383 {
1384         d->bibinfoCacheValid_ = false;
1385 }
1386
1387
1388 support::FileNameList const & Buffer::getBibfilesCache() const
1389 {
1390         // If this is a child document, use the parent's cache instead.
1391         if (d->parent_buffer)
1392                 return d->parent_buffer->getBibfilesCache();
1393
1394         // We update the cache when first used instead of at loading time.
1395         if (d->bibfilesCache_.empty())
1396                 const_cast<Buffer *>(this)->updateBibfilesCache();
1397
1398         return d->bibfilesCache_;
1399 }
1400
1401
1402 BiblioInfo const & Buffer::masterBibInfo() const
1403 {
1404         // if this is a child document and the parent is already loaded
1405         // use the parent's list instead  [ale990412]
1406         Buffer const * const tmp = masterBuffer();
1407         LASSERT(tmp, /**/);
1408         if (tmp != this)
1409                 return tmp->masterBibInfo();
1410         return localBibInfo();
1411 }
1412
1413
1414 BiblioInfo const & Buffer::localBibInfo() const
1415 {
1416         if (d->bibinfoCacheValid_) {
1417                 support::FileNameList const & bibfilesCache = getBibfilesCache();
1418                 // compare the cached timestamps with the actual ones.
1419                 support::FileNameList::const_iterator ei = bibfilesCache.begin();
1420                 support::FileNameList::const_iterator en = bibfilesCache.end();
1421                 for (; ei != en; ++ ei) {
1422                         time_t lastw = ei->lastModified();
1423                         if (lastw != d->bibfileStatus_[*ei]) {
1424                                 d->bibinfoCacheValid_ = false;
1425                                 d->bibfileStatus_[*ei] = lastw;
1426                                 break;
1427                         }
1428                 }
1429         }
1430
1431         if (!d->bibinfoCacheValid_) {
1432                 d->bibinfo_.clear();
1433                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1434                         it->fillWithBibKeys(d->bibinfo_, it);
1435                 d->bibinfoCacheValid_ = true;
1436         }
1437         return d->bibinfo_;
1438 }
1439
1440
1441 bool Buffer::isDepClean(string const & name) const
1442 {
1443         DepClean::const_iterator const it = d->dep_clean.find(name);
1444         if (it == d->dep_clean.end())
1445                 return true;
1446         return it->second;
1447 }
1448
1449
1450 void Buffer::markDepClean(string const & name)
1451 {
1452         d->dep_clean[name] = true;
1453 }
1454
1455
1456 bool Buffer::dispatch(string const & command, bool * result)
1457 {
1458         return dispatch(lyxaction.lookupFunc(command), result);
1459 }
1460
1461
1462 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1463 {
1464         bool dispatched = true;
1465
1466         switch (func.action) {
1467                 case LFUN_BUFFER_EXPORT: {
1468                         bool const tmp = doExport(to_utf8(func.argument()), false);
1469                         if (result)
1470                                 *result = tmp;
1471                         break;
1472                 }
1473
1474                 case LFUN_BRANCH_ACTIVATE:
1475                 case LFUN_BRANCH_DEACTIVATE: {
1476                         BranchList & branchList = params().branchlist();
1477                         docstring const branchName = func.argument();
1478                         Branch * branch = branchList.find(branchName);
1479                         if (!branch)
1480                                 LYXERR0("Branch " << branchName << " does not exist.");
1481                         else
1482                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1483                         if (result)
1484                                 *result = true;
1485                 }
1486
1487                 default:
1488                         dispatched = false;
1489         }
1490         return dispatched;
1491 }
1492
1493
1494 void Buffer::changeLanguage(Language const * from, Language const * to)
1495 {
1496         LASSERT(from, /**/);
1497         LASSERT(to, /**/);
1498
1499         for_each(par_iterator_begin(),
1500                  par_iterator_end(),
1501                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1502 }
1503
1504
1505 bool Buffer::isMultiLingual() const
1506 {
1507         ParConstIterator end = par_iterator_end();
1508         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1509                 if (it->isMultiLingual(params()))
1510                         return true;
1511
1512         return false;
1513 }
1514
1515
1516 DocIterator Buffer::getParFromID(int const id) const
1517 {
1518         if (id < 0) {
1519                 // John says this is called with id == -1 from undo
1520                 lyxerr << "getParFromID(), id: " << id << endl;
1521                 return doc_iterator_end(inset());
1522         }
1523
1524         for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1525                 if (it.paragraph().id() == id)
1526                         return it;
1527
1528         return doc_iterator_end(inset());
1529 }
1530
1531
1532 bool Buffer::hasParWithID(int const id) const
1533 {
1534         return !getParFromID(id).atEnd();
1535 }
1536
1537
1538 ParIterator Buffer::par_iterator_begin()
1539 {
1540         return ParIterator(doc_iterator_begin(inset()));
1541 }
1542
1543
1544 ParIterator Buffer::par_iterator_end()
1545 {
1546         return ParIterator(doc_iterator_end(inset()));
1547 }
1548
1549
1550 ParConstIterator Buffer::par_iterator_begin() const
1551 {
1552         return lyx::par_const_iterator_begin(inset());
1553 }
1554
1555
1556 ParConstIterator Buffer::par_iterator_end() const
1557 {
1558         return lyx::par_const_iterator_end(inset());
1559 }
1560
1561
1562 Language const * Buffer::language() const
1563 {
1564         return params().language;
1565 }
1566
1567
1568 docstring const Buffer::B_(string const & l10n) const
1569 {
1570         return params().B_(l10n);
1571 }
1572
1573
1574 bool Buffer::isClean() const
1575 {
1576         return d->lyx_clean;
1577 }
1578
1579
1580 bool Buffer::isBakClean() const
1581 {
1582         return d->bak_clean;
1583 }
1584
1585
1586 bool Buffer::isExternallyModified(CheckMethod method) const
1587 {
1588         LASSERT(d->filename.exists(), /**/);
1589         // if method == timestamp, check timestamp before checksum
1590         return (method == checksum_method
1591                 || d->timestamp_ != d->filename.lastModified())
1592                 && d->checksum_ != d->filename.checksum();
1593 }
1594
1595
1596 void Buffer::saveCheckSum(FileName const & file) const
1597 {
1598         if (file.exists()) {
1599                 d->timestamp_ = file.lastModified();
1600                 d->checksum_ = file.checksum();
1601         } else {
1602                 // in the case of save to a new file.
1603                 d->timestamp_ = 0;
1604                 d->checksum_ = 0;
1605         }
1606 }
1607
1608
1609 void Buffer::markClean() const
1610 {
1611         if (!d->lyx_clean) {
1612                 d->lyx_clean = true;
1613                 updateTitles();
1614         }
1615         // if the .lyx file has been saved, we don't need an
1616         // autosave
1617         d->bak_clean = true;
1618 }
1619
1620
1621 void Buffer::markBakClean() const
1622 {
1623         d->bak_clean = true;
1624 }
1625
1626
1627 void Buffer::setUnnamed(bool flag)
1628 {
1629         d->unnamed = flag;
1630 }
1631
1632
1633 bool Buffer::isUnnamed() const
1634 {
1635         return d->unnamed;
1636 }
1637
1638
1639 // FIXME: this function should be moved to buffer_pimpl.C
1640 void Buffer::markDirty()
1641 {
1642         if (d->lyx_clean) {
1643                 d->lyx_clean = false;
1644                 updateTitles();
1645         }
1646         d->bak_clean = false;
1647
1648         DepClean::iterator it = d->dep_clean.begin();
1649         DepClean::const_iterator const end = d->dep_clean.end();
1650
1651         for (; it != end; ++it)
1652                 it->second = false;
1653 }
1654
1655
1656 FileName Buffer::fileName() const
1657 {
1658         return d->filename;
1659 }
1660
1661
1662 string Buffer::absFileName() const
1663 {
1664         return d->filename.absFilename();
1665 }
1666
1667
1668 string Buffer::filePath() const
1669 {
1670         return d->filename.onlyPath().absFilename() + "/";
1671 }
1672
1673
1674 bool Buffer::isReadonly() const
1675 {
1676         return d->read_only;
1677 }
1678
1679
1680 void Buffer::setParent(Buffer const * buffer)
1681 {
1682         // Avoids recursive include.
1683         d->parent_buffer = buffer == this ? 0 : buffer;
1684         updateMacros();
1685 }
1686
1687
1688 Buffer const * Buffer::parent() const
1689 {
1690         return d->parent_buffer;
1691 }
1692
1693
1694 void Buffer::collectRelatives(BufferSet & bufs) const
1695 {
1696         bufs.insert(this);
1697         if (parent())
1698                 parent()->collectRelatives(bufs);
1699
1700         // loop over children
1701         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1702         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1703         for (; it != end; ++it)
1704                 bufs.insert(const_cast<Buffer *>(it->first));
1705 }
1706
1707
1708 std::vector<Buffer const *> Buffer::allRelatives() const
1709 {
1710         BufferSet bufs;
1711         collectRelatives(bufs);
1712         BufferSet::iterator it = bufs.begin();
1713         std::vector<Buffer const *> ret;
1714         for (; it != bufs.end(); ++it)
1715                 ret.push_back(*it);
1716         return ret;
1717 }
1718
1719
1720 Buffer const * Buffer::masterBuffer() const
1721 {
1722         if (!d->parent_buffer)
1723                 return this;
1724
1725         return d->parent_buffer->masterBuffer();
1726 }
1727
1728
1729 bool Buffer::isChild(Buffer * child) const
1730 {
1731         return d->children_positions.find(child) != d->children_positions.end();
1732 }
1733
1734
1735 DocIterator Buffer::firstChildPosition(Buffer const * child)
1736 {
1737         Impl::BufferPositionMap::iterator it;
1738         it = d->children_positions.find(child);
1739         if (it == d->children_positions.end())
1740                 return DocIterator();
1741         return it->second;
1742 }
1743
1744
1745 template<typename M>
1746 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1747 {
1748         if (m.empty())
1749                 return m.end();
1750
1751         typename M::iterator it = m.lower_bound(x);
1752         if (it == m.begin())
1753                 return m.end();
1754
1755         it--;
1756         return it;
1757 }
1758
1759
1760 MacroData const * Buffer::getBufferMacro(docstring const & name,
1761                                          DocIterator const & pos) const
1762 {
1763         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1764
1765         // if paragraphs have no macro context set, pos will be empty
1766         if (pos.empty())
1767                 return 0;
1768
1769         // we haven't found anything yet
1770         DocIterator bestPos = par_iterator_begin();
1771         MacroData const * bestData = 0;
1772
1773         // find macro definitions for name
1774         Impl::NamePositionScopeMacroMap::iterator nameIt
1775         = d->macros.find(name);
1776         if (nameIt != d->macros.end()) {
1777                 // find last definition in front of pos or at pos itself
1778                 Impl::PositionScopeMacroMap::const_iterator it
1779                 = greatest_below(nameIt->second, pos);
1780                 if (it != nameIt->second.end()) {
1781                         while (true) {
1782                                 // scope ends behind pos?
1783                                 if (pos < it->second.first) {
1784                                         // Looks good, remember this. If there
1785                                         // is no external macro behind this,
1786                                         // we found the right one already.
1787                                         bestPos = it->first;
1788                                         bestData = &it->second.second;
1789                                         break;
1790                                 }
1791
1792                                 // try previous macro if there is one
1793                                 if (it == nameIt->second.begin())
1794                                         break;
1795                                 it--;
1796                         }
1797                 }
1798         }
1799
1800         // find macros in included files
1801         Impl::PositionScopeBufferMap::const_iterator it
1802         = greatest_below(d->position_to_children, pos);
1803         if (it == d->position_to_children.end())
1804                 // no children before
1805                 return bestData;
1806
1807         while (true) {
1808                 // do we know something better (i.e. later) already?
1809                 if (it->first < bestPos )
1810                         break;
1811
1812                 // scope ends behind pos?
1813                 if (pos < it->second.first) {
1814                         // look for macro in external file
1815                         d->macro_lock = true;
1816                         MacroData const * data
1817                         = it->second.second->getMacro(name, false);
1818                         d->macro_lock = false;
1819                         if (data) {
1820                                 bestPos = it->first;
1821                                 bestData = data;
1822                                 break;
1823                         }
1824                 }
1825
1826                 // try previous file if there is one
1827                 if (it == d->position_to_children.begin())
1828                         break;
1829                 --it;
1830         }
1831
1832         // return the best macro we have found
1833         return bestData;
1834 }
1835
1836
1837 MacroData const * Buffer::getMacro(docstring const & name,
1838         DocIterator const & pos, bool global) const
1839 {
1840         if (d->macro_lock)
1841                 return 0;
1842
1843         // query buffer macros
1844         MacroData const * data = getBufferMacro(name, pos);
1845         if (data != 0)
1846                 return data;
1847
1848         // If there is a master buffer, query that
1849         if (d->parent_buffer) {
1850                 d->macro_lock = true;
1851                 MacroData const * macro = d->parent_buffer->getMacro(
1852                         name, *this, false);
1853                 d->macro_lock = false;
1854                 if (macro)
1855                         return macro;
1856         }
1857
1858         if (global) {
1859                 data = MacroTable::globalMacros().get(name);
1860                 if (data != 0)
1861                         return data;
1862         }
1863
1864         return 0;
1865 }
1866
1867
1868 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1869 {
1870         // set scope end behind the last paragraph
1871         DocIterator scope = par_iterator_begin();
1872         scope.pit() = scope.lastpit() + 1;
1873
1874         return getMacro(name, scope, global);
1875 }
1876
1877
1878 MacroData const * Buffer::getMacro(docstring const & name,
1879         Buffer const & child, bool global) const
1880 {
1881         // look where the child buffer is included first
1882         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1883         if (it == d->children_positions.end())
1884                 return 0;
1885
1886         // check for macros at the inclusion position
1887         return getMacro(name, it->second, global);
1888 }
1889
1890
1891 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1892 {
1893         pit_type lastpit = it.lastpit();
1894
1895         // look for macros in each paragraph
1896         while (it.pit() <= lastpit) {
1897                 Paragraph & par = it.paragraph();
1898
1899                 // iterate over the insets of the current paragraph
1900                 InsetList const & insets = par.insetList();
1901                 InsetList::const_iterator iit = insets.begin();
1902                 InsetList::const_iterator end = insets.end();
1903                 for (; iit != end; ++iit) {
1904                         it.pos() = iit->pos;
1905
1906                         // is it a nested text inset?
1907                         if (iit->inset->asInsetText()) {
1908                                 // Inset needs its own scope?
1909                                 InsetText const * itext
1910                                 = iit->inset->asInsetText();
1911                                 bool newScope = itext->isMacroScope();
1912
1913                                 // scope which ends just behind the inset
1914                                 DocIterator insetScope = it;
1915                                 ++insetScope.pos();
1916
1917                                 // collect macros in inset
1918                                 it.push_back(CursorSlice(*iit->inset));
1919                                 updateMacros(it, newScope ? insetScope : scope);
1920                                 it.pop_back();
1921                                 continue;
1922                         }
1923
1924                         // is it an external file?
1925                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1926                                 // get buffer of external file
1927                                 InsetCommand const & inset
1928                                         = static_cast<InsetCommand const &>(*iit->inset);
1929                                 InsetCommandParams const & ip = inset.params();
1930                                 d->macro_lock = true;
1931                                 Buffer * child = loadIfNeeded(*this, ip);
1932                                 d->macro_lock = false;
1933                                 if (!child)
1934                                         continue;
1935
1936                                 // register its position, but only when it is
1937                                 // included first in the buffer
1938                                 if (d->children_positions.find(child)
1939                                         == d->children_positions.end())
1940                                         d->children_positions[child] = it;
1941
1942                                 // register child with its scope
1943                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1944                                 continue;
1945                         }
1946
1947                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1948                                 continue;
1949
1950                         // get macro data
1951                         MathMacroTemplate & macroTemplate
1952                         = static_cast<MathMacroTemplate &>(*iit->inset);
1953                         MacroContext mc(*this, it);
1954                         macroTemplate.updateToContext(mc);
1955
1956                         // valid?
1957                         bool valid = macroTemplate.validMacro();
1958                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1959                         // then the BufferView's cursor will be invalid in
1960                         // some cases which leads to crashes.
1961                         if (!valid)
1962                                 continue;
1963
1964                         // register macro
1965                         d->macros[macroTemplate.name()][it] =
1966                                 Impl::ScopeMacro(scope, MacroData(*this, it));
1967                 }
1968
1969                 // next paragraph
1970                 it.pit()++;
1971                 it.pos() = 0;
1972         }
1973 }
1974
1975
1976 void Buffer::updateMacros() const
1977 {
1978         if (d->macro_lock)
1979                 return;
1980
1981         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1982
1983         // start with empty table
1984         d->macros.clear();
1985         d->children_positions.clear();
1986         d->position_to_children.clear();
1987
1988         // Iterate over buffer, starting with first paragraph
1989         // The scope must be bigger than any lookup DocIterator
1990         // later. For the global lookup, lastpit+1 is used, hence
1991         // we use lastpit+2 here.
1992         DocIterator it = par_iterator_begin();
1993         DocIterator outerScope = it;
1994         outerScope.pit() = outerScope.lastpit() + 2;
1995         updateMacros(it, outerScope);
1996 }
1997
1998
1999 void Buffer::updateMacroInstances() const
2000 {
2001         LYXERR(Debug::MACROS, "updateMacroInstances for "
2002                 << d->filename.onlyFileName());
2003         DocIterator it = doc_iterator_begin(inset());
2004         DocIterator end = doc_iterator_end(inset());
2005         for (; it != end; it.forwardPos()) {
2006                 // look for MathData cells in InsetMathNest insets
2007                 Inset * inset = it.nextInset();
2008                 if (!inset)
2009                         continue;
2010
2011                 InsetMath * minset = inset->asInsetMath();
2012                 if (!minset)
2013                         continue;
2014
2015                 // update macro in all cells of the InsetMathNest
2016                 DocIterator::idx_type n = minset->nargs();
2017                 MacroContext mc = MacroContext(*this, it);
2018                 for (DocIterator::idx_type i = 0; i < n; ++i) {
2019                         MathData & data = minset->cell(i);
2020                         data.updateMacros(0, mc);
2021                 }
2022         }
2023 }
2024
2025
2026 void Buffer::listMacroNames(MacroNameSet & macros) const
2027 {
2028         if (d->macro_lock)
2029                 return;
2030
2031         d->macro_lock = true;
2032
2033         // loop over macro names
2034         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
2035         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
2036         for (; nameIt != nameEnd; ++nameIt)
2037                 macros.insert(nameIt->first);
2038
2039         // loop over children
2040         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
2041         Impl::BufferPositionMap::iterator end = d->children_positions.end();
2042         for (; it != end; ++it)
2043                 it->first->listMacroNames(macros);
2044
2045         // call parent
2046         if (d->parent_buffer)
2047                 d->parent_buffer->listMacroNames(macros);
2048
2049         d->macro_lock = false;
2050 }
2051
2052
2053 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
2054 {
2055         if (!d->parent_buffer)
2056                 return;
2057
2058         MacroNameSet names;
2059         d->parent_buffer->listMacroNames(names);
2060
2061         // resolve macros
2062         MacroNameSet::iterator it = names.begin();
2063         MacroNameSet::iterator end = names.end();
2064         for (; it != end; ++it) {
2065                 // defined?
2066                 MacroData const * data =
2067                 d->parent_buffer->getMacro(*it, *this, false);
2068                 if (data) {
2069                         macros.insert(data);
2070
2071                         // we cannot access the original MathMacroTemplate anymore
2072                         // here to calls validate method. So we do its work here manually.
2073                         // FIXME: somehow make the template accessible here.
2074                         if (data->optionals() > 0)
2075                                 features.require("xargs");
2076                 }
2077         }
2078 }
2079
2080
2081 Buffer::References & Buffer::references(docstring const & label)
2082 {
2083         if (d->parent_buffer)
2084                 return const_cast<Buffer *>(masterBuffer())->references(label);
2085
2086         RefCache::iterator it = d->ref_cache_.find(label);
2087         if (it != d->ref_cache_.end())
2088                 return it->second.second;
2089
2090         static InsetLabel const * dummy_il = 0;
2091         static References const dummy_refs;
2092         it = d->ref_cache_.insert(
2093                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2094         return it->second.second;
2095 }
2096
2097
2098 Buffer::References const & Buffer::references(docstring const & label) const
2099 {
2100         return const_cast<Buffer *>(this)->references(label);
2101 }
2102
2103
2104 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2105 {
2106         masterBuffer()->d->ref_cache_[label].first = il;
2107 }
2108
2109
2110 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2111 {
2112         return masterBuffer()->d->ref_cache_[label].first;
2113 }
2114
2115
2116 void Buffer::clearReferenceCache() const
2117 {
2118         if (!d->parent_buffer)
2119                 d->ref_cache_.clear();
2120 }
2121
2122
2123 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2124         InsetCode code)
2125 {
2126         //FIXME: This does not work for child documents yet.
2127         LASSERT(code == CITE_CODE, /**/);
2128         // Check if the label 'from' appears more than once
2129         vector<docstring> labels;
2130         string paramName;
2131         BiblioInfo const & keys = masterBibInfo();
2132         BiblioInfo::const_iterator bit  = keys.begin();
2133         BiblioInfo::const_iterator bend = keys.end();
2134
2135         for (; bit != bend; ++bit)
2136                 // FIXME UNICODE
2137                 labels.push_back(bit->first);
2138         paramName = "key";
2139
2140         if (count(labels.begin(), labels.end(), from) > 1)
2141                 return;
2142
2143         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2144                 if (it->lyxCode() == code) {
2145                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2146                         docstring const oldValue = inset.getParam(paramName);
2147                         if (oldValue == from)
2148                                 inset.setParam(paramName, to);
2149                 }
2150         }
2151 }
2152
2153
2154 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2155         pit_type par_end, bool full_source) const
2156 {
2157         OutputParams runparams(&params().encoding());
2158         runparams.nice = true;
2159         runparams.flavor = OutputParams::LATEX;
2160         runparams.linelen = lyxrc.plaintext_linelen;
2161         // No side effect of file copying and image conversion
2162         runparams.dryrun = true;
2163
2164         d->texrow.reset();
2165         if (full_source) {
2166                 os << "% " << _("Preview source code") << "\n\n";
2167                 d->texrow.newline();
2168                 d->texrow.newline();
2169                 if (isDocBook())
2170                         writeDocBookSource(os, absFileName(), runparams, false);
2171                 else
2172                         // latex or literate
2173                         writeLaTeXSource(os, string(), runparams, true, true);
2174         } else {
2175                 runparams.par_begin = par_begin;
2176                 runparams.par_end = par_end;
2177                 if (par_begin + 1 == par_end) {
2178                         os << "% "
2179                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2180                            << "\n\n";
2181                 } else {
2182                         os << "% "
2183                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2184                                         convert<docstring>(par_begin),
2185                                         convert<docstring>(par_end - 1))
2186                            << "\n\n";
2187                 }
2188                 d->texrow.newline();
2189                 d->texrow.newline();
2190                 // output paragraphs
2191                 if (isDocBook())
2192                         docbookParagraphs(paragraphs(), *this, os, runparams);
2193                 else 
2194                         // latex or literate
2195                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2196         }
2197 }
2198
2199
2200 ErrorList & Buffer::errorList(string const & type) const
2201 {
2202         static ErrorList emptyErrorList;
2203         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2204         if (I == d->errorLists.end())
2205                 return emptyErrorList;
2206
2207         return I->second;
2208 }
2209
2210
2211 void Buffer::updateTocItem(std::string const & type,
2212         DocIterator const & dit) const
2213 {
2214         if (gui_)
2215                 gui_->updateTocItem(type, dit);
2216 }
2217
2218
2219 void Buffer::structureChanged() const
2220 {
2221         if (gui_)
2222                 gui_->structureChanged();
2223 }
2224
2225
2226 void Buffer::errors(string const & err) const
2227 {
2228         if (gui_)
2229                 gui_->errors(err);
2230 }
2231
2232
2233 void Buffer::message(docstring const & msg) const
2234 {
2235         if (gui_)
2236                 gui_->message(msg);
2237 }
2238
2239
2240 void Buffer::setBusy(bool on) const
2241 {
2242         if (gui_)
2243                 gui_->setBusy(on);
2244 }
2245
2246
2247 void Buffer::setReadOnly(bool on) const
2248 {
2249         if (d->wa_)
2250                 d->wa_->setReadOnly(on);
2251 }
2252
2253
2254 void Buffer::updateTitles() const
2255 {
2256         if (d->wa_)
2257                 d->wa_->updateTitles();
2258 }
2259
2260
2261 void Buffer::resetAutosaveTimers() const
2262 {
2263         if (gui_)
2264                 gui_->resetAutosaveTimers();
2265 }
2266
2267
2268 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2269 {
2270         gui_ = gui;
2271 }
2272
2273
2274
2275 namespace {
2276
2277 class AutoSaveBuffer : public ForkedProcess {
2278 public:
2279         ///
2280         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2281                 : buffer_(buffer), fname_(fname) {}
2282         ///
2283         virtual boost::shared_ptr<ForkedProcess> clone() const
2284         {
2285                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2286         }
2287         ///
2288         int start()
2289         {
2290                 command_ = to_utf8(bformat(_("Auto-saving %1$s"),
2291                                                  from_utf8(fname_.absFilename())));
2292                 return run(DontWait);
2293         }
2294 private:
2295         ///
2296         virtual int generateChild();
2297         ///
2298         Buffer const & buffer_;
2299         FileName fname_;
2300 };
2301
2302
2303 int AutoSaveBuffer::generateChild()
2304 {
2305         // tmp_ret will be located (usually) in /tmp
2306         // will that be a problem?
2307         // Note that this calls ForkedCalls::fork(), so it's
2308         // ok cross-platform.
2309         pid_t const pid = fork();
2310         // If you want to debug the autosave
2311         // you should set pid to -1, and comment out the fork.
2312         if (pid != 0 && pid != -1)
2313                 return pid;
2314
2315         // pid = -1 signifies that lyx was unable
2316         // to fork. But we will do the save
2317         // anyway.
2318         bool failed = false;
2319         FileName const tmp_ret = FileName::tempName("lyxauto");
2320         if (!tmp_ret.empty()) {
2321                 buffer_.writeFile(tmp_ret);
2322                 // assume successful write of tmp_ret
2323                 if (!tmp_ret.moveTo(fname_))
2324                         failed = true;
2325         } else
2326                 failed = true;
2327
2328         if (failed) {
2329                 // failed to write/rename tmp_ret so try writing direct
2330                 if (!buffer_.writeFile(fname_)) {
2331                         // It is dangerous to do this in the child,
2332                         // but safe in the parent, so...
2333                         if (pid == -1) // emit message signal.
2334                                 buffer_.message(_("Autosave failed!"));
2335                 }
2336         }
2337
2338         if (pid == 0) // we are the child so...
2339                 _exit(0);
2340
2341         return pid;
2342 }
2343
2344 } // namespace anon
2345
2346
2347 // Perfect target for a thread...
2348 void Buffer::autoSave() const
2349 {
2350         if (isBakClean() || isReadonly()) {
2351                 // We don't save now, but we'll try again later
2352                 resetAutosaveTimers();
2353                 return;
2354         }
2355
2356         // emit message signal.
2357         message(_("Autosaving current document..."));
2358
2359         // create autosave filename
2360         string fname = filePath();
2361         fname += '#';
2362         fname += d->filename.onlyFileName();
2363         fname += '#';
2364
2365         AutoSaveBuffer autosave(*this, FileName(fname));
2366         autosave.start();
2367
2368         markBakClean();
2369         resetAutosaveTimers();
2370 }
2371
2372
2373 string Buffer::bufferFormat() const
2374 {
2375         if (isDocBook())
2376                 return "docbook";
2377         if (isLiterate())
2378                 return "literate";
2379         if (params().encoding().package() == Encoding::japanese)
2380                 return "platex";
2381         return "latex";
2382 }
2383
2384
2385 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2386         string & result_file) const
2387 {
2388         string backend_format;
2389         OutputParams runparams(&params().encoding());
2390         runparams.flavor = OutputParams::LATEX;
2391         runparams.linelen = lyxrc.plaintext_linelen;
2392         vector<string> backs = backends();
2393         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2394                 // Get shortest path to format
2395                 Graph::EdgePath path;
2396                 for (vector<string>::const_iterator it = backs.begin();
2397                      it != backs.end(); ++it) {
2398                         Graph::EdgePath p = theConverters().getPath(*it, format);
2399                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2400                                 backend_format = *it;
2401                                 path = p;
2402                         }
2403                 }
2404                 if (!path.empty())
2405                         runparams.flavor = theConverters().getFlavor(path);
2406                 else {
2407                         Alert::error(_("Couldn't export file"),
2408                                 bformat(_("No information for exporting the format %1$s."),
2409                                    formats.prettyName(format)));
2410                         return false;
2411                 }
2412         } else {
2413                 backend_format = format;
2414                 // FIXME: Don't hardcode format names here, but use a flag
2415                 if (backend_format == "pdflatex")
2416                         runparams.flavor = OutputParams::PDFLATEX;
2417         }
2418
2419         string filename = latexName(false);
2420         filename = addName(temppath(), filename);
2421         filename = changeExtension(filename,
2422                                    formats.extension(backend_format));
2423
2424         // fix macros
2425         updateMacroInstances();
2426
2427         // Plain text backend
2428         if (backend_format == "text")
2429                 writePlaintextFile(*this, FileName(filename), runparams);
2430         // no backend
2431         else if (backend_format == "lyx")
2432                 writeFile(FileName(filename));
2433         // Docbook backend
2434         else if (isDocBook()) {
2435                 runparams.nice = !put_in_tempdir;
2436                 makeDocBookFile(FileName(filename), runparams);
2437         }
2438         // LaTeX backend
2439         else if (backend_format == format) {
2440                 runparams.nice = true;
2441                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2442                         return false;
2443         } else if (!lyxrc.tex_allows_spaces
2444                    && contains(filePath(), ' ')) {
2445                 Alert::error(_("File name error"),
2446                            _("The directory path to the document cannot contain spaces."));
2447                 return false;
2448         } else {
2449                 runparams.nice = false;
2450                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2451                         return false;
2452         }
2453
2454         string const error_type = (format == "program")
2455                 ? "Build" : bufferFormat();
2456         ErrorList & error_list = d->errorLists[error_type];
2457         string const ext = formats.extension(format);
2458         FileName const tmp_result_file(changeExtension(filename, ext));
2459         bool const success = theConverters().convert(this, FileName(filename),
2460                 tmp_result_file, FileName(absFileName()), backend_format, format,
2461                 error_list);
2462         // Emit the signal to show the error list.
2463         if (format != backend_format)
2464                 errors(error_type);
2465         if (!success)
2466                 return false;
2467
2468         if (put_in_tempdir) {
2469                 result_file = tmp_result_file.absFilename();
2470                 return true;
2471         }
2472
2473         result_file = changeExtension(absFileName(), ext);
2474         // We need to copy referenced files (e. g. included graphics
2475         // if format == "dvi") to the result dir.
2476         vector<ExportedFile> const files =
2477                 runparams.exportdata->externalFiles(format);
2478         string const dest = onlyPath(result_file);
2479         CopyStatus status = SUCCESS;
2480         for (vector<ExportedFile>::const_iterator it = files.begin();
2481                 it != files.end() && status != CANCEL; ++it) {
2482                 string const fmt = formats.getFormatFromFile(it->sourceName);
2483                 status = copyFile(fmt, it->sourceName,
2484                         makeAbsPath(it->exportName, dest),
2485                         it->exportName, status == FORCE);
2486         }
2487         if (status == CANCEL) {
2488                 message(_("Document export cancelled."));
2489         } else if (tmp_result_file.exists()) {
2490                 // Finally copy the main file
2491                 status = copyFile(format, tmp_result_file,
2492                         FileName(result_file), result_file,
2493                         status == FORCE);
2494                 message(bformat(_("Document exported as %1$s "
2495                         "to file `%2$s'"),
2496                         formats.prettyName(format),
2497                         makeDisplayPath(result_file)));
2498         } else {
2499                 // This must be a dummy converter like fax (bug 1888)
2500                 message(bformat(_("Document exported as %1$s"),
2501                         formats.prettyName(format)));
2502         }
2503
2504         return true;
2505 }
2506
2507
2508 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2509 {
2510         string result_file;
2511         return doExport(format, put_in_tempdir, result_file);
2512 }
2513
2514
2515 bool Buffer::preview(string const & format) const
2516 {
2517         string result_file;
2518         if (!doExport(format, true, result_file))
2519                 return false;
2520         return formats.view(*this, FileName(result_file), format);
2521 }
2522
2523
2524 bool Buffer::isExportable(string const & format) const
2525 {
2526         vector<string> backs = backends();
2527         for (vector<string>::const_iterator it = backs.begin();
2528              it != backs.end(); ++it)
2529                 if (theConverters().isReachable(*it, format))
2530                         return true;
2531         return false;
2532 }
2533
2534
2535 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2536 {
2537         vector<string> backs = backends();
2538         vector<Format const *> result =
2539                 theConverters().getReachable(backs[0], only_viewable, true);
2540         for (vector<string>::const_iterator it = backs.begin() + 1;
2541              it != backs.end(); ++it) {
2542                 vector<Format const *>  r =
2543                         theConverters().getReachable(*it, only_viewable, false);
2544                 result.insert(result.end(), r.begin(), r.end());
2545         }
2546         return result;
2547 }
2548
2549
2550 vector<string> Buffer::backends() const
2551 {
2552         vector<string> v;
2553         if (params().baseClass()->isTeXClassAvailable()) {
2554                 v.push_back(bufferFormat());
2555                 // FIXME: Don't hardcode format names here, but use a flag
2556                 if (v.back() == "latex")
2557                         v.push_back("pdflatex");
2558         }
2559         v.push_back("text");
2560         v.push_back("lyx");
2561         return v;
2562 }
2563
2564
2565 bool Buffer::readFileHelper(FileName const & s)
2566 {
2567         // File information about normal file
2568         if (!s.exists()) {
2569                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2570                 docstring text = bformat(_("The specified document\n%1$s"
2571                                                      "\ncould not be read."), file);
2572                 Alert::error(_("Could not read document"), text);
2573                 return false;
2574         }
2575
2576         // Check if emergency save file exists and is newer.
2577         FileName const e(s.absFilename() + ".emergency");
2578
2579         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2580                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2581                 docstring const text =
2582                         bformat(_("An emergency save of the document "
2583                                   "%1$s exists.\n\n"
2584                                                "Recover emergency save?"), file);
2585                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2586                                       _("&Recover"),  _("&Load Original"),
2587                                       _("&Cancel")))
2588                 {
2589                 case 0:
2590                         // the file is not saved if we load the emergency file.
2591                         markDirty();
2592                         return readFile(e);
2593                 case 1:
2594                         break;
2595                 default:
2596                         return false;
2597                 }
2598         }
2599
2600         // Now check if autosave file is newer.
2601         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2602
2603         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2604                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2605                 docstring const text =
2606                         bformat(_("The backup of the document "
2607                                   "%1$s is newer.\n\nLoad the "
2608                                                "backup instead?"), file);
2609                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2610                                       _("&Load backup"), _("Load &original"),
2611                                       _("&Cancel") ))
2612                 {
2613                 case 0:
2614                         // the file is not saved if we load the autosave file.
2615                         markDirty();
2616                         return readFile(a);
2617                 case 1:
2618                         // Here we delete the autosave
2619                         a.removeFile();
2620                         break;
2621                 default:
2622                         return false;
2623                 }
2624         }
2625         return readFile(s);
2626 }
2627
2628
2629 bool Buffer::loadLyXFile(FileName const & s)
2630 {
2631         if (s.isReadableFile()) {
2632                 if (readFileHelper(s)) {
2633                         lyxvc().file_found_hook(s);
2634                         if (!s.isWritable())
2635                                 setReadonly(true);
2636                         return true;
2637                 }
2638         } else {
2639                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2640                 // Here we probably should run
2641                 if (LyXVC::file_not_found_hook(s)) {
2642                         docstring const text =
2643                                 bformat(_("Do you want to retrieve the document"
2644                                                        " %1$s from version control?"), file);
2645                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2646                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2647
2648                         if (ret == 0) {
2649                                 // How can we know _how_ to do the checkout?
2650                                 // With the current VC support it has to be,
2651                                 // a RCS file since CVS do not have special ,v files.
2652                                 RCS::retrieve(s);
2653                                 return loadLyXFile(s);
2654                         }
2655                 }
2656         }
2657         return false;
2658 }
2659
2660
2661 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2662 {
2663         TeXErrors::Errors::const_iterator cit = terr.begin();
2664         TeXErrors::Errors::const_iterator end = terr.end();
2665
2666         for (; cit != end; ++cit) {
2667                 int id_start = -1;
2668                 int pos_start = -1;
2669                 int errorRow = cit->error_in_line;
2670                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2671                                                        pos_start);
2672                 int id_end = -1;
2673                 int pos_end = -1;
2674                 do {
2675                         ++errorRow;
2676                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2677                 } while (found && id_start == id_end && pos_start == pos_end);
2678
2679                 errorList.push_back(ErrorItem(cit->error_desc,
2680                         cit->error_text, id_start, pos_start, pos_end));
2681         }
2682 }
2683
2684
2685 // FIXME: buf should should be const because updateLabels() modifies
2686 // the contents of the paragraphs.
2687 void Buffer::updateLabels(bool childonly) const
2688 {
2689         // Use the master text class also for child documents
2690         Buffer const * const master = masterBuffer();
2691         DocumentClass const & textclass = master->params().documentClass();
2692
2693         // keep the buffers to be children in this set. If the call from the
2694         // master comes back we can see which of them were actually seen (i.e.
2695         // via an InsetInclude). The remaining ones in the set need still be updated.
2696         static std::set<Buffer const *> bufToUpdate;
2697         if (!childonly) {
2698                 // If this is a child document start with the master
2699                 if (master != this) {
2700                         bufToUpdate.insert(this);
2701                         master->updateLabels(false);
2702
2703                         // was buf referenced from the master (i.e. not in bufToUpdate anymore)?
2704                         if (bufToUpdate.find(this) == bufToUpdate.end())
2705                                 return;
2706                 }
2707
2708                 // start over the counters in the master
2709                 textclass.counters().reset();
2710         }
2711
2712         // update will be done below for this buffer
2713         bufToUpdate.erase(this);
2714
2715         // update all caches
2716         clearReferenceCache();
2717         inset().setBuffer(const_cast<Buffer &>(*this));
2718         updateMacros();
2719
2720         Buffer & cbuf = const_cast<Buffer &>(*this);
2721
2722         LASSERT(!text().paragraphs().empty(), /**/);
2723
2724         // do the real work
2725         ParIterator parit = cbuf.par_iterator_begin();
2726         updateLabels(parit);
2727
2728         if (master != this)
2729                 // TocBackend update will be done later.
2730                 return;
2731
2732         cbuf.tocBackend().update();
2733         if (!childonly)
2734                 cbuf.structureChanged();
2735 }
2736
2737
2738 static depth_type getDepth(DocIterator const & it)
2739 {
2740         depth_type depth = 0;
2741         for (size_t i = 0 ; i < it.depth() ; ++i)
2742                 if (!it[i].inset().inMathed())
2743                         depth += it[i].paragraph().getDepth() + 1;
2744         // remove 1 since the outer inset does not count
2745         return depth - 1;
2746 }
2747
2748 static depth_type getItemDepth(ParIterator const & it)
2749 {
2750         Paragraph const & par = *it;
2751         LabelType const labeltype = par.layout().labeltype;
2752
2753         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
2754                 return 0;
2755
2756         // this will hold the lowest depth encountered up to now.
2757         depth_type min_depth = getDepth(it);
2758         ParIterator prev_it = it;
2759         while (true) {
2760                 if (prev_it.pit())
2761                         --prev_it.top().pit();
2762                 else {
2763                         // start of nested inset: go to outer par
2764                         prev_it.pop_back();
2765                         if (prev_it.empty()) {
2766                                 // start of document: nothing to do
2767                                 return 0;
2768                         }
2769                 }
2770
2771                 // We search for the first paragraph with same label
2772                 // that is not more deeply nested.
2773                 Paragraph & prev_par = *prev_it;
2774                 depth_type const prev_depth = getDepth(prev_it);
2775                 if (labeltype == prev_par.layout().labeltype) {
2776                         if (prev_depth < min_depth)
2777                                 return prev_par.itemdepth + 1;
2778                         if (prev_depth == min_depth)
2779                                 return prev_par.itemdepth;
2780                 }
2781                 min_depth = min(min_depth, prev_depth);
2782                 // small optimization: if we are at depth 0, we won't
2783                 // find anything else
2784                 if (prev_depth == 0)
2785                         return 0;
2786         }
2787 }
2788
2789
2790 static bool needEnumCounterReset(ParIterator const & it)
2791 {
2792         Paragraph const & par = *it;
2793         LASSERT(par.layout().labeltype == LABEL_ENUMERATE, /**/);
2794         depth_type const cur_depth = par.getDepth();
2795         ParIterator prev_it = it;
2796         while (prev_it.pit()) {
2797                 --prev_it.top().pit();
2798                 Paragraph const & prev_par = *prev_it;
2799                 if (prev_par.getDepth() <= cur_depth)
2800                         return  prev_par.layout().labeltype != LABEL_ENUMERATE;
2801         }
2802         // start of nested inset: reset
2803         return true;
2804 }
2805
2806
2807 // set the label of a paragraph. This includes the counters.
2808 static void setLabel(Buffer const & buf, ParIterator & it)
2809 {
2810         BufferParams const & bp = buf.masterBuffer()->params();
2811         DocumentClass const & textclass = bp.documentClass();
2812         Paragraph & par = it.paragraph();
2813         Layout const & layout = par.layout();
2814         Counters & counters = textclass.counters();
2815
2816         if (par.params().startOfAppendix()) {
2817                 // FIXME: only the counter corresponding to toplevel
2818                 // sectionning should be reset
2819                 counters.reset();
2820                 counters.appendix(true);
2821         }
2822         par.params().appendix(counters.appendix());
2823
2824         // Compute the item depth of the paragraph
2825         par.itemdepth = getItemDepth(it);
2826
2827         if (layout.margintype == MARGIN_MANUAL) {
2828                 if (par.params().labelWidthString().empty())
2829                         par.params().labelWidthString(par.translateIfPossible(layout.labelstring(), bp));
2830         } else {
2831                 par.params().labelWidthString(docstring());
2832         }
2833
2834         switch(layout.labeltype) {
2835         case LABEL_COUNTER:
2836                 if (layout.toclevel <= bp.secnumdepth
2837                     && (layout.latextype != LATEX_ENVIRONMENT
2838                         || isFirstInSequence(it.pit(), it.plist()))) {
2839                         counters.step(layout.counter);
2840                         par.params().labelString(
2841                                 par.expandLabel(layout, bp));
2842                 } else
2843                         par.params().labelString(docstring());
2844                 break;
2845
2846         case LABEL_ITEMIZE: {
2847                 // At some point of time we should do something more
2848                 // clever here, like:
2849                 //   par.params().labelString(
2850                 //    bp.user_defined_bullet(par.itemdepth).getText());
2851                 // for now, use a simple hardcoded label
2852                 docstring itemlabel;
2853                 switch (par.itemdepth) {
2854                 case 0:
2855                         itemlabel = char_type(0x2022);
2856                         break;
2857                 case 1:
2858                         itemlabel = char_type(0x2013);
2859                         break;
2860                 case 2:
2861                         itemlabel = char_type(0x2217);
2862                         break;
2863                 case 3:
2864                         itemlabel = char_type(0x2219); // or 0x00b7
2865                         break;
2866                 }
2867                 par.params().labelString(itemlabel);
2868                 break;
2869         }
2870
2871         case LABEL_ENUMERATE: {
2872                 // FIXME: Yes I know this is a really, really! bad solution
2873                 // (Lgb)
2874                 docstring enumcounter = from_ascii("enum");
2875
2876                 switch (par.itemdepth) {
2877                 case 2:
2878                         enumcounter += 'i';
2879                 case 1:
2880                         enumcounter += 'i';
2881                 case 0:
2882                         enumcounter += 'i';
2883                         break;
2884                 case 3:
2885                         enumcounter += "iv";
2886                         break;
2887                 default:
2888                         // not a valid enumdepth...
2889                         break;
2890                 }
2891
2892                 // Maybe we have to reset the enumeration counter.
2893                 if (needEnumCounterReset(it))
2894                         counters.reset(enumcounter);
2895
2896                 counters.step(enumcounter);
2897
2898                 string format;
2899
2900                 switch (par.itemdepth) {
2901                 case 0:
2902                         format = N_("\\arabic{enumi}.");
2903                         break;
2904                 case 1:
2905                         format = N_("(\\alph{enumii})");
2906                         break;
2907                 case 2:
2908                         format = N_("\\roman{enumiii}.");
2909                         break;
2910                 case 3:
2911                         format = N_("\\Alph{enumiv}.");
2912                         break;
2913                 default:
2914                         // not a valid enumdepth...
2915                         break;
2916                 }
2917
2918                 par.params().labelString(counters.counterLabel(
2919                         par.translateIfPossible(from_ascii(format), bp)));
2920
2921                 break;
2922         }
2923
2924         case LABEL_SENSITIVE: {
2925                 string const & type = counters.current_float();
2926                 docstring full_label;
2927                 if (type.empty())
2928                         full_label = buf.B_("Senseless!!! ");
2929                 else {
2930                         docstring name = buf.B_(textclass.floats().getType(type).name());
2931                         if (counters.hasCounter(from_utf8(type))) {
2932                                 counters.step(from_utf8(type));
2933                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
2934                                                      name, 
2935                                                      counters.theCounter(from_utf8(type)));
2936                         } else
2937                                 full_label = bformat(from_ascii("%1$s #:"), name);      
2938                 }
2939                 par.params().labelString(full_label);   
2940                 break;
2941         }
2942
2943         case LABEL_NO_LABEL:
2944                 par.params().labelString(docstring());
2945                 break;
2946
2947         case LABEL_MANUAL:
2948         case LABEL_TOP_ENVIRONMENT:
2949         case LABEL_CENTERED_TOP_ENVIRONMENT:
2950         case LABEL_STATIC:      
2951         case LABEL_BIBLIO:
2952                 par.params().labelString(
2953                         par.translateIfPossible(layout.labelstring(), bp));
2954                 break;
2955         }
2956 }
2957
2958
2959 void Buffer::updateLabels(ParIterator & parit) const
2960 {
2961         LASSERT(parit.pit() == 0, /**/);
2962
2963         // set the position of the text in the buffer to be able
2964         // to resolve macros in it. This has nothing to do with
2965         // labels, but by putting it here we avoid implementing
2966         // a whole bunch of traversal routines just for this call.
2967         parit.text()->setMacrocontextPosition(parit);
2968
2969         depth_type maxdepth = 0;
2970         pit_type const lastpit = parit.lastpit();
2971         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
2972                 // reduce depth if necessary
2973                 parit->params().depth(min(parit->params().depth(), maxdepth));
2974                 maxdepth = parit->getMaxDepthAfter();
2975
2976                 // set the counter for this paragraph
2977                 setLabel(*this, parit);
2978
2979                 // Now the insets
2980                 InsetList::const_iterator iit = parit->insetList().begin();
2981                 InsetList::const_iterator end = parit->insetList().end();
2982                 for (; iit != end; ++iit) {
2983                         parit.pos() = iit->pos;
2984                         iit->inset->updateLabels(parit);
2985                 }
2986         }
2987 }
2988
2989 } // namespace lyx