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