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