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