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