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