]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Updates from Bennett and myself.
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "counters.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "debug.h"
24 #include "encoding.h"
25 #include "errorlist.h"
26 #include "exporter.h"
27 #include "format.h"
28 #include "funcrequest.h"
29 #include "gettext.h"
30 #include "insetiterator.h"
31 #include "language.h"
32 #include "LaTeX.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
35 #include "lyxlex.h"
36 #include "lyxtext.h"
37 #include "lyxrc.h"
38 #include "lyxvc.h"
39 #include "lyx_main.h"
40 #include "messages.h"
41 #include "output.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "paragraph.h"
45 #include "paragraph_funcs.h"
46 #include "ParagraphParameters.h"
47 #include "pariterator.h"
48 #include "sgml.h"
49 #include "texrow.h"
50 #include "TocBackend.h"
51 #include "undo.h"
52 #include "version.h"
53
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
58
59 #include "mathed/MathMacroTemplate.h"
60 #include "mathed/MathMacroTable.h"
61 #include "mathed/MathSupport.h"
62
63 #include "frontends/Alert.h"
64
65 #include "graphics/Previews.h"
66
67 #include "support/types.h"
68 #include "support/lyxalgo.h"
69 #include "support/filetools.h"
70 #include "support/fs_extras.h"
71 #include "support/lyxlib.h"
72 #include "support/os.h"
73 #include "support/path.h"
74 #include "support/textutils.h"
75 #include "support/convert.h"
76
77 #include <boost/iostreams/filtering_stream.hpp>
78 #include <boost/iostreams/filter/gzip.hpp>
79 #include <boost/iostreams/device/file.hpp>
80 #include <boost/bind.hpp>
81 #include <boost/filesystem/exception.hpp>
82 #include <boost/filesystem/operations.hpp>
83
84 #if defined (HAVE_UTIME_H)
85 #include <utime.h>
86 #elif defined (HAVE_SYS_UTIME_H)
87 #include <sys/utime.h>
88 #endif
89
90 #include <iomanip>
91 #include <stack>
92 #include <sstream>
93 #include <fstream>
94
95
96 namespace lyx {
97
98 using support::addName;
99 using support::bformat;
100 using support::changeExtension;
101 using support::cmd_ret;
102 using support::createBufferTmpDir;
103 using support::destroyDir;
104 using support::FileName;
105 using support::getFormatFromContents;
106 using support::isDirWriteable;
107 using support::libFileSearch;
108 using support::latex_path;
109 using support::ltrim;
110 using support::makeAbsPath;
111 using support::makeDisplayPath;
112 using support::makeLatexName;
113 using support::onlyFilename;
114 using support::onlyPath;
115 using support::quoteName;
116 using support::removeAutosaveFile;
117 using support::rename;
118 using support::runCommand;
119 using support::split;
120 using support::subst;
121 using support::tempName;
122 using support::trim;
123
124 namespace Alert = frontend::Alert;
125 namespace os = support::os;
126 namespace fs = boost::filesystem;
127 namespace io = boost::iostreams;
128
129 using std::endl;
130 using std::for_each;
131 using std::make_pair;
132
133 using std::ifstream;
134 using std::ios;
135 using std::map;
136 using std::ostream;
137 using std::ostringstream;
138 using std::ofstream;
139 using std::pair;
140 using std::stack;
141 using std::vector;
142 using std::string;
143
144
145 namespace {
146
147 int const LYX_FORMAT = 255;
148
149 } // namespace anon
150
151
152 typedef std::map<string, bool> DepClean;
153
154 class Buffer::Impl
155 {
156 public:
157         Impl(Buffer & parent, string const & file, bool readonly);
158
159         limited_stack<Undo> undostack;
160         limited_stack<Undo> redostack;
161         BufferParams params;
162         LyXVC lyxvc;
163         string temppath;
164         TexRow texrow;
165
166         /// need to regenerate .tex?
167         DepClean dep_clean;
168
169         /// is save needed?
170         mutable bool lyx_clean;
171
172         /// is autosave needed?
173         mutable bool bak_clean;
174
175         /// is this a unnamed file (New...)?
176         bool unnamed;
177
178         /// buffer is r/o
179         bool read_only;
180
181         /// name of the file the buffer is associated with.
182         string filename;
183
184         boost::scoped_ptr<Messages> messages;
185
186         /** Set to true only when the file is fully loaded.
187          *  Used to prevent the premature generation of previews
188          *  and by the citation inset.
189          */
190         bool file_fully_loaded;
191
192         /// our LyXText that should be wrapped in an InsetText
193         InsetText inset;
194
195         ///
196         MacroTable macros;
197
198         ///
199         TocBackend toc_backend;
200 };
201
202
203 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
204         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
205           filename(file), file_fully_loaded(false), inset(params),
206           toc_backend(&parent)
207 {
208         inset.setAutoBreakRows(true);
209         lyxvc.buffer(&parent);
210         temppath = createBufferTmpDir();
211         params.filepath = onlyPath(file);
212         // FIXME: And now do something if temppath == string(), because we
213         // assume from now on that temppath points to a valid temp dir.
214         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
215 }
216
217
218 Buffer::Buffer(string const & file, bool readonly)
219         : pimpl_(new Impl(*this, file, readonly))
220 {
221         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
222 }
223
224
225 Buffer::~Buffer()
226 {
227         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
228         // here the buffer should take care that it is
229         // saved properly, before it goes into the void.
230
231         closing();
232
233         if (!temppath().empty() && !destroyDir(temppath())) {
234                 Alert::warning(_("Could not remove temporary directory"),
235                         bformat(_("Could not remove the temporary directory %1$s"),
236                         from_utf8(temppath())));
237         }
238
239         // Remove any previewed LaTeX snippets associated with this buffer.
240         graphics::Previews::get().removeLoader(*this);
241 }
242
243
244 LyXText & Buffer::text() const
245 {
246         return const_cast<LyXText &>(pimpl_->inset.text_);
247 }
248
249
250 InsetBase & Buffer::inset() const
251 {
252         return const_cast<InsetText &>(pimpl_->inset);
253 }
254
255
256 limited_stack<Undo> & Buffer::undostack()
257 {
258         return pimpl_->undostack;
259 }
260
261
262 limited_stack<Undo> const & Buffer::undostack() const
263 {
264         return pimpl_->undostack;
265 }
266
267
268 limited_stack<Undo> & Buffer::redostack()
269 {
270         return pimpl_->redostack;
271 }
272
273
274 limited_stack<Undo> const & Buffer::redostack() const
275 {
276         return pimpl_->redostack;
277 }
278
279
280 BufferParams & Buffer::params()
281 {
282         return pimpl_->params;
283 }
284
285
286 BufferParams const & Buffer::params() const
287 {
288         return pimpl_->params;
289 }
290
291
292 ParagraphList & Buffer::paragraphs()
293 {
294         return text().paragraphs();
295 }
296
297
298 ParagraphList const & Buffer::paragraphs() const
299 {
300         return text().paragraphs();
301 }
302
303
304 LyXVC & Buffer::lyxvc()
305 {
306         return pimpl_->lyxvc;
307 }
308
309
310 LyXVC const & Buffer::lyxvc() const
311 {
312         return pimpl_->lyxvc;
313 }
314
315
316 string const & Buffer::temppath() const
317 {
318         return pimpl_->temppath;
319 }
320
321
322 TexRow & Buffer::texrow()
323 {
324         return pimpl_->texrow;
325 }
326
327
328 TexRow const & Buffer::texrow() const
329 {
330         return pimpl_->texrow;
331 }
332
333
334 TocBackend & Buffer::tocBackend()
335 {
336         return pimpl_->toc_backend;
337 }
338
339
340 TocBackend const & Buffer::tocBackend() const
341 {
342         return pimpl_->toc_backend;
343 }
344
345
346 string const Buffer::getLatexName(bool const no_path) const
347 {
348         string const name = changeExtension(makeLatexName(fileName()), ".tex");
349         return no_path ? onlyFilename(name) : name;
350 }
351
352
353 pair<Buffer::LogType, string> const Buffer::getLogName() const
354 {
355         string const filename = getLatexName(false);
356
357         if (filename.empty())
358                 return make_pair(Buffer::latexlog, string());
359
360         string const path = temppath();
361
362         string const fname = addName(path,
363                                      onlyFilename(changeExtension(filename,
364                                                                   ".log")));
365         string const bname =
366                 addName(path, onlyFilename(
367                         changeExtension(filename,
368                                         formats.extension("literate") + ".out")));
369
370         // If no Latex log or Build log is newer, show Build log
371
372         if (fs::exists(bname) &&
373             (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
374                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
375                 return make_pair(Buffer::buildlog, bname);
376         }
377         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
378         return make_pair(Buffer::latexlog, fname);
379 }
380
381
382 void Buffer::setReadonly(bool const flag)
383 {
384         if (pimpl_->read_only != flag) {
385                 pimpl_->read_only = flag;
386                 readonly(flag);
387         }
388 }
389
390
391 void Buffer::setFileName(string const & newfile)
392 {
393         pimpl_->filename = makeAbsPath(newfile);
394         params().filepath = onlyPath(pimpl_->filename);
395         setReadonly(fs::is_readonly(pimpl_->filename));
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
720         string s;
721         if (lyxrc.make_backup) {
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(fileName(), 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(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), FileName(fileName()));
751                 return false;
752         }
753         return true;
754 }
755
756
757 bool Buffer::writeFile(string const & fname) const
758 {
759         if (pimpl_->read_only && fname == 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));
766                 if (!ofs)
767                         return false;
768
769                 retval = do_writeFile(ofs);
770         } else {
771                 ofstream ofs(fname.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(string const & fname,
832                            string const & original_path,
833                            OutputParams const & runparams,
834                            bool output_preamble, bool output_body)
835 {
836         string encoding;
837         if (params().inputenc == "auto")
838                 encoding = params().language->encoding()->iconvName();
839         else {
840                 Encoding const * enc = encodings.getFromLaTeXName(params().inputenc);
841                 if (enc)
842                         encoding = enc->iconvName();
843                 else {
844                         lyxerr << "Unknown inputenc value `"
845                                << params().inputenc
846                                << "'. Using `auto' instead." << endl;
847                         encoding = params().language->encoding()->iconvName();
848                 }
849         }
850         lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
851                 << encoding << "..." << endl;
852
853         odocfstream ofs(encoding);
854         if (!openFileWrite(ofs, fname))
855                 return false;
856
857         try {
858                 writeLaTeXSource(ofs, original_path,
859                       runparams, output_preamble, output_body);
860         }
861         catch (iconv_codecvt_facet_exception &) {
862                 Alert::error(_("Encoding error"),
863                         _("Some characters of your document are not "
864                           "representable in the chosen encoding.\n"
865                           "Changing the document encoding to utf8 could help."));
866                 return false;
867         }
868
869         ofs.close();
870         if (ofs.fail()) {
871                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
872                 Alert::error(_("Error closing file"),
873                         _("The output file could not be closed properly.\n"
874                           " Probably some characters of your document are not "
875                           "representable in the chosen encoding.\n"
876                           "Changing the document encoding to utf8 could help."));
877                 return false;
878         }
879         return true;
880 }
881
882
883 void Buffer::writeLaTeXSource(odocstream & os,
884                            string const & original_path,
885                            OutputParams const & runparams_in,
886                            bool const output_preamble, bool const output_body)
887 {
888         OutputParams runparams = runparams_in;
889
890         // validate the buffer.
891         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
892         LaTeXFeatures features(*this, params(), runparams);
893         validate(features);
894         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
895
896         texrow().reset();
897
898         // The starting paragraph of the coming rows is the
899         // first paragraph of the document. (Asger)
900         texrow().start(paragraphs().begin()->id(), 0);
901
902         if (output_preamble && runparams.nice) {
903                 os << "%% LyX " << lyx_version << " created this file.  "
904                         "For more info, see http://www.lyx.org/.\n"
905                         "%% Do not edit unless you really know what "
906                         "you are doing.\n";
907                 texrow().newline();
908                 texrow().newline();
909         }
910         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
911         // There are a few differences between nice LaTeX and usual files:
912         // usual is \batchmode and has a
913         // special input@path to allow the including of figures
914         // with either \input or \includegraphics (what figinsets do).
915         // input@path is set when the actual parameter
916         // original_path is set. This is done for usual tex-file, but not
917         // for nice-latex-file. (Matthias 250696)
918         // Note that input@path is only needed for something the user does
919         // in the preamble, included .tex files or ERT, files included by
920         // LyX work without it.
921         if (output_preamble) {
922                 if (!runparams.nice) {
923                         // code for usual, NOT nice-latex-file
924                         os << "\\batchmode\n"; // changed
925                         // from \nonstopmode
926                         texrow().newline();
927                 }
928                 if (!original_path.empty()) {
929                         // FIXME UNICODE
930                         // We don't know the encoding of inputpath
931                         docstring const inputpath = from_utf8(latex_path(original_path));
932                         os << "\\makeatletter\n"
933                            << "\\def\\input@path{{"
934                            << inputpath << "/}}\n"
935                            << "\\makeatother\n";
936                         texrow().newline();
937                         texrow().newline();
938                         texrow().newline();
939                 }
940
941                 // Write the preamble
942                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
943
944                 if (!output_body)
945                         return;
946
947                 // make the body.
948                 os << "\\begin{document}\n";
949                 texrow().newline();
950         } // output_preamble
951         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
952
953         if (!lyxrc.language_auto_begin) {
954                 // FIXME UNICODE
955                 os << from_utf8(subst(lyxrc.language_command_begin,
956                                            "$$lang",
957                                            params().language->babel()))
958                    << '\n';
959                 texrow().newline();
960         }
961
962         // if we are doing a real file with body, even if this is the
963         // child of some other buffer, let's cut the link here.
964         // This happens for example if only a child document is printed.
965         string save_parentname;
966         if (output_preamble) {
967                 save_parentname = params().parentname;
968                 params().parentname.erase();
969         }
970
971         // the real stuff
972         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
973
974         // Restore the parenthood if needed
975         if (output_preamble)
976                 params().parentname = save_parentname;
977
978         // add this just in case after all the paragraphs
979         os << endl;
980         texrow().newline();
981
982         if (!lyxrc.language_auto_end) {
983                 os << from_utf8(subst(lyxrc.language_command_end,
984                                            "$$lang",
985                                            params().language->babel()))
986                    << '\n';
987                 texrow().newline();
988         }
989
990         if (output_preamble) {
991                 os << "\\end{document}\n";
992                 texrow().newline();
993
994                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
995         } else {
996                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
997                                      << endl;
998         }
999
1000         // Just to be sure. (Asger)
1001         texrow().newline();
1002
1003         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1004         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1005                             << '.' << endl;
1006 }
1007
1008
1009 bool Buffer::isLatex() const
1010 {
1011         return params().getLyXTextClass().outputType() == LATEX;
1012 }
1013
1014
1015 bool Buffer::isLiterate() const
1016 {
1017         return params().getLyXTextClass().outputType() == LITERATE;
1018 }
1019
1020
1021 bool Buffer::isDocBook() const
1022 {
1023         return params().getLyXTextClass().outputType() == DOCBOOK;
1024 }
1025
1026
1027 void Buffer::makeDocBookFile(string const & fname,
1028                               OutputParams const & runparams,
1029                               bool const body_only)
1030 {
1031         lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1032
1033         //ofstream ofs;
1034         odocfstream ofs;
1035         if (!openFileWrite(ofs, fname))
1036                 return;
1037
1038         writeDocBookSource(ofs, fname, runparams, body_only);
1039
1040         ofs.close();
1041         if (ofs.fail())
1042                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1043 }
1044
1045
1046 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1047                              OutputParams const & runparams,
1048                              bool const only_body)
1049 {
1050         LaTeXFeatures features(*this, params(), runparams);
1051         validate(features);
1052
1053         texrow().reset();
1054
1055         LyXTextClass const & tclass = params().getLyXTextClass();
1056         string const top_element = tclass.latexname();
1057
1058         if (!only_body) {
1059                 if (runparams.flavor == OutputParams::XML)
1060                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1061
1062                 // FIXME UNICODE
1063                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1064
1065                 // FIXME UNICODE
1066                 if (! tclass.class_header().empty())
1067                         os << from_ascii(tclass.class_header());
1068                 else if (runparams.flavor == OutputParams::XML)
1069                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1070                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1071                 else
1072                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1073
1074                 docstring preamble = from_utf8(params().preamble);
1075                 if (runparams.flavor != OutputParams::XML ) {
1076                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1077                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1078                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1079                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1080                 }
1081
1082                 string const name = runparams.nice ? changeExtension(pimpl_->filename, ".sgml")
1083                          : fname;
1084                 preamble += features.getIncludedFiles(name);
1085                 preamble += features.getLyXSGMLEntities();
1086
1087                 if (!preamble.empty()) {
1088                         os << "\n [ " << preamble << " ]";
1089                 }
1090                 os << ">\n\n";
1091         }
1092
1093         string top = top_element;
1094         top += " lang=\"";
1095         if (runparams.flavor == OutputParams::XML)
1096                 top += params().language->code();
1097         else
1098                 top += params().language->code().substr(0,2);
1099         top += '"';
1100
1101         if (!params().options.empty()) {
1102                 top += ' ';
1103                 top += params().options;
1104         }
1105
1106         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1107             << " file was created by LyX " << lyx_version
1108             << "\n  See http://www.lyx.org/ for more information -->\n";
1109
1110         params().getLyXTextClass().counters().reset();
1111
1112         sgml::openTag(os, top);
1113         os << '\n';
1114         docbookParagraphs(paragraphs(), *this, os, runparams);
1115         sgml::closeTag(os, top_element);
1116 }
1117
1118
1119 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1120 // Other flags: -wall -v0 -x
1121 int Buffer::runChktex()
1122 {
1123         busy(true);
1124
1125         // get LaTeX-Filename
1126         string const name = getLatexName();
1127         string const path = temppath();
1128         string const org_path = filePath();
1129
1130         support::Path p(path); // path to LaTeX file
1131         message(_("Running chktex..."));
1132
1133         // Generate the LaTeX file if neccessary
1134         OutputParams runparams;
1135         runparams.flavor = OutputParams::LATEX;
1136         runparams.nice = false;
1137         makeLaTeXFile(name, org_path, runparams);
1138
1139         TeXErrors terr;
1140         Chktex chktex(lyxrc.chktex_command, name, filePath());
1141         int const res = chktex.run(terr); // run chktex
1142
1143         if (res == -1) {
1144                 Alert::error(_("chktex failure"),
1145                              _("Could not run chktex successfully."));
1146         } else if (res > 0) {
1147                 // Fill-in the error list with the TeX errors
1148                 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1149         }
1150
1151         busy(false);
1152
1153         errors("ChkTeX");
1154
1155         return res;
1156 }
1157
1158
1159 void Buffer::validate(LaTeXFeatures & features) const
1160 {
1161         LyXTextClass const & tclass = params().getLyXTextClass();
1162
1163         if (features.isAvailable("dvipost") && params().outputChanges)
1164                 features.require("dvipost");
1165
1166         // AMS Style is at document level
1167         if (params().use_amsmath == BufferParams::package_on
1168             || tclass.provides(LyXTextClass::amsmath))
1169                 features.require("amsmath");
1170         if (params().use_esint == BufferParams::package_on)
1171                 features.require("esint");
1172
1173         for_each(paragraphs().begin(), paragraphs().end(),
1174                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1175
1176         // the bullet shapes are buffer level not paragraph level
1177         // so they are tested here
1178         for (int i = 0; i < 4; ++i) {
1179                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1180                         int const font = params().user_defined_bullet(i).getFont();
1181                         if (font == 0) {
1182                                 int const c = params()
1183                                         .user_defined_bullet(i)
1184                                         .getCharacter();
1185                                 if (c == 16
1186                                    || c == 17
1187                                    || c == 25
1188                                    || c == 26
1189                                    || c == 31) {
1190                                         features.require("latexsym");
1191                                 }
1192                         } else if (font == 1) {
1193                                 features.require("amssymb");
1194                         } else if ((font >= 2 && font <= 5)) {
1195                                 features.require("pifont");
1196                         }
1197                 }
1198         }
1199
1200         if (lyxerr.debugging(Debug::LATEX)) {
1201                 features.showStruct();
1202         }
1203 }
1204
1205
1206 void Buffer::getLabelList(vector<docstring> & list) const
1207 {
1208         /// if this is a child document and the parent is already loaded
1209         /// Use the parent's list instead  [ale990407]
1210         Buffer const * tmp = getMasterBuffer();
1211         if (!tmp) {
1212                 lyxerr << "getMasterBuffer() failed!" << endl;
1213                 BOOST_ASSERT(tmp);
1214         }
1215         if (tmp != this) {
1216                 tmp->getLabelList(list);
1217                 return;
1218         }
1219
1220         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1221                 it.nextInset()->getLabelList(*this, list);
1222 }
1223
1224
1225 // This is also a buffer property (ale)
1226 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1227         const
1228 {
1229         /// if this is a child document and the parent is already loaded
1230         /// use the parent's list instead  [ale990412]
1231         Buffer const * tmp = getMasterBuffer();
1232         BOOST_ASSERT(tmp);
1233         if (tmp != this) {
1234                 tmp->fillWithBibKeys(keys);
1235                 return;
1236         }
1237
1238         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1239                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1240                         InsetBibtex const & inset =
1241                                 dynamic_cast<InsetBibtex const &>(*it);
1242                         inset.fillWithBibKeys(*this, keys);
1243                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1244                         InsetInclude const & inset =
1245                                 dynamic_cast<InsetInclude const &>(*it);
1246                         inset.fillWithBibKeys(*this, keys);
1247                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1248                         InsetBibitem const & inset =
1249                                 dynamic_cast<InsetBibitem const &>(*it);
1250                         string const key = inset.getContents();
1251                         string const opt = inset.getOptions();
1252                         string const ref; // = pit->asString(this, false);
1253                         string const info = opt + "TheBibliographyRef" + ref;
1254                         keys.push_back(pair<string, string>(key, info));
1255                 }
1256         }
1257 }
1258
1259
1260 void Buffer::updateBibfilesCache()
1261 {
1262         // if this is a child document and the parent is already loaded
1263         // update the parent's cache instead
1264         Buffer * tmp = getMasterBuffer();
1265         BOOST_ASSERT(tmp);
1266         if (tmp != this) {
1267                 tmp->updateBibfilesCache();
1268                 return;
1269         }
1270
1271         bibfilesCache_.clear();
1272         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1273                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1274                         InsetBibtex const & inset =
1275                                 dynamic_cast<InsetBibtex const &>(*it);
1276                         vector<string> const bibfiles = inset.getFiles(*this);
1277                         bibfilesCache_.insert(bibfilesCache_.end(),
1278                                 bibfiles.begin(),
1279                                 bibfiles.end());
1280                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1281                         InsetInclude & inset =
1282                                 dynamic_cast<InsetInclude &>(*it);
1283                         inset.updateBibfilesCache(*this);
1284                         vector<string> const & bibfiles =
1285                                         inset.getBibfilesCache(*this);
1286                         bibfilesCache_.insert(bibfilesCache_.end(),
1287                                 bibfiles.begin(),
1288                                 bibfiles.end());
1289                 }
1290         }
1291 }
1292
1293
1294 vector<string> const & Buffer::getBibfilesCache() const
1295 {
1296         // if this is a child document and the parent is already loaded
1297         // use the parent's cache instead
1298         Buffer const * tmp = getMasterBuffer();
1299         BOOST_ASSERT(tmp);
1300         if (tmp != this)
1301                 return tmp->getBibfilesCache();
1302
1303         return bibfilesCache_;
1304 }
1305
1306
1307 bool Buffer::isDepClean(string const & name) const
1308 {
1309         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1310         if (it == pimpl_->dep_clean.end())
1311                 return true;
1312         return it->second;
1313 }
1314
1315
1316 void Buffer::markDepClean(string const & name)
1317 {
1318         pimpl_->dep_clean[name] = true;
1319 }
1320
1321
1322 bool Buffer::dispatch(string const & command, bool * result)
1323 {
1324         return dispatch(lyxaction.lookupFunc(command), result);
1325 }
1326
1327
1328 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1329 {
1330         bool dispatched = true;
1331
1332         switch (func.action) {
1333                 case LFUN_BUFFER_EXPORT: {
1334                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1335                         if (result)
1336                                 *result = tmp;
1337                         break;
1338                 }
1339
1340                 default:
1341                         dispatched = false;
1342         }
1343         return dispatched;
1344 }
1345
1346
1347 void Buffer::changeLanguage(Language const * from, Language const * to)
1348 {
1349         BOOST_ASSERT(from);
1350         BOOST_ASSERT(to);
1351
1352         // Take care of l10n/i18n
1353         updateDocLang(to);
1354
1355         for_each(par_iterator_begin(),
1356                  par_iterator_end(),
1357                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1358
1359         text().current_font.setLanguage(to);
1360         text().real_current_font.setLanguage(to);
1361 }
1362
1363
1364 void Buffer::updateDocLang(Language const * nlang)
1365 {
1366         BOOST_ASSERT(nlang);
1367
1368         pimpl_->messages.reset(new Messages(nlang->code()));
1369
1370         updateLabels(*this);
1371 }
1372
1373
1374 bool Buffer::isMultiLingual() const
1375 {
1376         ParConstIterator end = par_iterator_end();
1377         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1378                 if (it->isMultiLingual(params()))
1379                         return true;
1380
1381         return false;
1382 }
1383
1384
1385 ParIterator Buffer::getParFromID(int const id) const
1386 {
1387         ParConstIterator it = par_iterator_begin();
1388         ParConstIterator const end = par_iterator_end();
1389
1390         if (id < 0) {
1391                 // John says this is called with id == -1 from undo
1392                 lyxerr << "getParFromID(), id: " << id << endl;
1393                 return end;
1394         }
1395
1396         for (; it != end; ++it)
1397                 if (it->id() == id)
1398                         return it;
1399
1400         return end;
1401 }
1402
1403
1404 bool Buffer::hasParWithID(int const id) const
1405 {
1406         ParConstIterator const it = getParFromID(id);
1407         return it != par_iterator_end();
1408 }
1409
1410
1411 ParIterator Buffer::par_iterator_begin()
1412 {
1413         return lyx::par_iterator_begin(inset());
1414 }
1415
1416
1417 ParIterator Buffer::par_iterator_end()
1418 {
1419         return lyx::par_iterator_end(inset());
1420 }
1421
1422
1423 ParConstIterator Buffer::par_iterator_begin() const
1424 {
1425         return lyx::par_const_iterator_begin(inset());
1426 }
1427
1428
1429 ParConstIterator Buffer::par_iterator_end() const
1430 {
1431         return lyx::par_const_iterator_end(inset());
1432 }
1433
1434
1435 Language const * Buffer::getLanguage() const
1436 {
1437         return params().language;
1438 }
1439
1440
1441 docstring const Buffer::B_(string const & l10n) const
1442 {
1443         if (pimpl_->messages.get()) 
1444                 return pimpl_->messages->get(l10n);
1445
1446         return _(l10n);
1447 }
1448
1449
1450 docstring const Buffer::translateLabel(docstring const & label) const
1451 {
1452         if (support::isAscii(label))
1453                 // Probably standard layout, try to translate
1454                 return B_(to_ascii(label));
1455         else
1456                 // This must be a user defined layout. We cannot translate
1457                 // this, since gettext accepts only ascii keys.
1458                 return label;
1459 }
1460
1461
1462 bool Buffer::isClean() const
1463 {
1464         return pimpl_->lyx_clean;
1465 }
1466
1467
1468 bool Buffer::isBakClean() const
1469 {
1470         return pimpl_->bak_clean;
1471 }
1472
1473
1474 void Buffer::markClean() const
1475 {
1476         if (!pimpl_->lyx_clean) {
1477                 pimpl_->lyx_clean = true;
1478                 updateTitles();
1479         }
1480         // if the .lyx file has been saved, we don't need an
1481         // autosave
1482         pimpl_->bak_clean = true;
1483 }
1484
1485
1486 void Buffer::markBakClean()
1487 {
1488         pimpl_->bak_clean = true;
1489 }
1490
1491
1492 void Buffer::setUnnamed(bool flag)
1493 {
1494         pimpl_->unnamed = flag;
1495 }
1496
1497
1498 bool Buffer::isUnnamed() const
1499 {
1500         return pimpl_->unnamed;
1501 }
1502
1503
1504 #ifdef WITH_WARNINGS
1505 #warning this function should be moved to buffer_pimpl.C
1506 #endif
1507 void Buffer::markDirty()
1508 {
1509         if (pimpl_->lyx_clean) {
1510                 pimpl_->lyx_clean = false;
1511                 updateTitles();
1512         }
1513         pimpl_->bak_clean = false;
1514
1515         DepClean::iterator it = pimpl_->dep_clean.begin();
1516         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1517
1518         for (; it != end; ++it)
1519                 it->second = false;
1520 }
1521
1522
1523 string const & Buffer::fileName() const
1524 {
1525         return pimpl_->filename;
1526 }
1527
1528
1529 string const & Buffer::filePath() const
1530 {
1531         return params().filepath;
1532 }
1533
1534
1535 bool Buffer::isReadonly() const
1536 {
1537         return pimpl_->read_only;
1538 }
1539
1540
1541 void Buffer::setParentName(string const & name)
1542 {
1543         params().parentname = name;
1544 }
1545
1546
1547 Buffer const * Buffer::getMasterBuffer() const
1548 {
1549         if (!params().parentname.empty()
1550             && theBufferList().exists(params().parentname)) {
1551                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1552                 if (buf)
1553                         return buf->getMasterBuffer();
1554         }
1555
1556         return this;
1557 }
1558
1559
1560 Buffer * Buffer::getMasterBuffer()
1561 {
1562         if (!params().parentname.empty()
1563             && theBufferList().exists(params().parentname)) {
1564                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1565                 if (buf)
1566                         return buf->getMasterBuffer();
1567         }
1568
1569         return this;
1570 }
1571
1572
1573 MacroData const & Buffer::getMacro(docstring const & name) const
1574 {
1575         return pimpl_->macros.get(name);
1576 }
1577
1578
1579 bool Buffer::hasMacro(docstring const & name) const
1580 {
1581         return pimpl_->macros.has(name);
1582 }
1583
1584
1585 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1586 {
1587         MacroTable::globalMacros().insert(name, data);
1588         pimpl_->macros.insert(name, data);
1589 }
1590
1591
1592 void Buffer::buildMacros()
1593 {
1594         // Start with global table.
1595         pimpl_->macros = MacroTable::globalMacros();
1596
1597         // Now add our own.
1598         ParagraphList const & pars = text().paragraphs();
1599         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1600                 //lyxerr << "searching main par " << i
1601                 //      << " for macro definitions" << std::endl;
1602                 InsetList const & insets = pars[i].insetlist;
1603                 InsetList::const_iterator it = insets.begin();
1604                 InsetList::const_iterator end = insets.end();
1605                 for ( ; it != end; ++it) {
1606                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1607                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1608                                 MathMacroTemplate const & mac
1609                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1610                                 insertMacro(mac.name(), mac.asMacroData());
1611                         }
1612                 }
1613         }
1614 }
1615
1616
1617 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1618 {
1619         cursor_ = cur;
1620         anchor_ = anc;
1621 }
1622
1623
1624 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1625         InsetBase::Code code)
1626 {
1627         //FIXME: This does not work for child documents yet.
1628         BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1629         // Check if the label 'from' appears more than once
1630         vector<docstring> labels;
1631
1632         if (code == InsetBase::CITE_CODE) {
1633                 vector<pair<string, string> > keys;
1634                 fillWithBibKeys(keys);
1635                 vector<pair<string, string> >::const_iterator bit  = keys.begin();
1636                 vector<pair<string, string> >::const_iterator bend = keys.end();
1637
1638                 for (; bit != bend; ++bit)
1639                         // FIXME UNICODE
1640                         labels.push_back(from_utf8(bit->first));
1641         } else
1642                 getLabelList(labels);
1643
1644         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1645                 return;
1646
1647         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1648                 if (it->lyxCode() == code) {
1649                         InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1650                         inset.replaceContents(to_utf8(from), to_utf8(to));
1651                 }
1652         }
1653 }
1654
1655
1656 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1657         pit_type par_end, bool full_source)
1658 {
1659         OutputParams runparams;
1660         runparams.nice = true;
1661         runparams.flavor = OutputParams::LATEX;
1662         runparams.linelen = lyxrc.ascii_linelen;
1663         // No side effect of file copying and image conversion
1664         runparams.dryrun = true;
1665
1666         /* Support for docbook temprarily commented out. */
1667         if (full_source) {
1668                 os << "% Preview source code\n\n";
1669                 if (isLatex())
1670                         writeLaTeXSource(os, filePath(), runparams, true, true);
1671                 else {
1672                         writeDocBookSource(os, fileName(), runparams, false);
1673                 }
1674         } else {
1675                 runparams.par_begin = par_begin;
1676                 runparams.par_end = par_end;
1677                 if (par_begin + 1 == par_end)
1678                         os << "% Preview source code for paragraph " << par_begin << "\n\n";
1679                 else
1680                         os << "% Preview source code from paragraph " << par_begin
1681                            << " to " << par_end - 1 << "\n\n";
1682                 // output paragraphs
1683                 if (isLatex()) {
1684                         texrow().reset();
1685                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1686                 } else {
1687                         // DocBook
1688                         docbookParagraphs(paragraphs(), *this, os, runparams);
1689                 }
1690         }
1691 }
1692
1693
1694 ErrorList const & Buffer::errorList(string const & type) const
1695 {
1696         static ErrorList const emptyErrorList;
1697         std::map<std::string, ErrorList>::const_iterator I = errorLists_.find(type);
1698         if (I == errorLists_.end())
1699                 return emptyErrorList;
1700
1701         return I->second;
1702 }
1703
1704
1705 ErrorList & Buffer::errorList(string const & type)
1706 {
1707         return errorLists_[type];
1708 }
1709
1710
1711 } // namespace lyx