]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Fix bug 2138: copy and paste should preserve formatting between different
[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 = 256;
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         boost::scoped_ptr<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), 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
432         ErrorList & errorList = errorLists_["Parse"];
433
434         while (lex.isOK()) {
435                 lex.next();
436                 string const token = lex.getString();
437
438                 if (token.empty())
439                         continue;
440
441                 if (token == "\\end_header")
442                         break;
443
444                 ++line;
445                 if (token == "\\begin_header") {
446                         begin_header_line = line;
447                         continue;
448                 }
449
450                 lyxerr[Debug::PARSER] << "Handling document header token: `"
451                                       << token << '\'' << endl;
452
453                 string unknown = params().readToken(lex, token);
454                 if (!unknown.empty()) {
455                         if (unknown[0] != '\\' && token == "\\textclass") {
456                                 unknownClass(unknown);
457                         } else {
458                                 ++unknown_tokens;
459                                 docstring const s = bformat(_("Unknown token: "
460                                                                         "%1$s %2$s\n"),
461                                                          from_utf8(token),
462                                                          lex.getDocString());
463                                 errorList.push_back(ErrorItem(_("Document header error"),
464                                         s, -1, 0, 0));
465                         }
466                 }
467         }
468         if (begin_header_line) {
469                 docstring const s = _("\\begin_header is missing");
470                 errorList.push_back(ErrorItem(_("Document header error"),
471                         s, -1, 0, 0));
472         }
473
474         return unknown_tokens;
475 }
476
477
478 // Uwe C. Schroeder
479 // changed to be public and have one parameter
480 // Returns false if "\end_document" is not read (Asger)
481 bool Buffer::readDocument(LyXLex & lex)
482 {
483         ErrorList & errorList = errorLists_["Parse"];
484         errorList.clear();
485
486         lex.next();
487         string const token = lex.getString();
488         if (token != "\\begin_document") {
489                 docstring const s = _("\\begin_document is missing");
490                 errorList.push_back(ErrorItem(_("Document header error"),
491                         s, -1, 0, 0));
492         }
493
494         // we are reading in a brand new document
495         BOOST_ASSERT(paragraphs().empty());
496
497         readHeader(lex);
498         if (!params().getLyXTextClass().load(filePath())) {
499                 string theclass = params().getLyXTextClass().name();
500                 Alert::error(_("Can't load document class"), bformat(
501                         _("Using the default document class, because the "
502                                      "class %1$s could not be loaded."), from_utf8(theclass)));
503                 params().textclass = 0;
504         }
505
506         bool const res = text().read(*this, lex, errorList);
507         for_each(text().paragraphs().begin(),
508                  text().paragraphs().end(),
509                  bind(&Paragraph::setInsetOwner, _1, &inset()));
510
511         return res;
512 }
513
514
515 // needed to insert the selection
516 void Buffer::insertStringAsLines(ParagraphList & pars,
517         pit_type & pit, pos_type & pos,
518         LyXFont const & fn, docstring const & str, bool autobreakrows)
519 {
520         LyXFont font = fn;
521
522         // insert the string, don't insert doublespace
523         bool space_inserted = true;
524         for (docstring::const_iterator cit = str.begin();
525             cit != str.end(); ++cit) {
526                 Paragraph & par = pars[pit];
527                 if (*cit == '\n') {
528                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
529                                 breakParagraph(params(), pars, pit, pos,
530                                                par.layout()->isEnvironment());
531                                 ++pit;
532                                 pos = 0;
533                                 space_inserted = true;
534                         } else {
535                                 continue;
536                         }
537                         // do not insert consecutive spaces if !free_spacing
538                 } else if ((*cit == ' ' || *cit == '\t') &&
539                            space_inserted && !par.isFreeSpacing()) {
540                         continue;
541                 } else if (*cit == '\t') {
542                         if (!par.isFreeSpacing()) {
543                                 // tabs are like spaces here
544                                 par.insertChar(pos, ' ', font, params().trackChanges);
545                                 ++pos;
546                                 space_inserted = true;
547                         } else {
548                                 const pos_type n = 8 - pos % 8;
549                                 for (pos_type i = 0; i < n; ++i) {
550                                         par.insertChar(pos, ' ', font, params().trackChanges);
551                                         ++pos;
552                                 }
553                                 space_inserted = true;
554                         }
555                 } else if (!isPrintable(*cit)) {
556                         // Ignore unprintables
557                         continue;
558                 } else {
559                         // just insert the character
560                         par.insertChar(pos, *cit, font, params().trackChanges);
561                         ++pos;
562                         space_inserted = (*cit == ' ');
563                 }
564
565         }
566 }
567
568
569 bool Buffer::readString(std::string const & s)
570 {
571         params().compressed = false;
572
573         // remove dummy empty par
574         paragraphs().clear();
575         LyXLex lex(0, 0);
576         std::istringstream is(s);
577         lex.setStream(is);
578         FileName const name(tempName());
579         switch (readFile(lex, name)) {
580         case failure:
581                 return false;
582         case wrongversion: {
583                 // We need to call lyx2lyx, so write the input to a file
584                 std::ofstream os(name.toFilesystemEncoding().c_str());
585                 os << s;
586                 os.close();
587                 return readFile(name) == success;
588         }
589         case success:
590                 break;
591         }
592
593         // After we have read a file, we must ensure that the buffer
594         // language is set and used in the gui.
595         // If you know of a better place to put this, please tell me. (Lgb)
596         updateDocLang(params().language);
597
598         return true;
599 }
600
601
602 bool Buffer::readFile(FileName const & filename)
603 {
604         // Check if the file is compressed.
605         string const format = getFormatFromContents(filename);
606         if (format == "gzip" || format == "zip" || format == "compress") {
607                 params().compressed = true;
608         }
609
610         // remove dummy empty par
611         paragraphs().clear();
612         LyXLex lex(0, 0);
613         lex.setFile(filename);
614         if (readFile(lex, filename) != success)
615                 return false;
616
617         // After we have read a file, we must ensure that the buffer
618         // language is set and used in the gui.
619         // If you know of a better place to put this, please tell me. (Lgb)
620         updateDocLang(params().language);
621
622         return true;
623 }
624
625
626 bool Buffer::fully_loaded() const
627 {
628         return pimpl_->file_fully_loaded;
629 }
630
631
632 void Buffer::fully_loaded(bool const value)
633 {
634         pimpl_->file_fully_loaded = value;
635 }
636
637
638 Buffer::ReadStatus Buffer::readFile(LyXLex & lex, FileName const & filename,
639                 bool fromstring)
640 {
641         BOOST_ASSERT(!filename.empty());
642
643         if (!lex.isOK()) {
644                 Alert::error(_("Document could not be read"),
645                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
646                 return failure;
647         }
648
649         lex.next();
650         string const token(lex.getString());
651
652         if (!lex.isOK()) {
653                 Alert::error(_("Document could not be read"),
654                              bformat(_("%1$s could not be read."), from_utf8(filename.absFilename())));
655                 return failure;
656         }
657
658         // the first token _must_ be...
659         if (token != "\\lyxformat") {
660                 lyxerr << "Token: " << token << endl;
661
662                 Alert::error(_("Document format failure"),
663                              bformat(_("%1$s is not a LyX document."),
664                                        from_utf8(filename.absFilename())));
665                 return failure;
666         }
667
668         lex.next();
669         string tmp_format = lex.getString();
670         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
671         // if present remove ".," from string.
672         string::size_type dot = tmp_format.find_first_of(".,");
673         //lyxerr << "           dot found at " << dot << endl;
674         if (dot != string::npos)
675                         tmp_format.erase(dot, 1);
676         int const file_format = convert<int>(tmp_format);
677         //lyxerr << "format: " << file_format << endl;
678
679         if (file_format != LYX_FORMAT) {
680
681                 if (fromstring)
682                         // lyx2lyx would fail
683                         return wrongversion;
684
685                 FileName const tmpfile(tempName());
686                 if (tmpfile.empty()) {
687                         Alert::error(_("Conversion failed"),
688                                      bformat(_("%1$s is from an earlier"
689                                               " version of LyX, but a temporary"
690                                               " file for converting it could"
691                                                             " not be created."),
692                                               from_utf8(filename.absFilename())));
693                         return failure;
694                 }
695                 FileName const lyx2lyx = libFileSearch("lyx2lyx", "lyx2lyx");
696                 if (lyx2lyx.empty()) {
697                         Alert::error(_("Conversion script not found"),
698                                      bformat(_("%1$s is from an earlier"
699                                                " version of LyX, but the"
700                                                " conversion script lyx2lyx"
701                                                             " could not be found."),
702                                                from_utf8(filename.absFilename())));
703                         return failure;
704                 }
705                 ostringstream command;
706                 command << os::python()
707                         << ' ' << quoteName(lyx2lyx.toFilesystemEncoding())
708                         << " -t " << convert<string>(LYX_FORMAT)
709                         << " -o " << quoteName(tmpfile.toFilesystemEncoding())
710                         << ' ' << quoteName(filename.toFilesystemEncoding());
711                 string const command_str = command.str();
712
713                 lyxerr[Debug::INFO] << "Running '"
714                                     << command_str << '\''
715                                     << endl;
716
717                 cmd_ret const ret = runCommand(command_str);
718                 if (ret.first != 0) {
719                         Alert::error(_("Conversion script failed"),
720                                      bformat(_("%1$s is from an earlier version"
721                                               " of LyX, but the lyx2lyx script"
722                                                             " failed to convert it."),
723                                               from_utf8(filename.absFilename())));
724                         return failure;
725                 } else {
726                         bool const ret = readFile(tmpfile);
727                         // Do stuff with tmpfile name and buffer name here.
728                         return ret ? success : failure;
729                 }
730
731         }
732
733         if (readDocument(lex)) {
734                 Alert::error(_("Document format failure"),
735                              bformat(_("%1$s ended unexpectedly, which means"
736                                                     " that it is probably corrupted."),
737                                        from_utf8(filename.absFilename())));
738         }
739
740         //lyxerr << "removing " << MacroTable::localMacros().size()
741         //      << " temporary macro entries" << endl;
742         //MacroTable::localMacros().clear();
743
744         pimpl_->file_fully_loaded = true;
745         return success;
746 }
747
748
749 // Should probably be moved to somewhere else: BufferView? LyXView?
750 bool Buffer::save() const
751 {
752         // We don't need autosaves in the immediate future. (Asger)
753         resetAutosaveTimers();
754
755         // make a backup if the file already exists
756         string s;
757         if (lyxrc.make_backup && fs::exists(pimpl_->filename.toFilesystemEncoding())) {
758                 s = fileName() + '~';
759                 if (!lyxrc.backupdir_path.empty())
760                         s = addName(lyxrc.backupdir_path,
761                                     subst(os::internal_path(s),'/','!'));
762
763                 // It might very well be that this variant is just
764                 // good enough. (Lgb)
765                 // But to use this we need fs::copy_file to actually do a copy,
766                 // even when the target file exists. (Lgb)
767                 try {
768                     fs::copy_file(pimpl_->filename.toFilesystemEncoding(), s, false);
769                 }
770                 catch (fs::filesystem_error const & fe) {
771                         Alert::error(_("Backup failure"),
772                                      bformat(_("LyX was not able to make a backup copy in %1$s.\n"
773                                                             "Please check if the directory exists and is writeable."),
774                                           from_utf8(fs::path(s).branch_path().native_directory_string())));
775                         lyxerr[Debug::DEBUG] << "Fs error: "
776                                              << fe.what() << endl;
777                 }
778         }
779
780         if (writeFile(pimpl_->filename)) {
781                 markClean();
782                 removeAutosaveFile(fileName());
783         } else {
784                 // Saving failed, so backup is not backup
785                 if (lyxrc.make_backup)
786                         rename(FileName(s), pimpl_->filename);
787                 return false;
788         }
789         return true;
790 }
791
792
793 bool Buffer::writeFile(FileName const & fname) const
794 {
795         if (pimpl_->read_only && fname == pimpl_->filename)
796                 return false;
797
798         bool retval = false;
799
800         if (params().compressed) {
801                 io::filtering_ostream ofs(io::gzip_compressor() | io::file_sink(fname.toFilesystemEncoding()));
802                 if (!ofs)
803                         return false;
804
805                 retval = write(ofs);
806         } else {
807                 ofstream ofs(fname.toFilesystemEncoding().c_str(), ios::out|ios::trunc);
808                 if (!ofs)
809                         return false;
810
811                 retval = write(ofs);
812         }
813
814         return retval;
815 }
816
817
818 bool Buffer::write(ostream & ofs) const
819 {
820 #ifdef HAVE_LOCALE
821         // Use the standard "C" locale for file output.
822         ofs.imbue(std::locale::classic());
823 #endif
824
825         // The top of the file should not be written by params().
826
827         // write out a comment in the top of the file
828         ofs << "#LyX " << lyx_version
829             << " created this file. For more info see http://www.lyx.org/\n"
830             << "\\lyxformat " << LYX_FORMAT << "\n"
831             << "\\begin_document\n";
832
833         // now write out the buffer parameters.
834         ofs << "\\begin_header\n";
835         params().writeFile(ofs);
836         ofs << "\\end_header\n";
837
838         // write the text
839         ofs << "\n\\begin_body\n";
840         text().write(*this, ofs);
841         ofs << "\n\\end_body\n";
842
843         // Write marker that shows file is complete
844         ofs << "\\end_document" << endl;
845
846         // Shouldn't really be needed....
847         //ofs.close();
848
849         // how to check if close went ok?
850         // Following is an attempt... (BE 20001011)
851
852         // good() returns false if any error occured, including some
853         //        formatting error.
854         // bad()  returns true if something bad happened in the buffer,
855         //        which should include file system full errors.
856
857         bool status = true;
858         if (!ofs) {
859                 status = false;
860                 lyxerr << "File was not closed properly." << endl;
861         }
862
863         return status;
864 }
865
866
867 bool Buffer::makeLaTeXFile(FileName const & fname,
868                            string const & original_path,
869                            OutputParams const & runparams,
870                            bool output_preamble, bool output_body)
871 {
872         string const encoding = params().encoding().iconvName();
873         lyxerr[Debug::LATEX] << "makeLaTeXFile encoding: "
874                 << encoding << "..." << endl;
875
876         odocfstream ofs(encoding);
877         if (!openFileWrite(ofs, fname))
878                 return false;
879
880         try {
881                 writeLaTeXSource(ofs, original_path,
882                       runparams, output_preamble, output_body);
883         }
884         catch (iconv_codecvt_facet_exception &) {
885                 Alert::error(_("Encoding error"),
886                         _("Some characters of your document are not "
887                           "representable in the chosen encoding.\n"
888                           "Changing the document encoding to utf8 could help."));
889                 return false;
890         }
891
892         ofs.close();
893         if (ofs.fail()) {
894                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
895                 Alert::error(_("Error closing file"),
896                         _("The output file could not be closed properly.\n"
897                           " Probably some characters of your document are not "
898                           "representable in the chosen encoding.\n"
899                           "Changing the document encoding to utf8 could help."));
900                 return false;
901         }
902         return true;
903 }
904
905
906 void Buffer::writeLaTeXSource(odocstream & os,
907                            string const & original_path,
908                            OutputParams const & runparams_in,
909                            bool const output_preamble, bool const output_body)
910 {
911         OutputParams runparams = runparams_in;
912
913         // validate the buffer.
914         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
915         LaTeXFeatures features(*this, params(), runparams);
916         validate(features);
917         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
918
919         texrow().reset();
920
921         // The starting paragraph of the coming rows is the
922         // first paragraph of the document. (Asger)
923         texrow().start(paragraphs().begin()->id(), 0);
924
925         if (output_preamble && runparams.nice) {
926                 os << "%% LyX " << lyx_version << " created this file.  "
927                         "For more info, see http://www.lyx.org/.\n"
928                         "%% Do not edit unless you really know what "
929                         "you are doing.\n";
930                 texrow().newline();
931                 texrow().newline();
932         }
933         lyxerr[Debug::INFO] << "lyx document header finished" << endl;
934         // There are a few differences between nice LaTeX and usual files:
935         // usual is \batchmode and has a
936         // special input@path to allow the including of figures
937         // with either \input or \includegraphics (what figinsets do).
938         // input@path is set when the actual parameter
939         // original_path is set. This is done for usual tex-file, but not
940         // for nice-latex-file. (Matthias 250696)
941         // Note that input@path is only needed for something the user does
942         // in the preamble, included .tex files or ERT, files included by
943         // LyX work without it.
944         if (output_preamble) {
945                 if (!runparams.nice) {
946                         // code for usual, NOT nice-latex-file
947                         os << "\\batchmode\n"; // changed
948                         // from \nonstopmode
949                         texrow().newline();
950                 }
951                 if (!original_path.empty()) {
952                         // FIXME UNICODE
953                         // We don't know the encoding of inputpath
954                         docstring const inputpath = from_utf8(latex_path(original_path));
955                         os << "\\makeatletter\n"
956                            << "\\def\\input@path{{"
957                            << inputpath << "/}}\n"
958                            << "\\makeatother\n";
959                         texrow().newline();
960                         texrow().newline();
961                         texrow().newline();
962                 }
963
964                 // Write the preamble
965                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
966
967                 if (!output_body)
968                         return;
969
970                 // make the body.
971                 os << "\\begin{document}\n";
972                 texrow().newline();
973         } // output_preamble
974         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
975
976         if (!lyxrc.language_auto_begin) {
977                 // FIXME UNICODE
978                 os << from_utf8(subst(lyxrc.language_command_begin,
979                                            "$$lang",
980                                            params().language->babel()))
981                    << '\n';
982                 texrow().newline();
983         }
984
985         // if we are doing a real file with body, even if this is the
986         // child of some other buffer, let's cut the link here.
987         // This happens for example if only a child document is printed.
988         string save_parentname;
989         if (output_preamble) {
990                 save_parentname = params().parentname;
991                 params().parentname.erase();
992         }
993
994         // the real stuff
995         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
996
997         // Restore the parenthood if needed
998         if (output_preamble)
999                 params().parentname = save_parentname;
1000
1001         // add this just in case after all the paragraphs
1002         os << endl;
1003         texrow().newline();
1004
1005         if (!lyxrc.language_auto_end) {
1006                 os << from_utf8(subst(lyxrc.language_command_end,
1007                                            "$$lang",
1008                                            params().language->babel()))
1009                    << '\n';
1010                 texrow().newline();
1011         }
1012
1013         if (output_preamble) {
1014                 os << "\\end{document}\n";
1015                 texrow().newline();
1016
1017                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
1018         } else {
1019                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
1020                                      << endl;
1021         }
1022
1023         // Just to be sure. (Asger)
1024         texrow().newline();
1025
1026         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
1027         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
1028                             << '.' << endl;
1029 }
1030
1031
1032 bool Buffer::isLatex() const
1033 {
1034         return params().getLyXTextClass().outputType() == LATEX;
1035 }
1036
1037
1038 bool Buffer::isLiterate() const
1039 {
1040         return params().getLyXTextClass().outputType() == LITERATE;
1041 }
1042
1043
1044 bool Buffer::isDocBook() const
1045 {
1046         return params().getLyXTextClass().outputType() == DOCBOOK;
1047 }
1048
1049
1050 void Buffer::makeDocBookFile(FileName const & fname,
1051                               OutputParams const & runparams,
1052                               bool const body_only)
1053 {
1054         lyxerr[Debug::LATEX] << "makeDocBookFile..." << endl;
1055
1056         //ofstream ofs;
1057         odocfstream ofs;
1058         if (!openFileWrite(ofs, fname))
1059                 return;
1060
1061         writeDocBookSource(ofs, fname.absFilename(), runparams, body_only);
1062
1063         ofs.close();
1064         if (ofs.fail())
1065                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1066 }
1067
1068
1069 void Buffer::writeDocBookSource(odocstream & os, string const & fname,
1070                              OutputParams const & runparams,
1071                              bool const only_body)
1072 {
1073         LaTeXFeatures features(*this, params(), runparams);
1074         validate(features);
1075
1076         texrow().reset();
1077
1078         LyXTextClass const & tclass = params().getLyXTextClass();
1079         string const top_element = tclass.latexname();
1080
1081         if (!only_body) {
1082                 if (runparams.flavor == OutputParams::XML)
1083                         os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
1084
1085                 // FIXME UNICODE
1086                 os << "<!DOCTYPE " << from_ascii(top_element) << ' ';
1087
1088                 // FIXME UNICODE
1089                 if (! tclass.class_header().empty())
1090                         os << from_ascii(tclass.class_header());
1091                 else if (runparams.flavor == OutputParams::XML)
1092                         os << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1093                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1094                 else
1095                         os << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1096
1097                 docstring preamble = from_utf8(params().preamble);
1098                 if (runparams.flavor != OutputParams::XML ) {
1099                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1100                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1101                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1102                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1103                 }
1104
1105                 string const name = runparams.nice ? changeExtension(fileName(), ".sgml")
1106                          : fname;
1107                 preamble += features.getIncludedFiles(name);
1108                 preamble += features.getLyXSGMLEntities();
1109
1110                 if (!preamble.empty()) {
1111                         os << "\n [ " << preamble << " ]";
1112                 }
1113                 os << ">\n\n";
1114         }
1115
1116         string top = top_element;
1117         top += " lang=\"";
1118         if (runparams.flavor == OutputParams::XML)
1119                 top += params().language->code();
1120         else
1121                 top += params().language->code().substr(0,2);
1122         top += '"';
1123
1124         if (!params().options.empty()) {
1125                 top += ' ';
1126                 top += params().options;
1127         }
1128
1129         os << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1130             << " file was created by LyX " << lyx_version
1131             << "\n  See http://www.lyx.org/ for more information -->\n";
1132
1133         params().getLyXTextClass().counters().reset();
1134
1135         sgml::openTag(os, top);
1136         os << '\n';
1137         docbookParagraphs(paragraphs(), *this, os, runparams);
1138         sgml::closeTag(os, top_element);
1139 }
1140
1141
1142 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1143 // Other flags: -wall -v0 -x
1144 int Buffer::runChktex()
1145 {
1146         busy(true);
1147
1148         // get LaTeX-Filename
1149         string const name = getLatexName(false);
1150         string const path = temppath();
1151         string const org_path = filePath();
1152
1153         support::Path p(path); // path to LaTeX file
1154         message(_("Running chktex..."));
1155
1156         // Generate the LaTeX file if neccessary
1157         OutputParams runparams;
1158         runparams.flavor = OutputParams::LATEX;
1159         runparams.nice = false;
1160         makeLaTeXFile(FileName(name), org_path, runparams);
1161
1162         TeXErrors terr;
1163         Chktex chktex(lyxrc.chktex_command, onlyFilename(name), filePath());
1164         int const res = chktex.run(terr); // run chktex
1165
1166         if (res == -1) {
1167                 Alert::error(_("chktex failure"),
1168                              _("Could not run chktex successfully."));
1169         } else if (res > 0) {
1170                 // Fill-in the error list with the TeX errors
1171                 bufferErrors(*this, terr, errorLists_["ChkTex"]);
1172         }
1173
1174         busy(false);
1175
1176         errors("ChkTeX");
1177
1178         return res;
1179 }
1180
1181
1182 void Buffer::validate(LaTeXFeatures & features) const
1183 {
1184         LyXTextClass const & tclass = params().getLyXTextClass();
1185
1186         if (features.isAvailable("dvipost") && params().outputChanges)
1187                 features.require("dvipost");
1188
1189         // AMS Style is at document level
1190         if (params().use_amsmath == BufferParams::package_on
1191             || tclass.provides(LyXTextClass::amsmath))
1192                 features.require("amsmath");
1193         if (params().use_esint == BufferParams::package_on)
1194                 features.require("esint");
1195
1196         for_each(paragraphs().begin(), paragraphs().end(),
1197                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1198
1199         // the bullet shapes are buffer level not paragraph level
1200         // so they are tested here
1201         for (int i = 0; i < 4; ++i) {
1202                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1203                         int const font = params().user_defined_bullet(i).getFont();
1204                         if (font == 0) {
1205                                 int const c = params()
1206                                         .user_defined_bullet(i)
1207                                         .getCharacter();
1208                                 if (c == 16
1209                                    || c == 17
1210                                    || c == 25
1211                                    || c == 26
1212                                    || c == 31) {
1213                                         features.require("latexsym");
1214                                 }
1215                         } else if (font == 1) {
1216                                 features.require("amssymb");
1217                         } else if ((font >= 2 && font <= 5)) {
1218                                 features.require("pifont");
1219                         }
1220                 }
1221         }
1222
1223         if (lyxerr.debugging(Debug::LATEX)) {
1224                 features.showStruct();
1225         }
1226 }
1227
1228
1229 void Buffer::getLabelList(vector<docstring> & list) const
1230 {
1231         /// if this is a child document and the parent is already loaded
1232         /// Use the parent's list instead  [ale990407]
1233         Buffer const * tmp = getMasterBuffer();
1234         if (!tmp) {
1235                 lyxerr << "getMasterBuffer() failed!" << endl;
1236                 BOOST_ASSERT(tmp);
1237         }
1238         if (tmp != this) {
1239                 tmp->getLabelList(list);
1240                 return;
1241         }
1242
1243         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1244                 it.nextInset()->getLabelList(*this, list);
1245 }
1246
1247
1248 // This is also a buffer property (ale)
1249 void Buffer::fillWithBibKeys(vector<pair<string, docstring> > & keys)
1250         const
1251 {
1252         /// if this is a child document and the parent is already loaded
1253         /// use the parent's list instead  [ale990412]
1254         Buffer const * tmp = getMasterBuffer();
1255         BOOST_ASSERT(tmp);
1256         if (tmp != this) {
1257                 tmp->fillWithBibKeys(keys);
1258                 return;
1259         }
1260
1261         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1262                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1263                         InsetBibtex const & inset =
1264                                 dynamic_cast<InsetBibtex const &>(*it);
1265                         inset.fillWithBibKeys(*this, keys);
1266                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1267                         InsetInclude const & inset =
1268                                 dynamic_cast<InsetInclude const &>(*it);
1269                         inset.fillWithBibKeys(*this, keys);
1270                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1271                         InsetBibitem const & inset =
1272                                 dynamic_cast<InsetBibitem const &>(*it);
1273                         // FIXME UNICODE
1274                         string const key = to_utf8(inset.getParam("key"));
1275                         docstring const label = inset.getParam("label");
1276                         docstring const ref; // = pit->asString(this, false);
1277                         docstring const info = label + "TheBibliographyRef" + ref;
1278                         keys.push_back(pair<string, docstring>(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<FileName> 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<FileName> const & bibfiles =
1309                                         inset.getBibfilesCache(*this);
1310                         bibfilesCache_.insert(bibfilesCache_.end(),
1311                                 bibfiles.begin(),
1312                                 bibfiles.end());
1313                 }
1314         }
1315 }
1316
1317
1318 vector<FileName> 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         // We update the cache when first used instead of at loading time.
1328         if (bibfilesCache_.empty())
1329                 const_cast<Buffer *>(this)->updateBibfilesCache();
1330
1331         return bibfilesCache_;
1332 }
1333
1334
1335 bool Buffer::isDepClean(string const & name) const
1336 {
1337         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1338         if (it == pimpl_->dep_clean.end())
1339                 return true;
1340         return it->second;
1341 }
1342
1343
1344 void Buffer::markDepClean(string const & name)
1345 {
1346         pimpl_->dep_clean[name] = true;
1347 }
1348
1349
1350 bool Buffer::dispatch(string const & command, bool * result)
1351 {
1352         return dispatch(lyxaction.lookupFunc(command), result);
1353 }
1354
1355
1356 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1357 {
1358         bool dispatched = true;
1359
1360         switch (func.action) {
1361                 case LFUN_BUFFER_EXPORT: {
1362                         bool const tmp = Exporter::Export(this, to_utf8(func.argument()), false);
1363                         if (result)
1364                                 *result = tmp;
1365                         break;
1366                 }
1367
1368                 default:
1369                         dispatched = false;
1370         }
1371         return dispatched;
1372 }
1373
1374
1375 void Buffer::changeLanguage(Language const * from, Language const * to)
1376 {
1377         BOOST_ASSERT(from);
1378         BOOST_ASSERT(to);
1379
1380         // Take care of l10n/i18n
1381         updateDocLang(to);
1382
1383         for_each(par_iterator_begin(),
1384                  par_iterator_end(),
1385                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1386
1387         text().current_font.setLanguage(to);
1388         text().real_current_font.setLanguage(to);
1389 }
1390
1391
1392 void Buffer::updateDocLang(Language const * nlang)
1393 {
1394         BOOST_ASSERT(nlang);
1395
1396         pimpl_->messages.reset(new Messages(nlang->code()));
1397 }
1398
1399
1400 bool Buffer::isMultiLingual() const
1401 {
1402         ParConstIterator end = par_iterator_end();
1403         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1404                 if (it->isMultiLingual(params()))
1405                         return true;
1406
1407         return false;
1408 }
1409
1410
1411 ParIterator Buffer::getParFromID(int const id) const
1412 {
1413         ParConstIterator it = par_iterator_begin();
1414         ParConstIterator const end = par_iterator_end();
1415
1416         if (id < 0) {
1417                 // John says this is called with id == -1 from undo
1418                 lyxerr << "getParFromID(), id: " << id << endl;
1419                 return end;
1420         }
1421
1422         for (; it != end; ++it)
1423                 if (it->id() == id)
1424                         return it;
1425
1426         return end;
1427 }
1428
1429
1430 bool Buffer::hasParWithID(int const id) const
1431 {
1432         ParConstIterator const it = getParFromID(id);
1433         return it != par_iterator_end();
1434 }
1435
1436
1437 ParIterator Buffer::par_iterator_begin()
1438 {
1439         return lyx::par_iterator_begin(inset());
1440 }
1441
1442
1443 ParIterator Buffer::par_iterator_end()
1444 {
1445         return lyx::par_iterator_end(inset());
1446 }
1447
1448
1449 ParConstIterator Buffer::par_iterator_begin() const
1450 {
1451         return lyx::par_const_iterator_begin(inset());
1452 }
1453
1454
1455 ParConstIterator Buffer::par_iterator_end() const
1456 {
1457         return lyx::par_const_iterator_end(inset());
1458 }
1459
1460
1461 Language const * Buffer::getLanguage() const
1462 {
1463         return params().language;
1464 }
1465
1466
1467 docstring const Buffer::B_(string const & l10n) const
1468 {
1469         if (pimpl_->messages.get()) 
1470                 return pimpl_->messages->get(l10n);
1471
1472         return _(l10n);
1473 }
1474
1475
1476 docstring const Buffer::translateLabel(docstring const & label) const
1477 {
1478         if (support::isAscii(label))
1479                 // Probably standard layout, try to translate
1480                 return B_(to_ascii(label));
1481         else
1482                 // This must be a user defined layout. We cannot translate
1483                 // this, since gettext accepts only ascii keys.
1484                 return label;
1485 }
1486
1487
1488 bool Buffer::isClean() const
1489 {
1490         return pimpl_->lyx_clean;
1491 }
1492
1493
1494 bool Buffer::isBakClean() const
1495 {
1496         return pimpl_->bak_clean;
1497 }
1498
1499
1500 void Buffer::markClean() const
1501 {
1502         if (!pimpl_->lyx_clean) {
1503                 pimpl_->lyx_clean = true;
1504                 updateTitles();
1505         }
1506         // if the .lyx file has been saved, we don't need an
1507         // autosave
1508         pimpl_->bak_clean = true;
1509 }
1510
1511
1512 void Buffer::markBakClean()
1513 {
1514         pimpl_->bak_clean = true;
1515 }
1516
1517
1518 void Buffer::setUnnamed(bool flag)
1519 {
1520         pimpl_->unnamed = flag;
1521 }
1522
1523
1524 bool Buffer::isUnnamed() const
1525 {
1526         return pimpl_->unnamed;
1527 }
1528
1529
1530 #ifdef WITH_WARNINGS
1531 #warning this function should be moved to buffer_pimpl.C
1532 #endif
1533 void Buffer::markDirty()
1534 {
1535         if (pimpl_->lyx_clean) {
1536                 pimpl_->lyx_clean = false;
1537                 updateTitles();
1538         }
1539         pimpl_->bak_clean = false;
1540
1541         DepClean::iterator it = pimpl_->dep_clean.begin();
1542         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1543
1544         for (; it != end; ++it)
1545                 it->second = false;
1546 }
1547
1548
1549 string const Buffer::fileName() const
1550 {
1551         return pimpl_->filename.absFilename();
1552 }
1553
1554
1555 string const & Buffer::filePath() const
1556 {
1557         return params().filepath;
1558 }
1559
1560
1561 bool Buffer::isReadonly() const
1562 {
1563         return pimpl_->read_only;
1564 }
1565
1566
1567 void Buffer::setParentName(string const & name)
1568 {
1569         params().parentname = name;
1570 }
1571
1572
1573 Buffer const * Buffer::getMasterBuffer() const
1574 {
1575         if (!params().parentname.empty()
1576             && theBufferList().exists(params().parentname)) {
1577                 Buffer const * buf = theBufferList().getBuffer(params().parentname);
1578                 if (buf)
1579                         return buf->getMasterBuffer();
1580         }
1581
1582         return this;
1583 }
1584
1585
1586 Buffer * Buffer::getMasterBuffer()
1587 {
1588         if (!params().parentname.empty()
1589             && theBufferList().exists(params().parentname)) {
1590                 Buffer * buf = theBufferList().getBuffer(params().parentname);
1591                 if (buf)
1592                         return buf->getMasterBuffer();
1593         }
1594
1595         return this;
1596 }
1597
1598
1599 MacroData const & Buffer::getMacro(docstring const & name) const
1600 {
1601         return pimpl_->macros.get(name);
1602 }
1603
1604
1605 bool Buffer::hasMacro(docstring const & name) const
1606 {
1607         return pimpl_->macros.has(name);
1608 }
1609
1610
1611 void Buffer::insertMacro(docstring const & name, MacroData const & data)
1612 {
1613         MacroTable::globalMacros().insert(name, data);
1614         pimpl_->macros.insert(name, data);
1615 }
1616
1617
1618 void Buffer::buildMacros()
1619 {
1620         // Start with global table.
1621         pimpl_->macros = MacroTable::globalMacros();
1622
1623         // Now add our own.
1624         ParagraphList const & pars = text().paragraphs();
1625         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1626                 //lyxerr << "searching main par " << i
1627                 //      << " for macro definitions" << std::endl;
1628                 InsetList const & insets = pars[i].insetlist;
1629                 InsetList::const_iterator it = insets.begin();
1630                 InsetList::const_iterator end = insets.end();
1631                 for ( ; it != end; ++it) {
1632                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1633                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1634                                 MathMacroTemplate const & mac
1635                                         = static_cast<MathMacroTemplate const &>(*it->inset);
1636                                 insertMacro(mac.name(), mac.asMacroData());
1637                         }
1638                 }
1639         }
1640 }
1641
1642
1643 void Buffer::saveCursor(StableDocIterator cur, StableDocIterator anc)
1644 {
1645         cursor_ = cur;
1646         anchor_ = anc;
1647 }
1648
1649
1650 void Buffer::changeRefsIfUnique(docstring const & from, docstring const & to,
1651         InsetBase::Code code)
1652 {
1653         //FIXME: This does not work for child documents yet.
1654         BOOST_ASSERT(code == InsetBase::CITE_CODE || code == InsetBase::REF_CODE);
1655         // Check if the label 'from' appears more than once
1656         vector<docstring> labels;
1657
1658         if (code == InsetBase::CITE_CODE) {
1659                 vector<pair<string, docstring> > keys;
1660                 fillWithBibKeys(keys);
1661                 vector<pair<string, docstring> >::const_iterator bit  = keys.begin();
1662                 vector<pair<string, docstring> >::const_iterator bend = keys.end();
1663
1664                 for (; bit != bend; ++bit)
1665                         // FIXME UNICODE
1666                         labels.push_back(from_utf8(bit->first));
1667         } else
1668                 getLabelList(labels);
1669
1670         if (lyx::count(labels.begin(), labels.end(), from) > 1)
1671                 return;
1672
1673         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1674                 if (it->lyxCode() == code) {
1675                         InsetCommand & inset = dynamic_cast<InsetCommand &>(*it);
1676                         inset.replaceContents(to_utf8(from), to_utf8(to));
1677                 }
1678         }
1679 }
1680
1681
1682 void Buffer::getSourceCode(odocstream & os, pit_type par_begin,
1683         pit_type par_end, bool full_source)
1684 {
1685         OutputParams runparams;
1686         runparams.nice = true;
1687         runparams.flavor = OutputParams::LATEX;
1688         runparams.linelen = lyxrc.ascii_linelen;
1689         // No side effect of file copying and image conversion
1690         runparams.dryrun = true;
1691
1692         if (full_source) {
1693                 os << "% Preview source code\n\n";
1694                 if (isLatex())
1695                         writeLaTeXSource(os, filePath(), runparams, true, true);
1696                 else {
1697                         writeDocBookSource(os, fileName(), runparams, false);
1698                 }
1699         } else {
1700                 runparams.par_begin = par_begin;
1701                 runparams.par_end = par_end;
1702                 if (par_begin + 1 == par_end)
1703                         os << "% Preview source code for paragraph " << par_begin << "\n\n";
1704                 else
1705                         os << "% Preview source code from paragraph " << par_begin
1706                            << " to " << par_end - 1 << "\n\n";
1707                 // output paragraphs
1708                 if (isLatex()) {
1709                         texrow().reset();
1710                         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
1711                 } else {
1712                         // DocBook
1713                         docbookParagraphs(paragraphs(), *this, os, runparams);
1714                 }
1715         }
1716 }
1717
1718
1719 ErrorList const & Buffer::errorList(string const & type) const
1720 {
1721         static ErrorList const emptyErrorList;
1722         std::map<string, ErrorList>::const_iterator I = errorLists_.find(type);
1723         if (I == errorLists_.end())
1724                 return emptyErrorList;
1725
1726         return I->second;
1727 }
1728
1729
1730 ErrorList & Buffer::errorList(string const & type)
1731 {
1732         return errorLists_[type];
1733 }
1734
1735
1736 } // namespace lyx