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