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