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