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