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