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