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