-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
TextEditingTarget.java
4944 lines (4382 loc) · 164 KB
/
TextEditingTarget.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* TextEditingTarget.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.FontWeight;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.http.client.URL;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.MenuItem;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Provider;
import org.rstudio.core.client.*;
import org.rstudio.core.client.command.AppCommand;
import org.rstudio.core.client.command.CommandBinder;
import org.rstudio.core.client.command.Handler;
import org.rstudio.core.client.command.KeyboardHelper;
import org.rstudio.core.client.command.KeyboardShortcut;
import org.rstudio.core.client.events.EnsureHeightHandler;
import org.rstudio.core.client.events.EnsureVisibleHandler;
import org.rstudio.core.client.events.HasEnsureHeightHandlers;
import org.rstudio.core.client.events.HasEnsureVisibleHandlers;
import org.rstudio.core.client.files.FileSystemContext;
import org.rstudio.core.client.files.FileSystemItem;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.widget.*;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.ChangeFontSizeEvent;
import org.rstudio.studio.client.application.events.ChangeFontSizeHandler;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.*;
import org.rstudio.studio.client.common.debugging.BreakpointManager;
import org.rstudio.studio.client.common.debugging.events.BreakpointsSavedEvent;
import org.rstudio.studio.client.common.debugging.model.Breakpoint;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.FileType;
import org.rstudio.studio.client.common.filetypes.FileTypeCommands;
import org.rstudio.studio.client.common.filetypes.FileTypeRegistry;
import org.rstudio.studio.client.common.filetypes.SweaveFileType;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.r.roxygen.RoxygenHelper;
import org.rstudio.studio.client.common.rnw.RnwWeave;
import org.rstudio.studio.client.common.synctex.Synctex;
import org.rstudio.studio.client.common.synctex.SynctexUtils;
import org.rstudio.studio.client.common.synctex.model.SourceLocation;
import org.rstudio.studio.client.htmlpreview.events.ShowHTMLPreviewEvent;
import org.rstudio.studio.client.htmlpreview.model.HTMLPreviewParams;
import org.rstudio.studio.client.notebook.CompileNotebookOptions;
import org.rstudio.studio.client.notebook.CompileNotebookOptionsDialog;
import org.rstudio.studio.client.notebook.CompileNotebookPrefs;
import org.rstudio.studio.client.notebook.CompileNotebookResult;
import org.rstudio.studio.client.rmarkdown.events.ConvertToShinyDocEvent;
import org.rstudio.studio.client.rmarkdown.events.RmdOutputFormatChangedEvent;
import org.rstudio.studio.client.rmarkdown.model.RMarkdownContext;
import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatter;
import org.rstudio.studio.client.rmarkdown.model.RmdFrontMatterOutputOptions;
import org.rstudio.studio.client.rmarkdown.model.RmdOutputFormat;
import org.rstudio.studio.client.rmarkdown.model.RmdTemplateFormat;
import org.rstudio.studio.client.rmarkdown.model.RmdYamlData;
import org.rstudio.studio.client.rmarkdown.model.YamlFrontMatter;
import org.rstudio.studio.client.rmarkdown.ui.RmdTemplateOptionsDialog;
import org.rstudio.studio.client.rsconnect.events.RSConnectActionEvent;
import org.rstudio.studio.client.rsconnect.events.RSConnectDeployInitiatedEvent;
import org.rstudio.studio.client.rsconnect.model.RSConnectPublishSettings;
import org.rstudio.studio.client.server.ServerError;
import org.rstudio.studio.client.server.ServerRequestCallback;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.server.VoidServerRequestCallback;
import org.rstudio.studio.client.shiny.events.ShinyApplicationStatusEvent;
import org.rstudio.studio.client.workbench.WorkbenchContext;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.Session;
import org.rstudio.studio.client.workbench.model.SessionInfo;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.ui.FontSizeManager;
import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeEvent;
import org.rstudio.studio.client.workbench.views.files.events.FileChangeHandler;
import org.rstudio.studio.client.workbench.views.files.model.FileChange;
import org.rstudio.studio.client.workbench.views.help.events.ShowHelpEvent;
import org.rstudio.studio.client.workbench.views.output.compilepdf.events.CompilePdfEvent;
import org.rstudio.studio.client.workbench.views.output.lint.LintManager;
import org.rstudio.studio.client.workbench.views.presentation.events.SourceFileSaveCompletedEvent;
import org.rstudio.studio.client.workbench.views.presentation.model.PresentationState;
import org.rstudio.studio.client.workbench.views.source.SourceBuildHelper;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget;
import org.rstudio.studio.client.workbench.views.source.editors.EditingTargetCodeExecution;
import org.rstudio.studio.client.workbench.views.source.editors.text.DocDisplay.AnchoredSelection;
import org.rstudio.studio.client.workbench.views.source.editors.text.ScopeList.ContainsFoldPredicate;
import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTargetRMarkdownHelper.RmdSelectedTemplate;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceFold;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Range;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionOperation;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu;
import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupRequest;
import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler;
import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent;
import org.rstudio.studio.client.workbench.views.source.events.SourceNavigationEvent;
import org.rstudio.studio.client.workbench.views.source.model.*;
import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsDiffEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.ShowVcsHistoryEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsRevertFileEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.events.VcsViewOnGitHubEvent;
import org.rstudio.studio.client.workbench.views.vcs.common.model.GitHubViewRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
public class TextEditingTarget implements
EditingTarget,
EditingTargetCodeExecution.CodeExtractor
{
interface MyCommandBinder
extends CommandBinder<Commands, TextEditingTarget>
{
}
private static final String NOTEBOOK_TITLE = "notebook_title";
private static final String NOTEBOOK_AUTHOR = "notebook_author";
private static final String NOTEBOOK_TYPE = "notebook_type";
private static final MyCommandBinder commandBinder =
GWT.create(MyCommandBinder.class);
public interface Display extends TextDisplay,
WarningBarDisplay,
HasHandlers,
HasEnsureVisibleHandlers,
HasEnsureHeightHandlers
{
HasValue<Boolean> getSourceOnSave();
void ensureVisible();
void showFindReplace(boolean defaultForward);
void findNext();
void findPrevious();
void findSelectAll();
void findFromSelection();
void replaceAndFind();
StatusBar getStatusBar();
void showOutlineIcon(boolean show);
boolean isAttached();
void adaptToExtendedFileType(String extendedType);
void onShinyApplicationStateChanged(String state);
void debug_dumpContents();
void debug_importDump();
void setIsShinyFormat(boolean isPresentation);
void setFormatOptions(TextFileType fileType,
List<String> options,
List<String> values,
List<String> extensions,
String selected);
void setFormatOptionsVisible(boolean visible);
HandlerRegistration addRmdFormatChangedHandler(
RmdOutputFormatChangedEvent.Handler handler);
HandlerRegistration addShowOutlineHandler(ShowOutlineEvent.Handler handler);
HandlerRegistration addHideOutlineHandler(HideOutlineEvent.Handler handler);
void setPublishPath(String type, String publishPath);
}
private class SaveProgressIndicator implements ProgressIndicator
{
public SaveProgressIndicator(FileSystemItem file,
TextFileType fileType,
Command executeOnSuccess)
{
file_ = file;
newFileType_ = fileType;
executeOnSuccess_ = executeOnSuccess;
}
public void onProgress(String message)
{
}
public void clearProgress()
{
}
public void onCompleted()
{
// don't need to check again soon because we just saved
// (without this and when file monitoring is active we'd
// end up immediately checking for external edits)
externalEditCheckInterval_.reset(250);
if (newFileType_ != null)
fileType_ = newFileType_;
if (file_ != null)
{
ignoreDeletes_ = false;
forceSaveCommandActive_ = false;
commands_.reopenSourceDocWithEncoding().setEnabled(true);
name_.setValue(file_.getName(), true);
// Make sure tooltip gets updated, even if name hasn't changed
name_.fireChangeEvent();
// If we were dirty prior to saving, clean up the debug state so
// we don't continue highlighting after saving. (There are cases
// in which we want to restore highlighting after the dirty state
// is marked clean--i.e. when unwinding the undo stack.)
if (dirtyState_.getValue())
endDebugHighlighting();
dirtyState_.markClean();
}
if (newFileType_ != null)
{
// Make sure the icon gets updated, even if name hasn't changed
name_.fireChangeEvent();
updateStatusBarLanguage();
view_.adaptToFileType(newFileType_);
events_.fireEvent(new FileTypeChangedEvent());
if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave())
{
view_.getSourceOnSave().setValue(false, true);
}
}
if (executeOnSuccess_ != null)
executeOnSuccess_.execute();
}
public void onError(final String message)
{
// in case the error occured saving a document that wasn't
// in the foreground
view_.ensureVisible();
// command to show the error
final Command showErrorCommand = new Command() {
@Override
public void execute()
{
globalDisplay_.showErrorMessage("Error Saving File",
message);
}
};
// check whether the file exists and isn't writeable
if (file_ != null)
{
server_.isReadOnlyFile(file_.getPath(),
new ServerRequestCallback<Boolean>() {
@Override
public void onResponseReceived(Boolean isReadOnly)
{
if (isReadOnly)
{
String message = "This source file is read-only " +
"so changes cannot be saved";
view_.showWarningBar(message);
String saveAsPath = file_.getParentPath().completePath(
file_.getStem() + "-copy" + file_.getExtension());
saveNewFile(
saveAsPath,
null,
CommandUtil.join(postSaveCommand(), new Command() {
@Override
public void execute()
{
view_.hideWarningBar();
}
}));
}
else
{
showErrorCommand.execute();
}
}
@Override
public void onError(ServerError error)
{
Debug.logError(error);
showErrorCommand.execute();
}
});
}
else
{
showErrorCommand.execute();
}
}
private final FileSystemItem file_;
private final TextFileType newFileType_;
private final Command executeOnSuccess_;
}
@Inject
public TextEditingTarget(Commands commands,
SourceServerOperations server,
EventBus events,
GlobalDisplay globalDisplay,
FileDialogs fileDialogs,
FileTypeRegistry fileTypeRegistry,
FileTypeCommands fileTypeCommands,
ConsoleDispatcher consoleDispatcher,
WorkbenchContext workbenchContext,
Session session,
Synctex synctex,
FontSizeManager fontSizeManager,
DocDisplay docDisplay,
UIPrefs prefs,
BreakpointManager breakpointManager,
SourceBuildHelper sourceBuildHelper)
{
commands_ = commands;
server_ = server;
events_ = events;
globalDisplay_ = globalDisplay;
fileDialogs_ = fileDialogs;
fileTypeRegistry_ = fileTypeRegistry;
fileTypeCommands_ = fileTypeCommands;
consoleDispatcher_ = consoleDispatcher;
workbenchContext_ = workbenchContext;
session_ = session;
synctex_ = synctex;
fontSizeManager_ = fontSizeManager;
breakpointManager_ = breakpointManager;
sourceBuildHelper_ = sourceBuildHelper;
docDisplay_ = docDisplay;
dirtyState_ = new DirtyState(docDisplay_, false);
lintManager_ = new LintManager(this);
prefs_ = prefs;
codeExecution_ = new EditingTargetCodeExecution(docDisplay_, this);
compilePdfHelper_ = new TextEditingTargetCompilePdfHelper(docDisplay_);
rmarkdownHelper_ = new TextEditingTargetRMarkdownHelper();
cppHelper_ = new TextEditingTargetCppHelper(cppCompletionContext_,
docDisplay_);
presentationHelper_ = new TextEditingTargetPresentationHelper(
docDisplay_);
reformatHelper_ = new TextEditingTargetReformatHelper(docDisplay_);
snippets_ = new SnippetHelper((AceEditor) docDisplay_);
docDisplay_.setRnwCompletionContext(compilePdfHelper_);
docDisplay_.setCppCompletionContext(cppCompletionContext_);
docDisplay_.setRCompletionContext(rContext_);
scopeHelper_ = new TextEditingTargetScopeHelper(docDisplay_);
addRecordNavigationPositionHandler(releaseOnDismiss_,
docDisplay_,
events_,
this);
docDisplay_.addKeyDownHandler(new KeyDownHandler()
{
@SuppressWarnings("deprecation")
public void onKeyDown(KeyDownEvent event)
{
NativeEvent ne = event.getNativeEvent();
int mod = KeyboardShortcut.getModifierValue(ne);
if ((mod == KeyboardShortcut.META || (mod == KeyboardShortcut.CTRL && !BrowseCap.hasMetaKey()))
&& ne.getKeyCode() == 'F')
{
event.preventDefault();
event.stopPropagation();
commands_.findReplace().execute();
}
else if (BrowseCap.hasMetaKey() &&
(mod == KeyboardShortcut.META) &&
(ne.getKeyCode() == 'E'))
{
event.preventDefault();
event.stopPropagation();
commands_.findFromSelection().execute();
}
else if (mod == KeyboardShortcut.ALT &&
KeyboardHelper.isHyphenKeycode(ne.getKeyCode()))
{
event.preventDefault();
event.stopPropagation();
if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) ||
(!docDisplay_.hasSelection() &&
docDisplay_.getCursorPosition().getColumn() == 0))
docDisplay_.insertCode("<- ", false);
else
docDisplay_.insertCode(" <- ", false);
}
else if (mod == KeyboardShortcut.CTRL
&& ne.getKeyCode() == KeyCodes.KEY_UP
&& fileType_ == FileTypeRegistry.R)
{
event.preventDefault();
event.stopPropagation();
jumpToPreviousFunction();
}
else if (mod == KeyboardShortcut.CTRL
&& ne.getKeyCode() == KeyCodes.KEY_DOWN
&& fileType_ == FileTypeRegistry.R)
{
event.preventDefault();
event.stopPropagation();
jumpToNextFunction();
}
else if ((ne.getKeyCode() == KeyCodes.KEY_ESCAPE) &&
!prefs_.useVimMode().getValue())
{
event.preventDefault();
event.stopPropagation();
// Don't send an interrupt if a popup is visible
if (docDisplay_.isPopupVisible())
return;
if (commands_.interruptR().isEnabled())
commands_.interruptR().execute();
}
else if (ne.getKeyCode() == KeyCodes.KEY_M && (
(BrowseCap.hasMetaKey() &&
mod == (KeyboardShortcut.META + KeyboardShortcut.SHIFT)) ||
(!BrowseCap.hasMetaKey() &&
mod == (KeyboardShortcut.CTRL + KeyboardShortcut.SHIFT))))
{
event.preventDefault();
event.stopPropagation();
if (Character.isSpace(docDisplay_.getCharacterBeforeCursor()) ||
(!docDisplay_.hasSelection() &&
docDisplay_.getCursorPosition().getColumn() == 0))
docDisplay_.insertCode("%>% ", false);
else
docDisplay_.insertCode(" %>% ", false);
}
else if (
prefs_.continueCommentsOnNewline().getValue() &&
!docDisplay_.isPopupVisible() &&
ne.getKeyCode() == KeyCodes.KEY_ENTER && mod == 0 &&
(fileType_.isC() || isCursorInRMode() || isCursorInTexMode()))
{
String line = docDisplay_.getCurrentLineUpToCursor();
Pattern pattern = null;
if (isCursorInRMode())
pattern = Pattern.create("^(\\s*#+'?\\s*)");
else if (isCursorInTexMode())
pattern = Pattern.create("^(\\s*%+'?\\s*)");
else if (fileType_.isC())
{
// bail on attributes
if (!line.matches("^\\s*//\\s*\\[\\[.*\\]\\].*"))
pattern = Pattern.create("^(\\s*//'?\\s*)");
}
if (pattern != null)
{
Match match = pattern.match(line, 0);
if (match != null)
{
event.preventDefault();
event.stopPropagation();
docDisplay_.insertCode("\n" + match.getGroup(1));
docDisplay_.ensureCursorVisible();
}
}
}
else if (
prefs_.continueCommentsOnNewline().getValue() &&
!docDisplay_.isPopupVisible() &&
ne.getKeyCode() == KeyCodes.KEY_ENTER &&
mod == KeyboardShortcut.SHIFT)
{
event.preventDefault();
event.stopPropagation();
String indent = docDisplay_.getNextLineIndent();
docDisplay_.insertCode("\n" + indent);
}
}
});
docDisplay_.addCommandClickHandler(new CommandClickEvent.Handler()
{
@Override
public void onCommandClick(CommandClickEvent event)
{
if (fileType_.canCompilePDF() &&
commands_.synctexSearch().isEnabled())
{
// warn firefox users that this doesn't really work in Firefox
if (BrowseCap.isFirefox() && !BrowseCap.isMacintosh())
SynctexUtils.maybeShowFirefoxWarning("PDF preview");
doSynctexSearch(true);
}
else
{
docDisplay_.goToFunctionDefinition();
}
}
});
docDisplay_.addFindRequestedHandler(new FindRequestedEvent.Handler() {
@Override
public void onFindRequested(FindRequestedEvent event)
{
view_.showFindReplace(event.getDefaultForward());
}
});
events_.addHandler(
ShinyApplicationStatusEvent.TYPE,
new ShinyApplicationStatusEvent.Handler()
{
@Override
public void onShinyApplicationStatus(
ShinyApplicationStatusEvent event)
{
// If the document appears to be inside the directory
// associated with the event, update the view to match the
// new state.
if (getPath() != null &&
getPath().startsWith(event.getParams().getPath()))
{
view_.onShinyApplicationStateChanged(
event.getParams().getState());
}
}
});
events_.addHandler(
BreakpointsSavedEvent.TYPE,
new BreakpointsSavedEvent.Handler()
{
@Override
public void onBreakpointsSaved(BreakpointsSavedEvent event)
{
// if this document isn't ready for breakpoints, stop now
if (docUpdateSentinel_ == null)
{
return;
}
for (Breakpoint breakpoint: event.breakpoints())
{
// discard the breakpoint if it's not related to the file this
// editor instance is concerned with
if (!breakpoint.isInFile(getPath()))
{
continue;
}
// if the breakpoint was saved successfully, enable it on the
// editor surface; otherwise, just remove it.
if (event.successful())
{
docDisplay_.addOrUpdateBreakpoint(breakpoint);
}
else
{
// Show a warning for breakpoints that didn't get set (unless
// the reason the breakpoint wasn't set was that it's being
// removed)
if (breakpoint.getState() != Breakpoint.STATE_REMOVING)
{
view_.showWarningBar("Breakpoints can only be set inside "+
"the body of a function. ");
}
docDisplay_.removeBreakpoint(breakpoint);
}
}
updateBreakpointWarningBar();
}
});
events_.addHandler(ConvertToShinyDocEvent.TYPE,
new ConvertToShinyDocEvent.Handler()
{
@Override
public void onConvertToShinyDoc(ConvertToShinyDocEvent event)
{
if (getPath() != null &&
getPath().equals(event.getPath()))
{
String yaml = getRmdFrontMatter();
if (yaml == null)
return;
String newYaml = rmarkdownHelper_.convertYamlToShinyDoc(yaml);
applyRmdFrontMatter(newYaml);
renderRmd();
}
}
});
events_.addHandler(RSConnectDeployInitiatedEvent.TYPE,
new RSConnectDeployInitiatedEvent.Handler()
{
@Override
public void onRSConnectDeployInitiated(
RSConnectDeployInitiatedEvent event)
{
// no need to process this event if this target doesn't have a
// path, or if the event's contents don't include additional
// files.
if (getPath() == null)
return;
// see if the event corresponds to a deployment of this file
if (!getPath().equals(event.getSource().getSourceFile()))
return;
RSConnectPublishSettings settings = event.getSettings();
if (settings == null)
return;
// ignore deployments of static content generated from this
// file
if (settings.getAsStatic())
return;
if (settings.getAdditionalFiles() != null &&
settings.getAdditionalFiles().size() > 0)
{
addAdditionalResourceFiles(settings.getAdditionalFiles());
}
}
});
}
@Override
public void recordCurrentNavigationPosition()
{
docDisplay_.recordCurrentNavigationPosition();
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
docDisplay_.navigateToPosition(position, recordCurrent);
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent,
boolean highlightLine)
{
docDisplay_.navigateToPosition(position, recordCurrent, highlightLine);
}
@Override
public void restorePosition(SourcePosition position)
{
docDisplay_.restorePosition(position);
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
return docDisplay_.isAtSourceRow(position);
}
@Override
public void setCursorPosition(Position position)
{
docDisplay_.setCursorPosition(position);
}
@Override
public void ensureCursorVisible()
{
docDisplay_.ensureCursorVisible();
}
@Override
public void forceLineHighlighting()
{
docDisplay_.setHighlightSelectedLine(true);
}
@Override
public void highlightDebugLocation(
SourcePosition startPos,
SourcePosition endPos,
boolean executing)
{
debugStartPos_ = startPos;
debugEndPos_ = endPos;
docDisplay_.highlightDebugLocation(startPos, endPos, executing);
updateDebugWarningBar();
}
@Override
public void endDebugHighlighting()
{
docDisplay_.endDebugHighlighting();
debugStartPos_ = null;
debugEndPos_ = null;
updateDebugWarningBar();
}
private void updateDebugWarningBar()
{
// show the warning bar if we're debugging and the document is dirty
if (debugStartPos_ != null &&
dirtyState().getValue() &&
!isDebugWarningVisible_)
{
view_.showWarningBar("Debug lines may not match because the file contains unsaved changes.");
isDebugWarningVisible_ = true;
}
// hide the warning bar if the dirty state or debug state change
else if (isDebugWarningVisible_ &&
(debugStartPos_ == null || dirtyState().getValue() == false))
{
view_.hideWarningBar();
// if we're still debugging, start highlighting the line again
if (debugStartPos_ != null)
{
docDisplay_.highlightDebugLocation(
debugStartPos_,
debugEndPos_, false);
}
isDebugWarningVisible_ = false;
}
}
private void jumpToPreviousFunction()
{
Scope jumpTo = scopeHelper_.getPreviousFunction(
docDisplay_.getCursorPosition());
if (jumpTo != null)
docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true);
}
private void jumpToNextFunction()
{
Scope jumpTo = scopeHelper_.getNextFunction(
docDisplay_.getCursorPosition());
if (jumpTo != null)
docDisplay_.navigateToPosition(toSourcePosition(jumpTo), true);
}
public void initialize(SourceDocument document,
FileSystemContext fileContext,
FileType type,
Provider<String> defaultNameProvider)
{
id_ = document.getId();
fileContext_ = fileContext;
fileType_ = (TextFileType) type;
extendedType_ = document.getExtendedType();
extendedType_ = rmarkdownHelper_.detectExtendedType(document.getContents(),
extendedType_,
fileType_);
view_ = new TextEditingTargetWidget(commands_,
prefs_,
fileTypeRegistry_,
docDisplay_,
fileType_,
extendedType_,
events_,
session_);
docUpdateSentinel_ = new DocUpdateSentinel(
server_,
docDisplay_,
document,
globalDisplay_.getProgressIndicator("Save File"),
dirtyState_,
events_);
roxygenHelper_ = new RoxygenHelper(docDisplay_, view_);
// ensure that Makefile and Makevars always use tabs
name_.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event)
{
if ("Makefile".equals(event.getValue()) ||
"Makevars".equals(event.getValue()) ||
"Makevars.win".equals(event.getValue()))
{
docDisplay_.setUseSoftTabs(false);
}
}
});
name_.setValue(getNameFromDocument(document, defaultNameProvider), true);
docDisplay_.setCode(document.getContents(), false);
final ArrayList<Fold> folds = Fold.decode(document.getFoldSpec());
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
for (Fold fold : folds)
docDisplay_.addFold(fold.getRange());
}
});
registerPrefs(releaseOnDismiss_, prefs_, docDisplay_, document);
// Initialize sourceOnSave, and keep it in sync
view_.getSourceOnSave().setValue(document.sourceOnSave(), false);
view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>()
{
public void onValueChange(ValueChangeEvent<Boolean> event)
{
docUpdateSentinel_.setSourceOnSave(
event.getValue(),
globalDisplay_.getProgressIndicator("Error Saving Setting"));
}
});
if (document.isDirty())
dirtyState_.markDirty(false);
else
dirtyState_.markClean();
docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>()
{
public void onValueChange(ValueChangeEvent<Void> event)
{
dirtyState_.markDirty(true);
}
});
docDisplay_.addFocusHandler(new FocusHandler()
{
public void onFocus(FocusEvent event)
{
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
public boolean execute()
{
if (view_.isAttached())
checkForExternalEdit();
return false;
}
}, 500);
}
});
if (fileType_.isR())
{
docDisplay_.addBreakpointSetHandler(new BreakpointSetEvent.Handler()
{
@Override
public void onBreakpointSet(BreakpointSetEvent event)
{
if (event.isSet())
{
Breakpoint breakpoint = null;
// don't try to set breakpoints in unsaved code
if (isNewDoc())
{
view_.showWarningBar("Breakpoints cannot be set until " +
"the file is saved.");
return;
}
// don't try to set breakpoints if the R version is too old
if (!session_.getSessionInfo().getHaveSrcrefAttribute())
{
view_.showWarningBar("Editor breakpoints require R 2.14 " +
"or newer.");
return;
}
Position breakpointPosition =
Position.create(event.getLineNumber() - 1, 1);
// if we're not in function scope, or this is a Shiny file,
// set a top-level (aka. Shiny-deferred) breakpoint
ScopeFunction innerFunction = null;
if (!extendedType_.equals("shiny"))
innerFunction = docDisplay_.getFunctionAtPosition(
breakpointPosition, false);
if (innerFunction == null || !innerFunction.isFunction() ||
StringUtil.isNullOrEmpty(innerFunction.getFunctionName()))
{
breakpoint = breakpointManager_.setTopLevelBreakpoint(
getPath(),
event.getLineNumber());
}
// the scope tree will find nested functions, but in R these
// are addressable only as substeps of the parent function.
// keep walking up the scope tree until we've reached the top
// level function.
else
{
while (innerFunction.getParentScope() != null &&
innerFunction.getParentScope().isFunction())
{
innerFunction = (ScopeFunction) innerFunction.getParentScope();
}
String functionName = innerFunction.getFunctionName();
breakpoint = breakpointManager_.setBreakpoint(
getPath(),
functionName,
event.getLineNumber(),
dirtyState().getValue() == false);
}
docDisplay_.addOrUpdateBreakpoint(breakpoint);
}
else
{
breakpointManager_.removeBreakpoint(event.getBreakpointId());
}
updateBreakpointWarningBar();
}
});
docDisplay_.addBreakpointMoveHandler(new BreakpointMoveEvent.Handler()
{
@Override
public void onBreakpointMove(BreakpointMoveEvent event)
{
breakpointManager_.moveBreakpoint(event.getBreakpointId());
}
});
}
// validate required components (e.g. Tex, knitr, C++ etc.)
checkCompilePdfDependencies();
rmarkdownHelper_.verifyPrerequisites(view_, fileType_);
syncFontSize(releaseOnDismiss_, events_, view_, fontSizeManager_);
final String rTypeId = FileTypeRegistry.R.getTypeId();
releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler(
new ValueChangeHandler<Boolean>()
{
public void onValueChange(ValueChangeEvent<Boolean> evt)