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