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