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