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