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