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