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