]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
Only the packages subscript and ulem if they are automatically loaded
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "OutputEnums.h"
16 #include "OutputParams.h"
17
18 #include "insets/InsetCode.h"
19
20 #include "support/strfwd.h"
21 #include "support/types.h"
22
23 #include <map>
24 #include <list>
25 #include <set>
26 #include <string>
27 #include <vector>
28
29
30 namespace lyx {
31
32 class BiblioInfo;
33 class BibTeXInfo;
34 class BufferParams;
35 class DispatchResult;
36 class DocIterator;
37 class docstring_list;
38 class ErrorList;
39 class FuncRequest;
40 class FuncStatus;
41 class Inset;
42 class InsetLabel;
43 class InsetRef;
44 class Font;
45 class Format;
46 class Lexer;
47 class Text;
48 class LyXVC;
49 class LaTeXFeatures;
50 class Language;
51 class MacroData;
52 class MacroNameSet;
53 class MacroSet;
54 class OutputParams;
55 class Paragraph;
56 class ParConstIterator;
57 class ParIterator;
58 class ParagraphList;
59 class TeXErrors;
60 class TexRow;
61 class TocBackend;
62 class Undo;
63 class WordLangTuple;
64
65 namespace frontend {
66 class GuiBufferDelegate;
67 class WorkAreaManager;
68 }
69
70 namespace support {
71 class FileName;
72 class FileNameList;
73 }
74
75 namespace graphics {
76 class PreviewLoader;
77 }
78
79
80 class Buffer;
81 typedef std::list<Buffer *> ListOfBuffers;
82
83
84 /** The buffer object.
85  * This is the buffer object. It contains all the informations about
86  * a document loaded into LyX.
87  * The buffer object owns the Text (wrapped in an InsetText), which
88  * contains the individual paragraphs of the document.
89  *
90  *
91  * I am not sure if the class is complete or
92  * minimal, probably not.
93  * \author Lars Gullik Bjønnes
94  */
95 class Buffer {
96 public:
97         /// What type of log will \c getLogName() return?
98         enum LogType {
99                 latexlog, ///< LaTeX log
100                 buildlog  ///< Literate build log
101         };
102
103         /// Result of \c readFile()
104         enum ReadStatus {
105                 ReadSuccess,
106                 ReadCancel,
107                 // failures
108                 ReadFailure,
109                 ReadWrongVersion,
110                 ReadFileNotFound,
111                 ReadVCError,
112                 ReadAutosaveFailure,            
113                 ReadEmergencyFailure,
114                 ReadNoLyXFormat,
115                 ReadDocumentFailure,
116                 // lyx2lyx
117                 LyX2LyXNoTempFile,
118                 LyX2LyXNotFound,
119                 LyX2LyXOlderFormat,
120                 LyX2LyXNewerFormat,
121                 // other
122                 ReadOriginal
123         };
124
125         enum ExportStatus {
126                 // export
127                 ExportSuccess,
128                 ExportError,
129                 ExportNoPathToFormat,
130                 ExportTexPathHasSpaces,
131                 ExportConverterError,
132                 // preview
133                 PreviewSuccess,
134                 PreviewError
135         };
136
137         /// Method to check if a file is externally modified, used by
138         /// isExternallyModified()
139         /**
140          * timestamp is fast but inaccurate. For example, the granularity
141          * of timestamp on a FAT filesystem is 2 second. Also, various operations
142          * may touch the timestamp of a file even when its content is unchanged.
143          *
144          * checksum is accurate but slow, which can be a problem when it is
145          * frequently used, or used for a large file on a slow (network) file
146          * system.
147          *
148          * FIXME: replace this method with support/FileMonitor.
149          */
150         enum CheckMethod {
151                 checksum_method, ///< Use file checksum
152                 timestamp_method ///< Use timestamp, and checksum if timestamp has changed
153         };
154
155         ///
156         enum UpdateScope {
157                 UpdateMaster,
158                 UpdateChildOnly
159         };
160
161         /// Constructor
162         explicit Buffer(std::string const & file, bool readonly = false,
163                 Buffer const * cloned_buffer = 0);
164
165         /// Destructor
166         ~Buffer();
167
168         ///
169         Buffer * clone() const;
170         ///
171         bool isClone() const;
172
173         /** High-level interface to buffer functionality.
174             This function parses a command string and executes it.
175         */
176         void dispatch(std::string const & command, DispatchResult & result);
177
178         /// Maybe we know the function already by number...
179         void dispatch(FuncRequest const & func, DispatchResult & result);
180
181         /// Can this function be exectued?
182         /// \return true if we made a decision
183         bool getStatus(FuncRequest const & cmd, FuncStatus & flag);
184
185         ///
186         DocIterator getParFromID(int id) const;
187         /// do we have a paragraph with this id?
188         bool hasParWithID(int id) const;
189
190         ///
191         frontend::WorkAreaManager & workAreaManager() const;
192
193         /** Save file.
194             Takes care of auto-save files and backup file if requested.
195             Returns \c true if the save is successful, \c false otherwise.
196         */
197         bool save() const;
198         /// Renames and saves the buffer
199         bool saveAs(support::FileName const & fn);
200
201         /// Write document to stream. Returns \c false if unsuccessful.
202         bool write(std::ostream &) const;
203         /// Write file. Returns \c false if unsuccessful.
204         bool writeFile(support::FileName const &) const;
205
206         /// \name Functions involved in reading files/strings.
207         //@{
208         /// Loads the LyX file into the buffer. This function
209         /// tries to extract the file from version control if it
210         /// cannot be found. If it can be found, it will try to
211         /// read an emergency save file or an autosave file.
212         /// \sa loadThisLyXFile
213         ReadStatus loadLyXFile();
214         /// Loads the LyX file \c fn into the buffer. If you want
215         /// to check for files in a version control container,
216         /// emergency or autosave files, one should use \c loadLyXFile.
217         /// /sa loadLyXFile
218         ReadStatus loadThisLyXFile(support::FileName const & fn);
219         /// read a new document from a string
220         bool readString(std::string const &);
221         /// Reloads the LyX file
222         ReadStatus reload();
223 //FIXME: The following function should be private
224 //private:
225         /// read the header, returns number of unknown tokens
226         int readHeader(Lexer & lex);
227
228 private:
229         ///
230         typedef std::map<Buffer const *, Buffer *> BufferMap;
231         ///
232         void clone(BufferMap &) const;
233         /// save timestamp and checksum of the given file.
234         void saveCheckSum() const;      
235         /// read a new file
236         ReadStatus readFile(support::FileName const & fn);
237         /// Reads a file without header.
238         /// \param par if != 0 insert the file.
239         /// \return \c true if file is not completely read.
240         bool readDocument(Lexer &);
241         /// Try to extract the file from a version control container
242         /// before reading if the file cannot be found. This is only
243         /// implemented for RCS.
244         /// \sa LyXVC::file_not_found_hook
245         ReadStatus extractFromVC();
246         /// Reads the first tag of a LyX File and 
247         /// returns the file format number.
248         ReadStatus parseLyXFormat(Lexer & lex, support::FileName const & fn,
249                 int & file_format) const;
250         /// Convert the LyX file to the LYX_FORMAT using
251         /// the lyx2lyx script and returns the filename
252         /// of the temporary file to be read
253         ReadStatus convertLyXFormat(support::FileName const & fn, 
254                 support::FileName & tmpfile, int from_format);
255         //@}
256
257 public:
258         /// \name Functions involved in autosave and emergency files.
259         //@{
260         /// Save an autosave file to #filename.lyx#
261         bool autoSave() const;  
262         /// save emergency file
263         /// \return a status message towards the user.
264         docstring emergencyWrite();
265
266 //FIXME:The following function should be private
267 //private:
268         ///
269         void removeAutosaveFile() const;
270         
271 private:
272         /// Try to load an autosave file associated to \c fn.
273         ReadStatus loadAutosave();
274         /// Try to load an emergency file associated to \c fn. 
275         ReadStatus loadEmergency();
276         /// Get the filename of the emergency file associated with the Buffer
277         support::FileName getEmergencyFileName() const;
278         /// Get the filename of the autosave file associated with the Buffer
279         support::FileName getAutosaveFileName() const;
280         ///
281         void moveAutosaveFile(support::FileName const & old) const;
282         //@}
283
284 public:
285         /// Fill in the ErrorList with the TeXErrors
286         void bufferErrors(TeXErrors const &, ErrorList &) const;
287
288         enum OutputWhat {
289                 FullSource,
290                 OnlyBody,
291                 OnlyPreamble,
292                 CurrentParagraph
293         };
294
295         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
296         bool makeLaTeXFile(support::FileName const & filename,
297                            std::string const & original_path,
298                            OutputParams const &,
299                            OutputWhat output = FullSource) const;
300         /** Export the buffer to LaTeX.
301             If \p os is a file stream, and params().inputenc is "auto" or
302             "default", and the buffer contains text in different languages
303             with more than one encoding, then this method will change the
304             encoding associated to \p os. Therefore you must not call this
305             method with a string stream if the output is supposed to go to a
306             file. \code
307             ofdocstream ofs;
308             otexstream os(ofs, texrow);
309             ofs.open("test.tex");
310             writeLaTeXSource(os, ...);
311             ofs.close();
312             \endcode is NOT equivalent to \code
313             odocstringstream oss;
314             otexstream os(oss, texrow);
315             writeLaTeXSource(os, ...);
316             ofdocstream ofs;
317             ofs.open("test.tex");
318             ofs << oss.str();
319             ofs.close();
320             \endcode
321          */
322         void writeLaTeXSource(otexstream & os,
323                            std::string const & original_path,
324                            OutputParams const &,
325                            OutputWhat output = FullSource) const;
326         ///
327         void makeDocBookFile(support::FileName const & filename,
328                              OutputParams const & runparams_in,
329                              OutputWhat output = FullSource) const;
330         ///
331         void writeDocBookSource(odocstream & os, std::string const & filename,
332                              OutputParams const & runparams_in,
333                              OutputWhat output = FullSource) const;
334         ///
335         void makeLyXHTMLFile(support::FileName const & filename,
336                              OutputParams const & runparams_in) const;
337         ///
338         void writeLyXHTMLSource(odocstream & os,
339                              OutputParams const & runparams_in,
340                              OutputWhat output = FullSource) const;
341         /// returns the main language for the buffer (document)
342         Language const * language() const;
343         /// get l10n translated to the buffers language
344         docstring const B_(std::string const & l10n) const;
345
346         ///
347         int runChktex();
348         /// return true if the main lyx file does not need saving
349         bool isClean() const;
350         ///
351         bool isDepClean(std::string const & name) const;
352
353         /// whether or not disk file has been externally modified
354         bool isExternallyModified(CheckMethod method) const;
355
356         /// mark the main lyx file as not needing saving
357         void markClean() const;
358
359         ///
360         void markDepClean(std::string const & name);
361
362         ///
363         void setUnnamed(bool flag = true);
364
365         /// Whether or not a filename has been assigned to this buffer
366         bool isUnnamed() const;
367
368         /// Whether or not this buffer is internal.
369         ///
370         /// An internal buffer does not contain a real document, but some auxiliary text segment.
371         /// It is not associated with a filename, it is never saved, thus it does not need to be
372         /// automatically saved, nor it needs to trigger any "do you want to save ?" question.
373         bool isInternal() const;
374
375         /// Mark this buffer as dirty.
376         void markDirty();
377
378         /// Returns the buffer's filename. It is always an absolute path.
379         support::FileName fileName() const;
380
381         /// Returns the buffer's filename. It is always an absolute path.
382         std::string absFileName() const;
383
384         /// Returns the the path where the buffer lives.
385         /// It is always an absolute path.
386         std::string filePath() const;
387
388         /** A transformed version of the file name, adequate for LaTeX.
389             \param no_path optional if \c true then the path is stripped.
390         */
391         std::string latexName(bool no_path = true) const;
392
393         /// Get the name and type of the log.
394         std::string logName(LogType * type = 0) const;
395
396         /// Set document's parent Buffer.
397         void setParent(Buffer const *);
398         Buffer const * parent() const;
399
400         /** Get the document's master (or \c this if this is not a
401             child document)
402          */
403         Buffer const * masterBuffer() const;
404
405         /// \return true if \p child is a child of this \c Buffer.
406         bool isChild(Buffer * child) const;
407         
408         /// \return true if this \c Buffer has children
409         bool hasChildren() const;
410         
411         /// \return a list of the direct children of this Buffer.
412         /// this list has no duplicates and is in the order in which
413         /// the children appear.
414         ListOfBuffers getChildren() const;
415         
416         /// \return a list of all descendents of this Buffer (children,
417         /// grandchildren, etc). this list has no duplicates and is in
418         /// the order in which the children appear.
419         ListOfBuffers getDescendents() const;
420
421         /// Collect all relative buffers, in the order in which they appear.
422         /// I.e., the "root" Buffer is first, then its first child, then any
423         /// of its children, etc. However, there are no duplicates in this
424         /// list.
425         /// This is "stable", too, in the sense that it returns the same
426         /// thing from whichever Buffer it is called.
427         ListOfBuffers allRelatives() const;
428
429         /// Is buffer read-only?
430         bool isReadonly() const;
431
432         /// Set buffer read-only flag
433         void setReadonly(bool flag = true);
434
435         /** Validate a buffer for LaTeX.
436             This validates the buffer, and returns a struct for use by
437             #makeLaTeX# and others. Its main use is to figure out what
438             commands and packages need to be included in the LaTeX file.
439             It (should) also check that the needed constructs are there
440             (i.e. that the \refs points to coresponding \labels). It
441             should perhaps inset "error" insets to help the user correct
442             obvious mistakes.
443         */
444         void validate(LaTeXFeatures &) const;
445
446         /// Reference information is cached in the Buffer, so we do not
447         /// have to check or read things over and over. 
448         ///
449         /// There are two caches.
450         ///
451         /// One is a cache of the BibTeX files from which reference info is
452         /// being gathered. This cache is PER BUFFER, and the cache for the
453         /// master essentially includes the cache for its children. This gets
454         /// invalidated when an InsetBibtex is created, deleted, or modified.
455         /// 
456         /// The other is a cache of the reference information itself. This
457         /// exists only in the master buffer, and when it needs to be updated,
458         /// the children add their information to the master's cache.
459         
460         /// Calling this method invalidates the cache and so requires a
461         /// re-read.
462         void invalidateBibinfoCache() const;
463         /// This invalidates the cache of files we need to check.
464         void invalidateBibfileCache() const;
465         /// Updates the cached bibliography information, checking first to see
466         /// whether the cache is valid. If so, we do nothing. If not, then we
467         /// reload all the BibTeX info.
468         /// Note that this operates on the master document.
469         void reloadBibInfoCache() const;
470         /// \return the bibliography information for this buffer's master,
471         /// or just for it, if it isn't a child.
472         BiblioInfo const & masterBibInfo() const;
473         /// collect bibliography info from the various insets in this buffer.
474         void collectBibKeys() const;
475         /// add some BiblioInfo to our cache
476         void addBiblioInfo(BiblioInfo const & bi) const;
477         /// add a single piece of bibliography info to our cache
478         void addBibTeXInfo(docstring const & key, BibTeXInfo const & bi) const;
479         ///
480         bool citeLabelsValid() const;
481         ///
482         void getLabelList(std::vector<docstring> &) const;
483
484         ///
485         void changeLanguage(Language const * from, Language const * to);
486
487         ///
488         bool isMultiLingual() const;
489         ///
490         std::set<Language const *> getLanguages() const;
491
492         ///
493         BufferParams & params();
494         BufferParams const & params() const;
495
496         /** The list of paragraphs.
497             This is a linked list of paragraph, this list holds the
498             whole contents of the document.
499          */
500         ParagraphList & paragraphs();
501         ParagraphList const & paragraphs() const;
502
503         /// LyX version control object.
504         LyXVC & lyxvc();
505         LyXVC const & lyxvc() const;
506
507         /// Where to put temporary files.
508         std::string const temppath() const;
509
510         /// Used when typesetting to place errorboxes.
511         TexRow const & texrow() const;
512         TexRow & texrow();
513
514         ///
515         ParIterator par_iterator_begin();
516         ///
517         ParConstIterator par_iterator_begin() const;
518         ///
519         ParIterator par_iterator_end();
520         ///
521         ParConstIterator par_iterator_end() const;
522
523         // Position of the child buffer where it appears first in the master.
524         DocIterator firstChildPosition(Buffer const * child);
525
526         /** \returns true only when the file is fully loaded.
527          *  Used to prevent the premature generation of previews
528          *  and by the citation inset.
529          */
530         bool isFullyLoaded() const;
531         /// Set by buffer_funcs' newFile.
532         void setFullyLoaded(bool);
533
534         /// FIXME: Needed by RenderPreview.
535         graphics::PreviewLoader * loader() const;
536         /// Update the LaTeX preview snippets associated with this buffer
537         void updatePreviews() const;
538         /// Remove any previewed LaTeX snippets associated with this buffer
539         void removePreviews() const;
540
541         /// Our main text (inside the top InsetText)
542         Text & text() const;
543
544         /// Our top InsetText
545         Inset & inset() const;
546
547         //
548         // Macro handling
549         //
550         /// Collect macro definitions in paragraphs
551         void updateMacros() const;
552         /// Iterate through the whole buffer and try to resolve macros
553         void updateMacroInstances(UpdateType) const;
554
555         /// List macro names of this buffer, the parent and the children
556         void listMacroNames(MacroNameSet & macros) const;
557         /// Collect macros of the parent and its children in front of this buffer.
558         void listParentMacros(MacroSet & macros, LaTeXFeatures & features) const;
559
560         /// Return macro defined before pos (or in the master buffer)
561         MacroData const * getMacro(docstring const & name, DocIterator const & pos, bool global = true) const;
562         /// Return macro defined anywhere in the buffer (or in the master buffer)
563         MacroData const * getMacro(docstring const & name, bool global = true) const;
564         /// Return macro defined before the inclusion of the child
565         MacroData const * getMacro(docstring const & name, Buffer const & child, bool global = true) const;
566
567         /// Collect user macro names at loading time
568         typedef std::set<docstring> UserMacroSet;
569         mutable UserMacroSet usermacros;
570
571         /// Replace the inset contents for insets which InsetCode is equal
572         /// to the passed \p inset_code.
573         void changeRefsIfUnique(docstring const & from, docstring const & to,
574                 InsetCode code);
575
576         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
577         /// including preamble
578         void getSourceCode(odocstream & os, std::string const format,
579                            pit_type par_begin, pit_type par_end, OutputWhat output) const;
580
581         /// Access to error list.
582         /// This method is used only for GUI visualisation of Buffer related
583         /// errors (like parsing or LateX compilation). This method is const
584         /// because modifying the returned ErrorList does not touch the document
585         /// contents.
586         ErrorList & errorList(std::string const & type) const;
587
588         /// The Toc backend.
589         /// This is useful only for screen visualisation of the Buffer. This
590         /// method is const because modifying this backend does not touch
591         /// the document contents.
592         TocBackend & tocBackend() const;
593
594         ///
595         Undo & undo();
596
597         /// This function is called when the buffer is changed.
598         void changed(bool update_metrics) const;
599         ///
600         void setChild(DocIterator const & dit, Buffer * child);
601         ///
602         void updateTocItem(std::string const &, DocIterator const &) const;
603         /// This function is called when the buffer structure is changed.
604         void structureChanged() const;
605         /// This function is called when some parsing error shows up.
606         void errors(std::string const & err, bool from_master = false) const;
607         /// This function is called when the buffer busy status change.
608         void setBusy(bool on) const;
609         /// Update window titles of all users.
610         void updateTitles() const;
611         /// Reset autosave timers for all users.
612         void resetAutosaveTimers() const;
613         ///
614         void message(docstring const & msg) const;
615
616         ///
617         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
618         ///
619         bool hasGuiDelegate() const;
620
621         ///
622         ExportStatus doExport(std::string const & target, bool put_in_tempdir) const;
623         ///
624         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
625                 std::string & result_file) const;
626         ///
627         ExportStatus preview(std::string const & format) const;
628
629 private:
630         /// target is a format name optionally followed by a space
631         /// and a destination file-name
632         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
633                 bool includeall, std::string & result_file) const;
634         ///
635         ExportStatus doExport(std::string const & target, bool put_in_tempdir,
636                 bool includeall) const;
637         ///
638         ExportStatus preview(std::string const & format, bool includeall = false) const;
639
640 public:
641         ///
642         bool isExporting() const;
643
644         ///
645         typedef std::vector<std::pair<Inset *, ParIterator> > References;
646         References & references(docstring const & label);
647         References const & references(docstring const & label) const;
648         void clearReferenceCache() const;
649         void setInsetLabel(docstring const & label, InsetLabel const * il);
650         InsetLabel const * insetLabel(docstring const & label) const;
651
652         /// return a list of all used branches (also in children)
653         void getUsedBranches(std::list<docstring> &, bool const from_master = false) const;
654
655         /// sets the buffer_ member for every inset in this buffer.
656         // FIXME This really shouldn't be needed, but at the moment it's not
657         // clear how to do it just for the individual pieces we need.
658         void setBuffersForInsets() const;
659         /// Updates screen labels and some other information associated with
660         /// insets and paragraphs. Actually, it's more like a general "recurse
661         /// through the Buffer" routine, that visits all the insets and paragraphs.
662         void updateBuffer() const { updateBuffer(UpdateMaster, InternalUpdate); }
663         /// \param scope: whether to start with the master document or just
664         /// do this one.
665         /// \param output: whether we are preparing for output.
666         void updateBuffer(UpdateScope scope, UpdateType utype) const;
667         /// 
668         void updateBuffer(ParIterator & parit, UpdateType utype) const;
669
670         /// Spellcheck starting from \p from.
671         /// \p from initial position, will then points to the next misspelled
672         ///    word.
673         /// \p to will points to the end of the next misspelled word.
674         /// \p word_lang will contain the found misspelled word.
675         /// \return progress if a new word was found.
676         int spellCheck(DocIterator & from, DocIterator & to,
677                 WordLangTuple & word_lang, docstring_list & suggestions) const;
678         ///
679         void checkChildBuffers();
680
681 private:
682         class MarkAsExporting;
683         friend class MarkAsExporting;
684         /// mark the buffer as busy exporting something, or not
685         void setExportStatus(bool e) const;
686
687         /// Change name of buffer. Updates "read-only" flag.
688         void setFileName(support::FileName const & fname);
689         ///
690         void getLanguages(std::set<Language const *> &) const;
691         /// Checks whether any of the referenced bibfiles have changed since the
692         /// last time we loaded the cache. Note that this does NOT update the
693         /// cached information.
694         void checkIfBibInfoCacheIsValid() const;
695         /// Update the list of all bibfiles in use (including bibfiles
696         /// of loaded child documents).
697         void updateBibfilesCache(UpdateScope scope = UpdateMaster) const;
698         /// Return the list with all bibfiles in use (including bibfiles
699         /// of loaded child documents).
700         support::FileNameList const & 
701                 getBibfilesCache(UpdateScope scope = UpdateMaster) const;
702         ///
703         void collectChildren(ListOfBuffers & children, bool grand_children) const;
704
705         /// noncopyable
706         Buffer(Buffer const &);
707         void operator=(Buffer const &);
708
709         /// Use the Pimpl idiom to hide the internals.
710         class Impl;
711         /// The pointer never changes although *pimpl_'s contents may.
712         Impl * const d;
713 };
714
715
716 } // namespace lyx
717
718 #endif