]> git.lyx.org Git - lyx.git/blob - src/Buffer.cpp
Prepare code for refactorisation
[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/lyxlib.h"
72 #include "support/os.h"
73 #include "support/Path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
76
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
83
84 #if defined (HAVE_UTIME_H)
85 #include <utime.h>
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
88 #endif
89
90 #include <iomanip>
91 #include <stack>
92 #include <sstream>
93 #include <fstream>
94
95 using std::endl;
96 using std::for_each;
97 using std::make_pair;
98
99 using std::ios;
100 using std::map;
101 using std::ostream;
102 using std::ostringstream;
103 using std::ofstream;
104 using std::pair;
105 using std::stack;
106 using std::vector;
107 using std::string;
108
109
110 namespace lyx {
111
112 using support::addName;
113 using support::bformat;
114 using support::changeExtension;
115 using support::cmd_ret;
116 using support::createBufferTmpDir;
117 using support::destroyDir;
118 using support::FileName;
119 using support::getFormatFromContents;
120 using support::libFileSearch;
121 using support::latex_path;
122 using support::ltrim;
123 using support::makeAbsPath;
124 using support::makeDisplayPath;
125 using support::makeLatexName;
126 using support::onlyFilename;
127 using support::onlyPath;
128 using support::quoteName;
129 using support::removeAutosaveFile;
130 using support::rename;
131 using support::runCommand;
132 using support::split;
133 using support::subst;
134 using support::tempName;
135 using support::trim;
136
137 namespace Alert = frontend::Alert;
138 namespace os = support::os;
139 namespace fs = boost::filesystem;
140 namespace io = boost::iostreams;
141
142 namespace {
143
144 int const LYX_FORMAT = 276;
145
146 } // namespace anon
147
148
149 typedef std::map<string, bool> DepClean;
150
151 class Buffer::Impl
152 {
153 public:
154         Impl(Buffer & parent, FileName const & file, bool readonly);
155
156         limited_stack<Undo> undostack;
157         limited_stack<Undo> redostack;
158         BufferParams params;
159         LyXVC lyxvc;
160         string temppath;
161         TexRow texrow;
162
163         /// need to regenerate .tex?
164         DepClean dep_clean;
165
166         /// is save needed?
167         mutable bool lyx_clean;
168
169         /// is autosave needed?
170         mutable bool bak_clean;
171
172         /// is this a unnamed file (New...)?
173         bool unnamed;
174
175         /// buffer is r/o
176         bool read_only;
177
178         /// name of the file the buffer is associated with.
179         FileName filename;
180
181         /** Set to true only when the file is fully loaded.
182          *  Used to prevent the premature generation of previews
183          *  and by the citation inset.
184          */
185         bool file_fully_loaded;
186
187         /// our Text that should be wrapped in an InsetText
188         InsetText inset;
189
190         ///
191         MacroTable macros;
192
193         ///
194         TocBackend toc_backend;
195
196         /// Container for all sort of Buffer dependant errors.
197         map<string, ErrorList> errorLists;
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)
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         return success;
762 }
763
764
765 // Should probably be moved to somewhere else: BufferView? LyXView?
766 bool Buffer::save() const
767 {
768         // We don't need autosaves in the immediate future. (Asger)
769         resetAutosaveTimers();
770
771         string const encodedFilename = pimpl_->filename.toFilesystemEncoding();
772
773         FileName backupName;
774         bool madeBackup = false;
775
776         // make a backup if the file already exists
777         if (lyxrc.make_backup && fs::exists(encodedFilename)) {
778                 backupName = FileName(fileName() + '~');
779                 if (!lyxrc.backupdir_path.empty())
780                         backupName = FileName(addName(lyxrc.backupdir_path,
781                                               subst(os::internal_path(backupName.absFilename()), '/', '!')));
782
783                 try {
784                         fs::copy_file(encodedFilename, backupName.toFilesystemEncoding(), false);
785                         madeBackup = true;
786                 } catch (fs::filesystem_error const & fe) {
787                         Alert::error(_("Backup failure"),
788                                      bformat(_("Cannot create backup file %1$s.\n"
789                                                "Please check whether the directory exists and is writeable."),
790                                              from_utf8(backupName.absFilename())));
791                         LYXERR(Debug::DEBUG) << "Fs error: " << fe.what() << endl;
792                 }
793         }
794
795         if (writeFile(pimpl_->filename)) {
796                 markClean();
797                 removeAutosaveFile(fileName());
798                 return true;
799         } else {
800                 // Saving failed, so backup is not backup
801                 if (madeBackup)
802                         rename(backupName, pimpl_->filename);
803                 return false;
804         }
805 }
806
807
808 bool Buffer::writeFile(FileName const & fname) const
809 {
810         if (pimpl_->read_only && fname == pimpl_->filename)
811                 return false;
812
813         bool retval = false;
814
815         if (params().compressed) {
816                 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
817                 if (!ofs)
818                         return false;
819
820                 retval = write(ofs);
821         } else {
822                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
823                 if (!ofs)
824                         return false;
825
826                 retval = write(ofs);
827         }
828
829         return retval;
830 }
831
832
833 bool Buffer::write(ostream & ofs) const
834 {
835 #ifdef HAVE_LOCALE
836         // Use the standard "C" locale for file output.
837         ofs.imbue(std::locale::classic());
838 #endif
839
840         // The top of the file should not be written by params().
841
842         // write out a comment in the top of the file
843         ofs << "#LyX " << lyx_version
844             << " created this file. For more info see http://www.lyx.org/\n"
845             << "\\lyxformat " << LYX_FORMAT << "\n"
846             << "\\begin_document\n";
847
848
849         /// For each author, set 'used' to true if there is a change
850         /// by this author in the document; otherwise set it to 'false'.
851         AuthorList::Authors::const_iterator a_it = params().authors().begin();
852         AuthorList::Authors::const_iterator a_end = params().authors().end();
853         for (; a_it != a_end; ++a_it)
854                 a_it->second.used(false);
855
856         ParIterator const end = par_iterator_end();
857         ParIterator it = par_iterator_begin();
858         for ( ; it != end; ++it)
859                 it->checkAuthors(params().authors());
860
861         // now write out the buffer parameters.
862         ofs << "\\begin_header\n";
863         params().writeFile(ofs);
864         ofs << "\\end_header\n";
865
866         // write the text
867         ofs << "\n\\begin_body\n";
868         text().write(*this, ofs);
869         ofs << "\n\\end_body\n";
870
871         // Write marker that shows file is complete
872         ofs << "\\end_document" << endl;
873
874         // Shouldn't really be needed....
875         //ofs.close();
876
877         // how to check if close went ok?
878         // Following is an attempt... (BE 20001011)
879
880         // good() returns false if any error occured, including some
881         //        formatting error.
882         // bad()  returns true if something bad happened in the buffer,
883         //        which should include file system full errors.
884
885         bool status = true;
886         if (!ofs) {
887                 status = false;
888                 lyxerr << "File was not closed properly." << endl;
889         }
890
891         return status;
892 }
893
894
895 bool Buffer::makeLaTeXFile(FileName const & fname,
896                            string const & original_path,
897                            OutputParams const & runparams,
898                            bool output_preamble, bool output_body)
899 {
900         string const encoding = runparams.encoding->iconvName();
901         LYXERR(Debug::LATEX) << "makeLaTeXFile encoding: "
902                 << encoding << "..." << endl;
903
904         odocfstream ofs(encoding);
905         if (!openFileWrite(ofs, fname))
906                 return false;
907
908         bool failed_export = false;
909         try {
910                 writeLaTeXSource(ofs, original_path,
911                       runparams, output_preamble, output_body);
912         }
913         catch (iconv_codecvt_facet_exception & e) {
914                 lyxerr << "Caught iconv exception: " << e.what() << endl;
915                 failed_export = true;
916         }
917         catch (std::exception  const & e) {
918                 lyxerr << "Caught \"normal\" exception: " << e.what() << endl;
919                 failed_export = true;
920         }
921         catch (...) {
922                 lyxerr << "Caught some really weird exception..." << endl;
923                 LyX::cref().emergencyCleanup();
924                 abort();
925         }
926
927         ofs.close();
928         if (ofs.fail()) {
929                 failed_export = true;
930                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
931         }
932
933         if (failed_export) {
934                 Alert::error(_("Encoding error"),
935                         _("Some characters of your document are probably not "
936                         "representable in the chosen encoding.\n"
937                         "Changing the document encoding to utf8 could help."));
938                 return false;
939         }
940         return true;
941 }
942
943
944 void Buffer::writeLaTeXSource(odocstream & os,
945                            string const & original_path,
946                            OutputParams const & runparams_in,
947                            bool const output_preamble, bool const output_body)
948 {
949         OutputParams runparams = runparams_in;
950
951         // validate the buffer.
952         LYXERR(Debug::LATEX) << "  Validating buffer..." << endl;
953         LaTeXFeatures features(*this, params(), runparams);
954         validate(features);
955         LYXERR(Debug::LATEX) << "  Buffer validation done." << endl;
956
957         texrow().reset();
958
959         // The starting paragraph of the coming rows is the
960         // first paragraph of the document. (Asger)
961         texrow().start(paragraphs().begin()->id(), 0);
962
963         if (output_preamble && runparams.nice) {
964                 os << "%% LyX " << lyx_version << " created this file.  "
965                         "For more info, see http://www.lyx.org/.\n"
966                         "%% Do not edit unless you really know what "
967                         "you are doing.\n";
968                 texrow().newline();
969                 texrow().newline();
970         }
971         LYXERR(Debug::INFO) << "lyx document header finished" << endl;
972         // There are a few differences between nice LaTeX and usual files:
973         // usual is \batchmode and has a
974         // special input@path to allow the including of figures
975         // with either \input or \includegraphics (what figinsets do).
976         // input@path is set when the actual parameter
977         // original_path is set. This is done for usual tex-file, but not
978         // for nice-latex-file. (Matthias 250696)
979         // Note that input@path is only needed for something the user does
980         // in the preamble, included .tex files or ERT, files included by
981         // LyX work without it.
982         if (output_preamble) {
983                 if (!runparams.nice) {
984                         // code for usual, NOT nice-latex-file
985                         os << "\\batchmode\n"; // changed
986                         // from \nonstopmode
987                         texrow().newline();
988                 }
989                 if (!original_path.empty()) {
990                         // FIXME UNICODE
991                         // We don't know the encoding of inputpath
992                         docstring const inputpath = from_utf8(latex_path(original_path));
993                         os << "\\makeatletter\n"
994                            << "\\def\\input@path{{"
995                            << inputpath << "/}}\n"
996                            << "\\makeatother\n";
997                         texrow().newline();
998                         texrow().newline();
999                         texrow().newline();
1000                 }
1001
1002                 // Write the preamble
1003                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
1004
1005                 if (!output_body)
1006                         return;
1007
1008                 // make the body.
1009                 os << "\\begin{document}\n";
1010                 texrow().newline();
1011         } // output_preamble
1012         LYXERR(Debug::INFO) << "preamble finished, now the body." << endl;
1013
1014         if (!lyxrc.language_auto_begin &&
1015             !params().language->babel().empty()) {
1016                 // FIXME UNICODE
1017                 os << from_utf8(subst(lyxrc.language_command_begin,
1018                                            "$$lang",
1019                                            params().language->babel()))
1020                    << '\n';
1021                 texrow().newline();
1022         }
1023
1024         Encoding const & encoding = params().encoding();
1025         if (encoding.package() == Encoding::CJK) {
1026                 // Open a CJK environment, since in contrast to the encodings
1027                 // handled by inputenc the document encoding is not set in
1028                 // the preamble if it is handled by CJK.sty.
1029                 os << "\\begin{CJK}{" << from_ascii(encoding.latexName())
1030                    << "}{}\n";
1031                 texrow().newline();
1032         }
1033
1034         // if we are doing a real file with body, even if this is the
1035         // child of some other buffer, let's cut the link here.
1036         // This happens for example if only a child document is printed.
1037         string save_parentname;
1038         if (output_preamble) {
1039                 save_parentname = params().parentname;
1040                 params().parentname.erase();
1041         }
1042
1043         // the real stuff
1044         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1045
1046         // Restore the parenthood if needed
1047         if (output_preamble)
1048                 params().parentname = save_parentname;
1049
1050         // add this just in case after all the paragraphs
1051         os << endl;
1052         texrow().newline();
1053
1054         if (encoding.package() == Encoding::CJK) {
1055                 // Close the open CJK environment.
1056                 // latexParagraphs will have opened one even if the last text
1057                 // was not CJK.
1058                 os << "\\end{CJK}\n";
1059                 texrow().newline();
1060         }
1061
1062         if (!lyxrc.language_auto_end &&
1063             !params().language->babel().empty()) {
1064                 os << from_utf8(subst(lyxrc.language_command_end,
1065                                            "$$lang",
1066                                            params().language->babel()))
1067                    << '\n';
1068                 texrow().newline();
1069         }
1070
1071         if (output_preamble) {
1072                 os << "\\end{document}\n";
1073                 texrow().newline();
1074
1075                 LYXERR(Debug::LATEX) << "makeLaTeXFile...done" << endl;
1076         } else {
1077                 LYXERR(Debug::LATEX) << "LaTeXFile for inclusion made."
1078                                      << endl;
1079         }
1080         runparams_in.encoding = runparams.encoding;
1081
1082         // Just to be sure. (Asger)
1083         texrow().newline();
1084
1085         LYXERR(Debug::INFO) << "Finished making LaTeX file." << endl;
1086         LYXERR(Debug::INFO) << "Row count was " << texrow().rows() - 1
1087                             << '.' << endl;
1088 }
1089
1090
1091 bool Buffer::isLatex() const
1092 {
1093         return params().getTextClass().outputType() == LATEX;
1094 }
1095
1096
1097 bool Buffer::isLiterate() const
1098 {
1099         return params().getTextClass().outputType() == LITERATE;
1100 }
1101
1102
1103 bool Buffer::isDocBook() const
1104 {
1105         return params().getTextClass().outputType() == DOCBOOK;
1106 }
1107
1108
1109 void Buffer::makeDocBookFile(FileName const & fname,
1110                               OutputParams const & runparams,
1111                               bool const body_only)
1112 {
1113         LYXERR(Debug::LATEX) << "makeDocBookFile..." << endl;
1114
1115         //ofstream ofs;
1116         odocfstream ofs;
1117         if (!openFileWrite(ofs, fname))
1118                 return;
1119
1120         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1121
1122         ofs.close();
1123         if (ofs.fail())
1124                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1125 }
1126
1127
1128 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1129                              OutputParams const & runparams,
1130                              bool const only_body)
1131 {
1132         LaTeXFeatures features(*this, params(), runparams);
1133         validate(features);
1134
1135         texrow().reset();
1136
1137         TextClass const & tclass = params().getTextClass();
1138         string const top_element = tclass.latexname();
1139
1140         if (!only_body) {
1141                 if (runparams.flavor == OutputParams::XML)
1142                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1143
1144                 // FIXME UNICODE
1145                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1146
1147                 // FIXME UNICODE
1148                 if (! tclass.class_header().empty())
1149                         os << from_ascii(tclass.class_header());
1150                 else if (runparams.flavor == OutputParams::XML)
1151                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1152                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1153                 else
1154                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1155
1156                 docstring preamble = from_utf8(params().preamble);
1157                 if (runparams.flavor != OutputParams::XML ) {
1158                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1159                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1160                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1161                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1162                 }
1163
1164                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1165                          : fname;
1166                 preamble += features.getIncludedFiles(name);
1167                 preamble += features.getLyXSGMLEntities();
1168
1169                 if (!preamble.empty()) {
1170                         os << "\n [ " << preamble << " ]";
1171                 }
1172                 os << ">\n\n";
1173         }
1174
1175         string top = top_element;
1176         top += " lang=\"";
1177         if (runparams.flavor == OutputParams::XML)
1178                 top += params().language->code();
1179         else
1180                 top += params().language->code().substr(0,2);
1181         top += '"';
1182
1183         if (!params().options.empty()) {
1184                 top += ' ';
1185                 top += params().options;
1186         }
1187
1188         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1189             << " file was created by LyX " << lyx_version
1190             << "\n  See http://www.lyx.org/ for more information -->\n";
1191
1192         params().getTextClass().counters().reset();
1193
1194         sgml::openTag(os, top);
1195         os << '\n';
1196         docbookParagraphs(paragraphs(), *this, os, runparams);
1197         sgml::closeTag(os, top_element);
1198 }
1199
1200
1201 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1202 // Other flags: -wall -v0 -x
1203 int Buffer::runChktex()
1204 {
1205         busy(true);
1206
1207         // get LaTeX-Filename
1208         FileName const path(temppath());
1209         string const name = addName(path.absFilename(), getLatexName());
1210         string const org_path = filePath();
1211
1212         support::Path p(path); // path to LaTeX file
1213         message(_("Running chktex..."));
1214
1215         // Generate the LaTeX file if neccessary
1216         OutputParams runparams(&params().encoding());
1217         runparams.flavor = OutputParams::LATEX;
1218         runparams.nice = false;
1219         makeLaTeXFile(FileName(name), org_path, runparams);
1220
1221         TeXErrors terr;
1222         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1223         int const res = chktex.run(terr); // run chktex
1224
1225         if (res == -1) {
1226                 Alert::error(_("chktex failure"),
1227                              _("Could not run chktex successfully."));
1228         } else if (res > 0) {
1229                 ErrorList & errorList = pimpl_->errorLists["ChkTeX"];
1230                 // Clear out old errors
1231                 errorList.clear();
1232                 // Fill-in the error list with the TeX errors
1233                 bufferErrors(*this, terr, errorList);
1234         }
1235
1236         busy(false);
1237
1238         errors("ChkTeX");
1239
1240         return res;
1241 }
1242
1243
1244 void Buffer::validate(LaTeXFeatures & features) const
1245 {
1246         TextClass const & tclass = params().getTextClass();
1247
1248         if (params().outputChanges) {
1249                 bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
1250                 bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
1251                                   LaTeXFeatures::isAvailable("xcolor");
1252
1253                 if (features.runparams().flavor == OutputParams::LATEX) {
1254                         if (dvipost) {
1255                                 features.require("ct-dvipost");
1256                                 features.require("dvipost");
1257                         } else if (xcolorsoul) {
1258                                 features.require("ct-xcolor-soul");
1259                                 features.require("soul");
1260                                 features.require("xcolor");
1261                         } else {
1262                                 features.require("ct-none");
1263                         }
1264                 } else if (features.runparams().flavor == OutputParams::PDFLATEX ) {
1265                         if (xcolorsoul) {
1266                                 features.require("ct-xcolor-soul");
1267                                 features.require("soul");
1268                                 features.require("xcolor");
1269                                 features.require("pdfcolmk"); // improves color handling in PDF output
1270                         } else {
1271                                 features.require("ct-none");
1272                         }
1273                 }
1274         }
1275
1276         // AMS Style is at document level
1277         if (params().use_amsmath == BufferParams::package_on
1278             || tclass.provides("amsmath"))
1279                 features.require("amsmath");
1280         if (params().use_esint == BufferParams::package_on)
1281                 features.require("esint");
1282
1283         for_each(paragraphs().begin(), paragraphs().end(),
1284                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1285
1286         // the bullet shapes are buffer level not paragraph level
1287         // so they are tested here
1288         for (int i = 0; i < 4; ++i) {
1289                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1290                         int const font = params().user_defined_bullet(i).getFont();
1291                         if (font == 0) {
1292                                 int const c = params()
1293                                         .user_defined_bullet(i)
1294                                         .getCharacter();
1295                                 if (c == 16
1296                                    || c == 17
1297                                    || c == 25
1298                                    || c == 26
1299                                    || c == 31) {
1300                                         features.require("latexsym");
1301                                 }
1302                         } else if (font == 1) {
1303                                 features.require("amssymb");
1304                         } else if ((font >= 2 && font <= 5)) {
1305                                 features.require("pifont");
1306                         }
1307                 }
1308         }
1309
1310         if (lyxerr.debugging(Debug::LATEX)) {
1311                 features.showStruct();
1312         }
1313 }
1314
1315
1316 void Buffer::getLabelList(vector<docstring> & list) const
1317 {
1318         /// if this is a child document and the parent is already loaded
1319         /// Use the parent's list instead  [ale990407]
1320         Buffer const * tmp = getMasterBuffer();
1321         if (!tmp) {
1322                 lyxerr << "getMasterBuffer() failed!" << endl;
1323                 BOOST_ASSERT(tmp);
1324         }
1325         if (tmp != this) {
1326                 tmp->getLabelList(list);
1327                 return;
1328         }
1329
1330         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1331                 it.nextInset()->getLabelList(*this, list);
1332 }
1333
1334
1335 // This is also a buffer property (ale)
1336 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1337         const
1338 {
1339         /// if this is a child document and the parent is already loaded
1340         /// use the parent's list instead  [ale990412]
1341         Buffer const * tmp = getMasterBuffer();
1342         BOOST_ASSERT(tmp);
1343         if (tmp != this) {
1344                 tmp->fillWithBibKeys(keys);
1345                 return;
1346         }
1347
1348         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1349                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1350                         InsetBibtex const & inset =
1351                                 static_cast<InsetBibtex const &>(*it);
1352                         inset.fillWithBibKeys(*this, keys);
1353                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1354                         InsetInclude const & inset =
1355                                 static_cast<InsetInclude const &>(*it);
1356                         inset.fillWithBibKeys(*this, keys);
1357                 } else if (it->lyxCode() == Inset::BIBITEM_CODE) {
1358                         InsetBibitem const & inset =
1359                                 static_cast<InsetBibitem const &>(*it);
1360                         // FIXME UNICODE
1361                         string const key = to_utf8(inset.getParam("key"));
1362                         docstring const label = inset.getParam("label");
1363                         DocIterator doc_it(it); doc_it.forwardPos();
1364                         docstring const ref = doc_it.paragraph().asString(*this, false);
1365                         docstring const info = label + "TheBibliographyRef" + ref;
1366                         keys.push_back(pair<string, docstring>(key, info));
1367                 }
1368         }
1369 }
1370
1371
1372 void Buffer::updateBibfilesCache()
1373 {
1374         // if this is a child document and the parent is already loaded
1375         // update the parent's cache instead
1376         Buffer * tmp = getMasterBuffer();
1377         BOOST_ASSERT(tmp);
1378         if (tmp != this) {
1379                 tmp->updateBibfilesCache();
1380                 return;
1381         }
1382
1383         bibfilesCache_.clear();
1384         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1385                 if (it->lyxCode() == Inset::BIBTEX_CODE) {
1386                         InsetBibtex const & inset =
1387                                 static_cast<InsetBibtex const &>(*it);
1388                         vector<FileName> const bibfiles = inset.getFiles(*this);
1389                         bibfilesCache_.insert(bibfilesCache_.end(),
1390                                 bibfiles.begin(),
1391                                 bibfiles.end());
1392                 } else if (it->lyxCode() == Inset::INCLUDE_CODE) {
1393                         InsetInclude & inset =
1394                                 static_cast<InsetInclude &>(*it);
1395                         inset.updateBibfilesCache(*this);
1396                         vector<FileName> const & bibfiles =
1397                                         inset.getBibfilesCache(*this);
1398                         bibfilesCache_.insert(bibfilesCache_.end(),
1399                                 bibfiles.begin(),
1400                                 bibfiles.end());
1401                 }
1402         }
1403 }
1404
1405
1406 vector<FileName> const & Buffer::getBibfilesCache() const
1407 {
1408         // if this is a child document and the parent is already loaded
1409         // use the parent's cache instead
1410         Buffer const * tmp = getMasterBuffer();
1411         BOOST_ASSERT(tmp);
1412         if (tmp != this)
1413                 return tmp->getBibfilesCache();
1414
1415         // We update the cache when first used instead of at loading time.
1416         if (bibfilesCache_.empty())
1417                 const_cast<Buffer *>(this)->updateBibfilesCache();
1418
1419         return bibfilesCache_;
1420 }
1421
1422
1423 bool Buffer::isDepClean(string const & name) const
1424 {
1425         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1426         if (it == pimpl_->dep_clean.end())
1427                 return true;
1428         return it->second;
1429 }
1430
1431
1432 void Buffer::markDepClean(string const & name)
1433 {
1434         pimpl_->dep_clean[name] = true;
1435 }
1436
1437
1438 bool Buffer::dispatch(string const & command, bool * result)
1439 {
1440         return dispatch(lyxaction.lookupFunc(command), result);
1441 }
1442
1443
1444 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1445 {
1446         bool dispatched = true;
1447
1448         switch (func.action) {
1449                 case LFUN_BUFFER_EXPORT: {
1450                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1451                         if (result)
1452                                 *result = tmp;
1453                         break;
1454                 }
1455
1456                 default:
1457                         dispatched = false;
1458         }
1459         return dispatched;
1460 }
1461
1462
1463 void Buffer::changeLanguage(Language const * from, Language const * to)
1464 {
1465         BOOST_ASSERT(from);
1466         BOOST_ASSERT(to);
1467
1468         for_each(par_iterator_begin(),
1469                  par_iterator_end(),
1470                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1471
1472         text().current_font.setLanguage(to);
1473         text().real_current_font.setLanguage(to);
1474 }
1475
1476
1477 bool Buffer::isMultiLingual() const
1478 {
1479         ParConstIterator end = par_iterator_end();
1480         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1481                 if (it->isMultiLingual(params()))
1482                         return true;
1483
1484         return false;
1485 }
1486
1487
1488 ParIterator Buffer::getParFromID(int const id) const
1489 {
1490         ParConstIterator it = par_iterator_begin();
1491         ParConstIterator const end = par_iterator_end();
1492
1493         if (id < 0) {
1494                 // John says this is called with id == -1 from undo
1495                 lyxerr << "getParFromID(), id: " << id << endl;
1496                 return end;
1497         }
1498
1499         for (; it != end; ++it)
1500                 if (it->id() == id)
1501                         return it;
1502
1503         return end;
1504 }
1505
1506
1507 bool Buffer::hasParWithID(int const id) const
1508 {
1509         ParConstIterator const it = getParFromID(id);
1510         return it != par_iterator_end();
1511 }
1512
1513
1514 ParIterator Buffer::par_iterator_begin()
1515 {
1516         return lyx::par_iterator_begin(inset());
1517 }
1518
1519
1520 ParIterator Buffer::par_iterator_end()
1521 {
1522         return lyx::par_iterator_end(inset());
1523 }
1524
1525
1526 ParConstIterator Buffer::par_iterator_begin() const
1527 {
1528         return lyx::par_const_iterator_begin(inset());
1529 }
1530
1531
1532 ParConstIterator Buffer::par_iterator_end() const
1533 {
1534         return lyx::par_const_iterator_end(inset());
1535 }
1536
1537
1538 Language const * Buffer::getLanguage() const
1539 {
1540         return params().language;
1541 }
1542
1543
1544 docstring const Buffer::B_(string const & l10n) const
1545 {
1546         return params().B_(l10n);
1547 }
1548
1549
1550 bool Buffer::isClean() const
1551 {
1552         return pimpl_->lyx_clean;
1553 }
1554
1555
1556 bool Buffer::isBakClean() const
1557 {
1558         return pimpl_->bak_clean;
1559 }
1560
1561
1562 void Buffer::markClean() const
1563 {
1564         if (!pimpl_->lyx_clean) {
1565                 pimpl_->lyx_clean = true;
1566                 updateTitles();
1567         }
1568         // if the .lyx file has been saved, we don't need an
1569         // autosave
1570         pimpl_->bak_clean = true;
1571 }
1572
1573
1574 void Buffer::markBakClean()
1575 {
1576         pimpl_->bak_clean = true;
1577 }
1578
1579
1580 void Buffer::setUnnamed(bool flag)
1581 {
1582         pimpl_->unnamed = flag;
1583 }
1584
1585
1586 bool Buffer::isUnnamed() const
1587 {
1588         return pimpl_->unnamed;
1589 }
1590
1591
1592 #ifdef WITH_WARNINGS
1593 #warning this function should be moved to buffer_pimpl.C
1594 #endif
1595 void Buffer::markDirty()
1596 {
1597         if (pimpl_->lyx_clean) {
1598                 pimpl_->lyx_clean = false;
1599                 updateTitles();
1600         }
1601         pimpl_->bak_clean = false;
1602
1603         DepClean::iterator it = pimpl_->dep_clean.begin();
1604         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1605
1606         for (; it != end; ++it)
1607                 it->second = false;
1608 }
1609
1610
1611 string const Buffer::fileName() const
1612 {
1613         return pimpl_->filename.absFilename();
1614 }
1615
1616
1617 string const & Buffer::filePath() const
1618 {
1619         return params().filepath;
1620 }
1621
1622
1623 bool Buffer::isReadonly() const
1624 {
1625         return pimpl_->read_only;
1626 }
1627
1628
1629 void Buffer::setParentName(string const & name)
1630 {
1631         if (name == pimpl_->filename.absFilename())
1632                 // Avoids recursive include.
1633                 params().parentname.clear();
1634         else
1635                 params().parentname = name;
1636 }
1637
1638
1639 Buffer const * Buffer::getMasterBuffer() const
1640 {
1641         if (!params().parentname.empty()
1642             && theBufferList().exists(params().parentname)) {
1643                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1644                 //We need to check if the parent is us...
1645                 //FIXME RECURSIVE INCLUDE
1646                 //This is not sufficient, since recursive includes could be downstream.
1647                 if (buf && buf != this)
1648                         return buf->getMasterBuffer();
1649         }
1650
1651         return this;
1652 }
1653
1654
1655 Buffer * Buffer::getMasterBuffer()
1656 {
1657         if (!params().parentname.empty()
1658             && theBufferList().exists(params().parentname)) {
1659                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1660                 if (buf)
1661                         return buf->getMasterBuffer();
1662         }
1663
1664         return this;
1665 }
1666
1667
1668 MacroData const & Buffer::getMacro(docstring const & name) const
1669 {
1670         return pimpl_->macros.get(name);
1671 }
1672
1673
1674 bool Buffer::hasMacro(docstring const & name) const
1675 {
1676         return pimpl_->macros.has(name);
1677 }
1678
1679
1680 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1681 {
1682         MacroTable::globalMacros().insert(name, data);
1683         pimpl_->macros.insert(name, data);
1684 }
1685
1686
1687 void Buffer::buildMacros()
1688 {
1689         // Start with global table.
1690         pimpl_->macros = MacroTable::globalMacros();
1691
1692         // Now add our own.
1693         ParagraphList const & pars = text().paragraphs();
1694         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1695                 //lyxerr << "searching main par " << i
1696                 //      << " for macro definitions" << std::endl;
1697                 InsetList const & insets = pars[i].insetlist;
1698                 InsetList::const_iterator it = insets.begin();
1699                 InsetList::const_iterator end = insets.end();
1700                 for ( ; it != end; ++it) {
1701                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1702                         if (it->inset->lyxCode() == Inset::MATHMACRO_CODE) {
1703                                 MathMacroTemplate const & mac
1704                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1705                                 insertMacro(mac.name(), mac.asMacroData());
1706                         }
1707                 }
1708         }
1709 }
1710
1711
1712 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1713 {
1714         cursor_ = cur;
1715         anchor_ = anc;
1716 }
1717
1718
1719 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1720         Inset::Code code)
1721 {
1722         //FIXME: This does not work for child documents yet.
1723         BOOST_ASSERT(code == Inset::CITE_CODE || code == Inset::REF_CODE);
1724         // Check if the label 'from' appears more than once
1725         vector<docstring> labels;
1726
1727         if (code == Inset::CITE_CODE) {
1728                 vector<pair<string, docstring> > keys;
1729                 fillWithBibKeys(keys);
1730                 vector<pair<string, docstring> >::const_iterator bit  = keys.begin();
1731                 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1732
1733                 for (; bit != bend; ++bit)
1734                         // FIXME UNICODE
1735                         labels.push_back(from_utf8(bit->first));
1736         } else
1737                 getLabelList(labels);
1738
1739         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1740                 return;
1741
1742         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1743                 if (it->lyxCode() == code) {
1744                         InsetCommand & inset = static_cast<InsetCommand &>(*it);
1745                         inset.replaceContents(to_utf8(from), to_utf8(to));
1746                 }
1747         }
1748 }
1749
1750
1751 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1752         pit_type par_end, bool full_source)
1753 {
1754         OutputParams runparams(&params().encoding());
1755         runparams.nice = true;
1756         runparams.flavor = OutputParams::LATEX;
1757         runparams.linelen = lyxrc.plaintext_linelen;
1758         // No side effect of file copying and image conversion
1759         runparams.dryrun = true;
1760
1761         if (full_source) {
1762                 os << "% " << _("Preview source code") << "\n\n";
1763                 if (isLatex())
1764                         writeLaTeXSource(os, filePath(), runparams, true, true);
1765                 else {
1766                         writeDocBookSource(os, fileName(), runparams, false);
1767                 }
1768         } else {
1769                 runparams.par_begin = par_begin;
1770                 runparams.par_end = par_end;
1771                 if (par_begin + 1 == par_end)
1772                         os << "% "
1773                            << bformat(_("Preview source code for paragraph %1$s"), par_begin)
1774                            << "\n\n";
1775                 else
1776                         os << "% "
1777                            << bformat(_("Preview source code from paragraph %1$s to %2$s"),
1778                                         convert<docstring>(par_begin),
1779                                         convert<docstring>(par_end - 1))
1780                            << "\n\n";
1781                 // output paragraphs
1782                 if (isLatex()) {
1783                         texrow().reset();
1784                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1785                 } else {
1786                         // DocBook
1787                         docbookParagraphs(paragraphs(), *this, os, runparams);
1788                 }
1789         }
1790 }
1791
1792
1793 ErrorList const & Buffer::errorList(string const & type) const
1794 {
1795         static ErrorList const emptyErrorList;
1796         std::map<string, ErrorList>::const_iterator I = pimpl_->errorLists.find(type);
1797         if (I == pimpl_->errorLists.end())
1798                 return emptyErrorList;
1799
1800         return I->second;
1801 }
1802
1803
1804 ErrorList & Buffer::errorList(string const & type)
1805 {
1806         return pimpl_->errorLists[type];
1807 }
1808
1809
1810 } // namespace lyx