]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
267da451ec706c50ec5b915b9954f44e9e826448
[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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "Buffer.h"
14
15 #include "Author.h"
16 #include "BiblioInfo.h"
17 #include "BranchList.h"
18 #include "buffer_funcs.h"
19 #include "BufferList.h"
20 #include "BufferParams.h"
21 #include "Counters.h"
22 #include "Bullet.h"
23 #include "Chktex.h"
24 #include "debug.h"
25 #include "DocIterator.h"
26 #include "Encoding.h"
27 #include "ErrorList.h"
28 #include "Exporter.h"
29 #include "Format.h"
30 #include "FuncRequest.h"
31 #include "gettext.h"
32 #include "InsetIterator.h"
33 #include "Language.h"
34 #include "LaTeX.h"
35 #include "LaTeXFeatures.h"
36 #include "LyXAction.h"
37 #include "Lexer.h"
38 #include "Text.h"
39 #include "LyX.h"
40 #include "LyXRC.h"
41 #include "LyXVC.h"
42 #include "Messages.h"
43 #include "output.h"
44 #include "output_docbook.h"
45 #include "output_latex.h"
46 #include "Paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "ParIterator.h"
50 #include "sgml.h"
51 #include "TexRow.h"
52 #include "TextClassList.h"
53 #include "TexStream.h"
54 #include "TocBackend.h"
55 #include "Undo.h"
56 #include "version.h"
57
58 #include "insets/InsetBibitem.h"
59 #include "insets/InsetBibtex.h"
60 #include "insets/InsetInclude.h"
61 #include "insets/InsetText.h"
62
63 #include "mathed/MathMacroTemplate.h"
64 #include "mathed/MacroTable.h"
65 #include "mathed/MathSupport.h"
66
67 #include "frontends/alert.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/types.h"
72 #include "support/lyxalgo.h"
73 #include "support/filetools.h"
74 #include "support/fs_extras.h"
75 #include "support/gzstream.h"
76 #include "support/lyxlib.h"
77 #include "support/os.h"
78 #include "support/Path.h"
79 #include "support/textutils.h"
80 #include "support/convert.h"
81
82 #include <boost/bind.hpp>
83 #include <boost/filesystem/exception.hpp>
84 #include <boost/filesystem/operations.hpp>
85
86 #include <algorithm>
87 #include <iomanip>
88 #include <stack>
89 #include <sstream>
90 #include <fstream>
91
92 using std::endl;
93 using std::for_each;
94 using std::make_pair;
95
96 using std::ios;
97 using std::map;
98 using std::ostream;
99 using std::ostringstream;
100 using std::ofstream;
101 using std::pair;
102 using std::stack;
103 using std::vector;
104 using std::string;
105 using std::time_t;
106
107
108 namespace lyx {
109
110 using support::addName;
111 using support::bformat;
112 using support::changeExtension;
113 using support::cmd_ret;
114 using support::createBufferTmpDir;
115 using support::destroyDir;
116 using support::FileName;
117 using support::getFormatFromContents;
118 using support::libFileSearch;
119 using support::latex_path;
120 using support::ltrim;
121 using support::makeAbsPath;
122 using support::makeDisplayPath;
123 using support::makeLatexName;
124 using support::onlyFilename;
125 using support::onlyPath;
126 using support::quoteName;
127 using support::removeAutosaveFile;
128 using support::rename;
129 using support::runCommand;
130 using support::split;
131 using support::subst;
132 using support::tempName;
133 using support::trim;
134 using support::sum;
135
136 namespace Alert = frontend::Alert;
137 namespace os = support::os;
138 namespace fs = boost::filesystem;
139
140 namespace {
141
142 int const LYX_FORMAT = 281;
143
144 } // namespace anon
145
146
147 typedef std::map<string, bool> DepClean;
148
149 class Buffer::Impl
150 {
151 public:
152         Impl(Buffer & parent, FileName const & file, bool readonly);
153
154         limited_stack<Undo> undostack;
155         limited_stack<Undo> redostack;
156         BufferParams params;
157         LyXVC lyxvc;
158         string temppath;
159         TexRow texrow;
160
161         /// need to regenerate .tex?
162         DepClean dep_clean;
163
164         /// is save needed?
165         mutable bool lyx_clean;
166
167         /// is autosave needed?
168         mutable bool bak_clean;
169
170         /// is this a unnamed file (New...)?
171         bool unnamed;
172
173         /// buffer is r/o
174         bool read_only;
175
176         /// name of the file the buffer is associated with.
177         FileName filename;
178
179         /** Set to true only when the file is fully loaded.
180          *  Used to prevent the premature generation of previews
181          *  and by the citation inset.
182          */
183         bool file_fully_loaded;
184
185         /// our Text that should be wrapped in an InsetText
186         InsetText inset;
187
188         ///
189         MacroTable macros;
190
191         ///
192         TocBackend toc_backend;
193
194         /// Container for all sort of Buffer dependant errors.
195         map<string, ErrorList> errorLists;
196
197         /// timestamp and checksum used to test if the file has been externally
198         /// modified. (Used to properly enable 'File->Revert to saved', bug 4114).
199         time_t timestamp_;
200         unsigned long checksum_;
201 };
202
203
204 Buffer::Impl::Impl(Buffer & parent, FileName const & file, bool readonly_)
205         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
206           filename(file), file_fully_loaded(false), inset(params),
207           toc_backend(&parent), timestamp_(0), checksum_(0)
208 {
209         inset.setAutoBreakRows(true);
210         lyxvc.buffer(&parent);
211         temppath = createBufferTmpDir();
212         params.filepath = onlyPath(file.absFilename());
213         // FIXME: And now do something if temppath == string(), because we
214         // assume from now on that temppath points to a valid temp dir.
215         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
216 }
217
218
219 Buffer::Buffer(string const & file, bool readonly)
220         : pimpl_(new Impl(*this, FileName(file), readonly))
221 {
222         LYXERR(Debug::INFO) << "Buffer::Buffer()" << endl;
223 }
224
225
226 Buffer::~Buffer()
227 {
228         LYXERR(Debug::INFO) << "Buffer::~Buffer()" << endl;
229         // here the buffer should take care that it is
230         // saved properly, before it goes into the void.
231
232         Buffer * master = getMasterBuffer();
233         if (master != this && use_gui)
234                 // We are closing buf which was a child document so we
235                 // must update the labels and section numbering of its master
236                 // Buffer.
237                 updateLabels(*master);
238
239         if (!temppath().empty() && !destroyDir(FileName(temppath()))) {
240                 Alert::warning(_("Could not remove temporary directory"),
241                         bformat(_("Could not remove the temporary directory %1$s"),
242                         from_utf8(temppath())));
243         }
244
245         // Remove any previewed LaTeX snippets associated with this buffer.
246         graphics::Previews::get().removeLoader(*this);
247
248         closing(this);
249 }
250
251
252 Text & Buffer::text() const
253 {
254         return const_cast<Text &>(pimpl_->inset.text_);
255 }
256
257
258 Inset & Buffer::inset() const
259 {
260         return const_cast<InsetText &>(pimpl_->inset);
261 }
262
263
264 limited_stack<Undo> & Buffer::undostack()
265 {
266         return pimpl_->undostack;
267 }
268
269
270 limited_stack<Undo> const & Buffer::undostack() const
271 {
272         return pimpl_->undostack;
273 }
274
275
276 limited_stack<Undo> & Buffer::redostack()
277 {
278         return pimpl_->redostack;
279 }
280
281
282 limited_stack<Undo> const & Buffer::redostack() const
283 {
284         return pimpl_->redostack;
285 }
286
287
288 BufferParams & Buffer::params()
289 {
290         return pimpl_->params;
291 }
292
293
294 BufferParams const & Buffer::params() const
295 {
296         return pimpl_->params;
297 }
298
299
300 ParagraphList & Buffer::paragraphs()
301 {
302         return text().paragraphs();
303 }
304
305
306 ParagraphList const & Buffer::paragraphs() const
307 {
308         return text().paragraphs();
309 }
310
311
312 LyXVC & Buffer::lyxvc()
313 {
314         return pimpl_->lyxvc;
315 }
316
317
318 LyXVC const & Buffer::lyxvc() const
319 {
320         return pimpl_->lyxvc;
321 }
322
323
324 string const & Buffer::temppath() const
325 {
326         return pimpl_->temppath;
327 }
328
329
330 TexRow & Buffer::texrow()
331 {
332         return pimpl_->texrow;
333 }
334
335
336 TexRow const & Buffer::texrow() const
337 {
338         return pimpl_->texrow;
339 }
340
341
342 TocBackend & Buffer::tocBackend()
343 {
344         return pimpl_->toc_backend;
345 }
346
347
348 TocBackend const & Buffer::tocBackend() const
349 {
350         return pimpl_->toc_backend;
351 }
352
353
354 string const Buffer::getLatexName(bool const no_path) const
355 {
356         string const name = changeExtension(makeLatexName(fileName()), ".tex");
357         return no_path ? onlyFilename(name) : name;
358 }
359
360
361 pair<Buffer::LogType, string> const Buffer::getLogName() const
362 {
363         string const filename = getLatexName(false);
364
365         if (filename.empty())
366                 return make_pair(Buffer::latexlog, string());
367
368         string const path = temppath();
369
370         FileName const fname(addName(temppath(),
371                                      onlyFilename(changeExtension(filename,
372                                                                   ".log"))));
373         FileName const bname(
374                 addName(path, onlyFilename(
375                         changeExtension(filename,
376                                         formats.extension("literate") + ".out"))));
377
378         // If no Latex log or Build log is newer, show Build log
379
380         if (fs::exists(bname.toFilesystemEncoding()) &&
381             (!fs::exists(fname.toFilesystemEncoding()) ||
382              fs::last_write_time(fname.toFilesystemEncoding()) < fs::last_write_time(bname.toFilesystemEncoding()))) {
383                 LYXERR(Debug::FILES) << "Log name calculated as: " << bname << endl;
384                 return make_pair(Buffer::buildlog, bname.absFilename());
385         }
386         LYXERR(Debug::FILES) << "Log name calculated as: " << fname << endl;
387         return make_pair(Buffer::latexlog, fname.absFilename());
388 }
389
390
391 void Buffer::setReadonly(bool const flag)
392 {
393         if (pimpl_->read_only != flag) {
394                 pimpl_->read_only = flag;
395                 readonly(flag);
396         }
397 }
398
399
400 void Buffer::setFileName(string const & newfile)
401 {
402         pimpl_->filename = makeAbsPath(newfile);
403         params().filepath = onlyPath(pimpl_->filename.absFilename());
404         setReadonly(fs::is_readonly(pimpl_->filename.toFilesystemEncoding()));
405         updateTitles();
406 }
407
408
409 // We'll remove this later. (Lgb)
410 namespace {
411
412 void unknownClass(string const & unknown)
413 {
414         Alert::warning(_("Unknown document class"),
415                        bformat(_("Using the default document class, because the "
416                                               "class %1$s is unknown."), from_utf8(unknown)));
417 }
418
419 } // anon
420
421
422 int Buffer::readHeader(Lexer & lex)
423 {
424         int unknown_tokens = 0;
425         int line = -1;
426         int begin_header_line = -1;
427
428         // Initialize parameters that may be/go lacking in header:
429         params().branchlist().clear();
430         params().preamble.erase();
431         params().options.erase();
432         params().float_placement.erase();
433         params().paperwidth.erase();
434         params().paperheight.erase();
435         params().leftmargin.erase();
436         params().rightmargin.erase();
437         params().topmargin.erase();
438         params().bottommargin.erase();
439         params().headheight.erase();
440         params().headsep.erase();
441         params().footskip.erase();
442         params().listings_params.clear();
443         params().clearLayoutModules();
444         
445         for (int i = 0; i < 4; ++i) {
446                 params().user_defined_bullet(i) = ITEMIZE_DEFAULTS[i];
447                 params().temp_bullet(i) = ITEMIZE_DEFAULTS[i];
448         }
449
450         ErrorList & errorList = pimpl_->errorLists["Parse"];
451
452         while (lex.isOK()) {
453                 lex.next();
454                 string const token = lex.getString();
455
456                 if (token.empty())
457                         continue;
458
459                 if (token == "\\end_header")
460                         break;
461
462                 ++line;
463                 if (token == "\\begin_header") {
464                         begin_header_line = line;
465                         continue;
466                 }
467
468                 LYXERR(Debug::PARSER) << "Handling document header token: `"
469                                       << token << '\'' << endl;
470
471                 string unknown = params().readToken(lex, token);
472                 if (!unknown.empty()) {
473                         if (unknown[0] != '\\' && token == "\\textclass") {
474                                 unknownClass(unknown);
475                         } else {
476                                 ++unknown_tokens;
477                                 docstring const s = bformat(_("Unknown token: "
478                                                                         "%1$s %2$s\n"),
479                                                          from_utf8(token),
480                                                          lex.getDocString());
481                                 errorList.push_back(ErrorItem(_("Document header error"),
482                                         s, -1, 0, 0));
483                         }
484                 }
485         }
486         if (begin_header_line) {
487                 docstring const s = _("\\begin_header is missing");
488                 errorList.push_back(ErrorItem(_("Document header error"),
489                         s, -1, 0, 0));
490         }
491
492         return unknown_tokens;
493 }
494
495
496 // Uwe C. Schroeder
497 // changed to be public and have one parameter
498 // Returns false if "\end_document" is not read (Asger)
499 bool Buffer::readDocument(Lexer & lex)
500 {
501         ErrorList & errorList = pimpl_->errorLists["Parse"];
502         errorList.clear();
503
504         lex.next();
505         string const token = lex.getString();
506         if (token != "\\begin_document") {
507                 docstring const s = _("\\begin_document is missing");
508                 errorList.push_back(ErrorItem(_("Document header error"),
509                         s, -1, 0, 0));
510         }
511
512         // we are reading in a brand new document
513         BOOST_ASSERT(paragraphs().empty());
514
515         readHeader(lex);
516         if (!params().getTextClass().load(filePath())) {
517                 string theclass = params().getTextClass().name();
518                 Alert::error(_("Can't load document class"), bformat(
519                         _("Using the default document class, because the "
520                                      "class %1$s could not be loaded."), from_utf8(theclass)));
521                 params().setBaseClass(defaultTextclass());
522         }
523
524         if (params().outputChanges) {
525                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
526                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
527                                   LaTeXFeatures::isAvailable("xcolor");
528
529                 if (!dvipost && !xcolorsoul) {
530                         Alert::warning(_("Changes not shown in LaTeX output"),
531                                        _("Changes will not be highlighted in LaTeX output, "
532                                          "because neither dvipost nor xcolor/soul are installed.\n"
533                                          "Please install these packages or redefine "
534                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
535                 } else if (!xcolorsoul) {
536                         Alert::warning(_("Changes not shown in LaTeX output"),
537                                        _("Changes will not be highlighted in LaTeX output "
538                                          "when using pdflatex, because xcolor and soul are not installed.\n"
539                                          "Please install both packages or redefine "
540                                          "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
541                 }
542         }
543
544         bool const res = text().read(*this, lex, errorList);
545         for_each(text().paragraphs().begin(),
546                  text().paragraphs().end(),
547                  bind(&Paragraph::setInsetOwner, _1, &inset()));
548
549         return res;
550 }
551
552
553 // needed to insert the selection
554 void Buffer::insertStringAsLines(ParagraphList & pars,
555         pit_type & pit, pos_type & pos,
556         Font const & fn, docstring const & str, bool autobreakrows)
557 {
558         Font font = fn;
559
560         // insert the string, don't insert doublespace
561         bool space_inserted = true;
562         for (docstring::const_iterator cit = str.begin();
563             cit != str.end(); ++cit) {
564                 Paragraph & par = pars[pit];
565                 if (*cit == '\n') {
566                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
567                                 breakParagraph(params(), pars, pit, pos,
568                                                par.layout()->isEnvironment());
569                                 ++pit;
570                                 pos = 0;
571                                 space_inserted = true;
572                         } else {
573                                 continue;
574                         }
575                         // do not insert consecutive spaces if !free_spacing
576                 } else if ((*cit == ' ' || *cit == '\t') &&
577                            space_inserted && !par.isFreeSpacing()) {
578                         continue;
579                 } else if (*cit == '\t') {
580                         if (!par.isFreeSpacing()) {
581                                 // tabs are like spaces here
582                                 par.insertChar(pos, ' ', font, params().trackChanges);
583                                 ++pos;
584                                 space_inserted = true;
585                         } else {
586                                 const pos_type n = 8 - pos % 8;
587                                 for (pos_type i = 0; i < n; ++i) {
588                                         par.insertChar(pos, ' ', font, params().trackChanges);
589                                         ++pos;
590                                 }
591                                 space_inserted = true;
592                         }
593                 } else if (!isPrintable(*cit)) {
594                         // Ignore unprintables
595                         continue;
596                 } else {
597                         // just insert the character
598                         par.insertChar(pos, *cit, font, params().trackChanges);
599                         ++pos;
600                         space_inserted = (*cit == ' ');
601                 }
602
603         }
604 }
605
606
607 bool Buffer::readString(std::string const & s)
608 {
609         params().compressed = false;
610
611         // remove dummy empty par
612         paragraphs().clear();
613         Lexer lex(0, 0);
614         std::istringstream is(s);
615         lex.setStream(is);
616         FileName const name(tempName());
617         switch (readFile(lex, name, true)) {
618         case failure:
619                 return false;
620         case wrongversion: {
621                 // We need to call lyx2lyx, so write the input to a file
622                 std::ofstream os(name.toFilesystemEncoding().c_str());
623                 os << s;
624                 os.close();
625                 return readFile(name);
626         }
627         case success:
628                 break;
629         }
630
631         return true;
632 }
633
634
635 bool Buffer::readFile(FileName const & filename)
636 {
637         // Check if the file is compressed.
638         string const format = getFormatFromContents(filename);
639         if (format == "gzip" || format == "zip" || format == "compress") {
640                 params().compressed = true;
641         }
642
643         // remove dummy empty par
644         paragraphs().clear();
645         Lexer lex(0, 0);
646         lex.setFile(filename);
647         if (readFile(lex, filename) != success)
648                 return false;
649
650         return true;
651 }
652
653
654 bool Buffer::fully_loaded() const
655 {
656         return pimpl_->file_fully_loaded;
657 }
658
659
660 void Buffer::fully_loaded(bool const value)
661 {
662         pimpl_->file_fully_loaded = value;
663 }
664
665
666 Buffer::ReadStatus Buffer::readFile(Lexer & lex, FileName const & filename,
667                 bool fromstring)
668 {
669         BOOST_ASSERT(!filename.empty());
670
671         if (!lex.isOK()) {
672                 Alert::error(_("Document could not be read"),
673                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
674                 return failure;
675         }
676
677         lex.next();
678         string const token(lex.getString());
679
680         if (!lex) {
681                 Alert::error(_("Document could not be read"),
682                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
683                 return failure;
684         }
685
686         // the first token _must_ be...
687         if (token != "\\lyxformat") {
688                 lyxerr << "Token: " << token << endl;
689
690                 Alert::error(_("Document format failure"),
691                              bformat(_("%1$s is not a LyX document."),
692                                        from_utf8(filename.absFilename())));
693                 return failure;
694         }
695
696         lex.next();
697         string tmp_format = lex.getString();
698         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
699         // if present remove ".," from string.
700         string::size_type dot = tmp_format.find_first_of(".,");
701         //lyxerr << "           dot found at " << dot << endl;
702         if (dot != string::npos)
703                         tmp_format.erase(dot, 1);
704         int const file_format = convert<int>(tmp_format);
705         //lyxerr << "format: " << file_format << endl;
706
707         // save timestamp and checksum of the original disk file, making sure
708         // to not overwrite them with those of the file created in the tempdir
709         // when it has to be converted to the current format.
710         if (!pimpl_->checksum_) {
711                 pimpl_->timestamp_ = fs::last_write_time(filename.toFilesystemEncoding());
712                 pimpl_->checksum_ = sum(filename);
713         }
714
715         if (file_format != LYX_FORMAT) {
716
717                 if (fromstring)
718                         // lyx2lyx would fail
719                         return wrongversion;
720
721                 FileName const tmpfile(tempName());
722                 if (tmpfile.empty()) {
723                         Alert::error(_("Conversion failed"),
724                                      bformat(_("%1$s is from a different"
725                                               " version of LyX, but a temporary"
726                                               " file for converting it could"
727                                                             " not be created."),
728                                               from_utf8(filename.absFilename())));
729                         return failure;
730                 }
731                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
732                 if (lyx2lyx.empty()) {
733                         Alert::error(_("Conversion script not found"),
734                                      bformat(_("%1$s is from a different"
735                                                " version of LyX, but the"
736                                                " conversion script lyx2lyx"
737                                                             " could not be found."),
738                                                from_utf8(filename.absFilename())));
739                         return failure;
740                 }
741                 ostringstream command;
742                 command << os::python()
743                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
744                         << " -t " << convert<string>(LYX_FORMAT)
745                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
746                         << ' ' << quoteName(filename.toFilesystemEncoding());
747                 string const command_str = command.str();
748
749                 LYXERR(Debug::INFO) << "Running '"
750                                     << command_str << '\''
751                                     << endl;
752
753                 cmd_ret const ret = runCommand(command_str);
754                 if (ret.first != 0) {
755                         Alert::error(_("Conversion script failed"),
756                                      bformat(_("%1$s is from a different version"
757                                               " of LyX, but the lyx2lyx script"
758                                                             " failed to convert it."),
759                                               from_utf8(filename.absFilename())));
760                         return failure;
761                 } else {
762                         bool const ret = readFile(tmpfile);
763                         // Do stuff with tmpfile name and buffer name here.
764                         return ret ? success : failure;
765                 }
766
767         }
768
769         if (readDocument(lex)) {
770                 Alert::error(_("Document format failure"),
771                              bformat(_("%1$s ended unexpectedly, which means"
772                                                     " that it is probably corrupted."),
773                                        from_utf8(filename.absFilename())));
774         }
775
776         //lyxerr << "removing " << MacroTable::localMacros().size()
777         //      << " temporary macro entries" << endl;
778         //MacroTable::localMacros().clear();
779
780         pimpl_->file_fully_loaded = true;
781         return success;
782 }
783
784
785 // Should probably be moved to somewhere else: BufferView? LyXView?
786 bool Buffer::save() const
787 {
788         // We don't need autosaves in the immediate future. (Asger)
789         resetAutosaveTimers();
790
791         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
792
793         FileName backupName;
794         bool madeBackup = false;
795
796         // make a backup if the file already exists
797         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
798                 backupName = FileName(fileName() + '~');
799                 if (!lyxrc.backupdir_path.empty())
800                         backupName = FileName(addName(lyxrc.backupdir_path,
801                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
802
803                 try {
804                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
805                         madeBackup = true;
806                 } catch (fs::filesystem_error const & fe) {
807                         Alert::error(_("Backup failure"),
808                                      bformat(_("Cannot create backup file %1$s.\n"
809                                                "Please check whether the directory exists and is writeable."),
810                                              from_utf8(backupName.absFilename())));
811                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
812                 }
813         }
814
815         // ask if the disk file has been externally modified (use checksum method)
816         if (fs::exists(encodedFilename) && isExternallyModified(checksum_method)) {
817                 docstring const file = makeDisplayPath(fileName(), 20);
818                 docstring text = bformat(_("Document %1$s has been externally modified. Are you sure "
819                                                              "you want to overwrite this file?"), file);
820                 int const ret = Alert::prompt(_("Overwrite modified file?"),
821                         text, 1, 1, _("&Overwrite"), _("&Cancel"));
822                 if (ret == 1)
823                         return false;
824         }
825
826         if (writeFile(pimpl_->filename)) {
827                 markClean();
828                 removeAutosaveFile(fileName());
829                 pimpl_->timestamp_ = fs::last_write_time(pimpl_->filename.toFilesystemEncoding());
830                 pimpl_->checksum_ = sum(pimpl_->filename);
831                 return true;
832         } else {
833                 // Saving failed, so backup is not backup
834                 if (madeBackup)
835                         rename(backupName, pimpl_->filename);
836                 return false;
837         }
838 }
839
840
841 bool Buffer::writeFile(FileName const & fname) const
842 {
843         if (pimpl_->read_only && fname == pimpl_->filename)
844                 return false;
845
846         bool retval = false;
847
848         if (params().compressed) {
849                 gz::ogzstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
850                 if (!ofs)
851                         return false;
852
853                 retval = write(ofs);
854         } else {
855                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
856                 if (!ofs)
857                         return false;
858
859                 retval = write(ofs);
860         }
861
862         return retval;
863 }
864
865
866 bool Buffer::write(ostream & ofs) const
867 {
868 #ifdef HAVE_LOCALE
869         // Use the standard "C" locale for file output.
870         ofs.imbue(std::locale::classic());
871 #endif
872
873         // The top of the file should not be written by params().
874
875         // write out a comment in the top of the file
876         ofs << "#LyX " << lyx_version
877             << " created this file. For more info see http://www.lyx.org/\n"
878             << "\\lyxformat " << LYX_FORMAT << "\n"
879             << "\\begin_document\n";
880
881
882         /// For each author, set 'used' to true if there is a change
883         /// by this author in the document; otherwise set it to 'false'.
884         AuthorList::Authors::const_iterator a_it = params().authors().begin();
885         AuthorList::Authors::const_iterator a_end = params().authors().end();
886         for (; a_it != a_end; ++a_it)
887                 a_it->second.used(false);
888
889         ParIterator const end = par_iterator_end();
890         ParIterator it = par_iterator_begin();
891         for ( ; it != end; ++it)
892                 it->checkAuthors(params().authors());
893
894         // now write out the buffer parameters.
895         ofs << "\\begin_header\n";
896         params().writeFile(ofs);
897         ofs << "\\end_header\n";
898
899         // write the text
900         ofs << "\n\\begin_body\n";
901         text().write(*this, ofs);
902         ofs << "\n\\end_body\n";
903
904         // Write marker that shows file is complete
905         ofs << "\\end_document" << endl;
906
907         // Shouldn't really be needed....
908         //ofs.close();
909
910         // how to check if close went ok?
911         // Following is an attempt... (BE 20001011)
912
913         // good() returns false if any error occured, including some
914         //        formatting error.
915         // bad()  returns true if something bad happened in the buffer,
916         //        which should include file system full errors.
917
918         bool status = true;
919         if (!ofs) {
920                 status = false;
921                 lyxerr << "File was not closed properly." << endl;
922         }
923
924         return status;
925 }
926
927
928 bool Buffer::makeLaTeXFile(FileName const & fname,
929                            string const & original_path,
930                            OutputParams const & runparams,
931                            bool output_preamble, bool output_body)
932 {
933         string const encoding = runparams.encoding->iconvName();
934         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
935                 << encoding << "..." << endl;
936
937         odocfstream ofs(encoding);
938         if (!openFileWrite(ofs, fname))
939                 return false;
940
941         //TexStream ts(ofs.rdbuf(), &texrow());
942
943         bool failed_export = false;
944         try {
945                 texrow().reset();
946                 writeLaTeXSource(ofs, original_path,
947                       runparams, output_preamble, output_body);
948         }
949         catch (iconv_codecvt_facet_exception & e) {
950                 lyxerr << "Caught iconv exception: " << e.what() << endl;
951                 failed_export = true;
952         }
953         catch (std::exception const & e) {
954                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
955                 failed_export = true;
956         }
957         catch (...) {
958                 lyxerr << "Caught some really weird exception..." << endl;
959                 LyX::cref().emergencyCleanup();
960                 abort();
961         }
962
963         ofs.close();
964         if (ofs.fail()) {
965                 failed_export = true;
966                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
967         }
968
969         if (failed_export) {
970                 Alert::error(_("Encoding error"),
971                         _("Some characters of your document are probably not "
972                         "representable in the chosen encoding.\n"
973                         "Changing the document encoding to utf8 could help."));
974                 return false;
975         }
976         return true;
977 }
978
979
980 void Buffer::writeLaTeXSource(odocstream & os,
981                            string const & original_path,
982                            OutputParams const & runparams_in,
983                            bool const output_preamble, bool const output_body)
984 {
985         OutputParams runparams = runparams_in;
986
987         // validate the buffer.
988         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
989         LaTeXFeatures features(*this, params(), runparams);
990         validate(features);
991         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
992
993         // The starting paragraph of the coming rows is the
994         // first paragraph of the document. (Asger)
995         if (output_preamble && runparams.nice) {
996                 os << "%% LyX " << lyx_version << " created this file.  "
997                         "For more info, see http://www.lyx.org/.\n"
998                         "%% Do not edit unless you really know what "
999                         "you are doing.\n";
1000                 texrow().newline();
1001                 texrow().newline();
1002         }
1003         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
1004         // There are a few differences between nice LaTeX and usual files:
1005         // usual is \batchmode and has a
1006         // special input@path to allow the including of figures
1007         // with either \input or \includegraphics (what figinsets do).
1008         // input@path is set when the actual parameter
1009         // original_path is set. This is done for usual tex-file, but not
1010         // for nice-latex-file. (Matthias 250696)
1011         // Note that input@path is only needed for something the user does
1012         // in the preamble, included .tex files or ERT, files included by
1013         // LyX work without it.
1014         if (output_preamble) {
1015                 if (!runparams.nice) {
1016                         // code for usual, NOT nice-latex-file
1017                         os << "\\batchmode\n"; // changed
1018                         // from \nonstopmode
1019                         texrow().newline();
1020                 }
1021                 if (!original_path.empty()) {
1022                         // FIXME UNICODE
1023                         // We don't know the encoding of inputpath
1024                         docstring const inputpath = from_utf8(latex_path(original_path));
1025                         os << "\\makeatletter\n"
1026                            << "\\def\\input@path{{"
1027                            << inputpath << "/}}\n"
1028                            << "\\makeatother\n";
1029                         texrow().newline();
1030                         texrow().newline();
1031                         texrow().newline();
1032                 }
1033
1034                 // Write the preamble
1035                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1036
1037                 if (!output_body)
1038                         return;
1039
1040                 // make the body.
1041                 os << "\\begin{document}\n";
1042                 texrow().newline();
1043         } // output_preamble
1044
1045         texrow().start(paragraphs().begin()->id(), 0);
1046         
1047         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1048
1049         if (!lyxrc.language_auto_begin &&
1050             !params().language->babel().empty()) {
1051                 // FIXME UNICODE
1052                 os << from_utf8(subst(lyxrc.language_command_begin,
1053                                            "$$lang",
1054                                            params().language->babel()))
1055                    << '\n';
1056                 texrow().newline();
1057         }
1058
1059         Encoding const & encoding = params().encoding();
1060         if (encoding.package() == Encoding::CJK) {
1061                 // Open a CJK environment, since in contrast to the encodings
1062                 // handled by inputenc the document encoding is not set in
1063                 // the preamble if it is handled by CJK.sty.
1064                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1065                    << "}{}\n";
1066                 texrow().newline();
1067         }
1068
1069         // if we are doing a real file with body, even if this is the
1070         // child of some other buffer, let's cut the link here.
1071         // This happens for example if only a child document is printed.
1072         string save_parentname;
1073         if (output_preamble) {
1074                 save_parentname = params().parentname;
1075                 params().parentname.erase();
1076         }
1077
1078         loadChildDocuments(*this);
1079
1080         // the real stuff
1081         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1082
1083         // Restore the parenthood if needed
1084         if (output_preamble)
1085                 params().parentname = save_parentname;
1086
1087         // add this just in case after all the paragraphs
1088         os << endl;
1089         texrow().newline();
1090
1091         if (encoding.package() == Encoding::CJK) {
1092                 // Close the open CJK environment.
1093                 // latexParagraphs will have opened one even if the last text
1094                 // was not CJK.
1095                 os << "\\end{CJK}\n";
1096                 texrow().newline();
1097         }
1098
1099         if (!lyxrc.language_auto_end &&
1100             !params().language->babel().empty()) {
1101                 os << from_utf8(subst(lyxrc.language_command_end,
1102                                            "$$lang",
1103                                            params().language->babel()))
1104                    << '\n';
1105                 texrow().newline();
1106         }
1107
1108         if (output_preamble) {
1109                 os << "\\end{document}\n";
1110                 texrow().newline();
1111
1112                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1113         } else {
1114                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1115                                      << endl;
1116         }
1117         runparams_in.encoding = runparams.encoding;
1118
1119         // Just to be sure. (Asger)
1120         texrow().newline();
1121
1122         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1123         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1124                             << '.' << endl;
1125 }
1126
1127
1128 bool Buffer::isLatex() const
1129 {
1130         return params().getTextClass().outputType() == LATEX;
1131 }
1132
1133
1134 bool Buffer::isLiterate() const
1135 {
1136         return params().getTextClass().outputType() == LITERATE;
1137 }
1138
1139
1140 bool Buffer::isDocBook() const
1141 {
1142         return params().getTextClass().outputType() == DOCBOOK;
1143 }
1144
1145
1146 void Buffer::makeDocBookFile(FileName const & fname,
1147                               OutputParams const & runparams,
1148                               bool const body_only)
1149 {
1150         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1151
1152         //ofstream ofs;
1153         odocfstream ofs;
1154         if (!openFileWrite(ofs, fname))
1155                 return;
1156
1157         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1158
1159         ofs.close();
1160         if (ofs.fail())
1161                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1162 }
1163
1164
1165 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1166                              OutputParams const & runparams,
1167                              bool const only_body)
1168 {
1169         LaTeXFeatures features(*this, params(), runparams);
1170         validate(features);
1171
1172         texrow().reset();
1173
1174         TextClass const & tclass = params().getTextClass();
1175         string const top_element = tclass.latexname();
1176
1177         if (!only_body) {
1178                 if (runparams.flavor == OutputParams::XML)
1179                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1180
1181                 // FIXME UNICODE
1182                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1183
1184                 // FIXME UNICODE
1185                 if (! tclass.class_header().empty())
1186                         os << from_ascii(tclass.class_header());
1187                 else if (runparams.flavor == OutputParams::XML)
1188                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1189                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1190                 else
1191                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1192
1193                 docstring preamble = from_utf8(params().preamble);
1194                 if (runparams.flavor != OutputParams::XML ) {
1195                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1196                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1197                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1198                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1199                 }
1200
1201                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1202                          : fname;
1203                 preamble += features.getIncludedFiles(name);
1204                 preamble += features.getLyXSGMLEntities();
1205
1206                 if (!preamble.empty()) {
1207                         os << "\n [ " << preamble << " ]";
1208                 }
1209                 os << ">\n\n";
1210         }
1211
1212         string top = top_element;
1213         top += " lang=\"";
1214         if (runparams.flavor == OutputParams::XML)
1215                 top += params().language->code();
1216         else
1217                 top += params().language->code().substr(0,2);
1218         top += '"';
1219
1220         if (!params().options.empty()) {
1221                 top += ' ';
1222                 top += params().options;
1223         }
1224
1225         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1226             << " file was created by LyX " << lyx_version
1227             << "\n  See http://www.lyx.org/ for more information -->\n";
1228
1229         params().getTextClass().counters().reset();
1230
1231         loadChildDocuments(*this);
1232
1233         sgml::openTag(os, top);
1234         os << '\n';
1235         docbookParagraphs(paragraphs(), *this, os, runparams);
1236         sgml::closeTag(os, top_element);
1237 }
1238
1239
1240 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1241 // Other flags: -wall -v0 -x
1242 int Buffer::runChktex()
1243 {
1244         busy(true);
1245
1246         // get LaTeX-Filename
1247         FileName const path(temppath());
1248         string const name = addName(path.absFilename(), getLatexName());
1249         string const org_path = filePath();
1250
1251         support::Path p(path); // path to LaTeX file
1252         message(_("Running chktex..."));
1253
1254         // Generate the LaTeX file if neccessary
1255         OutputParams runparams(&params().encoding());
1256         runparams.flavor = OutputParams::LATEX;
1257         runparams.nice = false;
1258         makeLaTeXFile(FileName(name), org_path, runparams);
1259
1260         TeXErrors terr;
1261         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1262         int const res = chktex.run(terr); // run chktex
1263
1264         if (res == -1) {
1265                 Alert::error(_("chktex failure"),
1266                              _("Could not run chktex successfully."));
1267         } else if (res > 0) {
1268                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1269                 // Clear out old errors
1270                 errorList.clear();
1271                 // Fill-in the error list with the TeX errors
1272                 bufferErrors(*this, terr, errorList);
1273         }
1274
1275         busy(false);
1276
1277         errors("ChkTeX");
1278
1279         return res;
1280 }
1281
1282
1283 void Buffer::validate(LaTeXFeatures & features) const
1284 {
1285         TextClass const & tclass = params().getTextClass();
1286
1287         if (params().outputChanges) {
1288                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1289                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1290                                   LaTeXFeatures::isAvailable("xcolor");
1291
1292                 if (features.runparams().flavor == OutputParams::LATEX) {
1293                         if (dvipost) {
1294                                 features.require("ct-dvipost");
1295                                 features.require("dvipost");
1296                         } else if (xcolorsoul) {
1297                                 features.require("ct-xcolor-soul");
1298                                 features.require("soul");
1299                                 features.require("xcolor");
1300                         } else {
1301                                 features.require("ct-none");
1302                         }
1303                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1304                         if (xcolorsoul) {
1305                                 features.require("ct-xcolor-soul");
1306                                 features.require("soul");
1307                                 features.require("xcolor");
1308                                 features.require("pdfcolmk"); // improves color handling in PDF output
1309                         } else {
1310                                 features.require("ct-none");
1311                         }
1312                 }
1313         }
1314
1315         // AMS Style is at document level
1316         if (params().use_amsmath == BufferParams::package_on
1317             || tclass.provides("amsmath"))
1318                 features.require("amsmath");
1319         if (params().use_esint == BufferParams::package_on)
1320                 features.require("esint");
1321
1322         loadChildDocuments(*this);
1323
1324         for_each(paragraphs().begin(), paragraphs().end(),
1325                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1326
1327         // the bullet shapes are buffer level not paragraph level
1328         // so they are tested here
1329         for (int i = 0; i < 4; ++i) {
1330                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1331                         int const font = params().user_defined_bullet(i).getFont();
1332                         if (font == 0) {
1333                                 int const c = params()
1334                                         .user_defined_bullet(i)
1335                                         .getCharacter();
1336                                 if (c == 16
1337                                    || c == 17
1338                                    || c == 25
1339                                    || c == 26
1340                                    || c == 31) {
1341                                         features.require("latexsym");
1342                                 }
1343                         } else if (font == 1) {
1344                                 features.require("amssymb");
1345                         } else if ((font >= 2 && font <= 5)) {
1346                                 features.require("pifont");
1347                         }
1348                 }
1349         }
1350
1351         if (lyxerr.debugging(Debug::LATEX)) {
1352                 features.showStruct();
1353         }
1354 }
1355
1356
1357 void Buffer::getLabelList(vector<docstring> & list) const
1358 {
1359         /// if this is a child document and the parent is already loaded
1360         /// Use the parent's list instead  [ale990407]
1361         Buffer const * tmp = getMasterBuffer();
1362         if (!tmp) {
1363                 lyxerr << "getMasterBuffer() failed!" << endl;
1364                 BOOST_ASSERT(tmp);
1365         }
1366         if (tmp != this) {
1367                 tmp->getLabelList(list);
1368                 return;
1369         }
1370
1371         loadChildDocuments(*this);
1372
1373         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1374                 it.nextInset()->getLabelList(*this, list);
1375 }
1376
1377
1378 void Buffer::updateBibfilesCache()
1379 {
1380         // if this is a child document and the parent is already loaded
1381         // update the parent's cache instead
1382         Buffer * tmp = getMasterBuffer();
1383         BOOST_ASSERT(tmp);
1384         if (tmp != this) {
1385                 tmp->updateBibfilesCache();
1386                 return;
1387         }
1388
1389         bibfilesCache_.clear();
1390         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1391                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1392                         InsetBibtex const & inset =
1393                                 static_cast<InsetBibtex const &>(*it);
1394                         vector<FileName> const bibfiles = inset.getFiles(*this);
1395                         bibfilesCache_.insert(bibfilesCache_.end(),
1396                                 bibfiles.begin(),
1397                                 bibfiles.end());
1398                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1399                         InsetInclude & inset =
1400                                 static_cast<InsetInclude &>(*it);
1401                         inset.updateBibfilesCache(*this);
1402                         vector<FileName> const & bibfiles =
1403                                         inset.getBibfilesCache(*this);
1404                         bibfilesCache_.insert(bibfilesCache_.end(),
1405                                 bibfiles.begin(),
1406                                 bibfiles.end());
1407                 }
1408         }
1409 }
1410
1411
1412 vector<FileName> const & Buffer::getBibfilesCache() const
1413 {
1414         // if this is a child document and the parent is already loaded
1415         // use the parent's cache instead
1416         Buffer const * tmp = getMasterBuffer();
1417         BOOST_ASSERT(tmp);
1418         if (tmp != this)
1419                 return tmp->getBibfilesCache();
1420
1421         // We update the cache when first used instead of at loading time.
1422         if (bibfilesCache_.empty())
1423                 const_cast<Buffer *>(this)->updateBibfilesCache();
1424
1425         return bibfilesCache_;
1426 }
1427
1428
1429 bool Buffer::isDepClean(string const & name) const
1430 {
1431         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1432         if (it == pimpl_->dep_clean.end())
1433                 return true;
1434         return it->second;
1435 }
1436
1437
1438 void Buffer::markDepClean(string const & name)
1439 {
1440         pimpl_->dep_clean[name] = true;
1441 }
1442
1443
1444 bool Buffer::dispatch(string const & command, bool * result)
1445 {
1446         return dispatch(lyxaction.lookupFunc(command), result);
1447 }
1448
1449
1450 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1451 {
1452         bool dispatched = true;
1453
1454         switch (func.action) {
1455                 case LFUN_BUFFER_EXPORT: {
1456                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1457                         if (result)
1458                                 *result = tmp;
1459                         break;
1460                 }
1461
1462                 default:
1463                         dispatched = false;
1464         }
1465         return dispatched;
1466 }
1467
1468
1469 void Buffer::changeLanguage(Language const * from, Language const * to)
1470 {
1471         BOOST_ASSERT(from);
1472         BOOST_ASSERT(to);
1473
1474         for_each(par_iterator_begin(),
1475                  par_iterator_end(),
1476                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1477
1478         text().current_font.setLanguage(to);
1479         text().real_current_font.setLanguage(to);
1480 }
1481
1482
1483 bool Buffer::isMultiLingual() const
1484 {
1485         ParConstIterator end = par_iterator_end();
1486         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1487                 if (it->isMultiLingual(params()))
1488                         return true;
1489
1490         return false;
1491 }
1492
1493
1494 ParIterator Buffer::getParFromID(int const id) const
1495 {
1496         ParConstIterator it = par_iterator_begin();
1497         ParConstIterator const end = par_iterator_end();
1498
1499         if (id < 0) {
1500                 // John says this is called with id == -1 from undo
1501                 lyxerr << "getParFromID(), id: " << id << endl;
1502                 return end;
1503         }
1504
1505         for (; it != end; ++it)
1506                 if (it->id() == id)
1507                         return it;
1508
1509         return end;
1510 }
1511
1512
1513 bool Buffer::hasParWithID(int const id) const
1514 {
1515         ParConstIterator const it = getParFromID(id);
1516         return it != par_iterator_end();
1517 }
1518
1519
1520 ParIterator Buffer::par_iterator_begin()
1521 {
1522         return lyx::par_iterator_begin(inset());
1523 }
1524
1525
1526 ParIterator Buffer::par_iterator_end()
1527 {
1528         return lyx::par_iterator_end(inset());
1529 }
1530
1531
1532 ParConstIterator Buffer::par_iterator_begin() const
1533 {
1534         return lyx::par_const_iterator_begin(inset());
1535 }
1536
1537
1538 ParConstIterator Buffer::par_iterator_end() const
1539 {
1540         return lyx::par_const_iterator_end(inset());
1541 }
1542
1543
1544 Language const * Buffer::getLanguage() const
1545 {
1546         return params().language;
1547 }
1548
1549
1550 docstring const Buffer::B_(string const & l10n) const
1551 {
1552         return params().B_(l10n);
1553 }
1554
1555
1556 bool Buffer::isClean() const
1557 {
1558         return pimpl_->lyx_clean;
1559 }
1560
1561
1562 bool Buffer::isBakClean() const
1563 {
1564         return pimpl_->bak_clean;
1565 }
1566
1567
1568 bool Buffer::isExternallyModified(CheckMethod method) const
1569 {
1570         BOOST_ASSERT(fs::exists(pimpl_->filename.toFilesystemEncoding()));
1571         // if method == timestamp, check timestamp before checksum
1572         return (method == checksum_method 
1573                 || pimpl_->timestamp_ != fs::last_write_time(pimpl_->filename.toFilesystemEncoding()))
1574                 && pimpl_->checksum_ != sum(pimpl_->filename);
1575 }
1576
1577
1578 void Buffer::markClean() const
1579 {
1580         if (!pimpl_->lyx_clean) {
1581                 pimpl_->lyx_clean = true;
1582                 updateTitles();
1583         }
1584         // if the .lyx file has been saved, we don't need an
1585         // autosave
1586         pimpl_->bak_clean = true;
1587 }
1588
1589
1590 void Buffer::markBakClean()
1591 {
1592         pimpl_->bak_clean = true;
1593 }
1594
1595
1596 void Buffer::setUnnamed(bool flag)
1597 {
1598         pimpl_->unnamed = flag;
1599 }
1600
1601
1602 bool Buffer::isUnnamed() const
1603 {
1604         return pimpl_->unnamed;
1605 }
1606
1607
1608 // FIXME: this function should be moved to buffer_pimpl.C
1609 void Buffer::markDirty()
1610 {
1611         if (pimpl_->lyx_clean) {
1612                 pimpl_->lyx_clean = false;
1613                 updateTitles();
1614         }
1615         pimpl_->bak_clean = false;
1616
1617         DepClean::iterator it = pimpl_->dep_clean.begin();
1618         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1619
1620         for (; it != end; ++it)
1621                 it->second = false;
1622 }
1623
1624
1625 string const Buffer::fileName() const
1626 {
1627         return pimpl_->filename.absFilename();
1628 }
1629
1630
1631 string const & Buffer::filePath() const
1632 {
1633         return params().filepath;
1634 }
1635
1636
1637 bool Buffer::isReadonly() const
1638 {
1639         return pimpl_->read_only;
1640 }
1641
1642
1643 void Buffer::setParentName(string const & name)
1644 {
1645         if (name == pimpl_->filename.absFilename())
1646                 // Avoids recursive include.
1647                 params().parentname.clear();
1648         else
1649                 params().parentname = name;
1650 }
1651
1652
1653 Buffer const * Buffer::getMasterBuffer() const
1654 {
1655         if (!params().parentname.empty()
1656             && theBufferList().exists(params().parentname)) {
1657                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1658                 //We need to check if the parent is us...
1659                 //FIXME RECURSIVE INCLUDE
1660                 //This is not sufficient, since recursive includes could be downstream.
1661                 if (buf && buf != this)
1662                         return buf->getMasterBuffer();
1663         }
1664
1665         return this;
1666 }
1667
1668
1669 Buffer * Buffer::getMasterBuffer()
1670 {
1671         if (!params().parentname.empty()
1672             && theBufferList().exists(params().parentname)) {
1673                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1674                 if (buf)
1675                         return buf->getMasterBuffer();
1676         }
1677
1678         return this;
1679 }
1680
1681
1682 MacroData const & Buffer::getMacro(docstring const & name) const
1683 {
1684         return pimpl_->macros.get(name);
1685 }
1686
1687
1688 bool Buffer::hasMacro(docstring const & name) const
1689 {
1690         return pimpl_->macros.has(name);
1691 }
1692
1693
1694 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1695 {
1696         MacroTable::globalMacros().insert(name, data);
1697         pimpl_->macros.insert(name, data);
1698 }
1699
1700
1701 void Buffer::buildMacros()
1702 {
1703         // Start with global table.
1704         pimpl_->macros = MacroTable::globalMacros();
1705
1706         // Now add our own.
1707         ParagraphList const & pars = text().paragraphs();
1708         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1709                 //lyxerr << "searching main par " << i
1710                 //      << " for macro definitions" << std::endl;
1711                 InsetList const & insets = pars[i].insetlist;
1712                 InsetList::const_iterator it = insets.begin();
1713                 InsetList::const_iterator end = insets.end();
1714                 for ( ; it != end; ++it) {
1715                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1716                         if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1717                                 MathMacroTemplate const & mac
1718                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1719                                 insertMacro(mac.name(), mac.asMacroData());
1720                         }
1721                 }
1722         }
1723 }
1724
1725
1726 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1727         Inset::Code code)
1728 {
1729         //FIXME: This does not work for child documents yet.
1730         BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1731         // Check if the label 'from' appears more than once
1732         vector<docstring> labels;
1733
1734         if (code == Inset::CITE_CODE) {
1735                 BiblioInfo keys;
1736                 keys.fillWithBibKeys(this);
1737                 BiblioInfo::const_iterator bit  = keys.begin();
1738                 BiblioInfo::const_iterator bend = keys.end();
1739
1740                 for (; bit != bend; ++bit)
1741                         // FIXME UNICODE
1742                         labels.push_back(bit->first);
1743         } else
1744                 getLabelList(labels);
1745
1746         if (std::count(labels.begin(), labels.end(), from) > 1)
1747                 return;
1748
1749         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1750                 if (it->lyxCode() == code) {
1751                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1752                         inset.replaceContents(to_utf8(from), to_utf8(to));
1753                 }
1754         }
1755 }
1756
1757
1758 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1759         pit_type par_end, bool full_source)
1760 {
1761         OutputParams runparams(&params().encoding());
1762         runparams.nice = true;
1763         runparams.flavor = OutputParams::LATEX;
1764         runparams.linelen = lyxrc.plaintext_linelen;
1765         // No side effect of file copying and image conversion
1766         runparams.dryrun = true;
1767
1768         texrow().reset();
1769         if (full_source) {
1770                 os << "% " << _("Preview source code") << "\n\n";
1771                 texrow().newline();
1772                 texrow().newline();
1773                 if (isLatex())
1774                         writeLaTeXSource(os, filePath(), runparams, true, true);
1775                 else {
1776                         writeDocBookSource(os, fileName(), runparams, false);
1777                 }
1778         } else {
1779                 runparams.par_begin = par_begin;
1780                 runparams.par_end = par_end;
1781                 if (par_begin + 1 == par_end)
1782                         os << "% "
1783                            << bformat(_("Preview source code for paragraph %1$d"), par_begin)
1784                            << "\n\n";
1785                 else
1786                         os << "% "
1787                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1788                                         convert<docstring>(par_begin),
1789                                         convert<docstring>(par_end - 1))
1790                            << "\n\n";
1791                 texrow().newline();
1792                 texrow().newline();
1793                 // output paragraphs
1794                 if (isLatex()) {
1795                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1796                 } else {
1797                         // DocBook
1798                         docbookParagraphs(paragraphs(), *this, os, runparams);
1799                 }
1800         }
1801 }
1802
1803
1804 ErrorList const & Buffer::errorList(string const & type) const
1805 {
1806         static ErrorList const emptyErrorList;
1807         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1808         if (I == pimpl_->errorLists.end())
1809                 return emptyErrorList;
1810
1811         return I->second;
1812 }
1813
1814
1815 ErrorList & Buffer::errorList(string const & type)
1816 {
1817         return pimpl_->errorLists[type];
1818 }
1819
1820
1821 } // namespace lyx