]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
* GuiView.cpp:
[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                         if (lastw != d->bibfileStatus_[*ei]) {
1398                                 d->bibinfoCacheValid_ = false;
1399                                 d->bibfileStatus_[*ei] = lastw;
1400                                 break;
1401                         }
1402                 }
1403         }
1404
1405         if (!d->bibinfoCacheValid_) {
1406                 d->bibinfo_.clear();
1407                 for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1408                         it->fillWithBibKeys(d->bibinfo_, it);
1409                 d->bibinfoCacheValid_ = true;
1410         }
1411         return d->bibinfo_;
1412 }
1413
1414
1415 bool Buffer::isDepClean(string const & name) const
1416 {
1417         DepClean::const_iterator const it = d->dep_clean.find(name);
1418         if (it == d->dep_clean.end())
1419                 return true;
1420         return it->second;
1421 }
1422
1423
1424 void Buffer::markDepClean(string const & name)
1425 {
1426         d->dep_clean[name] = true;
1427 }
1428
1429
1430 bool Buffer::dispatch(string const & command, bool * result)
1431 {
1432         return dispatch(lyxaction.lookupFunc(command), result);
1433 }
1434
1435
1436 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1437 {
1438         bool dispatched = true;
1439
1440         switch (func.action) {
1441                 case LFUN_BUFFER_EXPORT: {
1442                         bool const tmp = doExport(to_utf8(func.argument()), false);
1443                         if (result)
1444                                 *result = tmp;
1445                         break;
1446                 }
1447
1448                 case LFUN_BRANCH_ACTIVATE:
1449                 case LFUN_BRANCH_DEACTIVATE: {
1450                         BranchList & branchList = params().branchlist();
1451                         docstring const branchName = func.argument();
1452                         Branch * branch = branchList.find(branchName);
1453                         if (!branch)
1454                                 LYXERR0("Branch " << branchName << " does not exist.");
1455                         else 
1456                                 branch->setSelected(func.action == LFUN_BRANCH_ACTIVATE);
1457                         if (result)
1458                                 *result = true;
1459                 }
1460
1461                 default:
1462                         dispatched = false;
1463         }
1464         return dispatched;
1465 }
1466
1467
1468 void Buffer::changeLanguage(Language const * from, Language const * to)
1469 {
1470         LASSERT(from, /**/);
1471         LASSERT(to, /**/);
1472
1473         for_each(par_iterator_begin(),
1474                  par_iterator_end(),
1475                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1476 }
1477
1478
1479 bool Buffer::isMultiLingual() const
1480 {
1481         ParConstIterator end = par_iterator_end();
1482         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1483                 if (it->isMultiLingual(params()))
1484                         return true;
1485
1486         return false;
1487 }
1488
1489
1490 DocIterator Buffer::getParFromID(int const id) const
1491 {
1492         if (id < 0) {
1493                 // John says this is called with id == -1 from undo
1494                 lyxerr << "getParFromID(), id: " << id << endl;
1495                 return doc_iterator_end(inset());
1496         }
1497
1498         for (DocIterator it = doc_iterator_begin(inset()); !it.atEnd(); it.forwardPar())
1499                 if (it.paragraph().id() == id)
1500                         return it;
1501
1502         return doc_iterator_end(inset());
1503 }
1504
1505
1506 bool Buffer::hasParWithID(int const id) const
1507 {
1508         return !getParFromID(id).atEnd();
1509 }
1510
1511
1512 ParIterator Buffer::par_iterator_begin()
1513 {
1514         return ParIterator(doc_iterator_begin(inset()));
1515 }
1516
1517
1518 ParIterator Buffer::par_iterator_end()
1519 {
1520         return ParIterator(doc_iterator_end(inset()));
1521 }
1522
1523
1524 ParConstIterator Buffer::par_iterator_begin() const
1525 {
1526         return lyx::par_const_iterator_begin(inset());
1527 }
1528
1529
1530 ParConstIterator Buffer::par_iterator_end() const
1531 {
1532         return lyx::par_const_iterator_end(inset());
1533 }
1534
1535
1536 Language const * Buffer::language() const
1537 {
1538         return params().language;
1539 }
1540
1541
1542 docstring const Buffer::B_(string const & l10n) const
1543 {
1544         return params().B_(l10n);
1545 }
1546
1547
1548 bool Buffer::isClean() const
1549 {
1550         return d->lyx_clean;
1551 }
1552
1553
1554 bool Buffer::isBakClean() const
1555 {
1556         return d->bak_clean;
1557 }
1558
1559
1560 bool Buffer::isExternallyModified(CheckMethod method) const
1561 {
1562         LASSERT(d->filename.exists(), /**/);
1563         // if method == timestamp, check timestamp before checksum
1564         return (method == checksum_method 
1565                 || d->timestamp_ != d->filename.lastModified())
1566                 && d->checksum_ != d->filename.checksum();
1567 }
1568
1569
1570 void Buffer::saveCheckSum(FileName const & file) const
1571 {
1572         if (file.exists()) {
1573                 d->timestamp_ = file.lastModified();
1574                 d->checksum_ = file.checksum();
1575         } else {
1576                 // in the case of save to a new file.
1577                 d->timestamp_ = 0;
1578                 d->checksum_ = 0;
1579         }
1580 }
1581
1582
1583 void Buffer::markClean() const
1584 {
1585         if (!d->lyx_clean) {
1586                 d->lyx_clean = true;
1587                 updateTitles();
1588         }
1589         // if the .lyx file has been saved, we don't need an
1590         // autosave
1591         d->bak_clean = true;
1592 }
1593
1594
1595 void Buffer::markBakClean() const
1596 {
1597         d->bak_clean = true;
1598 }
1599
1600
1601 void Buffer::setUnnamed(bool flag)
1602 {
1603         d->unnamed = flag;
1604 }
1605
1606
1607 bool Buffer::isUnnamed() const
1608 {
1609         return d->unnamed;
1610 }
1611
1612
1613 // FIXME: this function should be moved to buffer_pimpl.C
1614 void Buffer::markDirty()
1615 {
1616         if (d->lyx_clean) {
1617                 d->lyx_clean = false;
1618                 updateTitles();
1619         }
1620         d->bak_clean = false;
1621
1622         DepClean::iterator it = d->dep_clean.begin();
1623         DepClean::const_iterator const end = d->dep_clean.end();
1624
1625         for (; it != end; ++it)
1626                 it->second = false;
1627 }
1628
1629
1630 FileName Buffer::fileName() const
1631 {
1632         return d->filename;
1633 }
1634
1635
1636 string Buffer::absFileName() const
1637 {
1638         return d->filename.absFilename();
1639 }
1640
1641
1642 string Buffer::filePath() const
1643 {
1644         return d->filename.onlyPath().absFilename() + "/";
1645 }
1646
1647
1648 bool Buffer::isReadonly() const
1649 {
1650         return d->read_only;
1651 }
1652
1653
1654 void Buffer::setParent(Buffer const * buffer)
1655 {
1656         // Avoids recursive include.
1657         d->parent_buffer = buffer == this ? 0 : buffer;
1658         updateMacros();
1659 }
1660
1661
1662 Buffer const * Buffer::parent()
1663 {
1664         return d->parent_buffer;
1665 }
1666
1667
1668 Buffer const * Buffer::masterBuffer() const
1669 {
1670         if (!d->parent_buffer)
1671                 return this;
1672         
1673         return d->parent_buffer->masterBuffer();
1674 }
1675
1676
1677 template<typename M>
1678 typename M::iterator greatest_below(M & m, typename M::key_type const & x)
1679 {
1680         if (m.empty())
1681                 return m.end();
1682
1683         typename M::iterator it = m.lower_bound(x);
1684         if (it == m.begin())
1685                 return m.end();
1686
1687         it--;
1688         return it;      
1689 }
1690
1691
1692 MacroData const * Buffer::getBufferMacro(docstring const & name, 
1693                                          DocIterator const & pos) const
1694 {
1695         LYXERR(Debug::MACROS, "Searching for " << to_ascii(name) << " at " << pos);
1696
1697         // if paragraphs have no macro context set, pos will be empty
1698         if (pos.empty())
1699                 return 0;
1700
1701         // we haven't found anything yet
1702         DocIterator bestPos = par_iterator_begin();
1703         MacroData const * bestData = 0;
1704         
1705         // find macro definitions for name
1706         Impl::NamePositionScopeMacroMap::iterator nameIt
1707         = d->macros.find(name);
1708         if (nameIt != d->macros.end()) {
1709                 // find last definition in front of pos or at pos itself
1710                 Impl::PositionScopeMacroMap::const_iterator it
1711                 = greatest_below(nameIt->second, pos);
1712                 if (it != nameIt->second.end()) {
1713                         while (true) {
1714                                 // scope ends behind pos?
1715                                 if (pos < it->second.first) {
1716                                         // Looks good, remember this. If there
1717                                         // is no external macro behind this,
1718                                         // we found the right one already.
1719                                         bestPos = it->first;
1720                                         bestData = &it->second.second;
1721                                         break;
1722                                 }
1723                                 
1724                                 // try previous macro if there is one
1725                                 if (it == nameIt->second.begin())
1726                                         break;
1727                                 it--;
1728                         }
1729                 }
1730         }
1731
1732         // find macros in included files
1733         Impl::PositionScopeBufferMap::const_iterator it
1734         = greatest_below(d->position_to_children, pos);
1735         if (it == d->position_to_children.end())
1736                 // no children before
1737                 return bestData;
1738
1739         while (true) {
1740                 // do we know something better (i.e. later) already?
1741                 if (it->first < bestPos )
1742                         break;
1743
1744                 // scope ends behind pos?
1745                 if (pos < it->second.first) {
1746                         // look for macro in external file
1747                         d->macro_lock = true;
1748                         MacroData const * data
1749                         = it->second.second->getMacro(name, false);
1750                         d->macro_lock = false;
1751                         if (data) {
1752                                 bestPos = it->first;
1753                                 bestData = data;
1754                                 break;
1755                         }
1756                 }
1757
1758                 // try previous file if there is one
1759                 if (it == d->position_to_children.begin())
1760                         break;
1761                 --it;
1762         }
1763                 
1764         // return the best macro we have found
1765         return bestData;
1766 }
1767
1768
1769 MacroData const * Buffer::getMacro(docstring const & name,
1770         DocIterator const & pos, bool global) const
1771 {
1772         if (d->macro_lock)
1773                 return 0;       
1774
1775         // query buffer macros
1776         MacroData const * data = getBufferMacro(name, pos);
1777         if (data != 0)
1778                 return data;
1779
1780         // If there is a master buffer, query that
1781         if (d->parent_buffer) {
1782                 d->macro_lock = true;
1783                 MacroData const * macro = d->parent_buffer->getMacro(
1784                         name, *this, false);
1785                 d->macro_lock = false;
1786                 if (macro)
1787                         return macro;
1788         }
1789
1790         if (global) {
1791                 data = MacroTable::globalMacros().get(name);
1792                 if (data != 0)
1793                         return data;
1794         }
1795
1796         return 0;
1797 }
1798
1799
1800 MacroData const * Buffer::getMacro(docstring const & name, bool global) const
1801 {
1802         // set scope end behind the last paragraph
1803         DocIterator scope = par_iterator_begin();
1804         scope.pit() = scope.lastpit() + 1;
1805
1806         return getMacro(name, scope, global);
1807 }
1808
1809
1810 MacroData const * Buffer::getMacro(docstring const & name,
1811         Buffer const & child, bool global) const
1812 {
1813         // look where the child buffer is included first
1814         Impl::BufferPositionMap::iterator it = d->children_positions.find(&child);
1815         if (it == d->children_positions.end())
1816                 return 0;
1817
1818         // check for macros at the inclusion position
1819         return getMacro(name, it->second, global);
1820 }
1821
1822
1823 void Buffer::updateMacros(DocIterator & it, DocIterator & scope) const
1824 {
1825         pit_type lastpit = it.lastpit();
1826
1827         // look for macros in each paragraph
1828         while (it.pit() <= lastpit) {
1829                 Paragraph & par = it.paragraph();
1830
1831                 // iterate over the insets of the current paragraph
1832                 InsetList const & insets = par.insetList();
1833                 InsetList::const_iterator iit = insets.begin();
1834                 InsetList::const_iterator end = insets.end();
1835                 for (; iit != end; ++iit) {
1836                         it.pos() = iit->pos;
1837                         
1838                         // is it a nested text inset?
1839                         if (iit->inset->asInsetText()) {
1840                                 // Inset needs its own scope?
1841                                 InsetText const * itext 
1842                                 = iit->inset->asInsetText();
1843                                 bool newScope = itext->isMacroScope();
1844
1845                                 // scope which ends just behind the inset       
1846                                 DocIterator insetScope = it;
1847                                 ++insetScope.pos();
1848
1849                                 // collect macros in inset
1850                                 it.push_back(CursorSlice(*iit->inset));
1851                                 updateMacros(it, newScope ? insetScope : scope);
1852                                 it.pop_back();
1853                                 continue;
1854                         }
1855                                               
1856                         // is it an external file?
1857                         if (iit->inset->lyxCode() == INCLUDE_CODE) {
1858                                 // get buffer of external file
1859                                 InsetCommand const & inset 
1860                                         = static_cast<InsetCommand const &>(*iit->inset);
1861                                 InsetCommandParams const & ip = inset.params();
1862                                 d->macro_lock = true;
1863                                 Buffer * child = loadIfNeeded(*this, ip);
1864                                 d->macro_lock = false;
1865                                 if (!child)
1866                                         continue;                               
1867
1868                                 // register its position, but only when it is
1869                                 // included first in the buffer
1870                                 if (d->children_positions.find(child)
1871                                         == d->children_positions.end())
1872                                         d->children_positions[child] = it;
1873                                                                                                 
1874                                 // register child with its scope
1875                                 d->position_to_children[it] = Impl::ScopeBuffer(scope, child);
1876                                 continue;
1877                         }
1878
1879                         if (iit->inset->lyxCode() != MATHMACRO_CODE)
1880                                 continue;
1881                         
1882                         // get macro data
1883                         MathMacroTemplate & macroTemplate
1884                         = static_cast<MathMacroTemplate &>(*iit->inset);
1885                         MacroContext mc(*this, it);
1886                         macroTemplate.updateToContext(mc);
1887
1888                         // valid?
1889                         bool valid = macroTemplate.validMacro();
1890                         // FIXME: Should be fixNameAndCheckIfValid() in fact,
1891                         // then the BufferView's cursor will be invalid in
1892                         // some cases which leads to crashes.
1893                         if (!valid)
1894                                 continue;
1895
1896                         // register macro
1897                         d->macros[macroTemplate.name()][it] =
1898                                 Impl::ScopeMacro(scope, MacroData(*this, it));
1899                 }
1900
1901                 // next paragraph
1902                 it.pit()++;
1903                 it.pos() = 0;
1904         }
1905 }
1906
1907
1908 void Buffer::updateMacros() const
1909 {
1910         if (d->macro_lock)
1911                 return;
1912
1913         LYXERR(Debug::MACROS, "updateMacro of " << d->filename.onlyFileName());
1914
1915         // start with empty table
1916         d->macros.clear();
1917         d->children_positions.clear();
1918         d->position_to_children.clear();
1919
1920         // Iterate over buffer, starting with first paragraph
1921         // The scope must be bigger than any lookup DocIterator
1922         // later. For the global lookup, lastpit+1 is used, hence
1923         // we use lastpit+2 here.
1924         DocIterator it = par_iterator_begin();
1925         DocIterator outerScope = it;
1926         outerScope.pit() = outerScope.lastpit() + 2;
1927         updateMacros(it, outerScope);
1928 }
1929
1930
1931 void Buffer::updateMacroInstances() const
1932 {
1933         LYXERR(Debug::MACROS, "updateMacroInstances for "
1934                 << d->filename.onlyFileName());
1935         DocIterator it = doc_iterator_begin(inset());
1936         DocIterator end = doc_iterator_end(inset());
1937         for (; it != end; it.forwardPos()) {
1938                 // look for MathData cells in InsetMathNest insets
1939                 Inset * inset = it.nextInset();
1940                 if (!inset)
1941                         continue;
1942
1943                 InsetMath * minset = inset->asInsetMath();
1944                 if (!minset)
1945                         continue;
1946
1947                 // update macro in all cells of the InsetMathNest
1948                 DocIterator::idx_type n = minset->nargs();
1949                 MacroContext mc = MacroContext(*this, it);
1950                 for (DocIterator::idx_type i = 0; i < n; ++i) {
1951                         MathData & data = minset->cell(i);
1952                         data.updateMacros(0, mc);
1953                 }
1954         }
1955 }
1956
1957
1958 void Buffer::listMacroNames(MacroNameSet & macros) const
1959 {
1960         if (d->macro_lock)
1961                 return;
1962
1963         d->macro_lock = true;
1964         
1965         // loop over macro names
1966         Impl::NamePositionScopeMacroMap::iterator nameIt = d->macros.begin();
1967         Impl::NamePositionScopeMacroMap::iterator nameEnd = d->macros.end();
1968         for (; nameIt != nameEnd; ++nameIt)
1969                 macros.insert(nameIt->first);
1970
1971         // loop over children
1972         Impl::BufferPositionMap::iterator it = d->children_positions.begin();
1973         Impl::BufferPositionMap::iterator end = d->children_positions.end();
1974         for (; it != end; ++it)
1975                 it->first->listMacroNames(macros);
1976
1977         // call parent
1978         if (d->parent_buffer)
1979                 d->parent_buffer->listMacroNames(macros);
1980
1981         d->macro_lock = false;  
1982 }
1983
1984
1985 void Buffer::listParentMacros(MacroSet & macros, LaTeXFeatures & features) const
1986 {
1987         if (!d->parent_buffer)
1988                 return;
1989         
1990         MacroNameSet names;
1991         d->parent_buffer->listMacroNames(names);
1992         
1993         // resolve macros
1994         MacroNameSet::iterator it = names.begin();
1995         MacroNameSet::iterator end = names.end();
1996         for (; it != end; ++it) {
1997                 // defined?
1998                 MacroData const * data = 
1999                 d->parent_buffer->getMacro(*it, *this, false);
2000                 if (data) {
2001                         macros.insert(data);
2002                         
2003                         // we cannot access the original MathMacroTemplate anymore
2004                         // here to calls validate method. So we do its work here manually.
2005                         // FIXME: somehow make the template accessible here.
2006                         if (data->optionals() > 0)
2007                                 features.require("xargs");
2008                 }
2009         }
2010 }
2011
2012
2013 Buffer::References & Buffer::references(docstring const & label)
2014 {
2015         if (d->parent_buffer)
2016                 return const_cast<Buffer *>(masterBuffer())->references(label);
2017
2018         RefCache::iterator it = d->ref_cache_.find(label);
2019         if (it != d->ref_cache_.end())
2020                 return it->second.second;
2021
2022         static InsetLabel const * dummy_il = 0;
2023         static References const dummy_refs;
2024         it = d->ref_cache_.insert(
2025                 make_pair(label, make_pair(dummy_il, dummy_refs))).first;
2026         return it->second.second;
2027 }
2028
2029
2030 Buffer::References const & Buffer::references(docstring const & label) const
2031 {
2032         return const_cast<Buffer *>(this)->references(label);
2033 }
2034
2035
2036 void Buffer::setInsetLabel(docstring const & label, InsetLabel const * il)
2037 {
2038         masterBuffer()->d->ref_cache_[label].first = il;
2039 }
2040
2041
2042 InsetLabel const * Buffer::insetLabel(docstring const & label) const
2043 {
2044         return masterBuffer()->d->ref_cache_[label].first;
2045 }
2046
2047
2048 void Buffer::clearReferenceCache() const
2049 {
2050         if (!d->parent_buffer)
2051                 d->ref_cache_.clear();
2052 }
2053
2054
2055 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
2056         InsetCode code)
2057 {
2058         //FIXME: This does not work for child documents yet.
2059         LASSERT(code == CITE_CODE, /**/);
2060         // Check if the label 'from' appears more than once
2061         vector<docstring> labels;
2062         string paramName;
2063         BiblioInfo const & keys = masterBibInfo();
2064         BiblioInfo::const_iterator bit  = keys.begin();
2065         BiblioInfo::const_iterator bend = keys.end();
2066
2067         for (; bit != bend; ++bit)
2068                 // FIXME UNICODE
2069                 labels.push_back(bit->first);
2070         paramName = "key";
2071
2072         if (count(labels.begin(), labels.end(), from) > 1)
2073                 return;
2074
2075         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
2076                 if (it->lyxCode() == code) {
2077                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
2078                         docstring const oldValue = inset.getParam(paramName);
2079                         if (oldValue == from)
2080                                 inset.setParam(paramName, to);
2081                 }
2082         }
2083 }
2084
2085
2086 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
2087         pit_type par_end, bool full_source)
2088 {
2089         OutputParams runparams(&params().encoding());
2090         runparams.nice = true;
2091         runparams.flavor = OutputParams::LATEX;
2092         runparams.linelen = lyxrc.plaintext_linelen;
2093         // No side effect of file copying and image conversion
2094         runparams.dryrun = true;
2095
2096         d->texrow.reset();
2097         if (full_source) {
2098                 os << "% " << _("Preview source code") << "\n\n";
2099                 d->texrow.newline();
2100                 d->texrow.newline();
2101                 if (isLatex())
2102                         writeLaTeXSource(os, filePath(), runparams, true, true);
2103                 else
2104                         writeDocBookSource(os, absFileName(), runparams, false);
2105         } else {
2106                 runparams.par_begin = par_begin;
2107                 runparams.par_end = par_end;
2108                 if (par_begin + 1 == par_end) {
2109                         os << "% "
2110                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
2111                            << "\n\n";
2112                 } else {
2113                         os << "% "
2114                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
2115                                         convert<docstring>(par_begin),
2116                                         convert<docstring>(par_end - 1))
2117                            << "\n\n";
2118                 }
2119                 d->texrow.newline();
2120                 d->texrow.newline();
2121                 // output paragraphs
2122                 if (isLatex())
2123                         latexParagraphs(*this, text(), os, d->texrow, runparams);
2124                 else
2125                         // DocBook
2126                         docbookParagraphs(paragraphs(), *this, os, runparams);
2127         }
2128 }
2129
2130
2131 ErrorList & Buffer::errorList(string const & type) const
2132 {
2133         static ErrorList emptyErrorList;
2134         map<string, ErrorList>::iterator I = d->errorLists.find(type);
2135         if (I == d->errorLists.end())
2136                 return emptyErrorList;
2137
2138         return I->second;
2139 }
2140
2141
2142 void Buffer::structureChanged() const
2143 {
2144         if (gui_)
2145                 gui_->structureChanged();
2146 }
2147
2148
2149 void Buffer::errors(string const & err) const
2150 {
2151         if (gui_)
2152                 gui_->errors(err);
2153 }
2154
2155
2156 void Buffer::message(docstring const & msg) const
2157 {
2158         if (gui_)
2159                 gui_->message(msg);
2160 }
2161
2162
2163 void Buffer::setBusy(bool on) const
2164 {
2165         if (gui_)
2166                 gui_->setBusy(on);
2167 }
2168
2169
2170 void Buffer::setReadOnly(bool on) const
2171 {
2172         if (d->wa_)
2173                 d->wa_->setReadOnly(on);
2174 }
2175
2176
2177 void Buffer::updateTitles() const
2178 {
2179         if (d->wa_)
2180                 d->wa_->updateTitles();
2181 }
2182
2183
2184 void Buffer::resetAutosaveTimers() const
2185 {
2186         if (gui_)
2187                 gui_->resetAutosaveTimers();
2188 }
2189
2190
2191 void Buffer::setGuiDelegate(frontend::GuiBufferDelegate * gui)
2192 {
2193         gui_ = gui;
2194 }
2195
2196
2197
2198 namespace {
2199
2200 class AutoSaveBuffer : public ForkedProcess {
2201 public:
2202         ///
2203         AutoSaveBuffer(Buffer const & buffer, FileName const & fname)
2204                 : buffer_(buffer), fname_(fname) {}
2205         ///
2206         virtual boost::shared_ptr<ForkedProcess> clone() const
2207         {
2208                 return boost::shared_ptr<ForkedProcess>(new AutoSaveBuffer(*this));
2209         }
2210         ///
2211         int start()
2212         {
2213                 command_ = to_utf8(bformat(_("Auto-saving %1$s"), 
2214                                                  from_utf8(fname_.absFilename())));
2215                 return run(DontWait);
2216         }
2217 private:
2218         ///
2219         virtual int generateChild();
2220         ///
2221         Buffer const & buffer_;
2222         FileName fname_;
2223 };
2224
2225
2226 int AutoSaveBuffer::generateChild()
2227 {
2228         // tmp_ret will be located (usually) in /tmp
2229         // will that be a problem?
2230         // Note that this calls ForkedCalls::fork(), so it's
2231         // ok cross-platform.
2232         pid_t const pid = fork();
2233         // If you want to debug the autosave
2234         // you should set pid to -1, and comment out the fork.
2235         if (pid != 0 && pid != -1)
2236                 return pid;
2237
2238         // pid = -1 signifies that lyx was unable
2239         // to fork. But we will do the save
2240         // anyway.
2241         bool failed = false;
2242         FileName const tmp_ret = FileName::tempName("lyxauto");
2243         if (!tmp_ret.empty()) {
2244                 buffer_.writeFile(tmp_ret);
2245                 // assume successful write of tmp_ret
2246                 if (!tmp_ret.moveTo(fname_))
2247                         failed = true;
2248         } else
2249                 failed = true;
2250
2251         if (failed) {
2252                 // failed to write/rename tmp_ret so try writing direct
2253                 if (!buffer_.writeFile(fname_)) {
2254                         // It is dangerous to do this in the child,
2255                         // but safe in the parent, so...
2256                         if (pid == -1) // emit message signal.
2257                                 buffer_.message(_("Autosave failed!"));
2258                 }
2259         }
2260
2261         if (pid == 0) // we are the child so...
2262                 _exit(0);
2263
2264         return pid;
2265 }
2266
2267 } // namespace anon
2268
2269
2270 // Perfect target for a thread...
2271 void Buffer::autoSave() const
2272 {
2273         if (isBakClean() || isReadonly()) {
2274                 // We don't save now, but we'll try again later
2275                 resetAutosaveTimers();
2276                 return;
2277         }
2278
2279         // emit message signal.
2280         message(_("Autosaving current document..."));
2281
2282         // create autosave filename
2283         string fname = filePath();
2284         fname += '#';
2285         fname += d->filename.onlyFileName();
2286         fname += '#';
2287
2288         AutoSaveBuffer autosave(*this, FileName(fname));
2289         autosave.start();
2290
2291         markBakClean();
2292         resetAutosaveTimers();
2293 }
2294
2295
2296 string Buffer::bufferFormat() const
2297 {
2298         if (isDocBook())
2299                 return "docbook";
2300         if (isLiterate())
2301                 return "literate";
2302         return "latex";
2303 }
2304
2305
2306 bool Buffer::doExport(string const & format, bool put_in_tempdir,
2307         string & result_file) const
2308 {
2309         string backend_format;
2310         OutputParams runparams(&params().encoding());
2311         runparams.flavor = OutputParams::LATEX;
2312         runparams.linelen = lyxrc.plaintext_linelen;
2313         vector<string> backs = backends();
2314         if (find(backs.begin(), backs.end(), format) == backs.end()) {
2315                 // Get shortest path to format
2316                 Graph::EdgePath path;
2317                 for (vector<string>::const_iterator it = backs.begin();
2318                      it != backs.end(); ++it) {
2319                         Graph::EdgePath p = theConverters().getPath(*it, format);
2320                         if (!p.empty() && (path.empty() || p.size() < path.size())) {
2321                                 backend_format = *it;
2322                                 path = p;
2323                         }
2324                 }
2325                 if (!path.empty())
2326                         runparams.flavor = theConverters().getFlavor(path);
2327                 else {
2328                         Alert::error(_("Couldn't export file"),
2329                                 bformat(_("No information for exporting the format %1$s."),
2330                                    formats.prettyName(format)));
2331                         return false;
2332                 }
2333         } else {
2334                 backend_format = format;
2335                 // FIXME: Don't hardcode format names here, but use a flag
2336                 if (backend_format == "pdflatex")
2337                         runparams.flavor = OutputParams::PDFLATEX;
2338         }
2339
2340         string filename = latexName(false);
2341         filename = addName(temppath(), filename);
2342         filename = changeExtension(filename,
2343                                    formats.extension(backend_format));
2344
2345         // fix macros
2346         updateMacroInstances();
2347
2348         // Plain text backend
2349         if (backend_format == "text")
2350                 writePlaintextFile(*this, FileName(filename), runparams);
2351         // no backend
2352         else if (backend_format == "lyx")
2353                 writeFile(FileName(filename));
2354         // Docbook backend
2355         else if (isDocBook()) {
2356                 runparams.nice = !put_in_tempdir;
2357                 makeDocBookFile(FileName(filename), runparams);
2358         }
2359         // LaTeX backend
2360         else if (backend_format == format) {
2361                 runparams.nice = true;
2362                 if (!makeLaTeXFile(FileName(filename), string(), runparams))
2363                         return false;
2364         } else if (!lyxrc.tex_allows_spaces
2365                    && contains(filePath(), ' ')) {
2366                 Alert::error(_("File name error"),
2367                            _("The directory path to the document cannot contain spaces."));
2368                 return false;
2369         } else {
2370                 runparams.nice = false;
2371                 if (!makeLaTeXFile(FileName(filename), filePath(), runparams))
2372                         return false;
2373         }
2374
2375         string const error_type = (format == "program")
2376                 ? "Build" : bufferFormat();
2377         ErrorList & error_list = d->errorLists[error_type];
2378         string const ext = formats.extension(format);
2379         FileName const tmp_result_file(changeExtension(filename, ext));
2380         bool const success = theConverters().convert(this, FileName(filename),
2381                 tmp_result_file, FileName(absFileName()), backend_format, format,
2382                 error_list);
2383         // Emit the signal to show the error list.
2384         if (format != backend_format)
2385                 errors(error_type);
2386         if (!success)
2387                 return false;
2388
2389         if (put_in_tempdir) {
2390                 result_file = tmp_result_file.absFilename();
2391                 return true;
2392         }
2393
2394         result_file = changeExtension(absFileName(), ext);
2395         // We need to copy referenced files (e. g. included graphics
2396         // if format == "dvi") to the result dir.
2397         vector<ExportedFile> const files =
2398                 runparams.exportdata->externalFiles(format);
2399         string const dest = onlyPath(result_file);
2400         CopyStatus status = SUCCESS;
2401         for (vector<ExportedFile>::const_iterator it = files.begin();
2402                 it != files.end() && status != CANCEL; ++it) {
2403                 string const fmt = formats.getFormatFromFile(it->sourceName);
2404                 status = copyFile(fmt, it->sourceName,
2405                         makeAbsPath(it->exportName, dest),
2406                         it->exportName, status == FORCE);
2407         }
2408         if (status == CANCEL) {
2409                 message(_("Document export cancelled."));
2410         } else if (tmp_result_file.exists()) {
2411                 // Finally copy the main file
2412                 status = copyFile(format, tmp_result_file,
2413                         FileName(result_file), result_file,
2414                         status == FORCE);
2415                 message(bformat(_("Document exported as %1$s "
2416                         "to file `%2$s'"),
2417                         formats.prettyName(format),
2418                         makeDisplayPath(result_file)));
2419         } else {
2420                 // This must be a dummy converter like fax (bug 1888)
2421                 message(bformat(_("Document exported as %1$s"),
2422                         formats.prettyName(format)));
2423         }
2424
2425         return true;
2426 }
2427
2428
2429 bool Buffer::doExport(string const & format, bool put_in_tempdir) const
2430 {
2431         string result_file;
2432         return doExport(format, put_in_tempdir, result_file);
2433 }
2434
2435
2436 bool Buffer::preview(string const & format) const
2437 {
2438         string result_file;
2439         if (!doExport(format, true, result_file))
2440                 return false;
2441         return formats.view(*this, FileName(result_file), format);
2442 }
2443
2444
2445 bool Buffer::isExportable(string const & format) const
2446 {
2447         vector<string> backs = backends();
2448         for (vector<string>::const_iterator it = backs.begin();
2449              it != backs.end(); ++it)
2450                 if (theConverters().isReachable(*it, format))
2451                         return true;
2452         return false;
2453 }
2454
2455
2456 vector<Format const *> Buffer::exportableFormats(bool only_viewable) const
2457 {
2458         vector<string> backs = backends();
2459         vector<Format const *> result =
2460                 theConverters().getReachable(backs[0], only_viewable, true);
2461         for (vector<string>::const_iterator it = backs.begin() + 1;
2462              it != backs.end(); ++it) {
2463                 vector<Format const *>  r =
2464                         theConverters().getReachable(*it, only_viewable, false);
2465                 result.insert(result.end(), r.begin(), r.end());
2466         }
2467         return result;
2468 }
2469
2470
2471 vector<string> Buffer::backends() const
2472 {
2473         vector<string> v;
2474         if (params().baseClass()->isTeXClassAvailable()) {
2475                 v.push_back(bufferFormat());
2476                 // FIXME: Don't hardcode format names here, but use a flag
2477                 if (v.back() == "latex")
2478                         v.push_back("pdflatex");
2479         }
2480         v.push_back("text");
2481         v.push_back("lyx");
2482         return v;
2483 }
2484
2485
2486 bool Buffer::readFileHelper(FileName const & s)
2487 {
2488         // File information about normal file
2489         if (!s.exists()) {
2490                 docstring const file = makeDisplayPath(s.absFilename(), 50);
2491                 docstring text = bformat(_("The specified document\n%1$s"
2492                                                      "\ncould not be read."), file);
2493                 Alert::error(_("Could not read document"), text);
2494                 return false;
2495         }
2496
2497         // Check if emergency save file exists and is newer.
2498         FileName const e(s.absFilename() + ".emergency");
2499
2500         if (e.exists() && s.exists() && e.lastModified() > s.lastModified()) {
2501                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2502                 docstring const text =
2503                         bformat(_("An emergency save of the document "
2504                                   "%1$s exists.\n\n"
2505                                                "Recover emergency save?"), file);
2506                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
2507                                       _("&Recover"),  _("&Load Original"),
2508                                       _("&Cancel")))
2509                 {
2510                 case 0:
2511                         // the file is not saved if we load the emergency file.
2512                         markDirty();
2513                         return readFile(e);
2514                 case 1:
2515                         break;
2516                 default:
2517                         return false;
2518                 }
2519         }
2520
2521         // Now check if autosave file is newer.
2522         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
2523
2524         if (a.exists() && s.exists() && a.lastModified() > s.lastModified()) {
2525                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2526                 docstring const text =
2527                         bformat(_("The backup of the document "
2528                                   "%1$s is newer.\n\nLoad the "
2529                                                "backup instead?"), file);
2530                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
2531                                       _("&Load backup"), _("Load &original"),
2532                                       _("&Cancel") ))
2533                 {
2534                 case 0:
2535                         // the file is not saved if we load the autosave file.
2536                         markDirty();
2537                         return readFile(a);
2538                 case 1:
2539                         // Here we delete the autosave
2540                         a.removeFile();
2541                         break;
2542                 default:
2543                         return false;
2544                 }
2545         }
2546         return readFile(s);
2547 }
2548
2549
2550 bool Buffer::loadLyXFile(FileName const & s)
2551 {
2552         if (s.isReadableFile()) {
2553                 if (readFileHelper(s)) {
2554                         lyxvc().file_found_hook(s);
2555                         if (!s.isWritable())
2556                                 setReadonly(true);
2557                         return true;
2558                 }
2559         } else {
2560                 docstring const file = makeDisplayPath(s.absFilename(), 20);
2561                 // Here we probably should run
2562                 if (LyXVC::file_not_found_hook(s)) {
2563                         docstring const text =
2564                                 bformat(_("Do you want to retrieve the document"
2565                                                        " %1$s from version control?"), file);
2566                         int const ret = Alert::prompt(_("Retrieve from version control?"),
2567                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
2568
2569                         if (ret == 0) {
2570                                 // How can we know _how_ to do the checkout?
2571                                 // With the current VC support it has to be,
2572                                 // a RCS file since CVS do not have special ,v files.
2573                                 RCS::retrieve(s);
2574                                 return loadLyXFile(s);
2575                         }
2576                 }
2577         }
2578         return false;
2579 }
2580
2581
2582 void Buffer::bufferErrors(TeXErrors const & terr, ErrorList & errorList) const
2583 {
2584         TeXErrors::Errors::const_iterator cit = terr.begin();
2585         TeXErrors::Errors::const_iterator end = terr.end();
2586
2587         for (; cit != end; ++cit) {
2588                 int id_start = -1;
2589                 int pos_start = -1;
2590                 int errorRow = cit->error_in_line;
2591                 bool found = d->texrow.getIdFromRow(errorRow, id_start,
2592                                                        pos_start);
2593                 int id_end = -1;
2594                 int pos_end = -1;
2595                 do {
2596                         ++errorRow;
2597                         found = d->texrow.getIdFromRow(errorRow, id_end, pos_end);
2598                 } while (found && id_start == id_end && pos_start == pos_end);
2599
2600                 errorList.push_back(ErrorItem(cit->error_desc,
2601                         cit->error_text, id_start, pos_start, pos_end));
2602         }
2603 }
2604
2605
2606 } // namespace lyx