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