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