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