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