Suggestions for TeXShop 1.29 by Mitsu Shishikura

This time, you can search for "// mitsu 1.29" for changes.  

Here is the list of changes I made.  
(O) Multi page PDF view
(P) Command completion
(Q) Show Info
(R) beginEditing/endEditing for textStorage--fixColor2 is faster than fixColor

(S) Other PDF View changes--included in MyPDFView in (O)
(S1) Fix for Magnifying Glass in rotated views
(S2) Drag scrolling with control key
(S3) AutoScroll during Magnifying glass
(S4) View anchored at top left when scrolled--using flipped clip view
(S5) Double click and triple click for Magnifying Glass
(S6) topLeft for PDF view scrolling

(T) Other TextView related
(T0) Guideline
(T1) Fix for Japanese paste-undo bug
(T2) doCompletion -> insertSpecial/insertSepcialNonStandard
(T3) doCommandOrIndent
(T4) Autocompletion in insertText?

(U) Macro load/save
(V) "Untitled" for Japanese locaization
------------------------------------------------------------
Description:
(O) Multi page PDF view
I added multipage style (or mode) for pdfView.  You can choose the style from Preview menu.  There are so many changes, so I created MyPDFView (I wanted the name to be changed anyway) and wrote the new code there.  You can either use this or put the code back to MyView.  I also changed the order of methods so that it is easy to understand different parts of function.  I have been adding several features, including those I wrote in (S) earlier.  Here is a list:

	multipage style (single page/two page/multi-page/double multi-page)
		shows page shadow
		page number is displayed near scroller when scrolling in multipage styles
		setting in Preferences/Preview
	resize option--fit to width/window etc.
		if page width or height is shorter than the window, it is centered
		magnification toolbar item has a submenu in text only or overflow mode
		setting in Preferences/Preview
	select a region and copy/export in different image formats
		faster drawing of marquee using window's image caching mechanism
		supported formats: JPEG(high/medium/low), TIFF, PNG, GIF, PDF, EPS
		format setting in Preferences/Preview
	scroll by dragging (with control key)
	new magnifying glass routine which is faster and cleaner
		new routine uses window's image caching mechanism
		different logic for normal/large/full window sizes (I don't know if you like it)
		scale changes with command/control key
		autoscroll
	a toolbar item which allows you to switch "Mouse Mode" 
		-- scroll, magnifying glass (normal/large), select
		it also works in text only/overflow mode
		setting in Preferences/Preview
		modifier keys temporarily override the mode
	better support for non-pdf image files
	
I added a fair amount of comments in the source code.  So please read those comments.  Customize toolbar to see "Mouse Mode" toolbar item.  (Try also Text Only option.)

To use it:
Resources:
Add image files "OpenHandCursor.tiff", "GrabHandCursor.tiff", "MagGlass.tiff". MagGlassL.tiff" and "Select.tiff" to the project.  They are in icons folder.  

Nib files:
MainMenu.nib
Edit menu-- create items "Save Selection to a file" and "Image Copy format".  The former should be connected FirstResponder's "saveSelectionToFile:" method, the latter should have submenu with image format names which should be connected to "changeImageCopyType:".  Tags of these submenu items should be set correctly to IMAGE_TYPE_... constants.   
Preview menu-- create items "Single Page/Two Page/Multi-Page/Double Multi-Page" (need a better name?), which are to be connected to FirstResponder's "changePageStyle:" Their tags should be consistent with PAGE_STYLE constants.  
Create also "Actual Size/Fixed Magnification/Fit to Width/Fit to Window", and connect them to FirstResponder's "changePDFViewSize:", and set tags according to PDF_FIT_TO... constants.  A better name for "Fixed Magnification"?  ("Do not resize"?)

MyDocument.nib
If you are using MyPDFView, it should be assigned to the view of PDF window, instead of MyView.  Read "MyPDFView.h" from "Class" menu of ProjectBuilder.  
Create "Mouse Mode" toolbar item, which is a matrix with four button cells, each of which should be assigned one of the images and a tag constant "MOUSE_MODE_...".  These cells should be connected to MyPDFView's "changeMouseMode:".  Connect the outlets "mouseModeMatrix" of both MyPDFView and File's Owner (MyDocument) to the matrix.  
Create two menus "mouseModeMenu" and "magnificationMenu" which correspond to outlets of MyPDFView and File's Owner.  Each menu must have items with correct tags and connected to MyPDFView's "changeMouseMode:" or "changePDFViewSize:".  
It seems better to set the attribute of "currentPage" text field to "send action: Only on enter", in order to avoid to accidental message "goToPage" from that field.  
Add imageTypeView with imageTypePopup with items with correct tags and connect them to MyPDFView.  The action for imageTypePopup should be MyPDFView's chooseExportImageType.  

Preferences.nib
Create four boxes with popup buttons, "_pageStylePopup", "_resizeOptionPopup", "_imageCopyTypePopup" and "_mouseModePopup", correnpoding to outlets of File's Owner (TSPreferences).  Their actions must be set to corresponding methods of TSPreferences.  Again tags are important.  

To do/Comment:
Better names for "Multi-Page/Double Multi-Page", should remove "-"? "Continuous pages"?
Change background color, page shadow??
We have a menu item for image copy type and accessory popup for "export" save panel.  So it is not necessary to have a preference item?

I had a lot of trouble in the routine "imageDataFromSelectionType:".  There seems to be Apple's bugs in NSView's "convertRect:toView:" and "dataWithPDFInsideRect:".  I put temporary work-arounds, but there is a case I couldn't handle: Export to a PDF or EPS file when the view is 90 or -90 degree rotated.  (Who needs this?)  

(P) Command completion
This works as follows: 
when you are typing some command, you only type first few letters and hit escape key, then the word will be completed according to a user configured file.  For example, when you typed

\begin{enum
and hit escape, you get
\begin{enumerate}

Another escape will give you another candidate if any, and with more escapes the candidates are cycled. (Backwards with ShiftKey.)  
Word boundaries are searched for space, tab, period, comma, colon, semicolon, {, }, (, ), and tex character.  The configuration file "~/Library/TeXshop/CommandCompletion/CommandCompletion.txt" is a text file (which should be in the same encoding as the preference) and the contents are "commands" (or "words") separated by linefeeds.  The order of the candidates which appear will be the same as their order in this file.  So put frequently used ones at the beginng of the file.  
You can register a new word to the completion list be selecting the word and choosing "Register for CommandCompletion" in "Format" menu.  There is also "Edit CommandCompletion List" in "Format" menu.  

Special treatments:
if the word boundary is { or tex character, then they are included in the search string when commands are searched, while other characters are not included for search.  For example, 
if CommandCompletion.txt has 
abcabcabc
\abcdef
{abcxyz}
then the completion for "  abc" will be "  abcabcabc", that for "\abc" will be "\abcdef" and that for "{abc" will be "{abcxyz}".  I designed this way because these special cases will be the most used cases and this will reduce the number of candidates for each completion.  
If a line in CommandCompletion.txt has: 
  #INS# then it will be replaced by an empty string and the insertion point will be put there;  
  tabs then it will be replaced by linefeeds;   
  space, then the string after the first space will be inserted.  
For example, it has
\enumerate \begin{enumerate}(tab)  \item #INS#(tab)\end{enumerate}
then "\enum" will be completed to 
\begin{enumerate}
  \item 
\end{enumerate}
and the insertion point will come after \item.  
If you type "\begin{somecommand}" and hit esc, then it will be completed to 
\begin{somecommand}
\end{somecommand}
and the insertion point comes at the end of the first line.  In this case, {somecommand} does not need to be registered.  

You need to add the file CommandCompletion.txt to the project. Create menu items "Resgister for CommandCompletion" and "Edit CommandCompletion List"either in "Format" menu or "Edit" menu and connect them to FirstResponder's actions "registerForCommandCompletion" and "openCommanCompletionList", which should be created also.  

To do: 
Find a good collection of commands.  
Menu items "Resgister for CommandCompletion" and "Edit CommandCompletion List"are too long? Should go to "Edit" menu or other menu?
The activation key (escape) should be user configurable.  
When registering a word, check for redundancy.  

(Q) Show Info
Sometimes I was required to count number of characters (approximate, because it is difficult to count real number for TeX files).  So I made a command "showInfo".  At this moment it is not so useful for other purposes--line and word counting will be tricky.  You need to add a menu item "Show Info" to "File" menu in Nib file.  I hope you or somebody expand this to something more useful.  

(R) beginEditing/endEditing for textStorage--fixColor2 is faster than fixColor
When you are making changes to the text view, enclose the operation by 
	[[textView textStorage] beginEditing];
and 
	[[textView textStorage] endEditing];
"beginEditing" and "endEditing" are defined in MSMutableAttributedString, which is the superclass of the textStorage.  Once you declare "beginEditing", the change you made is stored in the buffer and the string is blocked from sending a notification of the changes, this causes speedup.In the FindPanel of TeXShop, the same thing is applied to a temporarily allocated attributed string (is this from TextEdit?).
Just by spelling two lines of magic words, fixColor2 becomes much faster than fixColor (5 times faster according to my test).  So use fixColor2, unless there is any problem with logic.  

(S) Other PDF View changes--included in MyPDFView in (O)
(S1) Fix for Magnifying Glass in rotated views
Fixed for 90 and -90 degree rotations.  But there seems to be Apple's bug in PDFImageRep' s drawAtPoint and NSView's setBounds, when 180 degree rotated.  So I suggest you to disable Magnifying Glass in this case.  
 
(S2) Drag scrolling with control key
You can scroll the pdf view just by dragging while Control Key is pressed.  
You need to add pictures "OpenHandCursor.tiff" and "GrabHandCursor.tiff" to the project.  

(S3) AutoScroll during Magnifying glass
While doing the Magnifying Glass, if the cursor goes out of the view, then it autoscrolls.  This can be especially useful in MultiPage mode.  To continously scroll, you have to keep the mouse moving.  

(S4) View anchored at top left when scrolled--using flipped clip view
By swapping the clip view (superview of pdfView and contentView of scrollView), to a "FlippedClipView", whose only difference is to say YES on isFlipped, the view can be anchored at top left when the window is resized.  
  
(S5) Double click and triple click for Magnifying Glass
A double click gives a larger Magnifying Glass and triple click magnifies whole visibleRect.  There is a flashing effect you mentioned, but it is convinient for viewing it by one hand.  

(S6) topLeft for PDF view scrolling
Since we now set (0,0) to be the origin of the bounds, the topLeft should be calculated from View's bounds not from ImageRep's bounds (which is not defined for ImageReps other than PDF ImageRep).  

(T) Other TextView related
(T0) Guideline
Apple's document "Subclassing NSTextView/Notifying About Changes to the Text" in "Text System User Interface Layer". says the following 
When you make a change to a text in text view,  bracket each batch of potential 
changes with "shouldChangeTextInRange:replacementString:" and "didChangeText" messages.  Then the delegate will be passed corresponding messages and you have a chance to examine the changes, e.g. color and tags.  
So I would like to suggest you to follow this guideline as much as possible.  
This way you can standardize the way the changes go through, and make it easier to handle coloring and tagging.  You seem to be running timers for coloring and tagging, but if you can intercept all changes, it shouldn't be necessary.  
Another advantage of this is that if you follow the guideline, "Undo" is automatically setup for the operation and you only need to set "ActionName" for undo menu item via [undoManager setActionName:..].  
The system seems to be grouping Undos by event kinds.  In some occasions such as autocompletion, you do not want your operation to be grouped with others, and in such a case, you need to handle it separately.  In my implementation, "insertSpecial:undoKey:" follows the guideline and "insertSpecialNonStabdard:undoKey:" does not.  

(T1) Fix for Japanese paste-undo bug
In Japanese encodings, the paste was previously done by calling "insertText:", this caused the following problem: after you paste, and do "Undo Paste", then the pasted text is not erased but grouped with prevoius other key-input text and erased together by next "Undo Typing".  I changes this so that it follows the above guideline.  

(T2) doCompletion -> insertSpecial/insertSepcialNonStandard
"doCompletion: was called for many purposes, LaTeX Panel, Macros, Autocompletion.  Undo titles was always "Undo Typing" (and was not localized).   Instead I created "insertSpecial:undoKey:" and "insertSpecialNonStabdard:undoKey:" mentioned above.  
Now LaTeX Panel and  Macros call "insertSpecial:undoKey:"  and Autocompletion calls "insertSpecialNonStabdard:undoKey:".  "insertSpecialNonStabdard:undoKey:" calls, in order to set up undo, "registerUndoWithString:location:length:key:" which requires "undoSpecial:".  
The methods "insertSpecial:undoKey:", "insertSpecialNonStabdard:undoKey:", "registerUndoWithString:location:length:key:", "undoSpecial:" are defined in MyTextView, but they can be easily moved to MyDocument if you prefer.  
Feb. 15: I moved these methods to MyDocument.  Old ones in MyTextView are kept but commented out.  You can decide which class should have these methods.  

(T3) doCommandOrIndent
In the same spirit, I created "doCommandOrIndent:" which replaces "doComment/doUncomment/doIndent/doUnindent" and "doModify".  It can be directly connected from menu item, and uses tags and title.  So the tags of the menu items should be correctly set.  It also uses common methods "registerUndoWithString:location:length:key:" and "undoSpecial:".  

(T4) Autocompletion in insertText?
As I mentioned before, it seems natural to handle autocompletion in "insertText:".  So I did several experiments.  
(1) If you #define AUTOCOMPLETE_IN_INSERTTEXT
both in MyTextView and in MyDocument, and comment out #define ALLOW_UNDO_AUTOCOMPLETION in MyTextView, Autocompletion is handled within "insertText:" and passes the result to super's "insertText:".  This case you cannot separately undo Autocompletion, and it will be grouped with other input for "Undo Typing".  
(2) If you #define AUTOCOMPLETE_IN_INSERTTEXT
both in MyTextView and in MyDocument, and also #define ALLOW_UNDO_AUTOCOMPLETION in MyTextView, Autocompletion is handled within "insertText:" and inserts the result directly.  Then it calls common method "registerUndoWithString:location:length:key:".  This case you can undo Autocompletion.  
(3) If you comment out both #define AUTOCOMPLETE_IN_INSERTTEXT
both in MyTextView and in MyDocument, Autocompletion is handled by MyDocument (delegate)'s "textView:shouldChangeTextInRange:replacementString:".  The only difference from previous version is to call "registerUndoWithString:location:length:key:" instead of calling "doCompletion:".  This case you can undo Autocompletion.  

(U) Macro load/save
When loading Macros, I now follow Apple's example in documentation "Using XML Property Lists".  When saving Macros, move old Macros.plist to Macros~.plist. 

(V) "Untitled" for Japanese locaization
The file name in Japanese corresponding to "Untitled" caused problems when you typeset (when TeX engine handles the file name in UTF8, so I modified the behavior of "displayName".  